Example #1
0
 public function run()
 {
     parent::run();
     $this->getInputJson();
     if (!($token = validateToken($this->input['token']))) {
         throw new \Exception("Invalid token.");
     }
     //TODO: delete global somehow
     global $user;
     $user = new \User($token['uid']);
     if (isset($this->input['remove'])) {
         if (!$user->removeFavorites($this->input['remove'])) {
             throw new \Exception("Could not remove favorites.");
         }
     }
     if (isset($this->input['add'])) {
         if (!$user->addFavorites($this->input['add'])) {
             throw new \Exception("Could not add favorites.");
         }
     }
     $favorites = array();
     $user->getFavorites();
     foreach ($user->favorites as $favorite) {
         $favorites[] = $favorite['tid'];
     }
     $this->return['favorites'] = $favorites;
 }
Example #2
0
/**
 * The function that handles adding, and deleting holiday data
 */
function ModifyHolidays()
{
    global $sourcedir, $scripturl, $txt, $context;
    // Submitting something...
    if (isset($_REQUEST['delete']) && !empty($_REQUEST['holiday'])) {
        checkSession();
        validateToken('admin-mc');
        foreach ($_REQUEST['holiday'] as $id => $value) {
            $_REQUEST['holiday'][$id] = (int) $id;
        }
        // Now the IDs are "safe" do the delete...
        require_once $sourcedir . '/Subs-Calendar.php';
        removeHolidays($_REQUEST['holiday']);
    }
    createToken('admin-mc');
    $listOptions = array('id' => 'holiday_list', 'title' => $txt['current_holidays'], 'items_per_page' => 20, 'base_href' => $scripturl . '?action=admin;area=managecalendar;sa=holidays', 'default_sort_col' => 'name', 'get_items' => array('file' => $sourcedir . '/Subs-Calendar.php', 'function' => 'list_getHolidays'), 'get_count' => array('file' => $sourcedir . '/Subs-Calendar.php', 'function' => 'list_getNumHolidays'), 'no_items_label' => $txt['holidays_no_entries'], 'columns' => array('name' => array('header' => array('value' => $txt['holidays_title']), 'data' => array('sprintf' => array('format' => '<a href="' . $scripturl . '?action=admin;area=managecalendar;sa=editholiday;holiday=%1$d">%2$s</a>', 'params' => array('id_holiday' => false, 'title' => false))), 'sort' => array('default' => 'title', 'reverse' => 'title DESC')), 'date' => array('header' => array('value' => $txt['date']), 'data' => array('function' => create_function('$rowData', '
						global $txt;

						// Recurring every year or just a single year?
						$year = $rowData[\'year\'] == \'0004\' ? sprintf(\'(%1$s)\', $txt[\'every_year\']) : $rowData[\'year\'];

						// Construct the date.
						return sprintf(\'%1$d %2$s %3$s\', $rowData[\'day\'], $txt[\'months\'][(int) $rowData[\'month\']], $year);
					')), 'sort' => array('default' => 'event_date', 'reverse' => 'event_date DESC')), 'check' => array('header' => array('value' => '<input type="checkbox" onclick="invertAll(this, this.form);" class="input_check" />'), 'data' => array('sprintf' => array('format' => '<input type="checkbox" name="holiday[%1$d]" class="input_check" />', 'params' => array('id_holiday' => false)), 'style' => 'text-align: center'))), 'form' => array('href' => $scripturl . '?action=admin;area=managecalendar;sa=holidays', 'token' => 'admin-mc'), 'additional_rows' => array(array('position' => 'below_table_data', 'value' => '

					<input type="submit" name="delete" value="' . $txt['quickmod_delete_selected'] . '" class="button_submit" />
					<a class="button_link" href="' . $scripturl . '?action=admin;area=managecalendar;sa=editholiday" style="margin: 0 1em">' . $txt['holidays_add'] . '</a>', 'style' => 'text-align: right;')));
    require_once $sourcedir . '/Subs-List.php';
    createList($listOptions);
    //loadTemplate('ManageCalendar');
    $context['page_title'] = $txt['manage_holidays'];
    // Since the list is the only thing to show, use the default list template.
    $context['default_list'] = 'holiday_list';
    $context['sub_template'] = 'show_list';
}
    /**
     * The function that handles adding, and deleting holiday data
     */
    public function action_holidays()
    {
        global $scripturl, $txt, $context;
        // Submitting something...
        if (isset($_REQUEST['delete']) && !empty($_REQUEST['holiday'])) {
            checkSession();
            validateToken('admin-mc');
            $to_remove = array_map('intval', array_keys($_REQUEST['holiday']));
            // Now the IDs are "safe" do the delete...
            require_once SUBSDIR . '/Calendar.subs.php';
            removeHolidays($to_remove);
        }
        createToken('admin-mc');
        $listOptions = array('id' => 'holiday_list', 'title' => $txt['current_holidays'], 'items_per_page' => 20, 'base_href' => $scripturl . '?action=admin;area=managecalendar;sa=holidays', 'default_sort_col' => 'name', 'get_items' => array('file' => SUBSDIR . '/Calendar.subs.php', 'function' => 'list_getHolidays'), 'get_count' => array('file' => SUBSDIR . '/Calendar.subs.php', 'function' => 'list_getNumHolidays'), 'no_items_label' => $txt['holidays_no_entries'], 'columns' => array('name' => array('header' => array('value' => $txt['holidays_title']), 'data' => array('sprintf' => array('format' => '<a href="' . $scripturl . '?action=admin;area=managecalendar;sa=editholiday;holiday=%1$d">%2$s</a>', 'params' => array('id_holiday' => false, 'title' => false))), 'sort' => array('default' => 'title', 'reverse' => 'title DESC')), 'date' => array('header' => array('value' => $txt['date']), 'data' => array('function' => create_function('$rowData', '
							global $txt;

							// Recurring every year or just a single year?
							$year = $rowData[\'year\'] == \'0004\' ? sprintf(\'(%1$s)\', $txt[\'every_year\']) : $rowData[\'year\'];

							// Construct the date.
							return sprintf(\'%1$d %2$s %3$s\', $rowData[\'day\'], $txt[\'months\'][(int) $rowData[\'month\']], $year);
						')), 'sort' => array('default' => 'event_date', 'reverse' => 'event_date DESC')), 'check' => array('header' => array('value' => '<input type="checkbox" onclick="invertAll(this, this.form);" class="input_check" />', 'class' => 'centertext'), 'data' => array('sprintf' => array('format' => '<input type="checkbox" name="holiday[%1$d]" class="input_check" />', 'params' => array('id_holiday' => false)), 'class' => 'centertext'))), 'form' => array('href' => $scripturl . '?action=admin;area=managecalendar;sa=holidays', 'token' => 'admin-mc'), 'additional_rows' => array(array('position' => 'below_table_data', 'class' => 'submitbutton', 'value' => '<input type="submit" name="delete" value="' . $txt['quickmod_delete_selected'] . '" class="right_submit" onclick="return confirm(\'' . $txt['holidays_delete_confirm'] . '\');" />
					<a class="linkbutton" href="' . $scripturl . '?action=admin;area=managecalendar;sa=editholiday">' . $txt['holidays_add'] . '</a>')));
        require_once SUBSDIR . '/GenericList.class.php';
        createList($listOptions);
        $context['page_title'] = $txt['manage_holidays'];
    }
Example #4
0
/**
 * Shows an interface to set and test censored words.
 * It uses the censor_vulgar, censor_proper, censorWholeWord, and censorIgnoreCase
 * settings.
 * Requires the admin_forum permission.
 * Accessed from ?action=admin;area=postsettings;sa=censor.
 *
 * @uses the Admin template and the edit_censored sub template.
 */
function SetCensor()
{
    global $txt, $modSettings, $context, $smcFunc, $sourcedir;
    if (!empty($_POST['save_censor'])) {
        // Make sure censoring is something they can do.
        checkSession();
        validateToken('admin-censor');
        $censored_vulgar = array();
        $censored_proper = array();
        // Rip it apart, then split it into two arrays.
        if (isset($_POST['censortext'])) {
            $_POST['censortext'] = explode("\n", strtr($_POST['censortext'], array("\r" => '')));
            foreach ($_POST['censortext'] as $c) {
                list($censored_vulgar[], $censored_proper[]) = array_pad(explode('=', trim($c)), 2, '');
            }
        } elseif (isset($_POST['censor_vulgar'], $_POST['censor_proper'])) {
            if (is_array($_POST['censor_vulgar'])) {
                foreach ($_POST['censor_vulgar'] as $i => $value) {
                    if (trim(strtr($value, '*', ' ')) == '') {
                        unset($_POST['censor_vulgar'][$i], $_POST['censor_proper'][$i]);
                    }
                }
                $censored_vulgar = $_POST['censor_vulgar'];
                $censored_proper = $_POST['censor_proper'];
            } else {
                $censored_vulgar = explode("\n", strtr($_POST['censor_vulgar'], array("\r" => '')));
                $censored_proper = explode("\n", strtr($_POST['censor_proper'], array("\r" => '')));
            }
        }
        // Set the new arrays and settings in the database.
        $updates = array('censor_vulgar' => implode("\n", $censored_vulgar), 'censor_proper' => implode("\n", $censored_proper), 'censorWholeWord' => empty($_POST['censorWholeWord']) ? '0' : '1', 'censorIgnoreCase' => empty($_POST['censorIgnoreCase']) ? '0' : '1');
        call_integration_hook('integrate_save_censors', array(&$updates));
        updateSettings($updates);
    }
    if (isset($_POST['censortest'])) {
        require_once $sourcedir . '/Subs-Post.php';
        $censorText = htmlspecialchars($_POST['censortest'], ENT_QUOTES);
        preparsecode($censorText);
        $context['censor_test'] = strtr(censorText($censorText), array('"' => '&quot;'));
    }
    // Set everything up for the template to do its thang.
    $censor_vulgar = explode("\n", $modSettings['censor_vulgar']);
    $censor_proper = explode("\n", $modSettings['censor_proper']);
    $context['censored_words'] = array();
    for ($i = 0, $n = count($censor_vulgar); $i < $n; $i++) {
        if (empty($censor_vulgar[$i])) {
            continue;
        }
        // Skip it, it's either spaces or stars only.
        if (trim(strtr($censor_vulgar[$i], '*', ' ')) == '') {
            continue;
        }
        $context['censored_words'][htmlspecialchars(trim($censor_vulgar[$i]))] = isset($censor_proper[$i]) ? htmlspecialchars($censor_proper[$i]) : '';
    }
    call_integration_hook('integrate_censors');
    $context['sub_template'] = 'edit_censored';
    $context['page_title'] = $txt['admin_censored_words'];
    createToken('admin-censor');
}
 public function validateInput()
 {
     parent::validateInput();
     if (!isset($this->input['token'])) {
         throw new \Exception("JSON input misses token.");
     }
     if (!($token = validateToken($this->input['token']))) {
         throw new \Exception("Invalid token.");
     }
 }
Example #6
0
 public function run()
 {
     parent::run();
     $this->getInputJson();
     if (!($token = validateToken($this->input['token']))) {
         throw new \Exception("Invalid token.");
     }
     //TODO: delete global somehow
     global $user;
     $user = new \User($token['uid']);
     $user->getFavorites();
     $data = array('username' => $user->username, 'nickname' => $user->nickname, 'name' => $user->name, 'email' => $user->email);
     foreach ($user->favorites as $favorite) {
         $data['favorites'][] = $favorite['tid'];
     }
     $this->return['user'] = $data;
 }
function validatePrivileges($privileges = array(), $no_error = false)
{
    return function () use($privileges, $no_error) {
        try {
            // Inicjalizacja modelu użytkownika
            $user = new \Model\User();
            // Pobranie instancji szkieletu Slim Framework
            $app = \Slim\Slim::getInstance();
            // Pobranie tokenu z pola Authorization nagłówka HTTP i jego walidacja
            $token = validateToken($app->request->headers->get('Authorization'));
            try {
                // Pobranie danych uzytkownika o zadanym tokenie
                $u = $user->getByToken($token, 'administrator');
            } catch (Exception $e) {
                throw new Exception('Użytkownik nie jest zalogowany.', 401);
            }
            // Sprawdzenie wymaganych uprawnień
            if (!in_array($u['privileges'], $privileges)) {
                throw new Exception('Brak uprawnień.', 401);
            }
            // Zapamiętanie danych potrzebnych do logowania jako zmienne globalne
            $GLOBALS['user_id'] = $u['user_id'];
            $GLOBALS['token'] = $token;
            $GLOBALS['privileges'] = $u['privileges'];
            try {
                // Jeśli różnica pomiędzy ostatnią aktywnością, a bierzącym czasem
                // wynosi 60 sekund, to odświeżamy autoryzację
                $diff = abs(strtotime(date('Y-m-d H:i:s')) - strtotime($u['last_auth']));
                if ($diff > 60) {
                    $res = $user->refreshAuth($token);
                }
            } catch (Exception $e) {
            }
        } catch (Exception $e) {
            $GLOBALS['user_id'] = -1;
            $GLOBALS['token'] = '';
            $GLOBALS['privileges'] = 'guest';
            if (!$no_error) {
                jsonError($app, $e, true);
            }
        }
    };
}
 /**
  * Edit a 'it bounced' template.
  *
  * @uses bounce_template sub template
  */
 public function action_modify_bounce_templates()
 {
     global $context, $txt, $user_info;
     require_once SUBSDIR . '/Moderation.subs.php';
     $context['id_template'] = isset($_REQUEST['tid']) ? (int) $_REQUEST['tid'] : 0;
     $context['is_edit'] = (bool) $context['id_template'];
     // Standard template things, you know the drill
     $context['page_title'] = $context['is_edit'] ? $txt['ml_bounce_template_modify'] : $txt['ml_bounce_template_add'];
     $context['sub_template'] = 'bounce_template';
     $context[$context['admin_menu_name']]['current_subsection'] = 'templates';
     // Defaults to show
     $context['template_data'] = array('title' => '', 'body' => $txt['ml_bounce_template_body_default'], 'subject' => $txt['ml_bounce_template_subject_default'], 'personal' => false, 'can_edit_personal' => true);
     // If it's an edit load it.
     if ($context['is_edit']) {
         modLoadTemplate($context['id_template'], 'bnctpl');
     }
     // Wait, we are saving?
     if (isset($_POST['save'])) {
         checkSession('post');
         validateToken('mod-mlt');
         // To check the BBC is good...
         require_once SUBSDIR . '/Post.subs.php';
         // Bit of cleaning!
         $template_body = trim($_POST['template_body']);
         $template_title = trim($_POST['template_title']);
         // Need something in both boxes.
         if (!empty($template_body) && !empty($template_title)) {
             // Safety first.
             $template_title = Util::htmlspecialchars($template_title);
             // Clean up BBC.
             preparsecode($template_body);
             // But put line breaks back!
             $template_body = strtr($template_body, array('<br />' => "\n"));
             // Is this personal?
             $recipient_id = !empty($_POST['make_personal']) ? $user_info['id'] : 0;
             // Updating or adding ?
             if ($context['is_edit']) {
                 // Simple update...
                 modAddUpdateTemplate($recipient_id, $template_title, $template_body, $context['id_template'], true, 'bnctpl');
                 // If it wasn't visible and now is they've effectively added it.
                 if ($context['template_data']['personal'] && !$recipient_id) {
                     logAction('add_bounce_template', array('template' => $template_title));
                 } elseif (!$context['template_data']['personal'] && $recipient_id) {
                     logAction('delete_bounce_template', array('template' => $template_title));
                 } else {
                     logAction('modify_bounce_template', array('template' => $template_title));
                 }
             } else {
                 modAddUpdateTemplate($recipient_id, $template_title, $template_body, $context['id_template'], false, 'bnctpl');
                 logAction('add_bounce_template', array('template' => $template_title));
             }
             // Get out of town...
             redirectexit('action=admin;area=maillist;sa=emailtemplates');
         } else {
             $context['warning_errors'] = array();
             $context['template_data']['title'] = !empty($template_title) ? $template_title : '';
             $context['template_data']['body'] = !empty($template_body) ? $template_body : $txt['ml_bounce_template_body_default'];
             $context['template_data']['personal'] = !empty($recipient_id);
             if (empty($template_title)) {
                 $context['warning_errors'][] = $txt['ml_bounce_template_error_no_title'];
             }
             if (empty($template_body)) {
                 $context['warning_errors'][] = $txt['ml_bounce_template_error_no_body'];
             }
         }
     }
     createToken('mod-mlt');
 }
Example #9
0
 /**
  * Shows the contact form for the user to fill out
  * Needs to be enabled to be used
  */
 public function action_contact()
 {
     global $context, $txt, $user_info, $modSettings;
     // Already inside, no need to use this, just send a PM
     // Disabled, you cannot enter.
     if (!$user_info['is_guest'] || empty($modSettings['enable_contactform']) || $modSettings['enable_contactform'] == 'disabled') {
         redirectexit();
     }
     loadLanguage('Login');
     loadTemplate('Register');
     if (isset($_REQUEST['send'])) {
         checkSession('post');
         validateToken('contact');
         spamProtection('contact');
         // No errors, yet.
         $context['errors'] = array();
         loadLanguage('Errors');
         // Could they get the right send topic verification code?
         require_once SUBSDIR . '/VerificationControls.class.php';
         require_once SUBSDIR . '/Members.subs.php';
         // form validation
         require_once SUBSDIR . '/DataValidator.class.php';
         $validator = new Data_Validator();
         $validator->sanitation_rules(array('emailaddress' => 'trim', 'contactmessage' => 'trim|Util::htmlspecialchars'));
         $validator->validation_rules(array('emailaddress' => 'required|valid_email', 'contactmessage' => 'required'));
         $validator->text_replacements(array('emailaddress' => $txt['error_email'], 'contactmessage' => $txt['error_message']));
         // Any form errors
         if (!$validator->validate($_POST)) {
             $context['errors'] = $validator->validation_errors();
         }
         // How about any verification errors
         $verificationOptions = array('id' => 'contactform');
         $context['require_verification'] = create_control_verification($verificationOptions, true);
         if (is_array($context['require_verification'])) {
             foreach ($context['require_verification'] as $error) {
                 $context['errors'][] = $txt['error_' . $error];
             }
         }
         // No errors, then send the PM to the admins
         if (empty($context['errors'])) {
             $admins = admins();
             if (!empty($admins)) {
                 require_once SUBSDIR . '/PersonalMessage.subs.php';
                 sendpm(array('to' => array_keys($admins), 'bcc' => array()), $txt['contact_subject'], $_REQUEST['contactmessage'], false, array('id' => 0, 'name' => $validator->emailaddress, 'username' => $validator->emailaddress));
             }
             // Send the PM
             redirectexit('action=contact;sa=done');
         } else {
             $context['emailaddress'] = $validator->emailaddress;
             $context['contactmessage'] = $validator->contactmessage;
         }
     }
     if (isset($_GET['sa']) && $_GET['sa'] == 'done') {
         $context['sub_template'] = 'contact_form_done';
     } else {
         $context['sub_template'] = 'contact_form';
         $context['page_title'] = $txt['admin_contact_form'];
         require_once SUBSDIR . '/VerificationControls.class.php';
         $verificationOptions = array('id' => 'contactform');
         $context['require_verification'] = create_control_verification($verificationOptions);
         $context['visual_verification_id'] = $verificationOptions['id'];
     }
     createToken('contact');
 }
Example #10
0
function list_integration_hooks()
{
    global $sourcedir, $scripturl, $context, $txt, $modSettings, $settings;
    $context['filter'] = '';
    $currentHooks = get_integration_hooks();
    if (isset($_GET['filter']) && in_array($_GET['filter'], array_keys($currentHooks))) {
        $context['filter'] = ';filter=' . $_GET['filter'];
    }
    if (!empty($modSettings['handlinghooks_enabled'])) {
        if (!empty($_REQUEST['do']) && isset($_REQUEST['hook']) && isset($_REQUEST['function'])) {
            checkSession('request');
            validateToken('admin-hook', 'request');
            if ($_REQUEST['do'] == 'remove') {
                remove_integration_function($_REQUEST['hook'], urldecode($_REQUEST['function']));
            } else {
                if ($_REQUEST['do'] == 'disable') {
                    // It's a hack I know...but I'm way too lazy!!!
                    $function_remove = $_REQUEST['function'];
                    $function_add = $_REQUEST['function'] . ']';
                } else {
                    $function_remove = $_REQUEST['function'] . ']';
                    $function_add = $_REQUEST['function'];
                }
                $file = !empty($_REQUEST['includedfile']) ? urldecode($_REQUEST['includedfile']) : '';
                remove_integration_function($_REQUEST['hook'], $function_remove, $file);
                add_integration_function($_REQUEST['hook'], $function_add, $file);
                redirectexit('action=admin;area=modsettings;sa=hooks' . $context['filter']);
            }
        }
    }
    $list_options = array('id' => 'list_integration_hooks', 'title' => $txt['hooks_title_list'], 'items_per_page' => 20, 'base_href' => $scripturl . '?action=admin;area=modsettings;sa=hooks' . $context['filter'] . ';' . $context['session_var'] . '=' . $context['session_id'], 'default_sort_col' => 'hook_name', 'get_items' => array('function' => 'get_integration_hooks_data'), 'get_count' => array('function' => 'get_integration_hooks_count'), 'no_items_label' => $txt['hooks_no_hooks'], 'columns' => array('hook_name' => array('header' => array('value' => $txt['hooks_field_hook_name']), 'data' => array('db' => 'hook_name'), 'sort' => array('default' => 'hook_name', 'reverse' => 'hook_name DESC')), 'function_name' => array('header' => array('value' => $txt['hooks_field_function_name']), 'data' => array('function' => create_function('$data', '
						global $txt;

						if (!empty($data[\'included_file\']))
							return $txt[\'hooks_field_function\'] . \': \' . $data[\'real_function\'] . \'<br />\' . $txt[\'hooks_field_included_file\'] . \': \' . $data[\'included_file\'];
						else
							return $data[\'real_function\'];
					')), 'sort' => array('default' => 'function_name', 'reverse' => 'function_name DESC')), 'file_name' => array('header' => array('value' => $txt['hooks_field_file_name']), 'data' => array('db' => 'file_name'), 'sort' => array('default' => 'file_name', 'reverse' => 'file_name DESC')), 'status' => array('header' => array('value' => $txt['hooks_field_hook_exists'], 'style' => 'width:3%'), 'data' => array('function' => create_function('$data', '
						global $txt, $settings, $scripturl, $context;

						$change_status = array(\'before\' => \'\', \'after\' => \'\');
						if ($data[\'can_be_disabled\'] && $data[\'status\'] != \'deny\')
						{
							$change_status[\'before\'] = \'<a href="\' . $scripturl . \'?action=admin;area=modsettings;sa=hooks;do=\' . ($data[\'enabled\'] ? \'disable\' : \'enable\') . \';hook=\' . $data[\'hook_name\'] . \';function=\' . $data[\'real_function\'] . (!empty($data[\'included_file\']) ? \';includedfile=\' . urlencode($data[\'included_file\']) : \'\') . $context[\'filter\'] . \';\' . $context[\'admin-hook_token_var\'] . \'=\' . $context[\'admin-hook_token\'] . \';\' . $context[\'session_var\'] . \'=\' . $context[\'session_id\'] . \'" onclick="return confirm(\' . javaScriptEscape($txt[\'quickmod_confirm\']) . \');">\';
							$change_status[\'after\'] = \'</a>\';
						}
						return $change_status[\'before\'] . \'<img src="\' . $settings[\'images_url\'] . \'/admin/post_moderation_\' . $data[\'status\'] . \'.png" alt="\' . $data[\'img_text\'] . \'" title="\' . $data[\'img_text\'] . \'" />\' . $change_status[\'after\'];
					'), 'class' => 'centertext'), 'sort' => array('default' => 'status', 'reverse' => 'status DESC'))), 'additional_rows' => array(array('position' => 'after_title', 'value' => $txt['hooks_disable_instructions'] . '<br />
					' . $txt['hooks_disable_legend'] . ':
									<ul style="list-style: none;">
					<li><img src="' . $settings['images_url'] . '/admin/post_moderation_allow.png" alt="' . $txt['hooks_active'] . '" title="' . $txt['hooks_active'] . '" /> ' . $txt['hooks_disable_legend_exists'] . '</li>
					<li><img src="' . $settings['images_url'] . '/admin/post_moderation_moderate.png" alt="' . $txt['hooks_disabled'] . '" title="' . $txt['hooks_disabled'] . '" /> ' . $txt['hooks_disable_legend_disabled'] . '</li>
					<li><img src="' . $settings['images_url'] . '/admin/post_moderation_deny.png" alt="' . $txt['hooks_missing'] . '" title="' . $txt['hooks_missing'] . '" /> ' . $txt['hooks_disable_legend_missing'] . '</li>
				</ul>')));
    if (!empty($modSettings['handlinghooks_enabled'])) {
        createToken('admin-hook', 'request');
        $list_options['columns']['remove'] = array('header' => array('value' => $txt['hooks_button_remove'], 'style' => 'width:3%'), 'data' => array('function' => create_function('$data', '
					global $txt, $settings, $scripturl, $context;

					if (!$data[\'hook_exists\'])
						return \'
						<a href="\' . $scripturl . \'?action=admin;area=modsettings;sa=hooks;do=remove;hook=\' . $data[\'hook_name\'] . \';function=\' . urlencode($data[\'function_name\']) . $context[\'filter\'] . \';\' . $context[\'admin-hook_token_var\'] . \'=\' . $context[\'admin-hook_token\'] . \';\' . $context[\'session_var\'] . \'=\' . $context[\'session_id\'] . \'" onclick="return confirm(\' . javaScriptEscape($txt[\'quickmod_confirm\']) . \');">
							<img src="\' . $settings[\'images_url\'] . \'/icons/quick_remove.png" alt="\' . $txt[\'hooks_button_remove\'] . \'" title="\' . $txt[\'hooks_button_remove\'] . \'" />
						</a>\';
				'), 'class' => 'centertext'));
        $list_options['form'] = array('href' => $scripturl . '?action=admin;area=modsettings;sa=hooks' . $context['filter'] . ';' . $context['session_var'] . '=' . $context['session_id'], 'name' => 'list_integration_hooks');
    }
    require_once $sourcedir . '/Subs-List.php';
    createList($list_options);
    $context['page_title'] = $txt['hooks_title_list'];
    $context['sub_template'] = 'show_list';
    $context['default_list'] = 'list_integration_hooks';
}
Example #11
0
function checkToken()
{
    if (isset($_POST["reg-borrower"])) {
        return true;
        // capcha support already there
        //return validateToken('reg-borrower');
    } else {
        if (isset($_POST["reg-lender"])) {
            return true;
            // capcha support already there
            //return validateToken('reg-lender');
        } else {
            if (isset($_POST['reg-partner'])) {
                return true;
                // capcha support already there
                //return validateToken('reg-partner');
            } else {
                if (isset($_POST["userlogin"])) {
                    return true;
                    //return validateToken('userlogin');
                } else {
                    if (isset($_POST['loanapplication'])) {
                        return validateToken('loanapplication');
                    } else {
                        if (isset($_POST['editloanapplication'])) {
                            return validateToken('editloanapplication');
                        } else {
                            if (isset($_POST['exrate'])) {
                                return validateToken('exrate');
                            } else {
                                if (isset($_POST['amt_entered'])) {
                                    return validateToken('amt_entered');
                                } else {
                                    if (isset($_POST['confirmApplication'])) {
                                        return validateToken('confirmApplication');
                                    } else {
                                        if (isset($_POST['lenderbid'])) {
                                            return validateToken('lenderbid');
                                        } else {
                                            if (isset($_POST['lenderbidUp'])) {
                                                return validateToken('lenderbidUp');
                                            } else {
                                                if (isset($_POST['minfundamount'])) {
                                                    return validateToken('minfundamount');
                                                } else {
                                                    if (isset($_POST['activatePartner'])) {
                                                        return validateToken('activatePartner');
                                                    } else {
                                                        if (isset($_POST['deactivatePartner'])) {
                                                            return validateToken('deactivatePartner');
                                                        } else {
                                                            if (isset($_POST['activateLender'])) {
                                                                return validateToken('activateLender');
                                                            } else {
                                                                if (isset($_POST['deactivateLender'])) {
                                                                    return validateToken('deactivateLender');
                                                                } else {
                                                                    if (isset($_POST['deactivateBorrower'])) {
                                                                        return validateToken('deactivateBorrower');
                                                                    } else {
                                                                        if (isset($_POST['deleteBorrower'])) {
                                                                            return validateToken('deleteBorrower');
                                                                        } else {
                                                                            if (isset($_POST['deletePartner'])) {
                                                                                return validateToken('deletePartner');
                                                                            } else {
                                                                                if (isset($_POST['deleteLender'])) {
                                                                                    return validateToken('deleteLender');
                                                                                } else {
                                                                                    if (isset($_POST['makeLoanExpire'])) {
                                                                                        return validateToken('makeLoanExpire');
                                                                                    } else {
                                                                                        if (isset($_POST['makeLoanActive'])) {
                                                                                            return validateToken('makeLoanActive');
                                                                                        } else {
                                                                                            if (isset($_POST['sendbulkmails'])) {
                                                                                                return validateToken('sendbulkmails');
                                                                                            } else {
                                                                                                if (isset($_POST['addpaymenttolender'])) {
                                                                                                    return validateToken('addpaymenttolender');
                                                                                                } else {
                                                                                                    if (isset($_POST['adddonationtolender'])) {
                                                                                                        return validateToken('adddonationtolender');
                                                                                                    } else {
                                                                                                        if (isset($_POST['changePassword'])) {
                                                                                                            return validateToken('changePassword');
                                                                                                        } else {
                                                                                                            if (isset($_POST['forgiveShare'])) {
                                                                                                                return validateToken('forgiveShare');
                                                                                                            } else {
                                                                                                                if (isset($_POST['assignedPartner'])) {
                                                                                                                    return true;
                                                                                                                } else {
                                                                                                                    if (isset($_POST['referral'])) {
                                                                                                                        return validateToken('referral');
                                                                                                                    } else {
                                                                                                                        if (isset($_POST['add-repayment_instruction'])) {
                                                                                                                            return validateToken('add-repayment_instruction');
                                                                                                                        }
                                                                                                                    }
                                                                                                                }
                                                                                                            }
                                                                                                        }
                                                                                                    }
                                                                                                }
                                                                                            }
                                                                                        }
                                                                                    }
                                                                                }
                                                                            }
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    if (isset($_POST["editborrower"])) {
        return validateToken('editborrower');
    } else {
        if (isset($_POST["editlender"])) {
            return validateToken('editlender');
        } else {
            if (isset($_POST['editpartner'])) {
                return validateToken('editpartner');
            } else {
                if (isset($_POST['activateBorrower'])) {
                    return validateToken('activateBorrower');
                } else {
                    if (isset($_POST['acceptbids'])) {
                        return validateToken('acceptbids');
                    } else {
                        if (isset($_POST['Payment'])) {
                            return validateToken('Payment');
                        } else {
                            if (isset($_POST['repaymentfeedback'])) {
                                return validateToken('repaymentfeedback');
                            } else {
                                if (isset($_POST['makeLoanDefault'])) {
                                    return validateToken('makeLoanDefault');
                                } else {
                                    if (isset($_POST['makeLoanUndoDefault'])) {
                                        return validateToken('makeLoanUndoDefault');
                                    } else {
                                        if (isset($_POST['cancelloan'])) {
                                            return validateToken('cancelloan');
                                        } else {
                                            if (isset($_POST['forgetpassword'])) {
                                                return validateToken('forgetpassword');
                                            } else {
                                                if (isset($_POST['withdraw'])) {
                                                    return validateToken('withdraw');
                                                } else {
                                                    if (isset($_POST['paywithdraw'])) {
                                                        return validateToken('paywithdraw');
                                                    } else {
                                                        if (isset($_POST['PaySimplewithdraw'])) {
                                                            return validateToken('PaySimplewithdraw');
                                                        } else {
                                                            if (isset($_POST['paysimplewithdrawadmin'])) {
                                                                return validateToken('paysimplewithdrawadmin');
                                                            } else {
                                                                if (isset($_POST['Otherwithdraw'])) {
                                                                    return validateToken('Otherwithdraw');
                                                                } else {
                                                                    if (isset($_POST['payotherwithdrawadmin'])) {
                                                                        return validateToken('payotherwithdrawadmin');
                                                                    } else {
                                                                        if (isset($_POST['emailregister'])) {
                                                                            return validateToken('emailregister');
                                                                        } else {
                                                                            if (isset($_POST['emailsent'])) {
                                                                                return validateToken('emailsent');
                                                                            } else {
                                                                                if (isset($_POST['portfolioreport'])) {
                                                                                    return validateToken('portfolioreport');
                                                                                } else {
                                                                                    if (isset($_POST['portfolioreportnew'])) {
                                                                                        return validateToken('portfolioreportnew');
                                                                                    } else {
                                                                                        if (isset($_POST['transactionhistory'])) {
                                                                                            return validateToken('transactionhistory');
                                                                                        } else {
                                                                                            if (isset($_POST['tr_hidden'])) {
                                                                                                return validateToken('tr_hidden');
                                                                                            } else {
                                                                                                if (isset($_POST['translatorhidden'])) {
                                                                                                    return validateToken('translatorhidden');
                                                                                                } else {
                                                                                                    if (isset($_POST['translatorlang'])) {
                                                                                                        return validateToken('translatorlang');
                                                                                                    } else {
                                                                                                        if (isset($_POST['giftcardorder'])) {
                                                                                                            return validateToken('giftcardorder');
                                                                                                        } else {
                                                                                                            if (isset($_POST['redeemCard'])) {
                                                                                                                return validateToken('redeemCard');
                                                                                                            } else {
                                                                                                                if (isset($_POST['donate_card'])) {
                                                                                                                    return validateToken('donate_card');
                                                                                                                } else {
                                                                                                                    if (isset($_POST['promotLoan'])) {
                                                                                                                        return validateToken('promotLoan');
                                                                                                                    } else {
                                                                                                                        if (isset($_POST['invite_frnds'])) {
                                                                                                                            return validateToken('invite_frnds');
                                                                                                                        } else {
                                                                                                                            if (isset($_POST['get_contacts'])) {
                                                                                                                                return validateToken('get_contacts');
                                                                                                                            } else {
                                                                                                                                if (isset($_POST['get_loans'])) {
                                                                                                                                    return validateToken('get_loans');
                                                                                                                                } else {
                                                                                                                                    if (isset($_POST['repay_report'])) {
                                                                                                                                        return validateToken('repay_report');
                                                                                                                                    } else {
                                                                                                                                        if (isset($_POST['declinedBorrower'])) {
                                                                                                                                            return validateToken('declinedBorrower');
                                                                                                                                        } else {
                                                                                                                                            if (isset($_POST['reScheduleLoan'])) {
                                                                                                                                                return validateToken('reScheduleLoan');
                                                                                                                                            } else {
                                                                                                                                                if (isset($_POST['update-repayment_instruction'])) {
                                                                                                                                                    return validateToken('update-repayment_instruction');
                                                                                                                                                } else {
                                                                                                                                                    if (isset($_POST['del-repayment_instruction'])) {
                                                                                                                                                        return validateToken('del-repayment_instruction');
                                                                                                                                                    } else {
                                                                                                                                                        if (isset($_POST['del-repayment_instruction'])) {
                                                                                                                                                            return validateToken('del-repayment_instruction');
                                                                                                                                                        } else {
                                                                                                                                                            if (isset($_POST['sendShareEmail'])) {
                                                                                                                                                                return validateToken('sendShareEmail');
                                                                                                                                                            } else {
                                                                                                                                                                if (isset($_POST['campaign'])) {
                                                                                                                                                                    return validateToken('campaign');
                                                                                                                                                                } else {
                                                                                                                                                                    if (isset($_POST['deactivateAccount'])) {
                                                                                                                                                                        return validateToken('deactivateAccount');
                                                                                                                                                                    } else {
                                                                                                                                                                        if (isset($_POST['emailedTo'])) {
                                                                                                                                                                            return true;
                                                                                                                                                                        } else {
                                                                                                                                                                            if (isset($_POST['automaticLending'])) {
                                                                                                                                                                                return validateToken('automaticLending');
                                                                                                                                                                            } else {
                                                                                                                                                                                if (isset($_POST['upload_funds'])) {
                                                                                                                                                                                    return validateToken('upload_funds');
                                                                                                                                                                                } else {
                                                                                                                                                                                    if (isset($_POST['lender_invite'])) {
                                                                                                                                                                                        return validateToken('lender_invite');
                                                                                                                                                                                    } else {
                                                                                                                                                                                        return true;
                                                                                                                                                                                    }
                                                                                                                                                                                }
                                                                                                                                                                            }
                                                                                                                                                                        }
                                                                                                                                                                    }
                                                                                                                                                                }
                                                                                                                                                            }
                                                                                                                                                        }
                                                                                                                                                    }
                                                                                                                                                }
                                                                                                                                            }
                                                                                                                                        }
                                                                                                                                    }
                                                                                                                                }
                                                                                                                            }
                                                                                                                        }
                                                                                                                    }
                                                                                                                }
                                                                                                            }
                                                                                                        }
                                                                                                    }
                                                                                                }
                                                                                            }
                                                                                        }
                                                                                    }
                                                                                }
                                                                            }
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
/**
 * Show the log of all tasks that have taken place.
 *
 * @uses ManageScheduledTasks language file
 */
function TaskLog()
{
    global $scripturl, $context, $txt, $smcFunc, $sourcedir;
    // Lets load the language just incase we are outside the Scheduled area.
    loadLanguage('ManageScheduledTasks');
    // Empty the log?
    if (!empty($_POST['removeAll'])) {
        checkSession();
        validateToken('admin-tl');
        $smcFunc['db_query']('truncate_table', '
			TRUNCATE {db_prefix}log_scheduled_tasks', array());
    }
    // Setup the list.
    $listOptions = array('id' => 'task_log', 'items_per_page' => 30, 'title' => $txt['scheduled_log'], 'no_items_label' => $txt['scheduled_log_empty'], 'base_href' => $context['admin_area'] == 'scheduledtasks' ? $scripturl . '?action=admin;area=scheduledtasks;sa=tasklog' : $scripturl . '?action=admin;area=logs;sa=tasklog', 'default_sort_col' => 'date', 'get_items' => array('function' => 'list_getTaskLogEntries'), 'get_count' => array('function' => 'list_getNumTaskLogEntries'), 'columns' => array('name' => array('header' => array('value' => $txt['scheduled_tasks_name']), 'data' => array('db' => 'name')), 'date' => array('header' => array('value' => $txt['scheduled_log_time_run']), 'data' => array('function' => create_function('$rowData', '
						return timeformat($rowData[\'time_run\'], true);
					')), 'sort' => array('default' => 'lst.id_log DESC', 'reverse' => 'lst.id_log')), 'time_taken' => array('header' => array('value' => $txt['scheduled_log_time_taken']), 'data' => array('sprintf' => array('format' => $txt['scheduled_log_time_taken_seconds'], 'params' => array('time_taken' => false))), 'sort' => array('default' => 'lst.time_taken', 'reverse' => 'lst.time_taken DESC'))), 'form' => array('href' => $context['admin_area'] == 'scheduledtasks' ? $scripturl . '?action=admin;area=scheduledtasks;sa=tasklog' : $scripturl . '?action=admin;area=logs;sa=tasklog', 'token' => 'admin-tl'), 'additional_rows' => array(array('position' => 'below_table_data', 'value' => '
					<input type="submit" name="removeAll" value="' . $txt['scheduled_log_empty_log'] . '" onclick="return confirm(\'' . $txt['scheduled_log_empty_log_confirm'] . '\');" class="button_submit" />', 'style' => 'text-align: right;'), array('position' => 'after_title', 'value' => $txt['scheduled_tasks_time_offset'], 'class' => 'windowbg2')));
    createToken('admin-tl');
    require_once $sourcedir . '/Subs-List.php';
    createList($listOptions);
    $context['sub_template'] = 'show_list';
    $context['default_list'] = 'task_log';
    // Make it all look tify.
    $context[$context['admin_menu_name']]['current_subsection'] = 'tasklog';
    $context['page_title'] = $txt['scheduled_log'];
}
    /**
     * Show the log of all tasks that have taken place.
     *
     * @uses ManageScheduledTasks language file
     */
    public function action_log()
    {
        global $scripturl, $context, $txt;
        require_once SUBSDIR . '/ScheduledTasks.subs.php';
        // Lets load the language just in case we are outside the Scheduled area.
        loadLanguage('ManageScheduledTasks');
        // Empty the log?
        if (!empty($_POST['removeAll'])) {
            checkSession();
            validateToken('admin-tl');
            emptyTaskLog();
        }
        // Setup the list.
        $listOptions = array('id' => 'task_log', 'items_per_page' => 30, 'title' => $txt['scheduled_log'], 'no_items_label' => $txt['scheduled_log_empty'], 'base_href' => $context['admin_area'] == 'scheduledtasks' ? $scripturl . '?action=admin;area=scheduledtasks;sa=tasklog' : $scripturl . '?action=admin;area=logs;sa=tasklog', 'default_sort_col' => 'date', 'get_items' => array('function' => array($this, 'list_getTaskLogEntries')), 'get_count' => array('function' => array($this, 'list_getNumTaskLogEntries')), 'columns' => array('name' => array('header' => array('value' => $txt['scheduled_tasks_name']), 'data' => array('db' => 'name')), 'date' => array('header' => array('value' => $txt['scheduled_log_time_run']), 'data' => array('function' => create_function('$rowData', '
							return standardTime($rowData[\'time_run\'], true);
						')), 'sort' => array('default' => 'lst.id_log DESC', 'reverse' => 'lst.id_log')), 'time_taken' => array('header' => array('value' => $txt['scheduled_log_time_taken']), 'data' => array('sprintf' => array('format' => $txt['scheduled_log_time_taken_seconds'], 'params' => array('time_taken' => false))), 'sort' => array('default' => 'lst.time_taken', 'reverse' => 'lst.time_taken DESC')), 'task_completed' => array('header' => array('value' => $txt['scheduled_log_completed']), 'data' => array('function' => create_function('$rowData', '
							global $settings, $txt;

							return \'<img src="\' . $settings[\'images_url\'] . \'/admin/complete_\' . ($rowData[\'task_completed\'] ? \'success\' : \'fail\') . \'.png" alt="\' . sprintf($txt[$rowData[\'task_completed\'] ? \'maintain_done\' : \'maintain_fail\'], $rowData[\'name\']) . \'" />\';
						')))), 'form' => array('href' => $context['admin_area'] == 'scheduledtasks' ? $scripturl . '?action=admin;area=scheduledtasks;sa=tasklog' : $scripturl . '?action=admin;area=logs;sa=tasklog', 'token' => 'admin-tl'), 'additional_rows' => array(array('position' => 'below_table_data', 'value' => '
						<input type="submit" name="removeAll" value="' . $txt['scheduled_log_empty_log'] . '" onclick="return confirm(\'' . $txt['scheduled_log_empty_log_confirm'] . '\');" class="right_submit" />'), array('position' => 'after_title', 'value' => $txt['scheduled_tasks_time_offset'], 'class' => 'windowbg2')));
        createToken('admin-tl');
        require_once SUBSDIR . '/GenericList.class.php';
        createList($listOptions);
        $context['sub_template'] = 'show_list';
        $context['default_list'] = 'task_log';
        // Make it all look tify.
        $context[$context['admin_menu_name']]['current_subsection'] = 'tasklog';
        $context['page_title'] = $txt['scheduled_log'];
    }
Example #14
0
/**
 * Editing a membergroup.
 * Screen to edit a specific membergroup.
 * Called by ?action=admin;area=membergroups;sa=edit;group=x.
 * It requires the manage_membergroups permission.
 * Also handles the delete button of the edit form.
 * Redirects to ?action=admin;area=membergroups.
 *
 * @uses the edit_group sub template of ManageMembergroups.
 */
function EditMembergroup()
{
    global $context, $txt, $sourcedir, $modSettings, $smcFunc;
    $_REQUEST['group'] = isset($_REQUEST['group']) && $_REQUEST['group'] > 0 ? (int) $_REQUEST['group'] : 0;
    if (!empty($modSettings['deny_boards_access'])) {
        loadLanguage('ManagePermissions');
    }
    // Make sure this group is editable.
    if (!empty($_REQUEST['group'])) {
        $request = $smcFunc['db_query']('', '
			SELECT id_group
			FROM {db_prefix}membergroups
			WHERE id_group = {int:current_group}' . (allowedTo('admin_forum') ? '' : '
				AND group_type != {int:is_protected}') . '
			LIMIT {int:limit}', array('current_group' => $_REQUEST['group'], 'is_protected' => 1, 'limit' => 1));
        list($_REQUEST['group']) = $smcFunc['db_fetch_row']($request);
        $smcFunc['db_free_result']($request);
    }
    // Now, do we have a valid id?
    if (empty($_REQUEST['group'])) {
        fatal_lang_error('membergroup_does_not_exist', false);
    }
    // The delete this membergroup button was pressed.
    if (isset($_POST['delete'])) {
        checkSession();
        validateToken('admin-mmg');
        require_once $sourcedir . '/Subs-Membergroups.php';
        deleteMembergroups($_REQUEST['group']);
        redirectexit('action=admin;area=membergroups;');
    } elseif (isset($_POST['save'])) {
        // Validate the session.
        checkSession();
        validateToken('admin-mmg');
        // Can they really inherit from this group?
        if (isset($_POST['group_inherit']) && $_POST['group_inherit'] != -2 && !allowedTo('admin_forum')) {
            $request = $smcFunc['db_query']('', '
				SELECT group_type
				FROM {db_prefix}membergroups
				WHERE id_group = {int:inherit_from}
				LIMIT {int:limit}', array('inherit_from' => $_POST['group_inherit'], 'limit' => 1));
            list($inherit_type) = $smcFunc['db_fetch_row']($request);
            $smcFunc['db_free_result']($request);
        }
        // Set variables to their proper value.
        $_POST['max_messages'] = isset($_POST['max_messages']) ? (int) $_POST['max_messages'] : 0;
        $_POST['min_posts'] = isset($_POST['min_posts']) && isset($_POST['group_type']) && $_POST['group_type'] == -1 && $_REQUEST['group'] > 3 ? abs($_POST['min_posts']) : ($_REQUEST['group'] == 4 ? 0 : -1);
        $_POST['icons'] = empty($_POST['icon_count']) || $_POST['icon_count'] < 0 ? '' : min((int) $_POST['icon_count'], 99) . '#' . $_POST['icon_image'];
        $_POST['group_desc'] = isset($_POST['group_desc']) && ($_REQUEST['group'] == 1 || isset($_POST['group_type']) && $_POST['group_type'] != -1) ? trim($_POST['group_desc']) : '';
        $_POST['group_type'] = !isset($_POST['group_type']) || $_POST['group_type'] < 0 || $_POST['group_type'] > 3 || $_POST['group_type'] == 1 && !allowedTo('admin_forum') ? 0 : (int) $_POST['group_type'];
        $_POST['group_hidden'] = empty($_POST['group_hidden']) || $_POST['min_posts'] != -1 || $_REQUEST['group'] == 3 ? 0 : (int) $_POST['group_hidden'];
        $_POST['group_inherit'] = $_REQUEST['group'] > 1 && $_REQUEST['group'] != 3 && (empty($inherit_type) || $inherit_type != 1) ? (int) $_POST['group_inherit'] : -2;
        //@todo Don't set online_color for the Moderators group?
        // Do the update of the membergroup settings.
        $smcFunc['db_query']('', '
			UPDATE {db_prefix}membergroups
			SET group_name = {string:group_name}, online_color = {string:online_color},
				max_messages = {int:max_messages}, min_posts = {int:min_posts}, icons = {string:icons},
				description = {string:group_desc}, group_type = {int:group_type}, hidden = {int:group_hidden},
				id_parent = {int:group_inherit}
			WHERE id_group = {int:current_group}', array('max_messages' => $_POST['max_messages'], 'min_posts' => $_POST['min_posts'], 'group_type' => $_POST['group_type'], 'group_hidden' => $_POST['group_hidden'], 'group_inherit' => $_POST['group_inherit'], 'current_group' => (int) $_REQUEST['group'], 'group_name' => $smcFunc['htmlspecialchars']($_POST['group_name']), 'online_color' => $_POST['online_color'], 'icons' => $_POST['icons'], 'group_desc' => $_POST['group_desc']));
        call_integration_hook('integrate_save_membergroup', array((int) $_REQUEST['group']));
        // Time to update the boards this membergroup has access to.
        if ($_REQUEST['group'] == 2 || $_REQUEST['group'] > 3) {
            $accesses = empty($_POST['boardaccess']) || !is_array($_POST['boardaccess']) ? array() : $_POST['boardaccess'];
            $changed_boards['allow'] = array();
            $changed_boards['deny'] = array();
            $changed_boards['ignore'] = array();
            foreach ($accesses as $group_id => $action) {
                $changed_boards[$action][] = (int) $group_id;
            }
            foreach (array('allow', 'deny') as $board_action) {
                // Find all board this group is in, but shouldn't be in.
                $request = $smcFunc['db_query']('', '
					SELECT id_board, {raw:column}
					FROM {db_prefix}boards
					WHERE FIND_IN_SET({string:current_group}, {raw:column}) != 0' . (empty($changed_boards[$board_action]) ? '' : '
						AND id_board NOT IN ({array_int:board_access_list})'), array('current_group' => (int) $_REQUEST['group'], 'board_access_list' => $changed_boards[$board_action], 'column' => $board_action == 'allow' ? 'member_groups' : 'deny_member_groups'));
                while ($row = $smcFunc['db_fetch_assoc']($request)) {
                    $smcFunc['db_query']('', '
						UPDATE {db_prefix}boards
						SET {raw:column} = {string:member_group_access}
						WHERE id_board = {int:current_board}', array('current_board' => $row['id_board'], 'member_group_access' => implode(',', array_diff(explode(',', $row['member_groups']), array($_REQUEST['group']))), 'column' => $board_action == 'allow' ? 'member_groups' : 'deny_member_groups'));
                }
                $smcFunc['db_free_result']($request);
                // Add the membergroup to all boards that hadn't been set yet.
                if (!empty($changed_boards[$board_action])) {
                    $smcFunc['db_query']('', '
						UPDATE {db_prefix}boards
						SET {raw:column} = CASE WHEN {raw:column} = {string:blank_string} THEN {string:group_id_string} ELSE CONCAT({raw:column}, {string:comma_group}) END
						WHERE id_board IN ({array_int:board_list})
							AND FIND_IN_SET({int:current_group}, {raw:column}) = 0', array('board_list' => $changed_boards[$board_action], 'blank_string' => '', 'current_group' => (int) $_REQUEST['group'], 'group_id_string' => (string) (int) $_REQUEST['group'], 'comma_group' => ',' . $_REQUEST['group'], 'column' => $board_action == 'allow' ? 'member_groups' : 'deny_member_groups'));
                }
            }
        }
        // Remove everyone from this group!
        if ($_POST['min_posts'] != -1) {
            $smcFunc['db_query']('', '
				UPDATE {db_prefix}members
				SET id_group = {int:regular_member}
				WHERE id_group = {int:current_group}', array('regular_member' => 0, 'current_group' => (int) $_REQUEST['group']));
            $request = $smcFunc['db_query']('', '
				SELECT id_member, additional_groups
				FROM {db_prefix}members
				WHERE FIND_IN_SET({string:current_group}, additional_groups) != 0', array('current_group' => (int) $_REQUEST['group']));
            $updates = array();
            while ($row = $smcFunc['db_fetch_assoc']($request)) {
                $updates[$row['additional_groups']][] = $row['id_member'];
            }
            $smcFunc['db_free_result']($request);
            foreach ($updates as $additional_groups => $memberArray) {
                updateMemberData($memberArray, array('additional_groups' => implode(',', array_diff(explode(',', $additional_groups), array((int) $_REQUEST['group'])))));
            }
        } elseif ($_REQUEST['group'] != 3) {
            // Making it a hidden group? If so remove everyone with it as primary group (Actually, just make them additional).
            if ($_POST['group_hidden'] == 2) {
                $request = $smcFunc['db_query']('', '
					SELECT id_member, additional_groups
					FROM {db_prefix}members
					WHERE id_group = {int:current_group}
						AND FIND_IN_SET({int:current_group}, additional_groups) = 0', array('current_group' => (int) $_REQUEST['group']));
                $updates = array();
                while ($row = $smcFunc['db_fetch_assoc']($request)) {
                    $updates[$row['additional_groups']][] = $row['id_member'];
                }
                $smcFunc['db_free_result']($request);
                foreach ($updates as $additional_groups => $memberArray) {
                    updateMemberData($memberArray, array('additional_groups' => implode(',', array_merge(explode(',', $additional_groups), array((int) $_REQUEST['group'])))));
                }
                $smcFunc['db_query']('', '
					UPDATE {db_prefix}members
					SET id_group = {int:regular_member}
					WHERE id_group = {int:current_group}', array('regular_member' => 0, 'current_group' => $_REQUEST['group']));
            }
            // Either way, let's check our "show group membership" setting is correct.
            $request = $smcFunc['db_query']('', '
				SELECT COUNT(*)
				FROM {db_prefix}membergroups
				WHERE group_type > {int:non_joinable}', array('non_joinable' => 1));
            list($have_joinable) = $smcFunc['db_fetch_row']($request);
            $smcFunc['db_free_result']($request);
            // Do we need to update the setting?
            if (empty($modSettings['show_group_membership']) && $have_joinable || !empty($modSettings['show_group_membership']) && !$have_joinable) {
                updateSettings(array('show_group_membership' => $have_joinable ? 1 : 0));
            }
        }
        // Do we need to set inherited permissions?
        if ($_POST['group_inherit'] != -2 && $_POST['group_inherit'] != $_POST['old_inherit']) {
            require_once $sourcedir . '/ManagePermissions.php';
            updateChildPermissions($_POST['group_inherit']);
        }
        // Finally, moderators!
        $moderator_string = isset($_POST['group_moderators']) ? trim($_POST['group_moderators']) : '';
        $smcFunc['db_query']('', '
			DELETE FROM {db_prefix}group_moderators
			WHERE id_group = {int:current_group}', array('current_group' => $_REQUEST['group']));
        if ((!empty($moderator_string) || !empty($_POST['moderator_list'])) && $_POST['min_posts'] == -1 && $_REQUEST['group'] != 3) {
            // Get all the usernames from the string
            if (!empty($moderator_string)) {
                $moderator_string = strtr(preg_replace('~&amp;#(\\d{4,5}|[2-9]\\d{2,4}|1[2-9]\\d);~', '&#$1;', htmlspecialchars($moderator_string), ENT_QUOTES), array('&quot;' => '"'));
                preg_match_all('~"([^"]+)"~', $moderator_string, $matches);
                $moderators = array_merge($matches[1], explode(',', preg_replace('~"[^"]+"~', '', $moderator_string)));
                for ($k = 0, $n = count($moderators); $k < $n; $k++) {
                    $moderators[$k] = trim($moderators[$k]);
                    if (strlen($moderators[$k]) == 0) {
                        unset($moderators[$k]);
                    }
                }
                // Find all the id_member's for the member_name's in the list.
                $group_moderators = array();
                if (!empty($moderators)) {
                    $request = $smcFunc['db_query']('', '
						SELECT id_member
						FROM {db_prefix}members
						WHERE member_name IN ({array_string:moderators}) OR real_name IN ({array_string:moderators})
						LIMIT ' . count($moderators), array('moderators' => $moderators));
                    while ($row = $smcFunc['db_fetch_assoc']($request)) {
                        $group_moderators[] = $row['id_member'];
                    }
                    $smcFunc['db_free_result']($request);
                }
            } else {
                $moderators = array();
                foreach ($_POST['moderator_list'] as $moderator) {
                    $moderators[] = (int) $moderator;
                }
                $group_moderators = array();
                if (!empty($moderators)) {
                    $request = $smcFunc['db_query']('', '
						SELECT id_member
						FROM {db_prefix}members
						WHERE id_member IN ({array_int:moderators})
						LIMIT {int:num_moderators}', array('moderators' => $moderators, 'num_moderators' => count($moderators)));
                    while ($row = $smcFunc['db_fetch_assoc']($request)) {
                        $group_moderators[] = $row['id_member'];
                    }
                    $smcFunc['db_free_result']($request);
                }
            }
            // Found some?
            if (!empty($group_moderators)) {
                $mod_insert = array();
                foreach ($group_moderators as $moderator) {
                    $mod_insert[] = array($_REQUEST['group'], $moderator);
                }
                $smcFunc['db_insert']('insert', '{db_prefix}group_moderators', array('id_group' => 'int', 'id_member' => 'int'), $mod_insert, array('id_group', 'id_member'));
            }
        }
        // There might have been some post group changes.
        updateStats('postgroups');
        // We've definitely changed some group stuff.
        updateSettings(array('settings_updated' => time()));
        // Log the edit.
        logAction('edited_group', array('group' => $_POST['group_name']), 'admin');
        redirectexit('action=admin;area=membergroups');
    }
    // Fetch the current group information.
    $request = $smcFunc['db_query']('', '
		SELECT group_name, description, min_posts, online_color, max_messages, icons, group_type, hidden, id_parent
		FROM {db_prefix}membergroups
		WHERE id_group = {int:current_group}
		LIMIT 1', array('current_group' => (int) $_REQUEST['group']));
    if ($smcFunc['db_num_rows']($request) == 0) {
        fatal_lang_error('membergroup_does_not_exist', false);
    }
    $row = $smcFunc['db_fetch_assoc']($request);
    $smcFunc['db_free_result']($request);
    $row['icons'] = explode('#', $row['icons']);
    $context['group'] = array('id' => $_REQUEST['group'], 'name' => $row['group_name'], 'description' => htmlspecialchars($row['description']), 'editable_name' => $row['group_name'], 'color' => $row['online_color'], 'min_posts' => $row['min_posts'], 'max_messages' => $row['max_messages'], 'icon_count' => (int) $row['icons'][0], 'icon_image' => isset($row['icons'][1]) ? $row['icons'][1] : '', 'is_post_group' => $row['min_posts'] != -1, 'type' => $row['min_posts'] != -1 ? 0 : $row['group_type'], 'hidden' => $row['min_posts'] == -1 ? $row['hidden'] : 0, 'inherited_from' => $row['id_parent'], 'allow_post_group' => $_REQUEST['group'] == 2 || $_REQUEST['group'] > 4, 'allow_delete' => $_REQUEST['group'] == 2 || $_REQUEST['group'] > 4, 'allow_protected' => allowedTo('admin_forum'));
    // Get any moderators for this group
    $request = $smcFunc['db_query']('', '
		SELECT mem.id_member, mem.real_name
		FROM {db_prefix}group_moderators AS mods
			INNER JOIN {db_prefix}members AS mem ON (mem.id_member = mods.id_member)
		WHERE mods.id_group = {int:current_group}', array('current_group' => $_REQUEST['group']));
    $context['group']['moderators'] = array();
    while ($row = $smcFunc['db_fetch_assoc']($request)) {
        $context['group']['moderators'][$row['id_member']] = $row['real_name'];
    }
    $smcFunc['db_free_result']($request);
    $context['group']['moderator_list'] = empty($context['group']['moderators']) ? '' : '&quot;' . implode('&quot;, &quot;', $context['group']['moderators']) . '&quot;';
    if (!empty($context['group']['moderators'])) {
        list($context['group']['last_moderator_id']) = array_slice(array_keys($context['group']['moderators']), -1);
    }
    // Get a list of boards this membergroup is allowed to see.
    $context['boards'] = array();
    if ($_REQUEST['group'] == 2 || $_REQUEST['group'] > 3) {
        $request = $smcFunc['db_query']('', '
			SELECT b.id_cat, c.name as cat_name, b.id_board, b.name, b.child_level,
			FIND_IN_SET({string:current_group}, b.member_groups) != 0 AS can_access, FIND_IN_SET({string:current_group}, b.deny_member_groups) != 0 AS cannot_access
			FROM {db_prefix}boards AS b
				LEFT JOIN {db_prefix}categories AS c ON (c.id_cat = b.id_cat)
			ORDER BY board_order', array('current_group' => (int) $_REQUEST['group']));
        $context['categories'] = array();
        while ($row = $smcFunc['db_fetch_assoc']($request)) {
            // This category hasn't been set up yet..
            if (!isset($context['categories'][$row['id_cat']])) {
                $context['categories'][$row['id_cat']] = array('id' => $row['id_cat'], 'name' => $row['cat_name'], 'boards' => array());
            }
            // Set this board up, and let the template know when it's a child.  (indent them..)
            $context['categories'][$row['id_cat']]['boards'][$row['id_board']] = array('id' => $row['id_board'], 'name' => $row['name'], 'child_level' => $row['child_level'], 'allow' => !(empty($row['can_access']) || $row['can_access'] == 'f'), 'deny' => !(empty($row['cannot_access']) || $row['cannot_access'] == 'f'));
        }
        $smcFunc['db_free_result']($request);
        // Now, let's sort the list of categories into the boards for templates that like that.
        $temp_boards = array();
        foreach ($context['categories'] as $category) {
            $temp_boards[] = array('name' => $category['name'], 'child_ids' => array_keys($category['boards']));
            $temp_boards = array_merge($temp_boards, array_values($category['boards']));
            // Include a list of boards per category for easy toggling.
            $context['categories'][$category['id']]['child_ids'] = array_keys($category['boards']);
        }
        $max_boards = ceil(count($temp_boards) / 2);
        if ($max_boards == 1) {
            $max_boards = 2;
        }
    }
    // Finally, get all the groups this could be inherited off.
    $request = $smcFunc['db_query']('', '
		SELECT id_group, group_name
		FROM {db_prefix}membergroups
		WHERE id_group != {int:current_group}' . (empty($modSettings['permission_enable_postgroups']) ? '
			AND min_posts = {int:min_posts}' : '') . (allowedTo('admin_forum') ? '' : '
			AND group_type != {int:is_protected}') . '
			AND id_group NOT IN (1, 3)
			AND id_parent = {int:not_inherited}', array('current_group' => (int) $_REQUEST['group'], 'min_posts' => -1, 'not_inherited' => -2, 'is_protected' => 1));
    $context['inheritable_groups'] = array();
    while ($row = $smcFunc['db_fetch_assoc']($request)) {
        $context['inheritable_groups'][$row['id_group']] = $row['group_name'];
    }
    $smcFunc['db_free_result']($request);
    call_integration_hook('integrate_view_membergroup');
    $context['sub_template'] = 'edit_group';
    $context['page_title'] = $txt['membergroups_edit_group'];
    createToken('admin-mmg');
}
 /**
  * Edit settings related to the sphinx or sphinxQL search function.
  *
  * - Called by ?action=admin;area=managesearch;sa=sphinx.
  * - Checks if connection to search daemon is possible
  */
 public function action_managesphinx()
 {
     global $txt, $context, $modSettings;
     // Saving the settings
     if (isset($_POST['save'])) {
         checkSession();
         validateToken('admin-mssphinx');
         updateSettings(array('sphinx_data_path' => rtrim($_POST['sphinx_data_path'], '/'), 'sphinx_log_path' => rtrim($_POST['sphinx_log_path'], '/'), 'sphinx_stopword_path' => $_POST['sphinx_stopword_path'], 'sphinx_indexer_mem' => (int) $_POST['sphinx_indexer_mem'], 'sphinx_searchd_server' => $_POST['sphinx_searchd_server'], 'sphinx_searchd_port' => (int) $_POST['sphinx_searchd_port'], 'sphinxql_searchd_port' => (int) $_POST['sphinxql_searchd_port'], 'sphinx_max_results' => (int) $_POST['sphinx_max_results']));
     } elseif (isset($_POST['checkconnect'])) {
         checkSession();
         validateToken('admin-mssphinx');
         // If they have not picked sphinx yet, let them know, but we can still check connections
         if (empty($modSettings['search_index']) || $modSettings['search_index'] !== 'sphinx' && $modSettings['search_index'] !== 'sphinxql') {
             $context['settings_message'][] = $txt['sphinx_test_not_selected'];
             $context['error_type'] = 'notice';
         }
         // Try to connect via Sphinx API?
         if (!empty($modSettings['search_index']) && ($modSettings['search_index'] === 'sphinx' || empty($modSettings['search_index']))) {
             if (@file_exists(SOURCEDIR . '/sphinxapi.php')) {
                 include_once SOURCEDIR . '/sphinxapi.php';
                 $mySphinx = new SphinxClient();
                 $mySphinx->SetServer($modSettings['sphinx_searchd_server'], (int) $modSettings['sphinx_searchd_port']);
                 $mySphinx->SetLimits(0, (int) $modSettings['sphinx_max_results']);
                 $mySphinx->SetMatchMode(SPH_MATCH_BOOLEAN);
                 $mySphinx->SetSortMode(SPH_SORT_ATTR_ASC, 'id_topic');
                 $request = $mySphinx->Query('test', 'elkarte_index');
                 if ($request === false) {
                     $context['settings_message'][] = $txt['sphinx_test_connect_failed'];
                     $context['error_type'] = 'serious';
                 } else {
                     $context['settings_message'][] = $txt['sphinx_test_passed'];
                 }
             } else {
                 $context['settings_message'][] = $txt['sphinx_test_api_missing'];
                 $context['error_type'] = 'serious';
             }
         }
         // Try to connect via SphinxQL
         if (!empty($modSettings['search_index']) && ($modSettings['search_index'] === 'sphinxql' || empty($modSettings['search_index']))) {
             if (!empty($modSettings['sphinx_searchd_server']) && !empty($modSettings['sphinxql_searchd_port'])) {
                 $result = @mysqli_connect($modSettings['sphinx_searchd_server'] === 'localhost' ? '127.0.0.1' : $modSettings['sphinx_searchd_server'], '', '', '', (int) $modSettings['sphinxql_searchd_port']);
                 if ($result === false) {
                     $context['settings_message'][] = $txt['sphinxql_test_connect_failed'];
                     $context['error_type'] = 'serious';
                 } else {
                     $context['settings_message'][] = $txt['sphinxql_test_passed'];
                 }
             } else {
                 $context['settings_message'][] = $txt['sphinxql_test_connect_failed'];
                 $context['error_type'] = 'serious';
             }
         }
     } elseif (isset($_POST['createconfig'])) {
         checkSession();
         validateToken('admin-mssphinx');
         require_once SUBSDIR . '/ManageSearch.subs.php';
         createSphinxConfig();
     }
     // Setup for the template
     $context['page_title'] = $txt['search_sphinx'];
     $context['page_description'] = $txt['sphinx_description'];
     $context['sub_template'] = 'manage_sphinx';
     createToken('admin-mssphinx');
 }
class ResponseItem
{
    public $isValid = false;
    public $validation;
    public $mediaId;
    public $renditions = array();
    function __construct($mediaId, $validation)
    {
        $this->mediaId = $mediaId;
        $this->validation = $validation;
        $this->isValid = $this->validation->isValid;
        if ($this->isValid) {
            $this->getRenditions();
        }
    }
    function getRenditions()
    {
        $mediaItems = createMediaItems();
        foreach ($mediaItems as $mediaItem) {
            if ($mediaItem->videoId == $this->mediaId) {
                $rendition = array("type" => "video/mp4", "src" => $mediaItem->getVideo());
                array_push($this->renditions, $rendition);
                break;
            }
        }
    }
}
$isValid = validateToken($requestorId, $resourceId, $shortMediaToken);
$response = new ResponseItem($mediaId, $isValid);
header('Content-type: application/json');
echo json_encode($response);
Example #17
0
    /**
     * Prepares the information from the moderation log for viewing.
     * Show the moderation log, or admin log...
     * Disallows the deletion of events within twenty-four hours of now.
     * Requires the admin_forum permission for admin log.
     * Accessed via ?action=moderate;area=modlog.
     *
     * @uses Modlog template, main sub-template.
     */
    public function action_log()
    {
        global $txt, $context, $scripturl;
        require_once SUBSDIR . '/Modlog.subs.php';
        // Are we looking at the moderation log or the administration log.
        $context['log_type'] = isset($_REQUEST['sa']) && $_REQUEST['sa'] == 'adminlog' ? 3 : 1;
        if ($context['log_type'] == 3) {
            isAllowedTo('admin_forum');
        }
        // These change dependant on whether we are viewing the moderation or admin log.
        if ($context['log_type'] == 3 || $_REQUEST['action'] == 'admin') {
            $context['url_start'] = '?action=admin;area=logs;sa=' . ($context['log_type'] == 3 ? 'adminlog' : 'modlog') . ';type=' . $context['log_type'];
        } else {
            $context['url_start'] = '?action=moderate;area=modlog;type=' . $context['log_type'];
        }
        $context['can_delete'] = allowedTo('admin_forum');
        loadLanguage('Modlog');
        $context['page_title'] = $context['log_type'] == 3 ? $txt['modlog_admin_log'] : $txt['modlog_view'];
        // The number of entries to show per page of log file.
        $context['displaypage'] = 30;
        // Amount of hours that must pass before allowed to delete file.
        $context['hoursdisable'] = 24;
        // Handle deletion...
        if (isset($_POST['removeall']) && $context['can_delete']) {
            checkSession();
            validateToken('mod-ml');
            deleteLogAction($context['log_type'], $context['hoursdisable']);
        } elseif (!empty($_POST['remove']) && isset($_POST['delete']) && $context['can_delete']) {
            checkSession();
            validateToken('mod-ml');
            deleteLogAction($context['log_type'], $context['hoursdisable'], $_POST['delete']);
        }
        // If we're coming from a search, get the variables.
        if (!empty($_REQUEST['params']) && empty($_REQUEST['is_search'])) {
            $search_params = base64_decode(strtr($_REQUEST['params'], array(' ' => '+')));
            $search_params = @unserialize($search_params);
        }
        // This array houses all the valid quick search types.
        $searchTypes = array('action' => array('sql' => 'lm.action', 'label' => $txt['modlog_action']), 'member' => array('sql' => 'mem.real_name', 'label' => $txt['modlog_member']), 'position' => array('sql' => 'mg.group_name', 'label' => $txt['modlog_position']), 'ip' => array('sql' => 'lm.ip', 'label' => $txt['modlog_ip']));
        // Setup the allowed search
        $context['order'] = isset($_REQUEST['sort']) && isset($searchTypes[$_REQUEST['sort']]) ? $_REQUEST['sort'] : 'member';
        if (!isset($search_params['string']) || !empty($_REQUEST['search']) && $search_params['string'] != $_REQUEST['search']) {
            $search_params_string = empty($_REQUEST['search']) ? '' : $_REQUEST['search'];
        } else {
            $search_params_string = $search_params['string'];
        }
        if (isset($_REQUEST['search_type']) || empty($search_params['type']) || !isset($searchTypes[$search_params['type']])) {
            $search_params_type = isset($_REQUEST['search_type']) && isset($searchTypes[$_REQUEST['search_type']]) ? $_REQUEST['search_type'] : $context['order'];
        } else {
            $search_params_type = $search_params['type'];
        }
        $search_params_column = $searchTypes[$search_params_type]['sql'];
        $search_params = array('string' => $search_params_string, 'type' => $search_params_type);
        // Setup the search context.
        $context['search_params'] = empty($search_params['string']) ? '' : base64_encode(serialize($search_params));
        $context['search'] = array('string' => $search_params['string'], 'type' => $search_params['type'], 'label' => $searchTypes[$search_params_type]['label']);
        // If they are searching by action, then we must do some manual intervention to search in their language!
        if ($search_params['type'] == 'action' && !empty($search_params['string'])) {
            // Build a regex which looks for the words
            $regex = '';
            $search = explode(' ', $search_params['string']);
            foreach ($search as $word) {
                $regex .= '(?=[\\w\\s]*' . $word . ')';
            }
            // For the moment they can only search for ONE action!
            foreach ($txt as $key => $text) {
                if (strpos($key, 'modlog_ac_') === 0 && preg_match('~' . $regex . '~i', $text)) {
                    $search_params['string'] = substr($key, 10);
                    break;
                }
            }
        }
        require_once SUBSDIR . '/GenericList.class.php';
        // This is all the information required for a moderation/admin log listing.
        $listOptions = array('id' => 'moderation_log_list', 'width' => '100%', 'items_per_page' => $context['displaypage'], 'no_items_label' => $txt['modlog_' . ($context['log_type'] == 3 ? 'admin_log_' : '') . 'no_entries_found'], 'base_href' => $scripturl . $context['url_start'] . (!empty($context['search_params']) ? ';params=' . $context['search_params'] : ''), 'default_sort_col' => 'time', 'get_items' => array('function' => array($this, 'getModLogEntries'), 'params' => array(!empty($search_params['string']) ? ' INSTR({raw:sql_type}, {string:search_string})' : '', array('sql_type' => $search_params_column, 'search_string' => $search_params['string']), $context['log_type'])), 'get_count' => array('function' => array($this, 'getModLogEntryCount'), 'params' => array(!empty($search_params['string']) ? ' INSTR({raw:sql_type}, {string:search_string})' : '', array('sql_type' => $search_params_column, 'search_string' => $search_params['string']), $context['log_type'])), 'columns' => array('action' => array('header' => array('value' => $txt['modlog_action'], 'class' => 'lefttext'), 'data' => array('db' => 'action_text', 'class' => 'smalltext'), 'sort' => array('default' => 'lm.action', 'reverse' => 'lm.action DESC')), 'time' => array('header' => array('value' => $txt['modlog_date'], 'class' => 'lefttext'), 'data' => array('db' => 'time', 'class' => 'smalltext'), 'sort' => array('default' => 'lm.log_time DESC', 'reverse' => 'lm.log_time')), 'moderator' => array('header' => array('value' => $txt['modlog_member'], 'class' => 'lefttext'), 'data' => array('db' => 'moderator_link', 'class' => 'smalltext'), 'sort' => array('default' => 'mem.real_name', 'reverse' => 'mem.real_name DESC')), 'position' => array('header' => array('value' => $txt['modlog_position'], 'class' => 'lefttext'), 'data' => array('db' => 'position', 'class' => 'smalltext'), 'sort' => array('default' => 'mg.group_name', 'reverse' => 'mg.group_name DESC')), 'ip' => array('header' => array('value' => $txt['modlog_ip'], 'class' => 'lefttext'), 'data' => array('db' => 'ip', 'class' => 'smalltext'), 'sort' => array('default' => 'lm.ip', 'reverse' => 'lm.ip DESC')), 'delete' => array('header' => array('value' => '<input type="checkbox" name="all" class="input_check" onclick="invertAll(this, this.form);" />', 'class' => 'centertext'), 'data' => array('function' => create_function('$entry', '
							return \'<input type="checkbox" class="input_check" name="delete[]" value="\' . $entry[\'id\'] . \'"\' . ($entry[\'editable\'] ? \'\' : \' disabled="disabled"\') . \' />\';
						'), 'class' => 'centertext'))), 'form' => array('href' => $scripturl . $context['url_start'], 'include_sort' => true, 'include_start' => true, 'hidden_fields' => array($context['session_var'] => $context['session_id'], 'params' => $context['search_params']), 'token' => 'mod-ml'), 'additional_rows' => array(array('class' => 'submitbutton', 'position' => 'below_table_data', 'value' => '
						<div id="quick_log_search">
							' . $txt['modlog_search'] . ' (' . $txt['modlog_by'] . ': ' . $context['search']['label'] . ')
							<input type="text" name="search" size="18" value="' . Util::htmlspecialchars($context['search']['string']) . '" class="input_text" />
							<input type="submit" name="is_search" value="' . $txt['modlog_go'] . '" class="button_submit" />
							' . ($context['can_delete'] ? '|&nbsp;
							<input type="submit" name="remove" value="' . $txt['modlog_remove'] . '" onclick="return confirm(\'' . $txt['modlog_remove_selected_confirm'] . '\');" class="right_submit" />
							<input type="submit" name="removeall" value="' . $txt['modlog_removeall'] . '" onclick="return confirm(\'' . $txt['modlog_remove_all_confirm'] . '\');" class="right_submit" />' : '') . '
						</div>')));
        createToken('mod-ml');
        // Create the log listing
        createList($listOptions);
        $context['sub_template'] = 'show_list';
        $context['default_list'] = 'moderation_log_list';
    }
Example #18
0
/**
 * Change moderation preferences.
 */
function ModerationSettings()
{
    global $context, $smcFunc, $txt, $sourcedir, $scripturl, $user_settings, $user_info;
    // Some useful context stuff.
    loadTemplate('ModerationCenter');
    $context['page_title'] = $txt['mc_settings'];
    $context['sub_template'] = 'moderation_settings';
    // What blocks can this user see?
    $context['homepage_blocks'] = array('n' => $txt['mc_prefs_latest_news'], 'p' => $txt['mc_notes']);
    if ($context['can_moderate_groups']) {
        $context['homepage_blocks']['g'] = $txt['mc_group_requests'];
    }
    if ($context['can_moderate_boards']) {
        $context['homepage_blocks']['r'] = $txt['mc_reported_posts'];
        $context['homepage_blocks']['w'] = $txt['mc_watched_users'];
    }
    // Does the user have any settings yet?
    if (empty($user_settings['mod_prefs'])) {
        $mod_blocks = 'n' . ($context['can_moderate_boards'] ? 'wr' : '') . ($context['can_moderate_groups'] ? 'g' : '');
        $pref_binary = 5;
        $show_reports = 1;
    } else {
        list($show_reports, $mod_blocks, $pref_binary) = explode('|', $user_settings['mod_prefs']);
    }
    // Are we saving?
    if (isset($_POST['save'])) {
        checkSession('post');
        validateToken('mod-set');
        /* Current format of mod_prefs is:
        			x|ABCD|yyy
        
        			WHERE:
        				x = Show report count on forum header.
        				ABCD = Block indexes to show on moderation main page.
        				yyy = Integer with the following bit status:
        					- yyy & 1 = Always notify on reports.
        					- yyy & 2 = Notify on reports for moderators only.
        					- yyy & 4 = Notify about posts awaiting approval.
        		*/
        // Do blocks first!
        $mod_blocks = '';
        if (!empty($_POST['mod_homepage'])) {
            foreach ($_POST['mod_homepage'] as $k => $v) {
                // Make sure they can add this...
                if (isset($context['homepage_blocks'][$k])) {
                    $mod_blocks .= $k;
                }
            }
        }
        // Now check other options!
        $pref_binary = 0;
        if ($context['can_moderate_approvals'] && !empty($_POST['mod_notify_approval'])) {
            $pref_binary |= 4;
        }
        if ($context['can_moderate_boards']) {
            if (!empty($_POST['mod_notify_report'])) {
                $pref_binary |= $_POST['mod_notify_report'] == 2 ? 1 : 2;
            }
            $show_reports = !empty($_POST['mod_show_reports']) ? 1 : 0;
        }
        // Put it all together.
        $mod_prefs = $show_reports . '|' . $mod_blocks . '|' . $pref_binary;
        updateMemberData($user_info['id'], array('mod_prefs' => $mod_prefs));
    }
    // What blocks does the user currently have selected?
    $context['mod_settings'] = array('show_reports' => $show_reports, 'notify_report' => $pref_binary & 2 ? 1 : ($pref_binary & 1 ? 2 : 0), 'notify_approval' => $pref_binary & 4, 'user_blocks' => str_split($mod_blocks));
    createToken('mod-set');
}
Example #19
0
 /**
  * Actually logs you in.
  *
  * What it does:
  * - checks credentials and checks that login was successful.
  * - it employs protection against a specific IP or user trying to brute force
  *   a login to an account.
  * - upgrades password encryption on login, if necessary.
  * - after successful login, redirects you to $_SESSION['login_url'].
  * - accessed from ?action=login2, by forms.
  *
  * On error, uses the same templates action_login() uses.
  */
 public function action_login2()
 {
     global $txt, $scripturl, $user_info, $user_settings, $modSettings, $context, $sc;
     // Load cookie authentication and all stuff.
     require_once SUBSDIR . '/Auth.subs.php';
     // Beyond this point you are assumed to be a guest trying to login.
     if (!$user_info['is_guest']) {
         redirectexit();
     }
     // Are you guessing with a script?
     checkSession('post');
     validateToken('login');
     spamProtection('login');
     // Set the login_url if it's not already set (but careful not to send us to an attachment).
     if (empty($_SESSION['login_url']) && isset($_SESSION['old_url']) && strpos($_SESSION['old_url'], 'dlattach') === false && preg_match('~(board|topic)[=,]~', $_SESSION['old_url']) != 0 || isset($_GET['quicklogin']) && isset($_SESSION['old_url']) && strpos($_SESSION['old_url'], 'login') === false) {
         $_SESSION['login_url'] = $_SESSION['old_url'];
     }
     // Been guessing a lot, haven't we?
     if (isset($_SESSION['failed_login']) && $_SESSION['failed_login'] >= $modSettings['failed_login_threshold'] * 3) {
         fatal_lang_error('login_threshold_fail', 'critical');
     }
     // Set up the cookie length.  (if it's invalid, just fall through and use the default.)
     if (isset($_POST['cookieneverexp']) || !empty($_POST['cookielength']) && $_POST['cookielength'] == -1) {
         $modSettings['cookieTime'] = 3153600;
     } elseif (!empty($_POST['cookielength']) && ($_POST['cookielength'] >= 1 || $_POST['cookielength'] <= 525600)) {
         $modSettings['cookieTime'] = (int) $_POST['cookielength'];
     }
     loadLanguage('Login');
     // Load the template stuff
     loadTemplate('Login');
     loadJavascriptFile('sha256.js', array('defer' => true));
     $context['sub_template'] = 'login';
     // Set up the default/fallback stuff.
     $context['default_username'] = isset($_POST['user']) ? preg_replace('~&amp;#(\\d{1,7}|x[0-9a-fA-F]{1,6});~', '&#\\1;', htmlspecialchars($_POST['user'], ENT_COMPAT, 'UTF-8')) : '';
     $context['default_password'] = '';
     $context['never_expire'] = $modSettings['cookieTime'] == 525600 || $modSettings['cookieTime'] == 3153600;
     $context['login_errors'] = array($txt['error_occurred']);
     $context['page_title'] = $txt['login'];
     // Add the login chain to the link tree.
     $context['linktree'][] = array('url' => $scripturl . '?action=login', 'name' => $txt['login']);
     // This is an OpenID login. Let's validate...
     if (!empty($_POST['openid_identifier']) && !empty($modSettings['enableOpenID'])) {
         require_once SUBSDIR . '/OpenID.subs.php';
         $open_id = new OpenID();
         if ($open_id->validate($_POST['openid_identifier']) !== 'no_data') {
             return $open_id;
         } else {
             $context['login_errors'] = array($txt['openid_not_found']);
             return;
         }
     }
     // You forgot to type your username, dummy!
     if (!isset($_POST['user']) || $_POST['user'] == '') {
         $context['login_errors'] = array($txt['need_username']);
         return;
     }
     // No one needs a username that long, plus we only support 80 chars in the db
     if (Util::strlen($_POST['user']) > 80) {
         $_POST['user'] = Util::substr($_POST['user'], 0, 80);
     }
     // Can't use a password > 64 characters sorry, to long and only good for a DoS attack
     // Plus we expect a 64 character one from SHA-256
     if (isset($_POST['passwrd']) && strlen($_POST['passwrd']) > 64 || isset($_POST['hash_passwrd']) && strlen($_POST['hash_passwrd']) > 64) {
         $context['login_errors'] = array($txt['improper_password']);
         return;
     }
     // Hmm... maybe 'admin' will login with no password. Uhh... NO!
     if ((!isset($_POST['passwrd']) || $_POST['passwrd'] == '') && (!isset($_POST['hash_passwrd']) || strlen($_POST['hash_passwrd']) != 64)) {
         $context['login_errors'] = array($txt['no_password']);
         return;
     }
     // No funky symbols either.
     if (preg_match('~[<>&"\'=\\\\]~', preg_replace('~(&#(\\d{1,7}|x[0-9a-fA-F]{1,6});)~', '', $_POST['user'])) != 0) {
         $context['login_errors'] = array($txt['error_invalid_characters_username']);
         return;
     }
     // Are we using any sort of integration to validate the login?
     if (in_array('retry', call_integration_hook('integrate_validate_login', array($_POST['user'], isset($_POST['hash_passwrd']) && strlen($_POST['hash_passwrd']) == 40 ? $_POST['hash_passwrd'] : null, $modSettings['cookieTime'])), true)) {
         $context['login_errors'] = array($txt['login_hash_error']);
         $context['disable_login_hashing'] = true;
         return;
     }
     // Find them... if we can
     $user_settings = loadExistingMember($_POST['user']);
     // Let them try again, it didn't match anything...
     if (empty($user_settings)) {
         $context['login_errors'] = array($txt['username_no_exist']);
         return;
     }
     // Figure out if the password is using Elk's encryption - if what they typed is right.
     if (isset($_POST['hash_passwrd']) && strlen($_POST['hash_passwrd']) === 64) {
         // Challenge what was passed
         $valid_password = validateLoginPassword($_POST['hash_passwrd'], $user_settings['passwd']);
         // Let them in
         if ($valid_password) {
             $sha_passwd = $_POST['hash_passwrd'];
             $valid_password = true;
         } elseif (preg_match('/^[0-9a-f]{40}$/i', $user_settings['passwd']) && isset($_POST['old_hash_passwrd']) && $_POST['old_hash_passwrd'] === hash('sha1', $user_settings['passwd'] . $sc)) {
             // Old password passed, turn off hashing and ask for it again so we can update the db to something more secure.
             $context['login_errors'] = array($txt['login_hash_error']);
             $context['disable_login_hashing'] = true;
             unset($user_settings);
             return;
         } else {
             // Don't allow this!
             validatePasswordFlood($user_settings['id_member'], $user_settings['passwd_flood']);
             $_SESSION['failed_login'] = isset($_SESSION['failed_login']) ? $_SESSION['failed_login'] + 1 : 1;
             // To many tries, maybe they need a reminder
             if ($_SESSION['failed_login'] >= $modSettings['failed_login_threshold']) {
                 redirectexit('action=reminder');
             } else {
                 log_error($txt['incorrect_password'] . ' - <span class="remove">' . $user_settings['member_name'] . '</span>', 'user');
                 // Wrong password, lets enable plain text responses in case form hashing is causing problems
                 $context['disable_login_hashing'] = true;
                 $context['login_errors'] = array($txt['incorrect_password']);
                 unset($user_settings);
                 return;
             }
         }
     } else {
         // validateLoginPassword will hash this like the form normally would and check its valid
         $sha_passwd = $_POST['passwrd'];
         $valid_password = validateLoginPassword($sha_passwd, $user_settings['passwd'], $user_settings['member_name']);
     }
     // Bad password!  Thought you could fool the database?!
     if ($valid_password === false) {
         // Let's be cautious, no hacking please. thanx.
         validatePasswordFlood($user_settings['id_member'], $user_settings['passwd_flood']);
         // Maybe we were too hasty... let's try some other authentication methods.
         $other_passwords = $this->_other_passwords($user_settings);
         // Whichever encryption it was using, let's make it use ElkArte's now ;).
         if (in_array($user_settings['passwd'], $other_passwords)) {
             $user_settings['passwd'] = validateLoginPassword($sha_passwd, '', '', true);
             $user_settings['password_salt'] = substr(md5(mt_rand()), 0, 4);
             // Update the password hash and set up the salt.
             updateMemberData($user_settings['id_member'], array('passwd' => $user_settings['passwd'], 'password_salt' => $user_settings['password_salt'], 'passwd_flood' => ''));
         } else {
             // They've messed up again - keep a count to see if they need a hand.
             $_SESSION['failed_login'] = isset($_SESSION['failed_login']) ? $_SESSION['failed_login'] + 1 : 1;
             // Hmm... don't remember it, do you?  Here, try the password reminder ;).
             if ($_SESSION['failed_login'] >= $modSettings['failed_login_threshold']) {
                 redirectexit('action=reminder');
             } else {
                 // Log an error so we know that it didn't go well in the error log.
                 log_error($txt['incorrect_password'] . ' - <span class="remove">' . $user_settings['member_name'] . '</span>', 'user');
                 $context['login_errors'] = array($txt['incorrect_password']);
                 return;
             }
         }
     } elseif (!empty($user_settings['passwd_flood'])) {
         // Let's be sure they weren't a little hacker.
         validatePasswordFlood($user_settings['id_member'], $user_settings['passwd_flood'], true);
         // If we got here then we can reset the flood counter.
         updateMemberData($user_settings['id_member'], array('passwd_flood' => ''));
     }
     // Correct password, but they've got no salt; fix it!
     if ($user_settings['password_salt'] == '') {
         $user_settings['password_salt'] = substr(md5(mt_rand()), 0, 4);
         updateMemberData($user_settings['id_member'], array('password_salt' => $user_settings['password_salt']));
     }
     // Check their activation status.
     if (!checkActivation()) {
         return;
     }
     doLogin();
 }
Example #20
0
 /**
  * Reorders the message icons from a drag/drop event
  */
 public function action_messageiconorder()
 {
     global $context, $txt;
     // Initilize
     $context['xml_data'] = array();
     $errors = array();
     $order = array();
     // Seems these will be needed
     loadLanguage('Errors');
     loadLanguage('ManageSmileys');
     require_once SUBSDIR . '/MessageIcons.subs.php';
     // You have to be allowed to do this
     $validation_token = validateToken('admin-sort', 'post', true, false);
     $validation_session = validateSession();
     if (empty($validation_session) && $validation_token === true) {
         // No questions that we are reordering
         if (isset($_POST['order']) && $_POST['order'] == 'reorder') {
             // Get the current list of icons.
             $message_icons = fetchMessageIconsDetails();
             $view_order = 0;
             $iconInsert = array();
             // The field ids arrive in 1-n view order, so we simply build an update array
             foreach ($_POST['list_message_icon_list'] as $id) {
                 $iconInsert[] = array($id, $message_icons[$id]['board_id'], $message_icons[$id]['title'], $message_icons[$id]['filename'], $view_order);
                 $view_order++;
             }
             // With the replace set
             if (!empty($iconInsert)) {
                 updateMessageIcon($iconInsert);
                 sortMessageIconTable();
             } else {
                 $errors[] = array('value' => $txt['no_sortable_items']);
             }
         }
         $order[] = array('value' => $txt['icons_reordered']);
     } else {
         if (!empty($validation_session)) {
             $errors[] = array('value' => $txt[$validation_session]);
         }
         if (empty($validation_token)) {
             $errors[] = array('value' => $txt['token_verify_fail']);
         }
     }
     // New generic token for use
     createToken('admin-sort', 'post');
     $tokens = array(array('value' => $context['admin-sort_token'], 'attributes' => array('type' => 'token')), array('value' => $context['admin-sort_token_var'], 'attributes' => array('type' => 'token_var')));
     // Return the response
     $context['sub_template'] = 'generic_xml';
     $context['xml_data'] = array('orders' => array('identifier' => 'order', 'children' => $order), 'tokens' => array('identifier' => 'token', 'children' => $tokens), 'errors' => array('identifier' => 'error', 'children' => $errors));
 }
 /**
  * Edit some profile fields?
  *
  * - Accessed with ?action=admin;area=featuresettings;sa=profileedit
  *
  * @uses sub template edit_profile_field
  */
 public function action_profileedit()
 {
     global $txt, $scripturl, $context;
     require_once SUBSDIR . '/ManageFeatures.subs.php';
     loadTemplate('ManageFeatures');
     // Sort out the context!
     $context['fid'] = isset($_GET['fid']) ? (int) $_GET['fid'] : 0;
     $context[$context['admin_menu_name']]['current_subsection'] = 'profile';
     $context['page_title'] = $context['fid'] ? $txt['custom_edit_title'] : $txt['custom_add_title'];
     $context['sub_template'] = 'edit_profile_field';
     // any errors messages to show?
     if (isset($_GET['msg'])) {
         loadLanguage('Errors');
         if (isset($txt['custom_option_' . $_GET['msg']])) {
             $context['custom_option__error'] = $txt['custom_option_' . $_GET['msg']];
         }
     }
     // Load the profile language for section names.
     loadLanguage('Profile');
     // Load up the profile field, if one was supplied
     if ($context['fid']) {
         $context['field'] = getProfileField($context['fid']);
     }
     // Setup the default values as needed.
     if (empty($context['field'])) {
         $context['field'] = array('name' => '', 'colname' => '???', 'desc' => '', 'profile_area' => 'forumprofile', 'reg' => false, 'display' => false, 'memberlist' => false, 'type' => 'text', 'max_length' => 255, 'rows' => 4, 'cols' => 30, 'bbc' => false, 'default_check' => false, 'default_select' => '', 'options' => array('', '', ''), 'active' => true, 'private' => false, 'can_search' => false, 'mask' => 'nohtml', 'regex' => '', 'enclose' => '', 'placement' => 0);
     }
     // All the javascript for this page... everything else is in admin.js
     addJavascriptVar(array('startOptID' => count($context['field']['options'])));
     addInlineJavascript('updateInputBoxes();', true);
     // Are we toggling which ones are active?
     if (isset($_POST['onoff'])) {
         checkSession();
         validateToken('admin-scp');
         // Enable and disable custom fields as required.
         $enabled = array(0);
         foreach ($_POST['cust'] as $id) {
             $enabled[] = (int) $id;
         }
         updateRenamedProfileStatus($enabled);
     } elseif (isset($_POST['save'])) {
         checkSession();
         validateToken('admin-ecp');
         // Everyone needs a name - even the (bracket) unknown...
         if (trim($_POST['field_name']) == '') {
             redirectexit($scripturl . '?action=admin;area=featuresettings;sa=profileedit;fid=' . $_GET['fid'] . ';msg=need_name');
         }
         // Regex you say?  Do a very basic test to see if the pattern is valid
         if (!empty($_POST['regex']) && @preg_match($_POST['regex'], 'dummy') === false) {
             redirectexit($scripturl . '?action=admin;area=featuresettings;sa=profileedit;fid=' . $_GET['fid'] . ';msg=regex_error');
         }
         $_POST['field_name'] = Util::htmlspecialchars($_POST['field_name']);
         $_POST['field_desc'] = Util::htmlspecialchars($_POST['field_desc']);
         // Checkboxes...
         $show_reg = isset($_POST['reg']) ? (int) $_POST['reg'] : 0;
         $show_display = isset($_POST['display']) ? 1 : 0;
         $show_memberlist = isset($_POST['memberlist']) ? 1 : 0;
         $bbc = isset($_POST['bbc']) ? 1 : 0;
         $show_profile = $_POST['profile_area'];
         $active = isset($_POST['active']) ? 1 : 0;
         $private = isset($_POST['private']) ? (int) $_POST['private'] : 0;
         $can_search = isset($_POST['can_search']) ? 1 : 0;
         // Some masking stuff...
         $mask = isset($_POST['mask']) ? $_POST['mask'] : '';
         if ($mask == 'regex' && isset($_POST['regex'])) {
             $mask .= $_POST['regex'];
         }
         $field_length = isset($_POST['max_length']) ? (int) $_POST['max_length'] : 255;
         $enclose = isset($_POST['enclose']) ? $_POST['enclose'] : '';
         $placement = isset($_POST['placement']) ? (int) $_POST['placement'] : 0;
         // Select options?
         $field_options = '';
         $newOptions = array();
         $default = isset($_POST['default_check']) && $_POST['field_type'] == 'check' ? 1 : '';
         if (!empty($_POST['select_option']) && ($_POST['field_type'] == 'select' || $_POST['field_type'] == 'radio')) {
             foreach ($_POST['select_option'] as $k => $v) {
                 // Clean, clean, clean...
                 $v = Util::htmlspecialchars($v);
                 $v = strtr($v, array(',' => ''));
                 // Nada, zip, etc...
                 if (trim($v) == '') {
                     continue;
                 }
                 // Otherwise, save it boy.
                 $field_options .= $v . ',';
                 // This is just for working out what happened with old options...
                 $newOptions[$k] = $v;
                 // Is it default?
                 if (isset($_POST['default_select']) && $_POST['default_select'] == $k) {
                     $default = $v;
                 }
             }
             if (isset($_POST['default_select']) && $_POST['default_select'] == 'no_default') {
                 $default = 'no_default';
             }
             $field_options = substr($field_options, 0, -1);
         }
         // Text area by default has dimensions
         if ($_POST['field_type'] == 'textarea') {
             $default = (int) $_POST['rows'] . ',' . (int) $_POST['cols'];
         }
         // Come up with the unique name?
         if (empty($context['fid'])) {
             $colname = Util::substr(strtr($_POST['field_name'], array(' ' => '')), 0, 6);
             preg_match('~([\\w\\d_-]+)~', $colname, $matches);
             // If there is nothing to the name, then let's start our own - for foreign languages etc.
             if (isset($matches[1])) {
                 $colname = $initial_colname = 'cust_' . strtolower($matches[1]);
             } else {
                 $colname = $initial_colname = 'cust_' . mt_rand(1, 999999);
             }
             $unique = ensureUniqueProfileField($colname, $initial_colname);
             // Still not a unique colum name? Leave it up to the user, then.
             if (!$unique) {
                 fatal_lang_error('custom_option_not_unique');
             }
         } else {
             // Anything going to check or select is pointless keeping - as is anything coming from check!
             if ($_POST['field_type'] == 'check' && $context['field']['type'] != 'check' || ($_POST['field_type'] == 'select' || $_POST['field_type'] == 'radio') && $context['field']['type'] != 'select' && $context['field']['type'] != 'radio' || $context['field']['type'] == 'check' && $_POST['field_type'] != 'check') {
                 deleteProfileFieldUserData($context['field']['colname']);
             } elseif ($_POST['field_type'] == 'select' || $_POST['field_type'] == 'radio') {
                 $optionChanges = array();
                 $takenKeys = array();
                 // Work out what's changed!
                 foreach ($context['field']['options'] as $k => $option) {
                     if (trim($option) == '') {
                         continue;
                     }
                     // Still exists?
                     if (in_array($option, $newOptions)) {
                         $takenKeys[] = $k;
                         continue;
                     }
                 }
                 // Finally - have we renamed it - or is it really gone?
                 foreach ($optionChanges as $k => $option) {
                     // Just been renamed?
                     if (!in_array($k, $takenKeys) && !empty($newOptions[$k])) {
                         updateRenamedProfileField($k, $newOptions, $context['field']['colname'], $option);
                     }
                 }
             }
             // @todo Maybe we should adjust based on new text length limits?
         }
         // Updating an existing field?
         if ($context['fid']) {
             $field_data = array('field_length' => $field_length, 'show_reg' => $show_reg, 'show_display' => $show_display, 'show_memberlist' => $show_memberlist, 'private' => $private, 'active' => $active, 'can_search' => $can_search, 'bbc' => $bbc, 'current_field' => $context['fid'], 'field_name' => $_POST['field_name'], 'field_desc' => $_POST['field_desc'], 'field_type' => $_POST['field_type'], 'field_options' => $field_options, 'show_profile' => $show_profile, 'default_value' => $default, 'mask' => $mask, 'enclose' => $enclose, 'placement' => $placement);
             updateProfileField($field_data);
             // Just clean up any old selects - these are a pain!
             if (($_POST['field_type'] == 'select' || $_POST['field_type'] == 'radio') && !empty($newOptions)) {
                 deleteOldProfileFieldSelects($newOptions, $context['field']['colname']);
             }
         } else {
             $new_field = array('col_name' => $colname, 'field_name' => $_POST['field_name'], 'field_desc' => $_POST['field_desc'], 'field_type' => $_POST['field_type'], 'field_length' => $field_length, 'field_options' => $field_options, 'show_reg' => $show_reg, 'show_display' => $show_display, 'show_memberlist' => $show_memberlist, 'show_profile' => $show_profile, 'private' => $private, 'active' => $active, 'default' => $default, 'can_search' => $can_search, 'bbc' => $bbc, 'mask' => $mask, 'enclose' => $enclose, 'placement' => $placement, 'vieworder' => list_getProfileFieldSize() + 1);
             addProfileField($new_field);
         }
     } elseif (isset($_POST['delete']) && $context['field']['colname']) {
         checkSession();
         validateToken('admin-ecp');
         // Delete the old data first, then the field.
         deleteProfileFieldUserData($context['field']['colname']);
         deleteProfileField($context['fid']);
     }
     // Rebuild display cache etc.
     if (isset($_POST['delete']) || isset($_POST['save']) || isset($_POST['onoff'])) {
         checkSession();
         // Update the display cache
         updateDisplayCache();
         redirectexit('action=admin;area=featuresettings;sa=profile');
     }
     createToken('admin-ecp');
 }
function getPlanned($token, $studentId, $semester, $year)
{
    $result = array();
    try {
        if (!validateToken($token, $studentId)) {
            return 403;
        }
        if (empty($studentId)) {
            return 404;
        }
        $conn = new PDO(DBCONNECTSTRING, DBUSER, DBPASSWORD);
        $sql = 'SELECT *  FROM course_records,courses WHERE type=2 AND courseId=courses.id AND studentId=:stuId AND semesterCode=:semester AND year=:year';
        $stmt = $conn->prepare($sql);
        $stmt->bindParam(':stuId', $studentId);
        $stmt->bindParam(':semester', $semester);
        $stmt->bindParam(':year', $year);
        $stmt->execute();
        $courses = $stmt->fetchAll();
        //echo "Hello";
        //echo $stmt->rowCount();
        if ($stmt->rowCount() <= 0) {
            return $result;
        }
        foreach ($courses as $course) {
            /*echo "<p>json:";
                     echo print_r($course);
              echo "</p>";
              */
            $c = new stdClass();
            $c->id = $course['id'];
            $c->dept = $course['dept'];
            $c->num = $course['num'];
            $c->type = $course['type'];
            $c->reqId = $course['reqId'];
            $c->proposedReqId = $course['proposedReqId'];
            $c->plannedSemester = $course['semesterCode'];
            $c->plannedSemesterName = getSemesterName($c->plannedSemester);
            $c->plannedYear = $course['year'];
            $result[] = $c;
        }
        $jsonResult = json_encode($result);
        /*echo "<p>json:";
                 echo $jsonResult;
          echo "</p>";
          */
        //json_encode
    } catch (PDOException $e) {
        //echo $sql . "<br>" . $e->getMessage();
        return 500;
    }
    $conn = null;
    return $jsonResult;
}
 /**
  * Shows an interface to set and test censored words.
  *
  * - It uses the censor_vulgar, censor_proper, censorWholeWord, and
  * censorIgnoreCase settings.
  * - Requires the admin_forum permission.
  * - Accessed from ?action=admin;area=postsettings;sa=censor.
  *
  * @uses the Admin template and the edit_censored sub template.
  */
 public function action_censor()
 {
     global $txt, $modSettings, $context;
     if (!empty($_POST['save_censor'])) {
         // Make sure censoring is something they can do.
         checkSession();
         validateToken('admin-censor');
         $censored_vulgar = array();
         $censored_proper = array();
         // Rip it apart, then split it into two arrays.
         if (isset($_POST['censortext'])) {
             $_POST['censortext'] = explode("\n", strtr($_POST['censortext'], array("\r" => '')));
             foreach ($_POST['censortext'] as $c) {
                 list($censored_vulgar[], $censored_proper[]) = array_pad(explode('=', trim($c)), 2, '');
             }
         } elseif (isset($_POST['censor_vulgar'], $_POST['censor_proper'])) {
             if (is_array($_POST['censor_vulgar'])) {
                 foreach ($_POST['censor_vulgar'] as $i => $value) {
                     if (trim(strtr($value, '*', ' ')) == '') {
                         unset($_POST['censor_vulgar'][$i], $_POST['censor_proper'][$i]);
                     }
                 }
                 $censored_vulgar = $_POST['censor_vulgar'];
                 $censored_proper = $_POST['censor_proper'];
             } else {
                 $censored_vulgar = explode("\n", strtr($_POST['censor_vulgar'], array("\r" => '')));
                 $censored_proper = explode("\n", strtr($_POST['censor_proper'], array("\r" => '')));
             }
         }
         // Set the new arrays and settings in the database.
         $updates = array('censor_vulgar' => implode("\n", $censored_vulgar), 'censor_proper' => implode("\n", $censored_proper), 'censorWholeWord' => empty($_POST['censorWholeWord']) ? '0' : '1', 'censorIgnoreCase' => empty($_POST['censorIgnoreCase']) ? '0' : '1');
         call_integration_hook('integrate_save_censors', array(&$updates));
         updateSettings($updates);
     }
     // Testing a word to see how it will be censored?
     if (isset($_POST['censortest'])) {
         require_once SUBSDIR . '/Post.subs.php';
         $censorText = htmlspecialchars($_POST['censortest'], ENT_QUOTES, 'UTF-8');
         preparsecode($censorText);
         $pre_censor = $censorText;
         $context['censor_test'] = strtr(censorText($censorText), array('"' => '&quot;'));
     }
     // Set everything up for the template to do its thang.
     $censor_vulgar = explode("\n", $modSettings['censor_vulgar']);
     $censor_proper = explode("\n", $modSettings['censor_proper']);
     $context['censored_words'] = array();
     for ($i = 0, $n = count($censor_vulgar); $i < $n; $i++) {
         if (empty($censor_vulgar[$i])) {
             continue;
         }
         // Skip it, it's either spaces or stars only.
         if (trim(strtr($censor_vulgar[$i], '*', ' ')) == '') {
             continue;
         }
         $context['censored_words'][htmlspecialchars(trim($censor_vulgar[$i]))] = isset($censor_proper[$i]) ? htmlspecialchars($censor_proper[$i], ENT_COMPAT, 'UTF-8') : '';
     }
     call_integration_hook('integrate_censors');
     createToken('admin-censor');
     // Using ajax?
     if (isset($_REQUEST['xml'], $_POST['censortest'])) {
         // Clear the templates
         $template_layers = Template_Layers::getInstance();
         $template_layers->removeAll();
         // Send back a response
         loadTemplate('Json');
         $context['sub_template'] = 'send_json';
         $context['json_data'] = array('result' => true, 'censor' => $pre_censor . ' <i class="fa fa-arrow-circle-right"></i> ' . $context['censor_test'], 'token_val' => $context['admin-censor_token_var'], 'token' => $context['admin-censor_token']);
     } else {
         $context['sub_template'] = 'edit_censored';
         $context['page_title'] = $txt['admin_censored_words'];
     }
 }
Example #24
0
require_once '../db_config/generated-conf/config.php';
$config = (include '../config.php');
use Illuminate\Filesystem\Filesystem;
use GuzzleHttp\Client;
$app = new \Slim\Slim();
$app->get('/getFiles', function () use($app) {
    logMessage("Accepted Request: getFiles " . date('m/d/Y h:i:s') . ".\n");
    //log something
    return validateToken($app->request->headers['TOKEN'], $app) === true ? getFiles() : validateToken($app->request->headers['TOKEN'], $app);
});
$app->post('/getSyncFiles', function () use($app) {
    $data = file_get_contents("php://input");
    $data = (array) json_decode($data);
    logMessage("Accepted Request: getSyncFiles param of DATE: " . $data['date'] . " and STORE of " . $data['store'] . ' on ' . date('m/d/Y h:i:s') . ".\n");
    //log something
    return validateToken($app->request->headers['TOKEN'], $app) === true ? getSyncFiles($data['date'], $data['store']) : validateToken($app->request->headers['TOKEN'], $app);
});
//Accept files to process from Netsuite
$app->post('/setToAccomplish', function () use($app) {
    logMessage("Accepted Request: setToAccomplish " . date('m/d/Y h:i:s') . ".\n");
    //log something
    $data = file_get_contents("php://input");
    //$data = json_encode($data, dio_truncate(fd, offset));
    $data = (array) json_decode($data);
    $client = new Client();
    //print_r($data);
    foreach ($data['po'] as $file) {
        echo $file . "<br/>";
        logMessage("Send Request: http://localhost:9000/post.php " . date('m/d/Y h:i:s') . ".\n");
        //log something
        $client->post('http://localhost:9000/post.php', ['body' => [json_encode(processFile($file))]]);
Example #25
0
use BlockCypher\Validation\TokenValidator;
error_reporting(E_ALL);
ini_set('display_errors', '1');
if (ini_set('precision', 17) === false) {
    die("Couldn't update precision.");
}
if (ini_set('serialize_precision', 17) === false) {
    die("Couldn't update serialize_precision.");
}
// Replace these values by entering your own token by visiting https://accounts.blockcypher.com/
/** @noinspection SpellCheckingInspection */
$token = 'c0afcccdde5081d6429de37d16166ead';
if (isset($_GET['token'])) {
    $token = $_GET['token'];
}
if (!validateToken($token)) {
    echo 'Invalid token. Please get new one: <a href="https://accounts.blockcypher.com/">https://accounts.blockcypher.com/</a>';
    exit(1);
}
/** @var \BlockCypher\Rest\ApiContext $apiContext */
$apiContextSdkConfigFile = getApiContextUsingConfigIni();
$apiContexts = createApiContextForAllChains($token);
$apiContexts['sdk_config'] = $apiContextSdkConfigFile;
// Add ApiContext created using sdk_config.ini custom settings
return $apiContexts;
/**
 * Create an ApiContext for each chain
 * @param $token
 * @return array
 */
function createApiContextForAllChains($token)
Example #26
0
/**
 * Edit the search method and search index used.
 * Calculates the size of the current search indexes in use.
 * Allows to create and delete a fulltext index on the messages table.
 * Allows to delete a custom index (that CreateMessageIndex() created).
 * Called by ?action=admin;area=managesearch;sa=method.
 * Requires the admin_forum permission.
 *
 * @uses ManageSearch template, 'select_search_method' sub-template.
 */
function EditSearchMethod()
{
    global $txt, $context, $modSettings, $smcFunc, $db_type, $db_prefix;
    $context[$context['admin_menu_name']]['current_subsection'] = 'method';
    $context['page_title'] = $txt['search_method_title'];
    $context['sub_template'] = 'select_search_method';
    $context['supports_fulltext'] = $smcFunc['db_search_support']('fulltext');
    // Load any apis.
    $context['search_apis'] = loadSearchAPIs();
    // Detect whether a fulltext index is set.
    if ($context['supports_fulltext']) {
        detectFulltextIndex();
    }
    if (!empty($_REQUEST['sa']) && $_REQUEST['sa'] == 'createfulltext') {
        checkSession('get');
        validateToken('admin-msm', 'get');
        // Make sure it's gone before creating it.
        $smcFunc['db_query']('', '
			ALTER TABLE {db_prefix}messages
			DROP INDEX body', array('db_error_skip' => true));
        $smcFunc['db_query']('', '
			ALTER TABLE {db_prefix}messages
			ADD FULLTEXT body (body)', array());
        $context['fulltext_index'] = 'body';
    } elseif (!empty($_REQUEST['sa']) && $_REQUEST['sa'] == 'removefulltext' && !empty($context['fulltext_index'])) {
        checkSession('get');
        validateToken('admin-msm', 'get');
        $smcFunc['db_query']('', '
			ALTER TABLE {db_prefix}messages
			DROP INDEX ' . implode(',
			DROP INDEX ', $context['fulltext_index']), array('db_error_skip' => true));
        $context['fulltext_index'] = '';
        // Go back to the default search method.
        if (!empty($modSettings['search_index']) && $modSettings['search_index'] == 'fulltext') {
            updateSettings(array('search_index' => ''));
        }
    } elseif (!empty($_REQUEST['sa']) && $_REQUEST['sa'] == 'removecustom') {
        checkSession('get');
        validateToken('admin-msm', 'get');
        db_extend();
        $tables = $smcFunc['db_list_tables'](false, $db_prefix . 'log_search_words');
        if (!empty($tables)) {
            $smcFunc['db_search_query']('drop_words_table', '
				DROP TABLE {db_prefix}log_search_words', array());
        }
        updateSettings(array('search_custom_index_config' => '', 'search_custom_index_resume' => ''));
        // Go back to the default search method.
        if (!empty($modSettings['search_index']) && $modSettings['search_index'] == 'custom') {
            updateSettings(array('search_index' => ''));
        }
    } elseif (isset($_POST['save'])) {
        checkSession();
        validateToken('admin-msmpost');
        updateSettings(array('search_index' => empty($_POST['search_index']) || !in_array($_POST['search_index'], array('fulltext', 'custom')) && !isset($context['search_apis'][$_POST['search_index']]) ? '' : $_POST['search_index'], 'search_force_index' => isset($_POST['search_force_index']) ? '1' : '0', 'search_match_words' => isset($_POST['search_match_words']) ? '1' : '0'));
    }
    $context['table_info'] = array('data_length' => 0, 'index_length' => 0, 'fulltext_length' => 0, 'custom_index_length' => 0);
    // Get some info about the messages table, to show its size and index size.
    if ($db_type == 'mysql') {
        if (preg_match('~^`(.+?)`\\.(.+?)$~', $db_prefix, $match) !== 0) {
            $request = $smcFunc['db_query']('', '
				SHOW TABLE STATUS
				FROM {string:database_name}
				LIKE {string:table_name}', array('database_name' => '`' . strtr($match[1], array('`' => '')) . '`', 'table_name' => str_replace('_', '\\_', $match[2]) . 'messages'));
        } else {
            $request = $smcFunc['db_query']('', '
				SHOW TABLE STATUS
				LIKE {string:table_name}', array('table_name' => str_replace('_', '\\_', $db_prefix) . 'messages'));
        }
        if ($request !== false && $smcFunc['db_num_rows']($request) == 1) {
            // Only do this if the user has permission to execute this query.
            $row = $smcFunc['db_fetch_assoc']($request);
            $context['table_info']['data_length'] = $row['Data_length'];
            $context['table_info']['index_length'] = $row['Index_length'];
            $context['table_info']['fulltext_length'] = $row['Index_length'];
            $smcFunc['db_free_result']($request);
        }
        // Now check the custom index table, if it exists at all.
        if (preg_match('~^`(.+?)`\\.(.+?)$~', $db_prefix, $match) !== 0) {
            $request = $smcFunc['db_query']('', '
				SHOW TABLE STATUS
				FROM {string:database_name}
				LIKE {string:table_name}', array('database_name' => '`' . strtr($match[1], array('`' => '')) . '`', 'table_name' => str_replace('_', '\\_', $match[2]) . 'log_search_words'));
        } else {
            $request = $smcFunc['db_query']('', '
				SHOW TABLE STATUS
				LIKE {string:table_name}', array('table_name' => str_replace('_', '\\_', $db_prefix) . 'log_search_words'));
        }
        if ($request !== false && $smcFunc['db_num_rows']($request) == 1) {
            // Only do this if the user has permission to execute this query.
            $row = $smcFunc['db_fetch_assoc']($request);
            $context['table_info']['index_length'] += $row['Data_length'] + $row['Index_length'];
            $context['table_info']['custom_index_length'] = $row['Data_length'] + $row['Index_length'];
            $smcFunc['db_free_result']($request);
        }
    } elseif ($db_type == 'postgresql') {
        // In order to report the sizes correctly we need to perform vacuum (optimize) on the tables we will be using.
        db_extend();
        $temp_tables = $smcFunc['db_list_tables']();
        foreach ($temp_tables as $table) {
            if ($table == $db_prefix . 'messages' || $table == $db_prefix . 'log_search_words') {
                $smcFunc['db_optimize_table']($table);
            }
        }
        // PostGreSql has some hidden sizes.
        $request = $smcFunc['db_query']('', '
			SELECT relname, relpages * 8 *1024 AS "KB" FROM pg_class
			WHERE relname = {string:messages} OR relname = {string:log_search_words}
			ORDER BY relpages DESC', array('messages' => $db_prefix . 'messages', 'log_search_words' => $db_prefix . 'log_search_words'));
        if ($request !== false && $smcFunc['db_num_rows']($request) > 0) {
            while ($row = $smcFunc['db_fetch_assoc']($request)) {
                if ($row['relname'] == $db_prefix . 'messages') {
                    $context['table_info']['data_length'] = (int) $row['KB'];
                    $context['table_info']['index_length'] = (int) $row['KB'];
                    // Doesn't support fulltext
                    $context['table_info']['fulltext_length'] = $txt['not_applicable'];
                } elseif ($row['relname'] == $db_prefix . 'log_search_words') {
                    $context['table_info']['index_length'] = (int) $row['KB'];
                    $context['table_info']['custom_index_length'] = (int) $row['KB'];
                }
            }
            $smcFunc['db_free_result']($request);
        } else {
            // Didn't work for some reason...
            $context['table_info'] = array('data_length' => $txt['not_applicable'], 'index_length' => $txt['not_applicable'], 'fulltext_length' => $txt['not_applicable'], 'custom_index_length' => $txt['not_applicable']);
        }
    } else {
        $context['table_info'] = array('data_length' => $txt['not_applicable'], 'index_length' => $txt['not_applicable'], 'fulltext_length' => $txt['not_applicable'], 'custom_index_length' => $txt['not_applicable']);
    }
    // Format the data and index length in kilobytes.
    foreach ($context['table_info'] as $type => $size) {
        // If it's not numeric then just break.  This database engine doesn't support size.
        if (!is_numeric($size)) {
            break;
        }
        $context['table_info'][$type] = comma_format($context['table_info'][$type] / 1024) . ' ' . $txt['search_method_kilobytes'];
    }
    $context['custom_index'] = !empty($modSettings['search_custom_index_config']);
    $context['partial_custom_index'] = !empty($modSettings['search_custom_index_resume']) && empty($modSettings['search_custom_index_config']);
    $context['double_index'] = !empty($context['fulltext_index']) && $context['custom_index'];
    createToken('admin-msmpost');
    createToken('admin-msm', 'get');
}
Example #27
0
$activity = $_POST['activity'];
$bps = $_POST['bps'];
$bpd = $_POST['bpd'];
$weight = $_POST['weight'];
$height = $_POST['height'];
$temperature = $_POST['temperature'];
$temp_method = $_POST['temp_method'];
$pulse = $_POST['pulse'];
$respiration = $_POST['respiration'];
$note = $_POST['note'];
$BMI = $_POST['BMI'];
$BMI_status = $_POST['BMI_status'];
$waist_circ = $_POST['waist_circ'];
$head_circ = $_POST['head_circ'];
$oxygen_saturation = $_POST['oxygen_saturation'];
if ($userId = validateToken($token)) {
    $user = getUsername($userId);
    $acl_allow = acl_check('encounters', 'auth_a', $user);
    if ($acl_allow) {
        $strQuery = "UPDATE `form_vitals` SET \n                                        `date`='" . add_escape_custom($date) . "',\n                                        `pid`='" . add_escape_custom($patientId) . "',\n                                        `user`='" . add_escape_custom($user) . "',\n                                        `groupname`='" . add_escape_custom($groupname) . "',\n                                        `authorized`='" . add_escape_custom($authorized) . "',\n                                        `activity`='" . add_escape_custom($activity) . "',\n                                        `bps`='" . add_escape_custom($bps) . "',\n                                        `bpd`='" . add_escape_custom($bpd) . "',\n                                        `weight`='" . add_escape_custom($weight) . "',\n                                        `height`='" . add_escape_custom($height) . "',\n                                        `temperature`='" . add_escape_custom($temperature) . "',\n                                        `temp_method`='" . add_escape_custom($temp_method) . "',\n                                        `pulse`='" . add_escape_custom($pulse) . "',\n                                        `respiration`='" . add_escape_custom($respiration) . "',\n                                        `note`='" . add_escape_custom($note) . "',\n                                        `BMI`='" . add_escape_custom($BMI) . "',\n                                        `BMI_status`='" . add_escape_custom($BMI_status) . "',\n                                        `waist_circ`='" . add_escape_custom($waist_circ) . "',\n                                        `head_circ`='" . add_escape_custom($head_circ) . "',\n                                        `oxygen_saturation`='" . add_escape_custom($oxygen_saturation) . "' \n                                         WHERE id = ?";
        $result = sqlStatement($strQuery, array($vital_id));
        if ($result !== FALSE) {
            $xml_array['status'] = 0;
            $xml_array['reason'] = 'Visit vital update successfully';
        } else {
            $xml_array['status'] = -1;
            $xml_array['reason'] = 'Could not update isit vital';
        }
    } else {
        $xml_string .= "<status>-2</status>\n";
        $xml_string .= "<reason>You are not Authorized to perform this action</reason>\n";
Example #28
0
/**
 * Step 0.5: Does the login work?
 */
function checkLogin()
{
    global $modSettings, $upcontext, $disable_security, $db_type, $support_js;
    // Login checks require hard database work :P
    $db = database();
    // Are we trying to login?
    if (isset($_POST['contbutt']) && (!empty($_POST['user']) || $disable_security)) {
        // If we've disabled security pick a suitable name!
        if (empty($_POST['user'])) {
            $_POST['user'] = '******';
        }
        // Before SMF 2.0 these column names were different!
        $oldDB = false;
        if (empty($db_type) || $db_type == 'mysql') {
            $request = $db->query('', '
				SHOW COLUMNS
				FROM {db_prefix}members
				LIKE {string:member_name}', array('member_name' => 'memberName', 'db_error_skip' => true));
            if ($db->num_rows($request) != 0) {
                $oldDB = true;
            }
            $db->free_result($request);
        }
        // Get what we believe to be their details.
        if (!$disable_security) {
            if ($oldDB) {
                $request = $db->query('', '
					SELECT id_member, memberName AS member_name, passwd, id_group,
					additionalGroups AS additional_groups, lngfile
					FROM {db_prefix}members
					WHERE memberName = {string:member_name}', array('member_name' => $_POST['user'], 'db_error_skip' => true));
            } else {
                $request = $db->query('', '
					SELECT id_member, member_name, passwd, id_group, additional_groups, lngfile
					FROM {db_prefix}members
					WHERE member_name = {string:member_name}', array('member_name' => $_POST['user'], 'db_error_skip' => true));
            }
            if ($db->num_rows($request) != 0) {
                list($id_member, $name, $password, $id_group, $addGroups, $user_language) = $db->fetch_row($request);
                // These will come in handy, if you want to login
                require_once SOURCEDIR . '/Security.php';
                require_once SUBSDIR . '/Auth.subs.php';
                $groups = explode(',', $addGroups);
                $groups[] = $id_group;
                foreach ($groups as $k => $v) {
                    $groups[$k] = (int) $v;
                }
                // Figure out if the password is using our encryption - if what they typed is right.
                if (isset($_REQUEST['hash_passwrd']) && strlen($_REQUEST['hash_passwrd']) === 64) {
                    validateToken('login');
                    $valid_password = validateLoginPassword($_REQUEST['hash_passwrd'], $password);
                    // Challenge passed.
                    if ($valid_password) {
                        $sha_passwd = $_REQUEST['hash_passwrd'];
                        $valid_password = true;
                    } elseif (preg_match('/^[0-9a-f]{40}$/i', $password)) {
                        // Might Need to update so we will need to ask for the password again.
                        $upcontext['disable_login_hashing'] = true;
                        $upcontext['login_hash_error'] = true;
                    }
                } else {
                    // validateLoginPassword will convert this to a SHA-256 pw and check it
                    $sha_passwd = $_POST['passwrd'];
                    $valid_password = validateLoginPassword($sha_passwd, $password, $_POST['user']);
                }
                // Password still not working?
                if ($valid_password === false && !empty($_POST['passwrd'])) {
                    // SHA-1 from SMF?
                    $sha_passwd = sha1(Util::strtolower($_POST['user']) . $_POST['passwrd']);
                    $valid_password = $sha_passwd === $password;
                    // Lets upgrade this to our new password
                    if ($valid_password) {
                        $password = validateLoginPassword($_POST['passwrd'], '', $_POST['user'], true);
                        $password_salt = substr(md5(mt_rand()), 0, 4);
                        // Update the password hash and set up the salt.
                        updateMemberData($id_member, array('passwd' => $password, 'password_salt' => $password_salt, 'passwd_flood' => ''));
                    }
                }
            } else {
                $upcontext['username_incorrect'] = true;
            }
            $db->free_result($request);
        }
        $upcontext['username'] = $_POST['user'];
        // Track whether javascript works!
        if (!empty($_POST['js_works'])) {
            $upcontext['upgrade_status']['js'] = 1;
            $support_js = 1;
        } else {
            $support_js = 0;
        }
        // Note down the version we are coming from.
        if (!empty($modSettings['elkVersion']) && empty($upcontext['user']['version'])) {
            $upcontext['user']['version'] = $modSettings['elkVersion'];
        }
        // Didn't get anywhere?
        if (empty($valid_password) && empty($upcontext['username_incorrect']) && !$disable_security) {
            // MD5?
            $md5pass = md5_hmac($_REQUEST['passwrd'], strtolower($_POST['user']));
            if ($md5pass != $password) {
                $upcontext['password_failed'] = true;
                // Disable the hashing this time.
                $upcontext['disable_login_hashing'] = true;
            }
        }
        if (empty($upcontext['password_failed']) && !empty($name) || $disable_security) {
            // Set the password.
            if (!$disable_security) {
                // Do we actually have permission?
                if (!in_array(1, $groups)) {
                    $request = $db->query('', '
						SELECT permission
						FROM {db_prefix}permissions
						WHERE id_group IN ({array_int:groups})
							AND permission = {string:admin_forum}', array('groups' => $groups, 'admin_forum' => 'admin_forum', 'db_error_skip' => true));
                    if ($db->num_rows($request) == 0) {
                        return throw_error('You need to be an admin to perform an upgrade!');
                    }
                    $db->free_result($request);
                }
                $upcontext['user']['id'] = $id_member;
                $upcontext['user']['name'] = $name;
            } else {
                $upcontext['user']['id'] = 1;
                $upcontext['user']['name'] = 'Administrator';
            }
            $upcontext['user']['pass'] = mt_rand(0, 60000);
            // This basically is used to match the GET variables to Settings.php.
            $upcontext['upgrade_status']['pass'] = $upcontext['user']['pass'];
            // Set the language to that of the user?
            if (isset($user_language) && $user_language != $upcontext['language'] && file_exists($modSettings['theme_dir'] . '/languages/' . basename($user_language, '.lng') . '/index.' . basename($user_language, '.lng') . '.php')) {
                $user_language = basename($user_language, '.lng');
                $temp = substr(@implode('', @file($modSettings['theme_dir'] . '/languages/' . $user_language . '/index.' . $user_language . '.php')), 0, 4096);
                preg_match('~(?://|/\\*)\\s*Version:\\s+(.+?);\\s*index(?:[\\s]{2}|\\*/)~i', $temp, $match);
                if (empty($match[1]) || $match[1] != CURRENT_LANG_VERSION) {
                    $upcontext['upgrade_options_warning'] = 'The language files for your selected language, ' . $user_language . ', have not been updated to the latest version. Upgrade will continue with the forum default, ' . $upcontext['language'] . '.';
                } elseif (!file_exists($modSettings['theme_dir'] . '/languages/' . $user_language . '/Install.' . $user_language . '.php')) {
                    $upcontext['upgrade_options_warning'] = 'The language files for your selected language, ' . $user_language . ', have not been uploaded/updated as the &quot;Install&quot; language file is missing. Upgrade will continue with the forum default, ' . $upcontext['language'] . '.';
                } else {
                    // Set this as the new language.
                    $upcontext['language'] = $user_language;
                    $upcontext['upgrade_status']['lang'] = $upcontext['language'];
                    // Include the file.
                    require_once $modSettings['theme_dir'] . '/languages/' . $user_language . '/Install.' . $user_language . '.php';
                }
            }
            // If we're resuming set the step and substep to be correct.
            if (isset($_POST['cont'])) {
                $upcontext['current_step'] = $upcontext['user']['step'];
                $_GET['substep'] = $upcontext['user']['substep'];
            }
            return true;
        }
    }
    return false;
}
Example #29
0
        if ($role == 3) {
            $res['status'] = '0';
            $res['admin'] = '1';
            echo json_encode($res);
            exit;
        } else {
            $res['status'] = '0';
            $res['admin'] = '0';
            echo json_encode($res);
            exit;
        }
    }
}
if (isset($_GET['news'])) {
    if ($_GET['news'] == 'private') {
        if (validateToken()) {
            $token = $_SERVER['HTTP_AUTHORIZATION'];
            $result = $conn->query("SELECT id FROM users WHERE token = '{$token}'");
            $id = $result->fetch_assoc()['id'];
            $result = $conn->query("SELECT subs_id FROM subs WHERE user_id={$id}");
            $news = [];
            while ($row = $result->fetch_assoc()) {
                $id = $row['subs_id'];
                $result2 = $conn->query("SELECT header,text,common FROM news WHERE user_id={$id}");
                while ($array = $result2->fetch_assoc()) {
                    $news[] = $array;
                }
            }
            $res['status'] = 0;
            $res['news'] = $news;
            echo json_encode($res);
Example #30
0
        $file = R::load('attachment', $data->fileId);
        if ($file->id) {
            $filename = $file->name;
            $before = $item->export();
            unlink('uploads/' . $file->filename);
            R::trash($file);
            R::store($item);
            logAction($actor->username . ' removed attachment ' . $filename . ' from item ' . $item->title, $before, $item, $itemId);
            $jsonResponse->addAlert('success', $filename . ' was deleted.');
            $jsonResponse->addBeans($item);
        }
    }
    $app->response->setBody($jsonResponse->asJson());
})->conditions(['itemId' => '\\d+']);
// Remove an item.
$app->post('/items/remove', function () use($app, $jsonResponse) {
    $data = json_decode($app->environment['slim.input']);
    if (validateToken(true)) {
        $item = R::load('item', $data->itemId);
        if ($item->id) {
            $before = $item->export();
            R::trash($item);
            renumberItems($item->lane_id, $item->position);
            $actor = getUser();
            logAction($actor->username . ' removed item ' . $item->title, $before, null, $data->itemId);
            $jsonResponse->addAlert('success', $item->title . ' was deleted.');
            $jsonResponse->addBeans(getBoards());
        }
    }
    $app->response->setBody($jsonResponse->asJson());
});