Skip to content

Commit

Permalink
Move myphpnet_* functions to the UserPreferences class (#1075)
Browse files Browse the repository at this point in the history
  • Loading branch information
MauricioFauth authored Nov 11, 2024
1 parent 7478275 commit 817a3e7
Show file tree
Hide file tree
Showing 8 changed files with 182 additions and 110 deletions.
2 changes: 1 addition & 1 deletion error.php
Original file line number Diff line number Diff line change
Expand Up @@ -725,7 +725,7 @@
// ============================================================================
// If no match was found till this point, the last action is to start a
// search with the URI the user typed in
$fallback = (myphpnet_urlsearch() === UserPreferences::URL_MANUAL ? "404manual" : "404quickref");
$fallback = ($userPreferences->searchType === UserPreferences::URL_MANUAL ? "404manual" : "404quickref");
mirror_redirect(
'/search.php?show=' . $fallback . '&lang=' . urlencode($LANG) .
'&pattern=' . substr($_SERVER['REQUEST_URI'], 1),
Expand Down
2 changes: 1 addition & 1 deletion include/langchooser.inc
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ $_SERVER['STRIPPED_URI'] = htmlspecialchars($_SERVER['REQUEST_URI'], ENT_QUOTES,

// The code is encapsulated in a function,
// so the variable namespace is not polluted
list($LANG, $EXPL_LANG) = (new LangChooser($LANGUAGES, $INACTIVE_ONLINE_LANGUAGES, myphpnet_language(), default_language() ?: ''))->chooseCode(
list($LANG, $EXPL_LANG) = (new LangChooser($LANGUAGES, $INACTIVE_ONLINE_LANGUAGES, $userPreferences->languageCode, default_language() ?: ''))->chooseCode(
$_REQUEST['lang'] ?? null,
$_SERVER['REQUEST_URI'],
$_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? null,
Expand Down
4 changes: 2 additions & 2 deletions include/layout.inc
Original file line number Diff line number Diff line change
Expand Up @@ -425,13 +425,13 @@ EOT;

function site_header(string $title = 'Hypertext Preprocessor', array $config = []): void
{
global $MYSITE;
global $MYSITE, $LANG;

$meta_image_path = $MYSITE . 'images/meta-image.png';
$meta_description = "PHP is a popular general-purpose scripting language that powers everything from your blog to the most popular websites in the world.";

$defaults = [
"lang" => myphpnet_language(),
"lang" => $LANG,
"current" => "",
"meta-navigation" => [],
'classes' => '',
Expand Down
86 changes: 3 additions & 83 deletions include/prepend.inc
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,10 @@ unset($COUNTRY);
unset($ONLOAD);
unset($LAST_UPDATED);

$userPreferences = new UserPreferences();

// Load the My PHP.net settings before any includes
myphpnet_load();
$userPreferences->load();

// Site details (mirror site information)
include __DIR__ . '/site.inc';
Expand All @@ -97,88 +99,6 @@ include __DIR__ . '/last_updated.inc';

// -----------------------------------------------------------------------------

// Load in the user preferences
function myphpnet_load(): void
{
UserPreferences::$languageCode = '';
UserPreferences::$searchType = UserPreferences::URL_NONE;
UserPreferences::$isUserGroupTipsEnabled = false;

if (!isset($_COOKIE['MYPHPNET']) || !is_string($_COOKIE['MYPHPNET']) || $_COOKIE['MYPHPNET'] === '') {
return;
}

/**
* 0 - Language code
* 1 - URL search fallback
* 2 - Mirror site (removed)
* 3 - User Group tips
* 4 - Documentation developmental server (removed)
*/
$preferences = explode(",", $_COOKIE['MYPHPNET']);
UserPreferences::$languageCode = $preferences[0] ?? '';
if (isset($preferences[1]) && in_array($preferences[1], [UserPreferences::URL_FUNC, UserPreferences::URL_MANUAL], true)) {
UserPreferences::$searchType = $preferences[1];
}

UserPreferences::$isUserGroupTipsEnabled = isset($preferences[3]) && $preferences[3];
}

// Get preferred language code
function myphpnet_language(): string
{
return UserPreferences::$languageCode;
}

// Set URL search fallback preference
function myphpnet_urlsearch($type = false)
{
// Set type if specified and if correct
if ($type && in_array($type, [UserPreferences::URL_FUNC, UserPreferences::URL_MANUAL], true)) {
UserPreferences::$searchType = $type;
}

return UserPreferences::$searchType;
}

function myphpnet_showug($enable = null) {
if (isset($_GET["showug"])) {
$enable = true;
}

if (is_bool($enable)) {
UserPreferences::$isUserGroupTipsEnabled = $enable;
}

// Show the ug tips to lucky few, depending on time.
if ($_SERVER["REQUEST_TIME"] % 10) {
UserPreferences::$isUserGroupTipsEnabled = true;
}

return UserPreferences::$isUserGroupTipsEnabled;
}

// Save user settings in cookie
function myphpnet_save(): void
{
/**
* 0 - Language code
* 1 - URL search fallback
* 2 - Mirror site (removed)
* 3 - User Group tips
* 4 - Documentation developmental server (removed)
*/
$preferences = [
UserPreferences::$languageCode,
UserPreferences::$searchType,
'',
UserPreferences::$isUserGroupTipsEnabled,
];

// Set all the preferred values for a year
mirror_setcookie("MYPHPNET", join(",", $preferences), 60 * 60 * 24 * 365);
}

// Embed Google Custom Search engine
function google_cse(): void {
$cse_snippet = <<<EOF
Expand Down
22 changes: 11 additions & 11 deletions my.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
if (isset($_POST['my_lang'], $langs[$_POST['my_lang']])) {

// Set the language preference
UserPreferences::$languageCode = $_POST['my_lang'];
$userPreferences->languageCode = $_POST['my_lang'];

// Add this as first option, selected
$options[] = '<option value="' . $_POST['my_lang'] . '" selected>' .
Expand All @@ -27,14 +27,14 @@
}

// We have received a cookie and it is an available language
elseif (isset($langs[myphpnet_language()])) {
elseif (isset($langs[$userPreferences->languageCode])) {

// Add this as first option, selected
$options[] = '<option value="' . myphpnet_language() . '" selected>' .
$langs[myphpnet_language()] . "</option>\n";
$options[] = '<option value="' . $userPreferences->languageCode . '" selected>' .
$langs[$userPreferences->languageCode] . "</option>\n";

// Remove, so it is not listed two times
unset($langs[myphpnet_language()]);
unset($langs[$userPreferences->languageCode]);
}

// We have no cookie and no form submitted
Expand All @@ -54,18 +54,18 @@

// Save URL shortcut fallback setting
if (isset($_POST['urlsearch'])) {
myphpnet_urlsearch($_POST['urlsearch']);
$userPreferences->setUrlSearchType($_POST['urlsearch']);
}

if (isset($_POST["showug"])) {
myphpnet_showug($_POST["showug"] === "enable");
$userPreferences->setIsUserGroupTipsEnabled($_POST["showug"] === "enable");
}

// Prepare mirror array
$mirror_sites = $MIRRORS;
$mirror_sites["NONE"] = [7 => MIRROR_OK];

myphpnet_save();
$userPreferences->save();

site_header("My PHP.net", ["current" => "community"]);
?>
Expand Down Expand Up @@ -177,7 +177,7 @@
<div class="indent">
Your setting: <input id="form-urlsearch-quickref" type="radio" name="urlsearch" value="quickref"
<?php
$type = myphpnet_urlsearch();
$type = $userPreferences->searchType;
if ($type === UserPreferences::URL_NONE || $type === UserPreferences::URL_FUNC) {
echo ' checked="checked"';
}
Expand All @@ -196,8 +196,8 @@
We are experimenting with listing nearby user groups. This feature is highly experimental
and will very likely change a lot and be broken at times.
</p>
<label for="showugenable">Enable UG tips</label> <input type="radio" name="showug" id="showugenable" value="enable" <?php echo myphpnet_showug() ? "checked=checked" : "" ?>><br>
<label for="showugdisable">Disable UG tips</label> <input type="radio" name="showug" id="showugdisable" value="disable" <?php echo myphpnet_showug() ? "" : "checked=checked" ?>>
<label for="showugenable">Enable UG tips</label> <input type="radio" name="showug" id="showugenable" value="enable" <?php echo $userPreferences->isUserGroupTipsEnabled ? "checked=checked" : "" ?>><br>
<label for="showugdisable">Disable UG tips</label> <input type="radio" name="showug" id="showugdisable" value="disable" <?php echo $userPreferences->isUserGroupTipsEnabled ? "" : "checked=checked" ?>>

<p class="center">
<input type="submit" value="Set All Preferences">
Expand Down
77 changes: 69 additions & 8 deletions src/UserPreferences.php
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
<?php

declare(strict_types=1);

namespace phpweb;

use function explode;
use function in_array;
use function is_string;
use function join;
use function mirror_setcookie;

/**
* Handles the "My PHP.net" preferences.
*/
Expand All @@ -13,14 +21,67 @@ final class UserPreferences

public const URL_MANUAL = 'manual';

public static string $languageCode = '';
/** @param self::URL_* $searchType URL search fallback */
public function __construct(
public string $languageCode = '',
public string|false $searchType = self::URL_NONE,
public bool $isUserGroupTipsEnabled = false,
) {
}

public function load(): void
{
$this->languageCode = '';
$this->searchType = self::URL_NONE;
$this->isUserGroupTipsEnabled = false;

if (!isset($_COOKIE['MYPHPNET']) || !is_string($_COOKIE['MYPHPNET']) || $_COOKIE['MYPHPNET'] === '') {
return;
}

/**
* 0 - Language code
* 1 - URL search fallback
* 2 - Mirror site (removed)
* 3 - User Group tips
* 4 - Documentation developmental server (removed)
*/
$preferences = explode(",", $_COOKIE['MYPHPNET']);
$this->languageCode = $preferences[0] ?? '';
$this->setUrlSearchType($preferences[1] ?? self::URL_NONE);
$this->isUserGroupTipsEnabled = isset($preferences[3]) && $preferences[3];
}

public function setUrlSearchType(mixed $type): void
{
if (!in_array($type, [self::URL_FUNC, self::URL_MANUAL, self::URL_NONE], true)) {
return;
}

$this->searchType = $type;
}

public function setIsUserGroupTipsEnabled(bool $enable): void {
// Show the ug tips to lucky few, depending on time.
if ($_SERVER["REQUEST_TIME"] % 10) {
$enable = true;
}

$this->isUserGroupTipsEnabled = $enable;
}

/**
* URL search fallback
*
* @var 'manual'|'quickref'|false
*/
public static string|false $searchType = self::URL_NONE;
public function save(): void
{
/**
* 0 - Language code
* 1 - URL search fallback
* 2 - Mirror site (removed)
* 3 - User Group tips
* 4 - Documentation developmental server (removed)
*/
$preferences = [$this->languageCode, $this->searchType, '', $this->isUserGroupTipsEnabled];

public static bool $isUserGroupTipsEnabled = false;
// Set all the preferred values for a year
mirror_setcookie("MYPHPNET", join(",", $preferences), 60 * 60 * 24 * 365);
}
}
5 changes: 1 addition & 4 deletions tests/Unit/LangChooserTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@

use phpweb\LangChooser;
use PHPUnit\Framework;
use phpweb\UserPreferences;

#[Framework\Attributes\CoversClass(LangChooser::class)]
class LangChooserTest extends Framework\TestCase
Expand Down Expand Up @@ -107,9 +106,7 @@ public function testChooseCodeWithLangParameterAndManualPath(): void

public function testChooseCodeWithManualPathAndUserPreference(): void
{
UserPreferences::$languageCode = 'en';

$langChooser = new LangChooser(self::DEFAULT_LANGUAGE_LIST, [], '', 'en');
$langChooser = new LangChooser(self::DEFAULT_LANGUAGE_LIST, [], 'en', 'en');
$result = $langChooser->chooseCode('', '/manual/de', null);

self::assertSame(['de', 'de'], $result);
Expand Down
Loading

0 comments on commit 817a3e7

Please sign in to comment.