diff options
Diffstat (limited to 'classes/pref/prefs.php')
-rw-r--r-- | classes/pref/prefs.php | 920 |
1 files changed, 554 insertions, 366 deletions
diff --git a/classes/pref/prefs.php b/classes/pref/prefs.php index ba63d76b3..16c41df9d 100644 --- a/classes/pref/prefs.php +++ b/classes/pref/prefs.php @@ -1,4 +1,5 @@ <?php +use chillerlan\QRCode; class Pref_Prefs extends Handler_Protected { @@ -7,6 +8,15 @@ class Pref_Prefs extends Handler_Protected { private $pref_help_bottom = []; private $pref_blacklist = []; + const PI_RES_ALREADY_INSTALLED = "PI_RES_ALREADY_INSTALLED"; + const PI_RES_SUCCESS = "PI_RES_SUCCESS"; + const PI_ERR_NO_CLASS = "PI_ERR_NO_CLASS"; + const PI_ERR_NO_INIT_PHP = "PI_ERR_NO_INIT_PHP"; + const PI_ERR_EXEC_FAILED = "PI_ERR_EXEC_FAILED"; + const PI_ERR_NO_TEMPDIR = "PI_ERR_NO_TEMPDIR"; + const PI_ERR_PLUGIN_NOT_FOUND = "PI_ERR_PLUGIN_NOT_FOUND"; + const PI_ERR_NO_WORKDIR = "PI_ERR_NO_WORKDIR"; + function csrf_ignore($method) { $csrf_ignored = array("index", "updateself", "otpqrcode"); @@ -64,6 +74,7 @@ class Pref_Prefs extends Handler_Protected { 'BLOCK_SEPARATOR', Prefs::SSL_CERT_SERIAL, 'BLOCK_SEPARATOR', + Prefs::DISABLE_CONDITIONAL_COUNTERS, Prefs::HEADLINES_NO_DISTINCT, ], __('Debugging') => [ @@ -105,6 +116,7 @@ class Pref_Prefs extends Handler_Protected { Prefs::USER_CSS_THEME => array(__("Theme")), Prefs::HEADLINES_NO_DISTINCT => array(__("Don't enforce DISTINCT headlines"), __("May produce duplicate entries")), Prefs::DEBUG_HEADLINE_IDS => array(__("Show article and feed IDs"), __("In the headlines buffer")), + Prefs::DISABLE_CONDITIONAL_COUNTERS => array(__("Disable conditional counter updates"), __("May increase server load")), ]; // hidden in the main prefs UI (use to hide things that have description set above) @@ -209,48 +221,45 @@ class Pref_Prefs extends Handler_Protected { } } - function changeemail() { + function changePersonalData() { + + $user = ORM::for_table('ttrss_users')->find_one($_SESSION['uid']); + $new_email = clean($_POST['email']); - $email = clean($_POST["email"]); - $full_name = clean($_POST["full_name"]); - $active_uid = $_SESSION["uid"]; + if ($user) { + $user->full_name = clean($_POST['full_name']); - $sth = $this->pdo->prepare("SELECT email, login, full_name FROM ttrss_users WHERE id = ?"); - $sth->execute([$active_uid]); + if ($user->email != $new_email) + Logger::log(E_USER_NOTICE, "Email address of user ".$user->login." has been changed to ${new_email}."); - if ($row = $sth->fetch()) { - $old_email = $row["email"]; + if ($user->email && $user->email != $new_email) { - if ($old_email != $email) { $mailer = new Mailer(); $tpl = new Templator(); $tpl->readTemplateFromFile("mail_change_template.txt"); - $tpl->setVariable('LOGIN', $row["login"]); - $tpl->setVariable('NEWMAIL', $email); + $tpl->setVariable('LOGIN', $user->login); + $tpl->setVariable('NEWMAIL', $new_email); $tpl->setVariable('TTRSS_HOST', Config::get(Config::SELF_URL_PATH)); $tpl->addBlock('message'); $tpl->generateOutputToString($message); - $mailer->mail(["to_name" => $row["login"], - "to_address" => $row["email"], - "subject" => "[tt-rss] Mail address change notification", + $mailer->mail(["to_name" => $user->login, + "to_address" => $user->email, + "subject" => "[tt-rss] Email address change notification", "message" => $message]); + $user->email = $new_email; } - } - $sth = $this->pdo->prepare("UPDATE ttrss_users SET email = ?, - full_name = ? WHERE id = ?"); - $sth->execute([$email, $full_name, $active_uid]); + $user->save(); + } print __("Your personal data has been saved."); - - return; } function resetconfig() { @@ -261,21 +270,13 @@ class Pref_Prefs extends Handler_Protected { private function index_auth_personal() { - $sth = $this->pdo->prepare("SELECT email,full_name,otp_enabled, - access_level FROM ttrss_users - WHERE id = ?"); - $sth->execute([$_SESSION["uid"]]); - $row = $sth->fetch(); - - $email = htmlspecialchars($row["email"]); - $full_name = htmlspecialchars($row["full_name"]); - $otp_enabled = sql_bool_to_bool($row["otp_enabled"]); + $user = ORM::for_table('ttrss_users')->find_one($_SESSION['uid']); ?> <form dojoType='dijit.form.Form'> <?= \Controls\hidden_tag("op", "pref-prefs") ?> - <?= \Controls\hidden_tag("method", "changeemail") ?> + <?= \Controls\hidden_tag("method", "changePersonalData") ?> <script type="dojo/method" event="onSubmit" args="evt"> evt.preventDefault(); @@ -289,18 +290,19 @@ class Pref_Prefs extends Handler_Protected { <fieldset> <label><?= __('Full name:') ?></label> - <input dojoType='dijit.form.ValidationTextBox' name='full_name' required='1' value="<?= $full_name ?>"> + <input dojoType='dijit.form.ValidationTextBox' name='full_name' required='1' value="<?= htmlspecialchars($user->full_name) ?>"> </fieldset> <fieldset> <label><?= __('E-mail:') ?></label> - <input dojoType='dijit.form.ValidationTextBox' name='email' required='1' value="<?= $email ?>"> + <input dojoType='dijit.form.ValidationTextBox' name='email' required='1' value="<?= htmlspecialchars($user->email) ?>"> </fieldset> <hr/> <button dojoType='dijit.form.Button' type='submit' class='alt-primary'> - <?= __("Save data") ?> + <?= \Controls\icon("save") ?> + <?= __("Save") ?> </button> </form> <?php @@ -313,7 +315,7 @@ class Pref_Prefs extends Handler_Protected { $authenticator = false; } - $otp_enabled = $this->is_otp_enabled(); + $otp_enabled = UserHelper::is_otp_enabled($_SESSION["uid"]); if ($authenticator && method_exists($authenticator, "change_password")) { ?> @@ -350,10 +352,6 @@ class Pref_Prefs extends Handler_Protected { } </script> - <?php if ($otp_enabled) { - print_notice(__("Changing your current password will disable OTP.")); - } ?> - <fieldset> <label><?= __("Old password:") ?></label> <input dojoType='dijit.form.ValidationTextBox' type='password' required='1' name='old_password'> @@ -372,6 +370,7 @@ class Pref_Prefs extends Handler_Protected { <hr/> <button dojoType='dijit.form.Button' type='submit' class='alt-primary'> + <?= \Controls\icon("security") ?> <?= __("Change password") ?> </button> </form> @@ -385,7 +384,7 @@ class Pref_Prefs extends Handler_Protected { } private function index_auth_app_passwords() { - print_notice("You can create separate passwords for API clients. Using one is required if you enable OTP."); + print_notice("Separate passwords used for API clients. Required if you enable OTP."); ?> <div id='app_passwords_holder'> @@ -395,31 +394,21 @@ class Pref_Prefs extends Handler_Protected { <hr> <button style='float : left' class='alt-primary' dojoType='dijit.form.Button' onclick="Helpers.AppPasswords.generate()"> - <?= __('Generate new password') ?> + <?= \Controls\icon("add") ?> + <?= __('Generate password') ?> </button> <button style='float : left' class='alt-danger' dojoType='dijit.form.Button' onclick="Helpers.AppPasswords.removeSelected()"> - <?= __('Remove selected passwords') ?> + <?= \Controls\icon("delete") ?> + <?= __('Remove selected') ?> </button> <?php } - private function is_otp_enabled() { - $sth = $this->pdo->prepare("SELECT otp_enabled FROM ttrss_users - WHERE id = ?"); - $sth->execute([$_SESSION["uid"]]); - - if ($row = $sth->fetch()) { - return sql_bool_to_bool($row["otp_enabled"]); - } - - return false; - } - private function index_auth_2fa() { - $otp_enabled = $this->is_otp_enabled(); + $otp_enabled = UserHelper::is_otp_enabled($_SESSION["uid"]); if ($_SESSION["auth_module"] == "auth_internal") { if ($otp_enabled) { @@ -455,6 +444,7 @@ class Pref_Prefs extends Handler_Protected { <hr/> <button dojoType='dijit.form.Button' type='submit' class='alt-danger'> + <?= \Controls\icon("lock_open") ?> <?= __("Disable OTP") ?> </button> @@ -464,19 +454,11 @@ class Pref_Prefs extends Handler_Protected { } else { - print_warning("You will need a compatible Authenticator to use this. Changing your password would automatically disable OTP."); - print_notice("You will need to generate app passwords for the API clients if you enable OTP."); + print "<img src=".($this->_get_otp_qrcode_img()).">"; - if (function_exists("imagecreatefromstring")) { - print "<h3>" . __("Scan the following code by the Authenticator application or copy the key manually") . "</h3>"; - $csrf_token_hash = sha1($_SESSION["csrf_token"]); - print "<img alt='otp qr-code' src='backend.php?op=pref-prefs&method=otpqrcode&csrf_token_hash=$csrf_token_hash'>"; - } else { - print_error("PHP GD functions are required to generate QR codes."); - print "<h3>" . __("Use the following OTP key with a compatible Authenticator application") . "</h3>"; - } + print_notice("You will need to generate app passwords for API clients if you enable OTP."); - $otp_secret = $this->otpsecret(); + $otp_secret = UserHelper::get_otp_secret($_SESSION["uid"]); ?> <form dojoType='dijit.form.Form'> @@ -486,7 +468,7 @@ class Pref_Prefs extends Handler_Protected { <fieldset> <label><?= __("OTP Key:") ?></label> - <input dojoType='dijit.form.ValidationTextBox' disabled='disabled' value="<?= $otp_secret ?>" size='32'> + <input dojoType='dijit.form.ValidationTextBox' disabled='disabled' value="<?= $otp_secret ?>" style='width : 215px'> </fieldset> <!-- TODO: return JSON from the backend call --> @@ -519,6 +501,7 @@ class Pref_Prefs extends Handler_Protected { <hr/> <button dojoType='dijit.form.Button' type='submit' class='alt-primary'> + <?= \Controls\icon("lock") ?> <?= __("Enable OTP") ?> </button> @@ -635,30 +618,27 @@ class Pref_Prefs extends Handler_Protected { } else if ($pref_name == "USER_CSS_THEME") { - $themes = array_merge(glob("themes/*.php"), glob("themes/*.css"), glob("themes.local/*.css")); - $themes = array_map("basename", $themes); - $themes = array_filter($themes, "theme_exists"); - asort($themes); - - if (!theme_exists($value)) $value = ""; + $theme_files = array_map("basename", + array_merge(glob("themes/*.php"), + glob("themes/*.css"), + glob("themes.local/*.css"))); - print "<select name='$pref_name' id='$pref_name' dojoType='fox.form.Select'>"; + asort($theme_files); - $issel = $value == "" ? "selected='selected'" : ""; - print "<option $issel value=''>".__("default")."</option>"; + $themes = [ "" => __("default") ]; - foreach ($themes as $theme) { - $issel = $value == $theme ? "selected='selected'" : ""; - print "<option $issel value='$theme'>$theme</option>"; + foreach ($theme_files as $file) { + $themes[$file] = basename($file, ".css"); } + ?> - print "</select>"; + <?= \Controls\select_hash($pref_name, $value, $themes) ?> + <?= \Controls\button_tag(\Controls\icon("palette") . " " . __("Customize"), "", + ["onclick" => "Helpers.Prefs.customizeCSS()"]) ?> + <?= \Controls\button_tag(\Controls\icon("open_in_new") . " " . __("More themes..."), "", + ["class" => "alt-info", "onclick" => "window.open(\"https://tt-rss.org/wiki/Themes\")"]) ?> - print " <button dojoType=\"dijit.form.Button\" class='alt-info' - onclick=\"Helpers.Prefs.customizeCSS()\">" . __('Customize') . "</button>"; - - print " <button dojoType='dijit.form.Button' onclick='window.open(\"https://tt-rss.org/wiki/Themes\")'> - <i class='material-icons'>open_in_new</i> ".__("More themes...")."</button>"; + <?php } else if ($pref_name == "DEFAULT_UPDATE_INTERVAL") { @@ -685,6 +665,11 @@ class Pref_Prefs extends Handler_Protected { print \Controls\checkbox_tag($pref_name, $is_checked, "true", ["disabled" => $is_disabled], "CB_$pref_name"); + if ($pref_name == Prefs::DIGEST_ENABLE) { + print \Controls\button_tag(\Controls\icon("info") . " " . __('Preview'), '', + ['onclick' => 'Helpers.Digest.preview()', 'style' => 'margin-left : 10px']); + } + } else if (in_array($pref_name, ['FRESH_ARTICLE_MAX_AGE', 'PURGE_OLD_DAYS', 'LONG_DATE_FORMAT', 'SHORT_DATE_FORMAT'])) { @@ -704,14 +689,14 @@ class Pref_Prefs extends Handler_Protected { print \Controls\input_tag($pref_name, $value, "text", ["readonly" => true], "SSL_CERT_SERIAL"); - $cert_serial = htmlspecialchars(get_ssl_certificate_id()); + $cert_serial = htmlspecialchars(self::_get_ssl_certificate_id()); $has_serial = ($cert_serial) ? true : false; - print \Controls\button_tag(__('Register'), "", [ + print \Controls\button_tag(\Controls\icon("security") . " " . __('Register'), "", [ "disabled" => !$has_serial, "onclick" => "dijit.byId('SSL_CERT_SERIAL').attr('value', '$cert_serial')"]); - print \Controls\button_tag(__('Clear'), "", [ + print \Controls\button_tag(\Controls\icon("clear") . " " . __('Clear'), "", [ "class" => "alt-danger", "onclick" => "dijit.byId('SSL_CERT_SERIAL').attr('value', '')"]); @@ -719,11 +704,10 @@ class Pref_Prefs extends Handler_Protected { "class" => "alt-info", "onclick" => "window.open('https://tt-rss.org/wiki/SSL%20Certificate%20Authentication')"]); - } else if ($pref_name == 'DIGEST_PREFERRED_TIME') { + } else if ($pref_name == Prefs::DIGEST_PREFERRED_TIME) { print "<input dojoType=\"dijit.form.ValidationTextBox\" id=\"$pref_name\" regexp=\"[012]?\d:\d\d\" placeHolder=\"12:00\" name=\"$pref_name\" value=\"$value\">"; - $item['help_text'] .= ". " . T_sprintf("Current server time: %s", date("H:i")); } else { $regexp = ($type_hint == Config::T_INT) ? 'regexp="^\d*$"' : ''; @@ -772,19 +756,21 @@ class Pref_Prefs extends Handler_Protected { <div dojoType="dijit.layout.ContentPane" region="bottom"> <div dojoType="fox.form.ComboButton" type="submit" class="alt-primary"> - <span><?= __('Save configuration') ?></span> + <span> <?= __('Save configuration') ?></span> <div dojoType="dijit.DropDownMenu"> <div dojoType="dijit.MenuItem" onclick="dijit.byId('changeSettingsForm').onSubmit(null, true)"> - <?= __("Save and exit preferences") ?> + <?= __("Save and exit") ?> </div> </div> </div> <button dojoType="dijit.form.Button" onclick="return Helpers.Profiles.edit()"> + <?= \Controls\icon("settings") ?> <?= __('Manage profiles') ?> </button> <button dojoType="dijit.form.Button" class="alt-danger" onclick="return Helpers.Prefs.confirmReset()"> + <?= \Controls\icon("clear") ?> <?= __('Reset to defaults') ?> </button> @@ -795,119 +781,73 @@ class Pref_Prefs extends Handler_Protected { <?php } - private function index_plugins_system() { - print_notice("System plugins are enabled in <strong>config.php</strong> for all users."); - - $system_enabled = array_map("trim", explode(",", (string)Config::get(Config::PLUGINS))); - - $tmppluginhost = new PluginHost(); - $tmppluginhost->load_all($tmppluginhost::KIND_ALL, $_SESSION["uid"], true); - - foreach ($tmppluginhost->get_plugins() as $name => $plugin) { - $about = $plugin->about(); - - if ($about[3] ?? false) { - $is_checked = in_array($name, $system_enabled) ? "checked" : ""; - ?> - <fieldset class='prefs plugin'> - <label><?= $name ?>:</label> - <label class='checkbox description text-muted' id="PLABEL-<?= htmlspecialchars($name) ?>"> - <input disabled='1' dojoType='dijit.form.CheckBox' <?= $is_checked ?> type='checkbox'><?= htmlspecialchars($about[1]) ?> - </label> - - <?php if ($about[4] ?? false) { ?> - <button dojoType='dijit.form.Button' class='alt-info' - onclick='window.open("<?= htmlspecialchars($about[4]) ?>")'> - <i class='material-icons'>open_in_new</i> <?= __("More info...") ?></button> - <?php } ?> - - <div dojoType='dijit.Tooltip' connectId='PLABEL-<?= htmlspecialchars($name) ?>' position='after'> - <?= htmlspecialchars(T_sprintf("v%.2f, by %s", $about[0], $about[2])) ?> - </div> - </fieldset> - <?php - } - } - } - - private function index_plugins_user() { + function getPluginsList() { $system_enabled = array_map("trim", explode(",", (string)Config::get(Config::PLUGINS))); $user_enabled = array_map("trim", explode(",", get_pref(Prefs::_ENABLED_PLUGINS))); $tmppluginhost = new PluginHost(); $tmppluginhost->load_all($tmppluginhost::KIND_ALL, $_SESSION["uid"], true); + $rv = []; + foreach ($tmppluginhost->get_plugins() as $name => $plugin) { $about = $plugin->about(); + $is_local = $tmppluginhost->is_local($plugin); + $version = htmlspecialchars($this->_get_plugin_version($plugin)); + + array_push($rv, [ + "name" => $name, + "is_local" => $is_local, + "system_enabled" => in_array($name, $system_enabled), + "user_enabled" => in_array($name, $user_enabled), + "has_data" => count($tmppluginhost->get_all($plugin)) > 0, + "is_system" => (bool)($about[3] ?? false), + "version" => $version, + "author" => $about[2] ?? "", + "description" => $about[1] ?? "", + "more_info" => $about[4] ?? "", + ]); + } - if (empty($about[3]) || $about[3] == false) { - - $is_checked = ""; - $is_disabled = ""; - - if (in_array($name, $system_enabled)) { - $is_checked = "checked='1'"; - $is_disabled = "disabled='1'"; - } else if (in_array($name, $user_enabled)) { - $is_checked = "checked='1'"; - } - - ?> - - <fieldset class='prefs plugin'> - <label><?= $name ?>:</label> - <label class='checkbox description text-muted' id="PLABEL-<?= htmlspecialchars($name) ?>"> - <input name='plugins[]' value="<?= htmlspecialchars($name) ?>" - dojoType='dijit.form.CheckBox' <?= $is_checked ?> <?= $is_disabled ?> type='checkbox'> - <?= htmlspecialchars($about[1]) ?> - </input> - </label> - - <?php if (count($tmppluginhost->get_all($plugin)) > 0) { - if (in_array($name, $system_enabled) || in_array($name, $user_enabled)) { ?> - <button dojoType='dijit.form.Button' - onclick='Helpers.Prefs.clearPluginData("<?= htmlspecialchars($name) ?>")'> - <i class='material-icons'>clear</i> <?= __("Clear data") ?></button> - <?php } - } ?> - - <?php if ($about[4] ?? false) { ?> - <button dojoType='dijit.form.Button' class='alt-info' - onclick='window.open("<?= htmlspecialchars($about[4]) ?>")'> - <i class='material-icons'>open_in_new</i> <?= __("More info...") ?></button> - <?php } ?> - - <div dojoType='dijit.Tooltip' connectId="PLABEL-<?= htmlspecialchars($name) ?>" position='after'> - <?= htmlspecialchars(T_sprintf("v%.2f, by %s", $about[0], $about[2])) ?> - </div> + usort($rv, function($a, $b) { return strcmp($a["name"], $b["name"]); }); - </fieldset> - <?php - } - } + print json_encode(['plugins' => $rv, 'is_admin' => $_SESSION['access_level'] >= 10]); } function index_plugins() { ?> <form dojoType="dijit.form.Form" id="changePluginsForm"> - <script type="dojo/method" event="onSubmit" args="evt"> - evt.preventDefault(); - if (this.validate()) { - xhr.post("backend.php", this.getValues(), () => { - Notify.close(); - if (confirm(__('Selected plugins have been enabled. Reload?'))) { - window.location.reload(); - } - }) - } - </script> <?= \Controls\hidden_tag("op", "pref-prefs") ?> <?= \Controls\hidden_tag("method", "setplugins") ?> <div dojoType="dijit.layout.BorderContainer" gutters="false"> + <div region="top" dojoType='fox.Toolbar'> + <div class='pull-right'> + <input name="search" type="search" onkeyup='Helpers.Plugins.search()' dojoType="dijit.form.TextBox"> + <button dojoType='dijit.form.Button' onclick='Helpers.Plugins.search()'> + <?= __('Search') ?> + </button> + </div> + + <div dojoType='fox.form.DropDownButton'> + <span><?= __('Select') ?></span> + <div dojoType='dijit.Menu' style='display: none'> + <div onclick="Lists.select('prefs-plugin-list', true)" + dojoType='dijit.MenuItem'><?= __('All') ?></div> + <div onclick="Lists.select('prefs-plugin-list', false)" + dojoType='dijit.MenuItem'><?= __('None') ?></div> + </div> + </div> + </div> + <div dojoType="dijit.layout.ContentPane" region="center" style="overflow-y : auto"> - <?php + + <script type="dojo/method" event="onShow"> + Helpers.Plugins.reload(); + </script> + + <!-- <?php if (!empty($_SESSION["safe_mode"])) { print_error("You have logged in using safe mode, no user plugins will be actually enabled until you login again."); } @@ -929,24 +869,41 @@ class Pref_Prefs extends Handler_Protected { ) . " (<a href='https://tt-rss.org/wiki/FeedHandlerPlugins' target='_blank'>".__("More info...")."</a>)" ); } - ?> + ?> --> - <h2><?= __("System plugins") ?></h2> - - <?php $this->index_plugins_system() ?> - - <h2><?= __("User plugins") ?></h2> - - <?php $this->index_plugins_user() ?> + <ul id="prefs-plugin-list" class="prefs-plugin-list list-unstyled"> + <li class='text-center'><?= __("Loading, please wait...") ?></li> + </ul> </div> <div dojoType="dijit.layout.ContentPane" region="bottom"> - <button dojoType='dijit.form.Button' style='float : left' class='alt-info' onclick='window.open("https://tt-rss.org/wiki/Plugins")'> - <i class='material-icons'>help</i> <?= __("More info...") ?> - </button> - <button dojoType='dijit.form.Button' class='alt-primary' type='submit'> - <?= __("Enable selected plugins") ?> + + <button dojoType='dijit.form.Button' class="alt-info pull-right" onclick='window.open("https://tt-rss.org/wiki/Plugins")'> + <i class='material-icons'>help</i> + <?= __("More info") ?> </button> + + <?= \Controls\button_tag(\Controls\icon("check") . " " .__("Enable selected"), "", ["class" => "alt-primary", + "onclick" => "Helpers.Plugins.enableSelected()"]) ?> + + <?= \Controls\button_tag(\Controls\icon("refresh"), "", ["title" => __("Reload"), "onclick" => "Helpers.Plugins.reload()"]) ?> + + <?php if ($_SESSION["access_level"] >= 10) { ?> + <?php if (Config::get(Config::CHECK_FOR_UPDATES) && Config::get(Config::CHECK_FOR_PLUGIN_UPDATES)) { ?> + + <button class='alt-warning' dojoType='dijit.form.Button' onclick="Helpers.Plugins.update()"> + <?= \Controls\icon("update") ?> + <?= __("Check for updates") ?> + </button> + <?php } ?> + + <?php if (Config::get(Config::ENABLE_PLUGIN_INSTALLER)) { ?> + <button dojoType='dijit.form.Button' onclick="Helpers.Plugins.install()"> + <?= \Controls\icon("add") ?> + <?= __("Install plugin") ?> + </button> + <?php } ?> + <?php } ?> </div> </div> </form> @@ -970,120 +927,44 @@ class Pref_Prefs extends Handler_Protected { <div dojoType='dijit.layout.AccordionPane' selected='true' title="<i class='material-icons'>settings</i> <?= __('Preferences') ?>"> <?php $this->index_prefs() ?> </div> - <div dojoType='dijit.layout.AccordionPane' title="<i class='material-icons'>extension</i> <?= __('Plugins') ?>"> - <script type='dojo/method' event='onSelected' args='evt'> - if (this.domNode.querySelector('.loading')) - window.setTimeout(() => { - xhr.post("backend.php", {op: 'pref-prefs', method: 'index_plugins'}, (reply) => { - this.attr('content', reply); - }); - }, 200); - </script> - <span class='loading'><?= __("Loading, please wait...") ?></span> + <div dojoType='dijit.layout.AccordionPane' style='padding : 0' title="<i class='material-icons'>extension</i> <?= __('Plugins') ?>"> + <?php $this->index_plugins() ?> </div> <?php PluginHost::getInstance()->run_hooks(PluginHost::HOOK_PREFS_TAB, "prefPrefs") ?> </div> <?php } - function toggleAdvanced() { - $_SESSION["prefs_show_advanced"] = !$_SESSION["prefs_show_advanced"]; - } - - function otpsecret() { - $sth = $this->pdo->prepare("SELECT salt, otp_enabled - FROM ttrss_users - WHERE id = ?"); - $sth->execute([$_SESSION['uid']]); + function _get_otp_qrcode_img() { + $secret = UserHelper::get_otp_secret($_SESSION["uid"]); + $login = UserHelper::get_login_by_id($_SESSION["uid"]); - if ($row = $sth->fetch()) { - $otp_enabled = sql_bool_to_bool($row["otp_enabled"]); + if ($secret && $login) { + $qrcode = new \chillerlan\QRCode\QRCode(); - if (!$otp_enabled) { - $base32 = new \OTPHP\Base32(); - $secret = $base32->encode(mb_substr(sha1($row["salt"]), 0, 12), false); + $otpurl = "otpauth://totp/".urlencode($login)."?secret=$secret&issuer=".urlencode("Tiny Tiny RSS"); - return $secret; - } + return $qrcode->render($otpurl); } return false; } - function otpqrcode() { - $csrf_token_hash = clean($_REQUEST["csrf_token_hash"]); - - if (sha1($_SESSION["csrf_token"]) === $csrf_token_hash) { - require_once "lib/phpqrcode/phpqrcode.php"; - - $sth = $this->pdo->prepare("SELECT login - FROM ttrss_users - WHERE id = ?"); - $sth->execute([$_SESSION['uid']]); - - if ($row = $sth->fetch()) { - $secret = $this->otpsecret(); - $login = $row['login']; - - if ($secret) { - QRcode::png("otpauth://totp/".urlencode($login). - "?secret=$secret&issuer=".urlencode("Tiny Tiny RSS")); - } - } - } else { - header("Content-Type: text/json"); - print Errors::to_json(Errors::E_UNAUTHORIZED); - } - } - function otpenable() { - $password = clean($_REQUEST["password"]); - $otp = clean($_REQUEST["otp"]); + $otp_check = clean($_REQUEST["otp"]); $authenticator = PluginHost::getInstance()->get_plugin($_SESSION["auth_module"]); if ($authenticator->check_password($_SESSION["uid"], $password)) { - - $secret = $this->otpsecret(); - - if ($secret) { - - $base32 = new \OTPHP\Base32(); - - $topt = new \OTPHP\TOTP($secret); - - $otp_check = $topt->now(); - - if ($otp == $otp_check) { - $sth = $this->pdo->prepare("UPDATE ttrss_users - SET otp_enabled = true WHERE id = ?"); - - $sth->execute([$_SESSION['uid']]); - - print "OK"; - } else { - print "ERROR:".__("Incorrect one time password"); - } + if (UserHelper::enable_otp($_SESSION["uid"], $otp_check)) { + print "OK"; + } else { + print "ERROR:".__("Incorrect one time password"); } - } else { print "ERROR:".__("Incorrect password"); } - - } - - static function isdefaultpassword() { - $authenticator = PluginHost::getInstance()->get_plugin($_SESSION["auth_module"]); - - if ($authenticator && - method_exists($authenticator, "check_password") && - $authenticator->check_password($_SESSION["uid"], "password")) { - - return true; - } - - return false; } function otpdisable() { @@ -1116,9 +997,7 @@ class Pref_Prefs extends Handler_Protected { "message" => $message]); } - $sth = $this->pdo->prepare("UPDATE ttrss_users SET otp_enabled = false WHERE - id = ?"); - $sth->execute([$_SESSION['uid']]); + UserHelper::disable_otp($_SESSION["uid"]); print "OK"; } else { @@ -1128,12 +1007,306 @@ class Pref_Prefs extends Handler_Protected { } function setplugins() { - if (is_array(clean($_REQUEST["plugins"]))) - $plugins = join(",", clean($_REQUEST["plugins"])); - else - $plugins = ""; + $plugins = array_filter($_REQUEST["plugins"], 'clean') ?? []; + + set_pref(Prefs::_ENABLED_PLUGINS, implode(",", $plugins)); + } + + function _get_plugin_version(Plugin $plugin) { + $about = $plugin->about(); + + if (!empty($about[0])) { + return T_sprintf("v%.2f, by %s", $about[0], $about[2]); + } else { + $ref = new ReflectionClass(get_class($plugin)); + + $plugin_dir = dirname($ref->getFileName()); + + if (basename($plugin_dir) == "plugins") { + return ""; + } + + if (is_dir("$plugin_dir/.git")) { + $ver = Config::get_version_from_git($plugin_dir); + + return $ver["status"] == 0 ? T_sprintf("v%s, by %s", $ver["version"], $about[2]) : $ver["version"]; + } + } + } + + static function _get_updated_plugins() { + $root_dir = dirname(dirname(__DIR__)); # we're in classes/pref/ + $plugin_dirs = array_filter(glob("$root_dir/plugins.local/*"), "is_dir"); + + $rv = []; + + foreach ($plugin_dirs as $dir) { + if (is_dir("$dir/.git")) { + $plugin_name = basename($dir); + + array_push($rv, ["plugin" => $plugin_name, "rv" => self::_plugin_needs_update($root_dir, $plugin_name)]); + } + } + + $rv = array_values(array_filter($rv, function ($item) { + return $item["rv"]["need_update"]; + })); + + return $rv; + } + + private static function _plugin_needs_update($root_dir, $plugin_name) { + $plugin_dir = "$root_dir/plugins.local/" . basename($plugin_name); + $rv = null; + + if (is_dir($plugin_dir) && is_dir("$plugin_dir/.git")) { + $pipes = []; + + $descriptorspec = [ + //0 => ["pipe", "r"], // STDIN + 1 => ["pipe", "w"], // STDOUT + 2 => ["pipe", "w"], // STDERR + ]; + + $proc = proc_open("git fetch -q origin -a && git log HEAD..origin/master --oneline", $descriptorspec, $pipes, $plugin_dir); + + if (is_resource($proc)) { + $rv = [ + "stdout" => stream_get_contents($pipes[1]), + "stderr" => stream_get_contents($pipes[2]), + "git_status" => proc_close($proc), + ]; + $rv["need_update"] = !empty($rv["stdout"]); + } + } + + return $rv; + } + + + private function _update_plugin($root_dir, $plugin_name) { + $plugin_dir = "$root_dir/plugins.local/" . basename($plugin_name); + $rv = []; + + if (is_dir($plugin_dir) && is_dir("$plugin_dir/.git")) { + $pipes = []; + + $descriptorspec = [ + //0 => ["pipe", "r"], // STDIN + 1 => ["pipe", "w"], // STDOUT + 2 => ["pipe", "w"], // STDERR + ]; + + $proc = proc_open("git fetch origin -a && git log HEAD..origin/master --oneline && git pull --ff-only origin master", $descriptorspec, $pipes, $plugin_dir); + + if (is_resource($proc)) { + $rv["stdout"] = stream_get_contents($pipes[1]); + $rv["stderr"] = stream_get_contents($pipes[2]); + $rv["git_status"] = proc_close($proc); + } + } + + return $rv; + } + + // https://gist.github.com/mindplay-dk/a4aad91f5a4f1283a5e2#gistcomment-2036828 + private function _recursive_rmdir(string $dir, bool $keep_root = false) { + // Handle bad arguments. + if (empty($dir) || !file_exists($dir)) { + return true; // No such file/dir$dir exists. + } elseif (is_file($dir) || is_link($dir)) { + return unlink($dir); // Delete file/link. + } + + // Delete all children. + $files = new \RecursiveIteratorIterator( + new \RecursiveDirectoryIterator($dir, \RecursiveDirectoryIterator::SKIP_DOTS), + \RecursiveIteratorIterator::CHILD_FIRST + ); + + foreach ($files as $fileinfo) { + $action = $fileinfo->isDir() ? 'rmdir' : 'unlink'; + if (!$action($fileinfo->getRealPath())) { + return false; // Abort due to the failure. + } + } + + return $keep_root ? true : rmdir($dir); + } + + // https://stackoverflow.com/questions/7153000/get-class-name-from-file + private function _get_class_name_from_file($file) { + $tokens = token_get_all(file_get_contents($file)); + + for ($i = 0; $i < count($tokens); $i++) { + if (isset($tokens[$i][0]) && $tokens[$i][0] == T_CLASS) { + for ($j = $i+1; $j < count($tokens); $j++) { + if (isset($tokens[$j][1]) && $tokens[$j][1] != " ") { + return $tokens[$j][1]; + } + } + } + } + } + + function uninstallPlugin() { + if ($_SESSION["access_level"] >= 10) { + $plugin_name = basename(clean($_REQUEST['plugin'])); + $status = 0; + + $plugin_dir = dirname(dirname(__DIR__)) . "/plugins.local/$plugin_name"; + + if (is_dir($plugin_dir)) { + $status = $this->_recursive_rmdir($plugin_dir); + } + + print json_encode(['status' => $status]); + } + } + + function installPlugin() { + if ($_SESSION["access_level"] >= 10 && Config::get(Config::ENABLE_PLUGIN_INSTALLER)) { + $plugin_name = basename(clean($_REQUEST['plugin'])); + $all_plugins = $this->_get_available_plugins(); + $plugin_dir = dirname(dirname(__DIR__)) . "/plugins.local"; + + $work_dir = "$plugin_dir/plugin-installer"; + + $rv = [ ]; + + if (is_dir($work_dir) || mkdir($work_dir)) { + foreach ($all_plugins as $plugin) { + if ($plugin['name'] == $plugin_name) { + + $tmp_dir = tempnam($work_dir, $plugin_name); + + if (file_exists($tmp_dir)) { + unlink($tmp_dir); + + $pipes = []; + + $descriptorspec = [ + 1 => ["pipe", "w"], // STDOUT + 2 => ["pipe", "w"], // STDERR + ]; + + $proc = proc_open("git clone " . escapeshellarg($plugin['clone_url']) . " " . $tmp_dir, + $descriptorspec, $pipes, sys_get_temp_dir()); + + $status = 0; + + if (is_resource($proc)) { + $rv["stdout"] = stream_get_contents($pipes[1]); + $rv["stderr"] = stream_get_contents($pipes[2]); + $status = proc_close($proc); + $rv["git_status"] = $status; + + // yeah I know about mysterious RC = -1 + if (file_exists("$tmp_dir/init.php")) { + $class_name = strtolower(basename($this->_get_class_name_from_file("$tmp_dir/init.php"))); + + if ($class_name) { + $dst_dir = "$plugin_dir/$class_name"; + + if (is_dir($dst_dir)) { + $rv['result'] = self::PI_RES_ALREADY_INSTALLED; + } else { + if (rename($tmp_dir, "$plugin_dir/$class_name")) { + $rv['result'] = self::PI_RES_SUCCESS; + } + } + } else { + $rv['result'] = self::PI_ERR_NO_CLASS; + } + } else { + $rv['result'] = self::PI_ERR_NO_INIT_PHP; + } + + } else { + $rv['result'] = self::PI_ERR_EXEC_FAILED; + } + } else { + $rv['result'] = self::PI_ERR_NO_TEMPDIR; + } + + // cleanup after failure + if ($tmp_dir && is_dir($tmp_dir)) { + $this->_recursive_rmdir($tmp_dir); + } + + break; + } + } + + if (empty($rv['result'])) + $rv['result'] = self::PI_ERR_PLUGIN_NOT_FOUND; + + } else { + $rv["result"] = self::PI_ERR_NO_WORKDIR; + } + + print json_encode($rv); + } + } + + private function _get_available_plugins() { + if ($_SESSION["access_level"] >= 10 && Config::get(Config::ENABLE_PLUGIN_INSTALLER)) { + return json_decode(UrlHelper::fetch(['url' => 'https://tt-rss.org/plugins.json']), true); + } + } + function getAvailablePlugins() { + if ($_SESSION["access_level"] >= 10) { + print json_encode($this->_get_available_plugins()); + } + } + + function checkForPluginUpdates() { + if ($_SESSION["access_level"] >= 10 && Config::get(Config::CHECK_FOR_UPDATES) && Config::get(Config::CHECK_FOR_PLUGIN_UPDATES)) { + $plugin_name = $_REQUEST["name"] ?? ""; + + $root_dir = dirname(dirname(__DIR__)); # we're in classes/pref/ - set_pref(Prefs::_ENABLED_PLUGINS, $plugins); + if (!empty($plugin_name)) { + $rv = [["plugin" => $plugin_name, "rv" => self::_plugin_needs_update($root_dir, $plugin_name)]]; + } else { + $rv = self::_get_updated_plugins(); + } + + print json_encode($rv); + } + } + + function updateLocalPlugins() { + if ($_SESSION["access_level"] >= 10) { + $plugins = explode(",", $_REQUEST["plugins"] ?? ""); + + # we're in classes/pref/ + $root_dir = dirname(dirname(__DIR__)); + + $rv = []; + + if (count($plugins) > 0) { + foreach ($plugins as $plugin_name) { + array_push($rv, ["plugin" => $plugin_name, "rv" => $this->_update_plugin($root_dir, $plugin_name)]); + } + // @phpstan-ignore-next-line + } else { + $plugin_dirs = array_filter(glob("$root_dir/plugins.local/*"), "is_dir"); + + foreach ($plugin_dirs as $dir) { + if (is_dir("$dir/.git")) { + $plugin_name = basename($dir); + + $test = self::_plugin_needs_update($root_dir, $plugin_name); + + if (!empty($test["o"])) + array_push($rv, ["plugin" => $plugin_name, "rv" => $this->_update_plugin($root_dir, $plugin_name)]); + } + } + } + + print json_encode($rv); + } } function clearplugindata() { @@ -1150,66 +1323,61 @@ class Pref_Prefs extends Handler_Protected { } function activateprofile() { - $_SESSION["profile"] = (int) clean($_REQUEST["id"]); + $id = (int) $_REQUEST['id'] ?? 0; + + $profile = ORM::for_table('ttrss_settings_profiles') + ->where('owner_uid', $_SESSION['uid']) + ->find_one($id); - // default value - if (!$_SESSION["profile"]) $_SESSION["profile"] = null; + if ($profile) { + $_SESSION["profile"] = $id; + } else { + $_SESSION["profile"] = null; + } } function remprofiles() { - $ids = explode(",", clean($_REQUEST["ids"])); + $ids = $_REQUEST["ids"] ?? []; - foreach ($ids as $id) { - if ($_SESSION["profile"] != $id) { - $sth = $this->pdo->prepare("DELETE FROM ttrss_settings_profiles WHERE id = ? AND - owner_uid = ?"); - $sth->execute([$id, $_SESSION['uid']]); - } - } + ORM::for_table('ttrss_settings_profiles') + ->where('owner_uid', $_SESSION['uid']) + ->where_in('id', $ids) + ->where_not_equal('id', $_SESSION['profile'] ?? 0) + ->delete_many(); } function addprofile() { $title = clean($_REQUEST["title"]); if ($title) { - $this->pdo->beginTransaction(); - - $sth = $this->pdo->prepare("SELECT id FROM ttrss_settings_profiles - WHERE title = ? AND owner_uid = ?"); - $sth->execute([$title, $_SESSION['uid']]); - - if (!$sth->fetch()) { + $profile = ORM::for_table('ttrss_settings_profiles') + ->where('owner_uid', $_SESSION['uid']) + ->where('title', $title) + ->find_one(); - $sth = $this->pdo->prepare("INSERT INTO ttrss_settings_profiles (title, owner_uid) - VALUES (?, ?)"); + if (!$profile) { + $profile = ORM::for_table('ttrss_settings_profiles')->create(); - $sth->execute([$title, $_SESSION['uid']]); - - $sth = $this->pdo->prepare("SELECT id FROM ttrss_settings_profiles WHERE - title = ? AND owner_uid = ?"); - $sth->execute([$title, $_SESSION['uid']]); + $profile->title = $title; + $profile->owner_uid = $_SESSION['uid']; + $profile->save(); } - - $this->pdo->commit(); } } function saveprofile() { - $id = clean($_REQUEST["id"]); - $title = clean($_REQUEST["title"]); + $id = (int)$_REQUEST["id"]; + $title = clean($_REQUEST["value"]); - if ($id == 0) { - print __("Default profile"); - return; - } - - if ($title) { - $sth = $this->pdo->prepare("UPDATE ttrss_settings_profiles - SET title = ? WHERE id = ? AND - owner_uid = ?"); + if ($title && $id) { + $profile = ORM::for_table('ttrss_settings_profiles') + ->where('owner_uid', $_SESSION['uid']) + ->find_one($id); - $sth->execute([$title, $id, $_SESSION['uid']]); - print $title; + if ($profile) { + $profile->title = $title; + $profile->save(); + } } } @@ -1217,18 +1385,19 @@ class Pref_Prefs extends Handler_Protected { function getProfiles() { $rv = []; - $sth = $this->pdo->prepare("SELECT title,id FROM ttrss_settings_profiles - WHERE owner_uid = ? ORDER BY title"); - $sth->execute([$_SESSION['uid']]); + $profiles = ORM::for_table('ttrss_settings_profiles') + ->where('owner_uid', $_SESSION['uid']) + ->order_by_expr('title') + ->find_many(); array_push($rv, ["title" => __("Default profile"), "id" => 0, "active" => empty($_SESSION["profile"]) ]); - while ($row = $sth->fetch(PDO::FETCH_ASSOC)) { - $row["active"] = isset($_SESSION["profile"]) && $_SESSION["profile"] == $row["id"]; - array_push($rv, $row); + foreach ($profiles as $profile) { + $profile['active'] = ($_SESSION["profile"] ?? 0) == $profile->id; + array_push($rv, $profile->as_array()); }; print json_encode($rv); @@ -1271,23 +1440,25 @@ class Pref_Prefs extends Handler_Protected { <th align='right'><?= __("Last used") ?></th> </tr> <?php - $sth = $this->pdo->prepare("SELECT id, title, created, last_used - FROM ttrss_app_passwords WHERE owner_uid = ?"); - $sth->execute([$_SESSION['uid']]); - while ($row = $sth->fetch()) { ?> - <tr data-row-id='<?= $row['id'] ?>'> + $passwords = ORM::for_table('ttrss_app_passwords') + ->where('owner_uid', $_SESSION['uid']) + ->order_by_asc('title') + ->find_many(); + + foreach ($passwords as $pass) { ?> + <tr data-row-id='<?= $pass['id'] ?>'> <td align='center'> <input onclick='Tables.onRowChecked(this)' dojoType='dijit.form.CheckBox' type='checkbox'> </td> <td> - <?= htmlspecialchars($row["title"]) ?> + <?= htmlspecialchars($pass["title"]) ?> </td> <td align='right' class='text-muted'> - <?= TimeHelper::make_local_datetime($row['created'], false) ?> + <?= TimeHelper::make_local_datetime($pass['created'], false) ?> </td> <td align='right' class='text-muted'> - <?= TimeHelper::make_local_datetime($row['last_used'], false) ?> + <?= TimeHelper::make_local_datetime($pass['last_used'], false) ?> </td> </tr> <?php } ?> @@ -1296,18 +1467,11 @@ class Pref_Prefs extends Handler_Protected { <?php } - private function _encrypt_app_password($password) { - $salt = substr(bin2hex(get_random_bytes(24)), 0, 24); - - return "SSHA-512:".hash('sha512', $salt . $password). ":$salt"; - } - - function deleteAppPassword() { - $ids = explode(",", clean($_REQUEST['ids'])); - $ids_qmarks = arr_qmarks($ids); - - $sth = $this->pdo->prepare("DELETE FROM ttrss_app_passwords WHERE id IN ($ids_qmarks) AND owner_uid = ?"); - $sth->execute(array_merge($ids, [$_SESSION['uid']])); + function deleteAppPasswords() { + $passwords = ORM::for_table('ttrss_app_passwords') + ->where('owner_uid', $_SESSION['uid']) + ->where_in('id', $_REQUEST['ids'] ?? []) + ->delete_many(); $this->appPasswordList(); } @@ -1315,17 +1479,41 @@ class Pref_Prefs extends Handler_Protected { function generateAppPassword() { $title = clean($_REQUEST['title']); $new_password = make_password(16); - $new_password_hash = $this->_encrypt_app_password($new_password); + $new_salt = UserHelper::get_salt(); + $new_password_hash = UserHelper::hash_password($new_password, $new_salt, UserHelper::HASH_ALGOS[0]); print_warning(T_sprintf("Generated password <strong>%s</strong> for %s. Please remember it for future reference.", $new_password, $title)); - $sth = $this->pdo->prepare("INSERT INTO ttrss_app_passwords - (title, pwd_hash, service, created, owner_uid) - VALUES - (?, ?, ?, NOW(), ?)"); + $password = ORM::for_table('ttrss_app_passwords')->create(); - $sth->execute([$title, $new_password_hash, Auth_Base::AUTH_SERVICE_API, $_SESSION['uid']]); + $password->title = $title; + $password->owner_uid = $_SESSION['uid']; + $password->pwd_hash = "$new_password_hash:$new_salt"; + $password->service = Auth_Base::AUTH_SERVICE_API; + $password->created = Db::NOW(); + + $password->save(); $this->appPasswordList(); } + + function previewDigest() { + print json_encode(Digest::prepare_headlines_digest($_SESSION["uid"], 1, 16)); + } + + static function _get_ssl_certificate_id() { + if ($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"] ?? false) { + return sha1($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"] . + $_SERVER["REDIRECT_SSL_CLIENT_V_START"] . + $_SERVER["REDIRECT_SSL_CLIENT_V_END"] . + $_SERVER["REDIRECT_SSL_CLIENT_S_DN"]); + } + if ($_SERVER["SSL_CLIENT_M_SERIAL"] ?? false) { + return sha1($_SERVER["SSL_CLIENT_M_SERIAL"] . + $_SERVER["SSL_CLIENT_V_START"] . + $_SERVER["SSL_CLIENT_V_END"] . + $_SERVER["SSL_CLIENT_S_DN"]); + } + return ""; + } } |