]> git.mxchange.org Git - friendica.git/commitdiff
Merge pull request #7095 from annando/ap-connect
authorHypolite Petovan <hypolite@mrpetovan.com>
Sun, 5 May 2019 13:37:43 +0000 (09:37 -0400)
committerGitHub <noreply@github.com>
Sun, 5 May 2019 13:37:43 +0000 (09:37 -0400)
Switching from legacy DFRN connect to ActivityPub

270 files changed:
include/api.php
mod/_well_known.php [deleted file]
mod/admin.php [deleted file]
mod/allfriends.php [deleted file]
mod/amcd.php [deleted file]
mod/bookmarklet.php [deleted file]
mod/cal.php
mod/dfrn_notify.php
mod/dfrn_poll.php
mod/directory.php [deleted file]
mod/display.php
mod/editpost.php
mod/events.php
mod/fbrowser.php
mod/fetch.php [deleted file]
mod/follow.php
mod/hcard.php
mod/help.php [deleted file]
mod/home.php [deleted file]
mod/hostxrd.php [deleted file]
mod/hovercard.php
mod/invite.php [deleted file]
mod/like.php [deleted file]
mod/lostpass.php
mod/nogroup.php [deleted file]
mod/notice.php
mod/notify.php
mod/opensearch.php
mod/photos.php
mod/phpinfo.php [deleted file]
mod/ping.php
mod/poco.php
mod/poke.php
mod/probe.php
mod/pubsub.php
mod/pubsubhubbub.php
mod/receive.php
mod/rsd_xml.php [deleted file]
mod/salmon.php
mod/search.php
mod/subthread.php
mod/suggest.php
mod/tagger.php
mod/toggle_mobile.php
mod/uexport.php
mod/videos.php
mod/viewcontacts.php
mod/viewsrc.php
mod/webfinger.php [deleted file]
mod/xrd.php [deleted file]
src/App.php
src/App/Router.php
src/BaseModule.php
src/Console/ArchiveContact.php [new file with mode: 0644]
src/Console/AutomaticInstallation.php [new file with mode: 0644]
src/Console/Cache.php [new file with mode: 0644]
src/Console/Config.php [new file with mode: 0644]
src/Console/CreateDoxygen.php [new file with mode: 0644]
src/Console/DatabaseStructure.php [new file with mode: 0644]
src/Console/DocBloxErrorChecker.php [new file with mode: 0644]
src/Console/Extract.php [new file with mode: 0644]
src/Console/GlobalCommunityBlock.php [new file with mode: 0644]
src/Console/GlobalCommunitySilence.php [new file with mode: 0644]
src/Console/Maintenance.php [new file with mode: 0644]
src/Console/NewPassword.php [new file with mode: 0644]
src/Console/PhpToPo.php [new file with mode: 0644]
src/Console/PoToPhp.php [new file with mode: 0644]
src/Console/PostUpdate.php [new file with mode: 0644]
src/Console/ServerBlock.php [new file with mode: 0644]
src/Console/Storage.php [new file with mode: 0644]
src/Console/Typo.php [new file with mode: 0644]
src/Content/Nav.php
src/Content/OEmbed.php
src/Core/Addon.php
src/Core/Console.php
src/Core/Console/ArchiveContact.php [deleted file]
src/Core/Console/AutomaticInstallation.php [deleted file]
src/Core/Console/Cache.php [deleted file]
src/Core/Console/Config.php [deleted file]
src/Core/Console/CreateDoxygen.php [deleted file]
src/Core/Console/DatabaseStructure.php [deleted file]
src/Core/Console/DocBloxErrorChecker.php [deleted file]
src/Core/Console/Extract.php [deleted file]
src/Core/Console/GlobalCommunityBlock.php [deleted file]
src/Core/Console/GlobalCommunitySilence.php [deleted file]
src/Core/Console/Maintenance.php [deleted file]
src/Core/Console/NewPassword.php [deleted file]
src/Core/Console/PhpToPo.php [deleted file]
src/Core/Console/PoToPhp.php [deleted file]
src/Core/Console/PostUpdate.php [deleted file]
src/Core/Console/ServerBlock.php [deleted file]
src/Core/Console/Storage.php [deleted file]
src/Core/Console/Typo.php [deleted file]
src/Core/Renderer.php
src/Core/System.php
src/Core/Theme.php
src/Model/Contact.php
src/Model/Item.php
src/Model/Profile.php
src/Model/Search.php [new file with mode: 0644]
src/Model/User.php
src/Module/AccountManagementControlDocument.php [new file with mode: 0644]
src/Module/Admin/Addons/Details.php [new file with mode: 0644]
src/Module/Admin/Addons/Index.php [new file with mode: 0644]
src/Module/Admin/Blocklist/Contact.php [new file with mode: 0644]
src/Module/Admin/Blocklist/Server.php [new file with mode: 0644]
src/Module/Admin/DBSync.php [new file with mode: 0644]
src/Module/Admin/Features.php [new file with mode: 0644]
src/Module/Admin/Federation.php [new file with mode: 0644]
src/Module/Admin/Item/Delete.php [new file with mode: 0644]
src/Module/Admin/Item/Source.php [new file with mode: 0644]
src/Module/Admin/Logs/Settings.php [new file with mode: 0644]
src/Module/Admin/Logs/View.php [new file with mode: 0644]
src/Module/Admin/PhpInfo.php [new file with mode: 0644]
src/Module/Admin/Queue.php [new file with mode: 0644]
src/Module/Admin/Site.php [new file with mode: 0644]
src/Module/Admin/Summary.php [new file with mode: 0644]
src/Module/Admin/Themes/Details.php [new file with mode: 0644]
src/Module/Admin/Themes/Embed.php [new file with mode: 0644]
src/Module/Admin/Themes/Index.php [new file with mode: 0644]
src/Module/Admin/Tos.php [new file with mode: 0644]
src/Module/Admin/Users.php [new file with mode: 0644]
src/Module/AllFriends.php [new file with mode: 0644]
src/Module/Attach.php
src/Module/BaseAdminModule.php [new file with mode: 0644]
src/Module/BookMarklet.php [new file with mode: 0644]
src/Module/Contact.php
src/Module/Diaspora/Fetch.php [new file with mode: 0644]
src/Module/Directory.php [new file with mode: 0644]
src/Module/Feed.php
src/Module/Filer.php
src/Module/Followers.php
src/Module/Following.php
src/Module/Group.php
src/Module/Help.php [new file with mode: 0644]
src/Module/Home.php [new file with mode: 0644]
src/Module/Inbox.php
src/Module/Install.php
src/Module/Invite.php [new file with mode: 0644]
src/Module/Itemsource.php
src/Module/Like.php [new file with mode: 0644]
src/Module/Manifest.php
src/Module/NodeInfo.php [new file with mode: 0644]
src/Module/Nodeinfo.php [deleted file]
src/Module/Objects.php
src/Module/Oembed.php
src/Module/Outbox.php
src/Module/PageNotFound.php [new file with mode: 0644]
src/Module/Photo.php
src/Module/Profile.php
src/Module/Proxy.php
src/Module/README.md
src/Module/ReallySimpleDiscovery.php [new file with mode: 0644]
src/Module/Register.php
src/Module/Special/HTTPException.php [new file with mode: 0644]
src/Module/Statistics.php [new file with mode: 0644]
src/Module/Statistics_json.php [deleted file]
src/Module/WebFinger.php [new file with mode: 0644]
src/Module/WellKnown/HostMeta.php [new file with mode: 0644]
src/Module/WellKnown/XSocialRelay.php [new file with mode: 0644]
src/Module/Xrd.php [new file with mode: 0644]
src/Network/HTTPException.php
src/Network/HTTPException/AcceptedException.php [new file with mode: 0644]
src/Network/HTTPException/BadGatewayException.php
src/Network/HTTPException/BadRequestException.php
src/Network/HTTPException/ConflictException.php
src/Network/HTTPException/ExpectationFailedException.php
src/Network/HTTPException/ForbiddenException.php
src/Network/HTTPException/GatewayTimeoutException.php
src/Network/HTTPException/GoneException.php
src/Network/HTTPException/ImATeapotException.php
src/Network/HTTPException/InternalServerErrorException.php
src/Network/HTTPException/LenghtRequiredException.php
src/Network/HTTPException/MethodNotAllowedException.php
src/Network/HTTPException/NoContentException.php [new file with mode: 0644]
src/Network/HTTPException/NonAcceptableException.php
src/Network/HTTPException/NotFoundException.php
src/Network/HTTPException/NotImplementedException.php
src/Network/HTTPException/OKException.php [new file with mode: 0644]
src/Network/HTTPException/PreconditionFailedException.php
src/Network/HTTPException/ServiceUnavaiableException.php
src/Network/HTTPException/TooManyRequestsException.php
src/Network/HTTPException/UnauthorizedException.php
src/Network/HTTPException/UnprocessableEntityException.php
src/Network/HTTPException/UnsupportedMediaTypeException.php
src/Protocol/DFRN.php
src/Protocol/Diaspora.php
tests/include/ApiTest.php
tests/src/BaseObjectTest.php
tests/src/Console/AutomaticInstallationConsoleTest.php [new file with mode: 0644]
tests/src/Console/ConfigConsoleTest.php [new file with mode: 0644]
tests/src/Console/ConsoleTest.php [new file with mode: 0644]
tests/src/Console/ServerBlockConsoleTest.php [new file with mode: 0644]
tests/src/Core/Console/AutomaticInstallationConsoleTest.php [deleted file]
tests/src/Core/Console/ConfigConsoleTest.php [deleted file]
tests/src/Core/Console/ConsoleTest.php [deleted file]
tests/src/Core/Console/ServerBlockConsoleTest.php [deleted file]
view/php/minimal.php
view/templates/admin/addon_details.tpl [deleted file]
view/templates/admin/addons.tpl [deleted file]
view/templates/admin/addons/details.tpl [new file with mode: 0644]
view/templates/admin/addons/embed.tpl [new file with mode: 0644]
view/templates/admin/addons/index.tpl [new file with mode: 0644]
view/templates/admin/blocklist.tpl [deleted file]
view/templates/admin/blocklist/contact.tpl [new file with mode: 0644]
view/templates/admin/blocklist/server.tpl [new file with mode: 0644]
view/templates/admin/contactblock.tpl [deleted file]
view/templates/admin/dbsync/failed_updates.tpl [new file with mode: 0644]
view/templates/admin/dbsync/structure_check.tpl [new file with mode: 0644]
view/templates/admin/deleteitem.tpl [deleted file]
view/templates/admin/features.tpl [new file with mode: 0644]
view/templates/admin/item/delete.tpl [new file with mode: 0644]
view/templates/admin/item/source.tpl [new file with mode: 0644]
view/templates/admin/logs.tpl [deleted file]
view/templates/admin/logs/settings.tpl [new file with mode: 0644]
view/templates/admin/logs/view.tpl [new file with mode: 0644]
view/templates/admin/queue.tpl
view/templates/admin/settings_features.tpl [deleted file]
view/templates/admin/site.tpl
view/templates/admin/summary.tpl
view/templates/admin/users.tpl
view/templates/admin/viewlogs.tpl [deleted file]
view/templates/admin/workerqueue.tpl [deleted file]
view/templates/album_edit.tpl
view/templates/debug/itemsource.tpl [deleted file]
view/templates/exception.tpl [new file with mode: 0644]
view/templates/failed_updates.tpl [deleted file]
view/templates/home.tpl
view/templates/photo_album.tpl
view/templates/photo_edit.tpl
view/templates/photo_view.tpl
view/templates/rsd.tpl [new file with mode: 0644]
view/templates/structure_check.tpl [deleted file]
view/templates/webfinger.tpl [new file with mode: 0644]
view/theme/duepuntozero/config.php
view/theme/duepuntozero/style.css
view/theme/frio/config.php
view/theme/frio/css/style.css
view/theme/frio/frameworks/jRange/LICENSE [deleted file]
view/theme/frio/frameworks/jRange/README.md [deleted file]
view/theme/frio/frameworks/jRange/jquery.range-min.js [deleted file]
view/theme/frio/frameworks/jRange/jquery.range.css [deleted file]
view/theme/frio/frameworks/jRange/jquery.range.js [deleted file]
view/theme/frio/frameworks/jRange/jquery.range.less [deleted file]
view/theme/frio/frameworks/jRange/package.json [deleted file]
view/theme/frio/js/filebrowser.js
view/theme/frio/js/mod_photos.js
view/theme/frio/js/modal.js
view/theme/frio/php/default.php
view/theme/frio/php/minimal.php [new file with mode: 0644]
view/theme/frio/templates/admin/addons.tpl [deleted file]
view/theme/frio/templates/admin/aside.tpl
view/theme/frio/templates/admin/blocklist/contact.tpl [new file with mode: 0644]
view/theme/frio/templates/admin/contactblock.tpl [deleted file]
view/theme/frio/templates/admin/queue.tpl
view/theme/frio/templates/admin/site.tpl
view/theme/frio/templates/admin/summary.tpl
view/theme/frio/templates/admin/users.tpl
view/theme/frio/templates/admin/workerqueue.tpl [deleted file]
view/theme/frio/templates/album_edit.tpl
view/theme/frio/templates/confirm.tpl
view/theme/frio/templates/field_colorinput.tpl
view/theme/frio/templates/photo_album.tpl
view/theme/frio/templates/photo_view.tpl
view/theme/frio/templates/theme_settings.tpl
view/theme/quattro/config.php
view/theme/quattro/templates/admin/users.tpl
view/theme/quattro/templates/photo_view.tpl
view/theme/vier/config.php
view/theme/vier/templates/photo_view.tpl

index 698fa2f995766722e4d556a1cc57c6ea9ab3125f..f360dc4116762b916dc0932120f21116ba331f9e 100644 (file)
@@ -364,7 +364,7 @@ function api_call(App $a)
                Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call']);
                throw new NotImplementedException();
        } catch (HTTPException $e) {
-               header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
+               header("HTTP/1.1 {$e->getCode()} {$e->httpdesc}");
                return api_error($type, $e);
        }
 }
@@ -384,7 +384,7 @@ function api_error($type, $e)
        /// @TODO:  https://dev.twitter.com/overview/api/response-codes
 
        $error = ["error" => $error,
-                       "code" => $e->httpcode . " " . $e->httpdesc,
+                       "code" => $e->getCode() . " " . $e->httpdesc,
                        "request" => $a->query_string];
 
        $return = api_format_data('status', $type, ['status' => $error]);
diff --git a/mod/_well_known.php b/mod/_well_known.php
deleted file mode 100644 (file)
index 8e82dab..0000000
+++ /dev/null
@@ -1,82 +0,0 @@
-<?php
-
-use Friendica\App;
-use Friendica\Core\Config;
-use Friendica\Core\System;
-use Friendica\Module\Nodeinfo;
-
-require_once 'mod/hostxrd.php';
-require_once 'mod/xrd.php';
-
-function _well_known_init(App $a)
-{
-       if ($a->argc > 1) {
-               switch ($a->argv[1]) {
-                       case "host-meta":
-                               hostxrd_init($a);
-                               break;
-                       case "x-social-relay":
-                               wk_social_relay();
-                               break;
-                       case "nodeinfo":
-                               Nodeinfo::printWellKnown($a);
-                               break;
-                       case "webfinger":
-                               xrd_init($a);
-                               break;
-               }
-       }
-       System::httpExit(404);
-}
-
-function wk_social_relay()
-{
-       $subscribe = (bool) Config::get('system', 'relay_subscribe', false);
-
-       if ($subscribe) {
-               $scope = Config::get('system', 'relay_scope', SR_SCOPE_ALL);
-       } else {
-               $scope = SR_SCOPE_NONE;
-       }
-
-       $tags = [];
-
-       if ($scope == SR_SCOPE_TAGS) {
-               $server_tags = Config::get('system', 'relay_server_tags');
-               $tagitems = explode(",", $server_tags);
-
-               /// @todo Check if it was better to use "strtolower" on the tags
-               foreach ($tagitems AS $tag) {
-                       $tag = trim($tag, "# ");
-                       $tags[$tag] = $tag;
-               }
-
-               if (Config::get('system', 'relay_user_tags')) {
-                       $terms = q("SELECT DISTINCT(`term`) FROM `search`");
-
-                       foreach ($terms AS $term) {
-                               $tag = trim($term["term"], "#");
-                               $tags[$tag] = $tag;
-                       }
-               }
-       }
-
-       $taglist = [];
-       foreach ($tags AS $tag) {
-               if (!empty($tag)) {
-                       $taglist[] = $tag;
-               }
-       }
-
-       $relay = [
-               'subscribe' => $subscribe,
-               'scope' => $scope,
-               'tags' => $taglist,
-               'protocols' => ['diaspora' => ['receive' => System::baseUrl() . '/receive/public'],
-                       'dfrn' => ['receive' => System::baseUrl() . '/dfrn_notify']]
-       ];
-
-       header('Content-type: application/json; charset=utf-8');
-       echo json_encode($relay, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
-       exit;
-}
diff --git a/mod/admin.php b/mod/admin.php
deleted file mode 100644 (file)
index 22bb662..0000000
+++ /dev/null
@@ -1,2667 +0,0 @@
-<?php
-/**
- * @file mod/admin.php
- *
- * @brief Friendica admin
- */
-
-use Friendica\App;
-use Friendica\BaseModule;
-use Friendica\Content\Feature;
-use Friendica\Content\Pager;
-use Friendica\Content\Text\Markdown;
-use Friendica\Core\Addon;
-use Friendica\Core\Config;
-use Friendica\Core\L10n;
-use Friendica\Core\Logger;
-use Friendica\Core\Renderer;
-use Friendica\Core\StorageManager;
-use Friendica\Core\System;
-use Friendica\Core\Theme;
-use Friendica\Core\Update;
-use Friendica\Core\Worker;
-use Friendica\Database\DBA;
-use Friendica\Database\DBStructure;
-use Friendica\Model\Contact;
-use Friendica\Model\Item;
-use Friendica\Model\Register;
-use Friendica\Model\User;
-use Friendica\Module;
-use Friendica\Module\Login;
-use Friendica\Module\Tos;
-use Friendica\Protocol\PortableContact;
-use Friendica\Util\Arrays;
-use Friendica\Util\BasePath;
-use Friendica\Util\BaseURL;
-use Friendica\Util\DateTimeFormat;
-use Friendica\Util\Network;
-use Friendica\Util\Strings;
-use Friendica\Util\Temporal;
-use Psr\Log\LogLevel;
-
-/**
- * Sets the current theme for theme settings pages.
- *
- * This needs to be done before the post() or content() methods are called.
- *
- * @param App $a
- */
-function admin_init(App $a)
-{
-       if ($a->argc > 2 && $a->argv[1] == 'themes') {
-               $theme = $a->argv[2];
-               if (is_file("view/theme/$theme/config.php")) {
-                       $a->setCurrentTheme($theme);
-               }
-       }
-}
-
-/**
- * @brief Process send data from the admin panels subpages
- *
- * This function acts as relay for processing the data send from the subpages
- * of the admin panel. Depending on the 1st parameter of the url (argv[1])
- * specialized functions are called to process the data from the subpages.
- *
- * The function itself does not return anything, but the subsequently function
- * return the HTML for the pages of the admin panel.
- *
- * @param App $a
- * @throws ImagickException
- * @throws \Friendica\Network\HTTPException\InternalServerErrorException
- */
-function admin_post(App $a)
-{
-       if (!is_site_admin()) {
-               return;
-       }
-
-       // do not allow a page manager to access the admin panel at all.
-
-       if (!empty($_SESSION['submanage'])) {
-               return;
-       }
-
-       $return_path = 'admin';
-       if ($a->argc > 1) {
-               switch ($a->argv[1]) {
-                       case 'site':
-                               admin_page_site_post($a);
-                               break;
-                       case 'users':
-                               admin_page_users_post($a);
-                               break;
-                       case 'addons':
-                               if ($a->argc > 2 &&
-                                       is_file("addon/" . $a->argv[2] . "/" . $a->argv[2] . ".php")) {
-                                       include_once "addon/" . $a->argv[2] . "/" . $a->argv[2] . ".php";
-                                       if (function_exists($a->argv[2] . '_addon_admin_post')) {
-                                               $func = $a->argv[2] . '_addon_admin_post';
-                                               $func($a);
-                                       }
-                               }
-                               $return_path = 'admin/addons/' . $a->argv[2];
-                               break;
-                       case 'themes':
-                               if ($a->argc < 2) {
-                                       if ($a->isAjax()) {
-                                               return;
-                                       }
-                                       $a->internalRedirect('admin/');
-                                       return;
-                               }
-
-                               $theme = $a->argv[2];
-                               if (is_file("view/theme/$theme/config.php")) {
-                                       require_once "view/theme/$theme/config.php";
-
-                                       if (function_exists('theme_admin_post')) {
-                                               theme_admin_post($a);
-                                       }
-                               }
-
-                               info(L10n::t('Theme settings updated.'));
-                               if ($a->isAjax()) {
-                                       return;
-                               }
-                               $return_path = 'admin/themes/' . $theme . (!empty($_GET['mode']) ? '?mode=' . $_GET['mode'] : '');
-                               break;
-                       case 'tos':
-                               admin_page_tos_post($a);
-                               break;
-                       case 'features':
-                               admin_page_features_post($a);
-                               break;
-                       case 'logs':
-                               admin_page_logs_post($a);
-                               break;
-                       case 'contactblock':
-                               admin_page_contactblock_post($a);
-                               break;
-                       case 'blocklist':
-                               admin_page_blocklist_post($a);
-                               break;
-                       case 'deleteitem':
-                               admin_page_deleteitem_post($a);
-                               break;
-               }
-       }
-
-       $a->internalRedirect($return_path);
-       return; // NOTREACHED
-}
-
-/**
- * @brief Generates content of the admin panel pages
- *
- * This function generates the content for the admin panel. It consists of the
- * aside menu (same for the entire admin panel) and the code for the soecified
- * subpage of the panel.
- *
- * The structure of the adress is: /admin/subpage/details though "details" is
- * only necessary for some subpages, like themes or addons where it is the name
- * of one theme resp. addon from which the details should be shown. Content for
- * the subpages is generated in separate functions for each of the subpages.
- *
- * The returned string hold the generated HTML code of the page.
- *
- * @param App $a
- * @return string
- * @throws \Friendica\Network\HTTPException\InternalServerErrorException
- */
-function admin_content(App $a)
-{
-       if (!is_site_admin()) {
-               return Login::form();
-       }
-
-       if (!empty($_SESSION['submanage'])) {
-               return "";
-       }
-
-       // APC deactivated, since there are problems with PHP 5.5
-       //if (function_exists("apc_delete")) {
-       // $toDelete = new APCIterator('user', APC_ITER_VALUE);
-       // apc_delete($toDelete);
-       //}
-       // Header stuff
-       $a->page['htmlhead'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate('admin/settings_head.tpl'), []);
-
-       /*
-        * Side bar links
-        */
-       $aside_tools = [];
-       // array(url, name, extra css classes)
-       // not part of $aside to make the template more adjustable
-       $aside_sub = [
-               'information' => [L10n::t('Information'), [
-                       'overview' => ['admin/', L10n::t('Overview'), 'overview'],
-                       'federation'   => ['admin/federation/'  , L10n::t('Federation Statistics'), 'federation']]],
-               'configuration' => [L10n::t('Configuration'), [
-                       'site'         => ['admin/site/'        , L10n::t('Site')                    , 'site'],
-                       'users'        => ['admin/users/'       , L10n::t('Users')                   , 'users'],
-                       'addons'       => ['admin/addons/'      , L10n::t('Addons')                  , 'addons'],
-                       'themes'       => ['admin/themes/'      , L10n::t('Themes')                  , 'themes'],
-                       'features'     => ['admin/features/'    , L10n::t('Additional features')     , 'features'],
-                       'tos'          => ['admin/tos/'         , L10n::t('Terms of Service')        , 'tos']]],
-               'database' => [L10n::t('Database'), [
-                       'dbsync'       => ['admin/dbsync/'      , L10n::t('DB updates')              , 'dbsync'],
-                       'deferred'     => ['admin/deferred/'    , L10n::t('Inspect Deferred Workers'), 'deferred'],
-                       'workerqueue'  => ['admin/workerqueue/' , L10n::t('Inspect worker Queue')    , 'workerqueue']]],
-               'tools' => [L10n::t('Tools'), [
-                       'contactblock' => ['admin/contactblock/', L10n::t('Contact Blocklist')       , 'contactblock'],
-                       'blocklist'    => ['admin/blocklist/'   , L10n::t('Server Blocklist')        , 'blocklist'],
-                       'deleteitem'   => ['admin/deleteitem/'  , L10n::t('Delete Item')             , 'deleteitem'],]],
-               'logs' => [L10n::t('Logs'), [
-                       'logsconfig' => ['admin/logs/', L10n::t('Logs'), 'logs'],
-                       'logsview' => ['admin/viewlogs/', L10n::t('View Logs'), 'viewlogs']
-               ]],
-               'diagnostics' => [L10n::t('Diagnostics'), [
-                       'phpinfo' => ['phpinfo/', L10n::t('PHP Info'), 'phpinfo'],
-                       'probe' => ['probe/', L10n::t('probe address'), 'probe'],
-                       'webfinger' =>['webfinger/', L10n::t('check webfinger'), 'webfinger']
-               ]]
-       ];
-
-       /* get addons admin page */
-
-       $r = q("SELECT `name` FROM `addon` WHERE `plugin_admin` = 1 ORDER BY `name`");
-       $aside_tools['addons_admin'] = [];
-       $addons_admin = [];
-       foreach ($r as $h) {
-               $addon = $h['name'];
-               $aside_tools['addons_admin'][] = ["admin/addons/" . $addon, $addon, "addon"];
-               // temp addons with admin
-               $addons_admin[] = $addon;
-       }
-
-       $t = Renderer::getMarkupTemplate('admin/aside.tpl');
-       $a->page['aside'] .= Renderer::replaceMacros($t, [
-               '$admin' => $aside_tools,
-               '$subpages' => $aside_sub,
-               '$admtxt' => L10n::t('Admin'),
-               '$plugadmtxt' => L10n::t('Addon Features'),
-               '$h_pending' => L10n::t('User registrations waiting for confirmation'),
-               '$admurl' => "admin/"
-       ]);
-
-       // Page content
-       $o = '';
-       // urls
-       if ($a->argc > 1) {
-               switch ($a->argv[1]) {
-                       case 'site':
-                               $o = admin_page_site($a);
-                               break;
-                       case 'users':
-                               $o = admin_page_users($a);
-                               break;
-                       case 'addons':
-                               $o = admin_page_addons($a, $addons_admin);
-                               break;
-                       case 'themes':
-                               $o = admin_page_themes($a);
-                               break;
-                       case 'features':
-                               $o = admin_page_features($a);
-                               break;
-                       case 'logs':
-                               $o = admin_page_logs($a);
-                               break;
-                       case 'viewlogs':
-                               $o = admin_page_viewlogs($a);
-                               break;
-                       case 'dbsync':
-                               $o = admin_page_dbsync($a);
-                               break;
-                       case 'deferred':
-                               $o = admin_page_workerqueue($a, true);
-                               break;
-                       case 'workerqueue':
-                               $o = admin_page_workerqueue($a, false);
-                               break;
-                       case 'federation':
-                               $o = admin_page_federation($a);
-                               break;
-                       case 'contactblock':
-                               $o = admin_page_contactblock($a);
-                               break;
-                       case 'blocklist':
-                               $o = admin_page_blocklist($a);
-                               break;
-                       case 'deleteitem':
-                               $o = admin_page_deleteitem($a);
-                               break;
-                       case 'tos':
-                               $o = admin_page_tos($a);
-                               break;
-                       default:
-                               notice(L10n::t("Item not found."));
-               }
-       } else {
-               $o = admin_page_summary($a);
-       }
-
-       if ($a->isAjax()) {
-               echo $o;
-               exit();
-       } else {
-               return $o;
-       }
-}
-
-/**
- * @brief Subpage to define the display of a Terms of Usage page.
- *
- * @param App $a
- * @return string
- * @throws \Friendica\Network\HTTPException\InternalServerErrorException
- */
-function admin_page_tos(App $a)
-{
-       $tos = new Tos();
-       $t = Renderer::getMarkupTemplate('admin/tos.tpl');
-       return Renderer::replaceMacros($t, [
-               '$title' => L10n::t('Administration'),
-               '$page' => L10n::t('Terms of Service'),
-               '$displaytos' => ['displaytos', L10n::t('Display Terms of Service'), Config::get('system', 'tosdisplay'), L10n::t('Enable the Terms of Service page. If this is enabled a link to the terms will be added to the registration form and the general information page.')],
-               '$displayprivstatement' => ['displayprivstatement', L10n::t('Display Privacy Statement'), Config::get('system', 'tosprivstatement'), L10n::t('Show some informations regarding the needed information to operate the node according e.g. to <a href="%s" target="_blank">EU-GDPR</a>.', 'https://en.wikipedia.org/wiki/General_Data_Protection_Regulation')],
-               '$preview' => L10n::t('Privacy Statement Preview'),
-               '$privtext' => $tos->privacy_complete,
-               '$tostext' => ['tostext', L10n::t('The Terms of Service'), Config::get('system', 'tostext'), L10n::t('Enter the Terms of Service for your node here. You can use BBCode. Headers of sections should be [h2] and below.')],
-               '$form_security_token' => BaseModule::getFormSecurityToken("admin_tos"),
-               '$submit' => L10n::t('Save Settings'),
-       ]);
-}
-
-/**
- * @brief Process send data from Admin TOS Page
- *
- * @param App $a
- * @throws \Friendica\Network\HTTPException\InternalServerErrorException
- */
-function admin_page_tos_post(App $a)
-{
-       BaseModule::checkFormSecurityTokenRedirectOnError('/admin/tos', 'admin_tos');
-
-       if (empty($_POST['page_tos'])) {
-               return;
-       }
-
-       $displaytos = !empty($_POST['displaytos']);
-       $displayprivstatement = !empty($_POST['displayprivstatement']);
-       $tostext = (!empty($_POST['tostext']) ? strip_tags(trim($_POST['tostext'])) : '');
-
-       Config::set('system', 'tosdisplay', $displaytos);
-       Config::set('system', 'tosprivstatement', $displayprivstatement);
-       Config::set('system', 'tostext', $tostext);
-
-       $a->internalRedirect('admin/tos');
-
-       return; // NOTREACHED
-}
-
-/**
- * @brief Subpage to modify the server wide block list via the admin panel.
- *
- * This function generates the subpage of the admin panel to allow the
- * modification of the node wide block/black list to block entire
- * remote servers from communication with this node. The page allows
- * adding, removing and editing of entries from the blocklist.
- *
- * @param App $a
- * @return string
- * @throws \Friendica\Network\HTTPException\InternalServerErrorException
- */
-function admin_page_blocklist(App $a)
-{
-       $blocklist = Config::get('system', 'blocklist');
-       $blocklistform = [];
-       if (is_array($blocklist)) {
-               foreach ($blocklist as $id => $b) {
-                       $blocklistform[] = [
-                               'domain' => ["domain[$id]", L10n::t('Blocked domain'), $b['domain'], '', L10n::t('The blocked domain'), 'required', '', ''],
-                               'reason' => ["reason[$id]", L10n::t("Reason for the block"), $b['reason'], L10n::t('The reason why you blocked this domain.') . '(' . $b['domain'] . ')', 'required', '', ''],
-                               'delete' => ["delete[$id]", L10n::t("Delete domain") . ' (' . $b['domain'] . ')', false, L10n::t("Check to delete this entry from the blocklist")]
-                       ];
-               }
-       }
-       $t = Renderer::getMarkupTemplate('admin/blocklist.tpl');
-       return Renderer::replaceMacros($t, [
-               '$title' => L10n::t('Administration'),
-               '$page' => L10n::t('Server Blocklist'),
-               '$intro' => L10n::t('This page can be used to define a black list of servers from the federated network that are not allowed to interact with your node. For all entered domains you should also give a reason why you have blocked the remote server.'),
-               '$public' => L10n::t('The list of blocked servers will be made publically available on the /friendica page so that your users and people investigating communication problems can find the reason easily.'),
-               '$addtitle' => L10n::t('Add new entry to block list'),
-               '$newdomain' => ['newentry_domain', L10n::t('Server Domain'), '', L10n::t('The domain of the new server to add to the block list. Do not include the protocol.'), 'required', '', ''],
-               '$newreason' => ['newentry_reason', L10n::t('Block reason'), '', L10n::t('The reason why you blocked this domain.'), 'required', '', ''],
-               '$submit' => L10n::t('Add Entry'),
-               '$savechanges' => L10n::t('Save changes to the blocklist'),
-               '$currenttitle' => L10n::t('Current Entries in the Blocklist'),
-               '$thurl' => L10n::t('Blocked domain'),
-               '$threason' => L10n::t('Reason for the block'),
-               '$delentry' => L10n::t('Delete entry from blocklist'),
-               '$entries' => $blocklistform,
-               '$baseurl' => System::baseUrl(true),
-               '$confirm_delete' => L10n::t('Delete entry from blocklist?'),
-               '$form_security_token' => BaseModule::getFormSecurityToken("admin_blocklist")
-       ]);
-}
-
-/**
- * @brief Process send data from Admin Blocklist Page
- *
- * @param App $a
- * @throws \Friendica\Network\HTTPException\InternalServerErrorException
- */
-function admin_page_blocklist_post(App $a)
-{
-       if (empty($_POST['page_blocklist_save']) && empty($_POST['page_blocklist_edit'])) {
-               return;
-       }
-
-       BaseModule::checkFormSecurityTokenRedirectOnError('/admin/blocklist', 'admin_blocklist');
-
-       if (!empty($_POST['page_blocklist_save'])) {
-               //  Add new item to blocklist
-               $blocklist = Config::get('system', 'blocklist');
-               $blocklist[] = [
-                       'domain' => Strings::escapeTags(trim($_POST['newentry_domain'])),
-                       'reason' => Strings::escapeTags(trim($_POST['newentry_reason']))
-               ];
-               Config::set('system', 'blocklist', $blocklist);
-               info(L10n::t('Server added to blocklist.') . EOL);
-       } else {
-               // Edit the entries from blocklist
-               $blocklist = [];
-               foreach ($_POST['domain'] as $id => $domain) {
-                       // Trimming whitespaces as well as any lingering slashes
-                       $domain = Strings::escapeTags(trim($domain, "\x00..\x1F/"));
-                       $reason = Strings::escapeTags(trim($_POST['reason'][$id]));
-                       if (empty($_POST['delete'][$id])) {
-                               $blocklist[] = [
-                                       'domain' => $domain,
-                                       'reason' => $reason
-                               ];
-                       }
-               }
-               Config::set('system', 'blocklist', $blocklist);
-               info(L10n::t('Site blocklist updated.') . EOL);
-       }
-       $a->internalRedirect('admin/blocklist');
-
-       return; // NOTREACHED
-}
-
-/**
- * @brief Process data send by the contact block admin page
- *
- * @param App $a
- * @throws ImagickException
- * @throws \Friendica\Network\HTTPException\InternalServerErrorException
- */
-function admin_page_contactblock_post(App $a)
-{
-       $contact_url = defaults($_POST, 'contact_url', '');
-       $contacts    = defaults($_POST, 'contacts', []);
-
-       BaseModule::checkFormSecurityTokenRedirectOnError('/admin/contactblock', 'admin_contactblock');
-
-       if (!empty($_POST['page_contactblock_block'])) {
-               $contact_id = Contact::getIdForURL($contact_url);
-               if ($contact_id) {
-                       Contact::block($contact_id);
-                       notice(L10n::t('The contact has been blocked from the node'));
-               } else {
-                       notice(L10n::t("Could not find any contact entry for this URL \x28%s\x29", $contact_url));
-               }
-       }
-       if (!empty($_POST['page_contactblock_unblock'])) {
-               foreach ($contacts as $uid) {
-                       Contact::unblock($uid);
-               }
-               notice(L10n::tt("%s contact unblocked", "%s contacts unblocked", count($contacts)));
-       }
-       $a->internalRedirect('admin/contactblock');
-       return; // NOTREACHED
-}
-
-/**
- * @brief Admin panel for server-wide contact block
- *
- * @param App $a
- * @return string
- * @throws \Friendica\Network\HTTPException\InternalServerErrorException
- */
-function admin_page_contactblock(App $a)
-{
-       $condition = ['uid' => 0, 'blocked' => true];
-
-       $total = DBA::count('contact', $condition);
-
-       $pager = new Pager($a->query_string, 30);
-
-       $statement = DBA::select('contact', [], $condition, ['limit' => [$pager->getStart(), $pager->getItemsPerPage()]]);
-
-       $contacts = DBA::toArray($statement);
-
-       $t = Renderer::getMarkupTemplate('admin/contactblock.tpl');
-       $o = Renderer::replaceMacros($t, [
-               // strings //
-               '$title'       => L10n::t('Administration'),
-               '$page'        => L10n::t('Remote Contact Blocklist'),
-               '$description' => L10n::t('This page allows you to prevent any message from a remote contact to reach your node.'),
-               '$submit'      => L10n::t('Block Remote Contact'),
-               '$select_all'  => L10n::t('select all'),
-               '$select_none' => L10n::t('select none'),
-               '$block'       => L10n::t('Block'),
-               '$unblock'     => L10n::t('Unblock'),
-               '$no_data'     => L10n::t('No remote contact is blocked from this node.'),
-
-               '$h_contacts'  => L10n::t('Blocked Remote Contacts'),
-               '$h_newblock'  => L10n::t('Block New Remote Contact'),
-               '$th_contacts' => [L10n::t('Photo'), L10n::t('Name'), L10n::t('Address'), L10n::t('Profile URL')],
-
-               '$form_security_token' => BaseModule::getFormSecurityToken("admin_contactblock"),
-
-               // values //
-               '$baseurl'    => System::baseUrl(true),
-
-               '$contacts'   => $contacts,
-               '$total_contacts' => L10n::tt('%s total blocked contact', '%s total blocked contacts', $total),
-               '$paginate'   => $pager->renderFull($total),
-               '$contacturl' => ['contact_url', L10n::t("Profile URL"), '', L10n::t("URL of the remote contact to block.")],
-       ]);
-       return $o;
-}
-
-/**
- * @brief Subpage where the admin can delete an item from their node given the GUID
- *
- * This subpage of the admin panel offers the nodes admin to delete an item from
- * the node, given the GUID or the display URL such as http://example.com/display/123456.
- * The item will then be marked as deleted in the database and processed accordingly.
- *
- * @param App $a
- * @return string
- * @throws \Friendica\Network\HTTPException\InternalServerErrorException
- */
-function admin_page_deleteitem(App $a)
-{
-       $t = Renderer::getMarkupTemplate('admin/deleteitem.tpl');
-
-       return Renderer::replaceMacros($t, [
-               '$title' => L10n::t('Administration'),
-               '$page' => L10n::t('Delete Item'),
-               '$submit' => L10n::t('Delete this Item'),
-               '$intro1' => L10n::t('On this page you can delete an item from your node. If the item is a top level posting, the entire thread will be deleted.'),
-               '$intro2' => L10n::t('You need to know the GUID of the item. You can find it e.g. by looking at the display URL. The last part of http://example.com/display/123456 is the GUID, here 123456.'),
-               '$deleteitemguid' => ['deleteitemguid', L10n::t("GUID"), '', L10n::t("The GUID of the item you want to delete."), 'required', 'autofocus'],
-               '$baseurl' => System::baseUrl(),
-               '$form_security_token' => BaseModule::getFormSecurityToken("admin_deleteitem")
-       ]);
-}
-
-/**
- * @brief Process send data from Admin Delete Item Page
- *
- * The GUID passed through the form should be only the GUID. But we also parse
- * URLs like the full /display URL to make the process more easy for the admin.
- *
- * @param App $a
- * @throws \Friendica\Network\HTTPException\InternalServerErrorException
- */
-function admin_page_deleteitem_post(App $a)
-{
-       if (empty($_POST['page_deleteitem_submit'])) {
-               return;
-       }
-
-       BaseModule::checkFormSecurityTokenRedirectOnError('/admin/deleteitem/', 'admin_deleteitem');
-
-       if (!empty($_POST['page_deleteitem_submit'])) {
-               $guid = trim(Strings::escapeTags($_POST['deleteitemguid']));
-               // The GUID should not include a "/", so if there is one, we got an URL
-               // and the last part of it is most likely the GUID.
-               if (strpos($guid, '/')) {
-                       $guid = substr($guid, strrpos($guid, '/') + 1);
-               }
-               // Now that we have the GUID, drop those items, which will also delete the
-               // associated threads.
-               Item::delete(['guid' => $guid]);
-       }
-
-       info(L10n::t('Item marked for deletion.') . EOL);
-       $a->internalRedirect('admin/deleteitem');
-       return; // NOTREACHED
-}
-
-/**
- * @brief Subpage with some stats about "the federation" network
- *
- * This function generates the "Federation Statistics" subpage for the admin
- * panel. The page lists some numbers to the part of "The Federation" known to
- * the node. This data includes the different connected networks (e.g.
- * Diaspora, Hubzilla, GNU Social) and the used versions in the different
- * networks.
- *
- * The returned string contains the HTML code of the subpage for display.
- *
- * @param App $a
- * @return string
- * @throws \Friendica\Network\HTTPException\InternalServerErrorException
- */
-function admin_page_federation(App $a)
-{
-       // get counts on active friendica, diaspora, redmatrix, hubzilla, gnu
-       // social and statusnet nodes this node is knowing
-       //
-       // We are looking for the following platforms in the DB, "Red" should find
-       // all variants of that platform ID string as the q() function is stripping
-       // off one % two of them are needed in the query
-       // Add more platforms if you like, when one returns 0 known nodes it is not
-       // displayed on the stats page.
-       $platforms = ['Friendi%%a', 'Diaspora', '%%red%%', 'Hubzilla', 'BlaBlaNet', 'GNU Social', 'StatusNet', 'Mastodon', 'Pleroma', 'socialhome', 'ganggo'];
-       $colors = [
-               'Friendi%%a' => '#ffc018', // orange from the logo
-               'Diaspora'   => '#a1a1a1', // logo is black and white, makes a gray
-               '%%red%%'    => '#c50001', // fire red from the logo
-               'Hubzilla'   => '#43488a', // blue from the logo
-               'BlaBlaNet'  => '#3B5998', // blue from the navbar at blablanet-dot-com
-               'GNU Social' => '#a22430', // dark red from the logo
-               'StatusNet'  => '#789240', // the green from the logo (red and blue have already others
-               'Mastodon'   => '#1a9df9', // blue from the Mastodon logo
-               'Pleroma'    => '#E46F0F', // Orange from the text that is used on Pleroma instances
-               'socialhome' => '#52056b' , // lilac from the Django Image used at the Socialhome homepage
-               'ganggo'     => '#69d7e2' // from the favicon
-       ];
-       $counts = [];
-       $total = 0;
-       $users = 0;
-
-       foreach ($platforms as $p) {
-               // get a total count for the platform, the name and version of the
-               // highest version and the protocol tpe
-               $c = q('SELECT COUNT(*) AS `total`, SUM(`registered-users`) AS `users`, ANY_VALUE(`platform`) AS `platform`,
-                               ANY_VALUE(`network`) AS `network`, MAX(`version`) AS `version` FROM `gserver`
-                               WHERE `platform` LIKE "%s" AND `last_contact` >= `last_failure`
-                               ORDER BY `version` ASC;', $p);
-               $total += $c[0]['total'];
-               $users += $c[0]['users'];
-
-               // what versions for that platform do we know at all?
-               // again only the active nodes
-               $v = q('SELECT COUNT(*) AS `total`, `version` FROM `gserver`
-                               WHERE `last_contact` >= `last_failure` AND `platform` LIKE "%s"
-                               GROUP BY `version`
-                               ORDER BY `version`;', $p);
-
-               //
-               // clean up version numbers
-               //
-               // some platforms do not provide version information, add a unkown there
-               // to the version string for the displayed list.
-               foreach ($v as $key => $value) {
-                       if ($v[$key]['version'] == '') {
-                               $v[$key] = ['total' => $v[$key]['total'], 'version' => L10n::t('unknown')];
-                       }
-               }
-
-               // Reformat and compact version numbers
-               if ($p == 'Pleroma') {
-                       $compacted = [];
-
-                       foreach ($v as $key => $value) {
-                               $version = $v[$key]['version'];
-                               $parts = explode(' ', trim($version));
-                               do {
-                                       $part = array_pop($parts);
-                               } while (!empty($parts) && ((strlen($part) >= 40) || (strlen($part) <= 3)));
-                               // only take the x.x.x part of the version, not the "release" after the dash
-                               $part = array_shift(explode('-', $part));
-
-                               if (!empty($part)) {
-                                       if (empty($compacted[$part])) {
-                                               $compacted[$part] = $v[$key]['total'];
-                                       } else {
-                                               $compacted[$part] += $v[$key]['total'];
-                                       }
-                               }
-                       }
-
-                       $v = [];
-                       foreach ($compacted as $version => $pl_total) {
-                               $v[] = ['version' => $version, 'total' => $pl_total];
-                       }
-               }
-
-               // in the DB the Diaspora versions have the format x.x.x.x-xx the last
-               // part (-xx) should be removed to clean up the versions from the "head
-               // commit" information and combined into a single entry for x.x.x.x
-               if ($p == 'Diaspora') {
-                       $newV = [];
-                       $newVv = [];
-                       foreach ($v as $vv) {
-                               $newVC = $vv['total'];
-                               $newVV = $vv['version'];
-                               $posDash = strpos($newVV, '-');
-                               if ($posDash) {
-                                       $newVV = substr($newVV, 0, $posDash);
-                               }
-                               if (isset($newV[$newVV])) {
-                                       $newV[$newVV] += $newVC;
-                               } else {
-                                       $newV[$newVV] = $newVC;
-                               }
-                       }
-                       foreach ($newV as $key => $value) {
-                               array_push($newVv, ['total' => $value, 'version' => $key]);
-                       }
-                       $v = $newVv;
-               }
-
-               // early friendica versions have the format x.x.xxxx where xxxx is the
-               // DB version stamp; those should be operated out and versions be
-               // conbined
-               if ($p == 'Friendi%%a') {
-                       $newV = [];
-                       $newVv = [];
-                       foreach ($v as $vv) {
-                               $newVC = $vv['total'];
-                               $newVV = $vv['version'];
-                               $lastDot = strrpos($newVV, '.');
-                               $len = strlen($newVV) - 1;
-                               if (($lastDot == $len - 4) && (!strrpos($newVV, '-rc') == $len - 3)) {
-                                       $newVV = substr($newVV, 0, $lastDot);
-                               }
-                               if (isset($newV[$newVV])) {
-                                       $newV[$newVV] += $newVC;
-                               } else {
-                                       $newV[$newVV] = $newVC;
-                               }
-                       }
-                       foreach ($newV as $key => $value) {
-                               array_push($newVv, ['total' => $value, 'version' => $key]);
-                       }
-                       $v = $newVv;
-               }
-
-               // Assure that the versions are sorted correctly
-               $v2 = [];
-               $versions = [];
-               foreach ($v as $vv) {
-                       $version = trim(strip_tags($vv["version"]));
-                       $v2[$version] = $vv;
-                       $versions[] = $version;
-               }
-
-               usort($versions, 'version_compare');
-
-               $v = [];
-               foreach ($versions as $version) {
-                       $v[] = $v2[$version];
-               }
-
-               // the 3rd array item is needed for the JavaScript graphs as JS does
-               // not like some characters in the names of variables...
-               $counts[$p] = [$c[0], $v, str_replace([' ', '%'], '', $p), $colors[$p]];
-       }
-
-       // some helpful text
-       $intro = L10n::t('This page offers you some numbers to the known part of the federated social network your Friendica node is part of. These numbers are not complete but only reflect the part of the network your node is aware of.');
-       $hint = L10n::t('The <em>Auto Discovered Contact Directory</em> feature is not enabled, it will improve the data displayed here.');
-
-       // load the template, replace the macros and return the page content
-       $t = Renderer::getMarkupTemplate('admin/federation.tpl');
-       return Renderer::replaceMacros($t, [
-               '$title' => L10n::t('Administration'),
-               '$page' => L10n::t('Federation Statistics'),
-               '$intro' => $intro,
-               '$hint' => $hint,
-               '$autoactive' => Config::get('system', 'poco_completion'),
-               '$counts' => $counts,
-               '$version' => FRIENDICA_VERSION,
-               '$legendtext' => L10n::t('Currently this node is aware of %d nodes with %d registered users from the following platforms:', $total, $users),
-               '$baseurl' => System::baseUrl(),
-       ]);
-}
-
-/**
- * @brief Admin Inspect Worker Queue Page
- *
- * Generates a page for the admin to have a look into the current queue of
- * worker jobs. Shown are the parameters for the job and its priority.
- *
- * The returned string holds the content of the page.
- *
- * @param App $a
- * @param     $deferred
- * @return string
- * @throws \Friendica\Network\HTTPException\InternalServerErrorException
- */
-function admin_page_workerqueue(App $a, $deferred)
-{
-       // get jobs from the workerqueue table
-       if ($deferred) {
-               $condition = ["NOT `done` AND `next_try` > ?", DateTimeFormat::utcNow()];
-               $sub_title = L10n::t('Inspect Deferred Worker Queue');
-               $info = L10n::t("This page lists the deferred worker jobs. This are jobs that couldn't be executed at the first time.");
-       } else {
-               $condition = ["NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
-               $sub_title = L10n::t('Inspect Worker Queue');
-               $info = L10n::t('This page lists the currently queued worker jobs. These jobs are handled by the worker cronjob you\'ve set up during install.');
-       }
-
-       $entries = DBA::select('workerqueue', ['id', 'parameter', 'created', 'priority'], $condition, ['order' => ['priority']]);
-
-       $r = [];
-       while ($entry = DBA::fetch($entries)) {
-               // fix GH-5469. ref: src/Core/Worker.php:217
-               $entry['parameter'] = Arrays::recursiveImplode(json_decode($entry['parameter'], true), ': ');
-               $entry['created'] = DateTimeFormat::local($entry['created']);
-               $r[] = $entry;
-       }
-       DBA::close($entries);
-
-       $t = Renderer::getMarkupTemplate('admin/workerqueue.tpl');
-       return Renderer::replaceMacros($t, [
-               '$title' => L10n::t('Administration'),
-               '$page' => $sub_title,
-               '$count' => count($r),
-               '$id_header' => L10n::t('ID'),
-               '$param_header' => L10n::t('Job Parameters'),
-               '$created_header' => L10n::t('Created'),
-               '$prio_header' => L10n::t('Priority'),
-               '$info' => $info,
-               '$entries' => $r,
-       ]);
-}
-
-/**
- * @brief Admin Summary Page
- *
- * The summary page is the "start page" of the admin panel. It gives the admin
- * a first overview of the open adminastrative tasks.
- *
- * The returned string contains the HTML content of the generated page.
- *
- * @param App $a
- * @return string
- * @throws \Friendica\Network\HTTPException\InternalServerErrorException
- */
-function admin_page_summary(App $a)
-{
-       // are there MyISAM tables in the DB? If so, trigger a warning message
-       $r = q("SELECT `engine` FROM `information_schema`.`tables` WHERE `engine` = 'myisam' AND `table_schema` = '%s' LIMIT 1", DBA::escape(DBA::databaseName()));
-       $showwarning = false;
-       $warningtext = [];
-       if (DBA::isResult($r)) {
-               $showwarning = true;
-               $warningtext[] = L10n::t('Your DB still runs with MyISAM tables. You should change the engine type to InnoDB. As Friendica will use InnoDB only features in the future, you should change this! See <a href="%s">here</a> for a guide that may be helpful converting the table engines. You may also use the command <tt>php bin/console.php dbstructure toinnodb</tt> of your Friendica installation for an automatic conversion.<br />', 'https://dev.mysql.com/doc/refman/5.7/en/converting-tables-to-innodb.html');
-       }
-       // Check if github.com/friendica/master/VERSION is higher then
-       // the local version of Friendica. Check is opt-in, source may be master or devel branch
-       if (Config::get('system', 'check_new_version_url', 'none') != 'none') {
-               $gitversion = Config::get('system', 'git_friendica_version');
-               if (version_compare(FRIENDICA_VERSION, $gitversion) < 0) {
-                       $warningtext[] = L10n::t('There is a new version of Friendica available for download. Your current version is %1$s, upstream version is %2$s', FRIENDICA_VERSION, $gitversion);
-                       $showwarning = true;
-               }
-       }
-
-       if (Config::get('system', 'dbupdate', DBStructure::UPDATE_NOT_CHECKED) == DBStructure::UPDATE_NOT_CHECKED) {
-               DBStructure::update($a->getBasePath(), false, true);
-       }
-       if (Config::get('system', 'dbupdate') == DBStructure::UPDATE_FAILED) {
-               $showwarning = true;
-               $warningtext[] = L10n::t('The database update failed. Please run "php bin/console.php dbstructure update" from the command line and have a look at the errors that might appear.');
-       }
-       if (Config::get('system', 'update') == Update::FAILED) {
-               $showwarning = true;
-               $warningtext[] = L10n::t('The last update failed. Please run "php bin/console.php dbstructure update" from the command line and have a look at the errors that might appear. (Some of the errors are possibly inside the logfile.)');
-       }
-
-       $last_worker_call = Config::get('system', 'last_worker_execution', false);
-       if (!$last_worker_call) {
-               $showwarning = true;
-               $warningtext[] = L10n::t('The worker was never executed. Please check your database structure!');
-       } elseif ((strtotime(DateTimeFormat::utcNow()) - strtotime($last_worker_call)) > 60 * 60) {
-               $showwarning = true;
-               $warningtext[] = L10n::t('The last worker execution was on %s UTC. This is older than one hour. Please check your crontab settings.', $last_worker_call);
-       }
-
-       // Legacy config file warning
-       if (file_exists('.htconfig.php')) {
-               $showwarning = true;
-               $warningtext[] = L10n::t('Friendica\'s configuration now is stored in config/local.config.php, please copy config/local-sample.config.php and move your config from <code>.htconfig.php</code>. See <a href="%s">the Config help page</a> for help with the transition.', $a->getBaseURL() . '/help/Config');
-       }
-       if (file_exists('config/local.ini.php')) {
-               $showwarning = true;
-               $warningtext[] = L10n::t('Friendica\'s configuration now is stored in config/local.config.php, please copy config/local-sample.config.php and move your config from <code>config/local.ini.php</code>. See <a href="%s">the Config help page</a> for help with the transition.', $a->getBaseURL() . '/help/Config');
-       }
-
-       // Check server vitality
-       if (!admin_page_server_vital()) {
-               $showwarning = true;
-               $well_known = $a->getBaseURL() . '/.well-known/host-meta';
-               $warningtext[] = L10n::t('<a href="%s">%s</a> is not reachable on your system. This is a severe configuration issue that prevents server to server communication. See <a href="%s">the installation page</a> for help.',
-                       $well_known, $well_known, $a->getBaseURL() . '/help/Install');
-       }
-
-       $r = q("SELECT `page-flags`, COUNT(`uid`) AS `count` FROM `user` GROUP BY `page-flags`");
-       $accounts = [
-               [L10n::t('Normal Account'), 0],
-               [L10n::t('Automatic Follower Account'), 0],
-               [L10n::t('Public Forum Account'), 0],
-               [L10n::t('Automatic Friend Account'), 0],
-               [L10n::t('Blog Account'), 0],
-               [L10n::t('Private Forum Account'), 0]
-       ];
-
-       $users = 0;
-       foreach ($r as $u) {
-               $accounts[$u['page-flags']][1] = $u['count'];
-               $users += $u['count'];
-       }
-
-       Logger::log('accounts: ' . print_r($accounts, true), Logger::DATA);
-
-       $pending = Register::getPendingCount();
-
-       $deferred = DBA::count('workerqueue', ["`executed` <= ? AND NOT `done` AND `next_try` > ?",
-               DBA::NULL_DATETIME, DateTimeFormat::utcNow()]);
-
-       $workerqueue = DBA::count('workerqueue', ["`executed` <= ? AND NOT `done` AND `next_try` < ?",
-               DBA::NULL_DATETIME, DateTimeFormat::utcNow()]);
-
-       // We can do better, but this is a quick queue status
-
-       $queues = ['label' => L10n::t('Message queues'), 'deferred' => $deferred, 'workerq' => $workerqueue];
-
-
-       $r = q("SHOW variables LIKE 'max_allowed_packet'");
-       $max_allowed_packet = (($r) ? $r[0]['Value'] : 0);
-
-       $server_settings = ['label' => L10n::t('Server Settings'),
-               'php' => ['upload_max_filesize' => ini_get('upload_max_filesize'),
-                       'post_max_size' => ini_get('post_max_size'),
-                       'memory_limit' => ini_get('memory_limit')],
-               'mysql' => ['max_allowed_packet' => $max_allowed_packet]];
-
-       $t = Renderer::getMarkupTemplate('admin/summary.tpl');
-       return Renderer::replaceMacros($t, [
-               '$title' => L10n::t('Administration'),
-               '$page' => L10n::t('Summary'),
-               '$queues' => $queues,
-               '$users' => [L10n::t('Registered users'), $users],
-               '$accounts' => $accounts,
-               '$pending' => [L10n::t('Pending registrations'), $pending],
-               '$version' => [L10n::t('Version'), FRIENDICA_VERSION],
-               '$baseurl' => System::baseUrl(),
-               '$platform' => FRIENDICA_PLATFORM,
-               '$codename' => FRIENDICA_CODENAME,
-               '$build' => Config::get('system', 'build'),
-               '$addons' => [L10n::t('Active addons'), Addon::getEnabledList()],
-               '$serversettings' => $server_settings,
-               '$showwarning' => $showwarning,
-               '$warningtext' => $warningtext
-       ]);
-}
-
-/**
- * @brief Process send data from Admin Site Page
- *
- * @param App $a
- * @throws \Friendica\Network\HTTPException\InternalServerErrorException
- */
-function admin_page_site_post(App $a)
-{
-       BaseModule::checkFormSecurityTokenRedirectOnError('/admin/site', 'admin_site');
-
-       if (!empty($_POST['republish_directory'])) {
-               Worker::add(PRIORITY_LOW, 'Directory');
-               return;
-       }
-
-       if (empty($_POST['page_site'])) {
-               return;
-       }
-
-       // relocate
-       if (!empty($_POST['relocate']) && !empty($_POST['relocate_url']) && $_POST['relocate_url'] != "") {
-               $new_url = $_POST['relocate_url'];
-               $new_url = rtrim($new_url, "/");
-
-               $parsed = @parse_url($new_url);
-               if (!is_array($parsed) || empty($parsed['host']) || empty($parsed['scheme'])) {
-                       notice(L10n::t("Can not parse base url. Must have at least <scheme>://<domain>"));
-                       $a->internalRedirect('admin/site');
-               }
-
-               /* steps:
-                * replace all "baseurl" to "new_url" in config, profile, term, items and contacts
-                * send relocate for every local user
-                * */
-
-               $old_url = $a->getBaseURL(true);
-
-               // Generate host names for relocation the addresses in the format user@address.tld
-               $new_host = str_replace("http://", "@", Strings::normaliseLink($new_url));
-               $old_host = str_replace("http://", "@", Strings::normaliseLink($old_url));
-
-               function update_table(App $a, $table_name, $fields, $old_url, $new_url)
-               {
-                       $dbold = DBA::escape($old_url);
-                       $dbnew = DBA::escape($new_url);
-
-                       $upd = [];
-                       foreach ($fields as $f) {
-                               $upd[] = "`$f` = REPLACE(`$f`, '$dbold', '$dbnew')";
-                       }
-
-                       $upds = implode(", ", $upd);
-
-                       $r = q("UPDATE %s SET %s;", $table_name, $upds);
-
-                       if (!DBA::isResult($r)) {
-                               notice("Failed updating '$table_name': " . DBA::errorMessage());
-                               $a->internalRedirect('admin/site');
-                       }
-               }
-
-               // update tables
-               // update profile links in the format "http://server.tld"
-               update_table($a, "profile", ['photo', 'thumb'], $old_url, $new_url);
-               update_table($a, "term", ['url'], $old_url, $new_url);
-               update_table($a, "contact", ['photo', 'thumb', 'micro', 'url', 'nurl', 'alias', 'request', 'notify', 'poll', 'confirm', 'poco', 'avatar'], $old_url, $new_url);
-               update_table($a, "gcontact", ['url', 'nurl', 'photo', 'server_url', 'notify', 'alias'], $old_url, $new_url);
-               update_table($a, "item", ['owner-link', 'author-link', 'body', 'plink', 'tag'], $old_url, $new_url);
-
-               // update profile addresses in the format "user@server.tld"
-               update_table($a, "contact", ['addr'], $old_host, $new_host);
-               update_table($a, "gcontact", ['connect', 'addr'], $old_host, $new_host);
-
-               // update config
-               Config::set('system', 'url', $new_url);
-               $a->setBaseURL($new_url);
-
-               // send relocate
-               $users = q("SELECT `uid` FROM `user` WHERE `account_removed` = 0 AND `account_expired` = 0");
-
-               foreach ($users as $user) {
-                       Worker::add(PRIORITY_HIGH, 'Notifier', 'relocate', $user['uid']);
-               }
-
-               info("Relocation started. Could take a while to complete.");
-
-               $a->internalRedirect('admin/site');
-       }
-       // end relocate
-
-       $sitename         = (!empty($_POST['sitename'])         ? Strings::escapeTags(trim($_POST['sitename']))      : '');
-       $sender_email     = (!empty($_POST['sender_email'])     ? Strings::escapeTags(trim($_POST['sender_email']))  : '');
-       $banner           = (!empty($_POST['banner'])           ? trim($_POST['banner'])                             : false);
-       $shortcut_icon    = (!empty($_POST['shortcut_icon'])    ? Strings::escapeTags(trim($_POST['shortcut_icon'])) : '');
-       $touch_icon       = (!empty($_POST['touch_icon'])       ? Strings::escapeTags(trim($_POST['touch_icon']))    : '');
-       $additional_info  = (!empty($_POST['additional_info'])  ? trim($_POST['additional_info'])                    : '');
-       $language         = (!empty($_POST['language'])         ? Strings::escapeTags(trim($_POST['language']))      : '');
-       $theme            = (!empty($_POST['theme'])            ? Strings::escapeTags(trim($_POST['theme']))         : '');
-       $theme_mobile     = (!empty($_POST['theme_mobile'])     ? Strings::escapeTags(trim($_POST['theme_mobile']))  : '');
-       $maximagesize     = (!empty($_POST['maximagesize'])     ? intval(trim($_POST['maximagesize']))               : 0);
-       $maximagelength   = (!empty($_POST['maximagelength'])   ? intval(trim($_POST['maximagelength']))             : MAX_IMAGE_LENGTH);
-       $jpegimagequality = (!empty($_POST['jpegimagequality']) ? intval(trim($_POST['jpegimagequality']))           : JPEG_QUALITY);
-
-       $register_policy        = (!empty($_POST['register_policy'])         ? intval(trim($_POST['register_policy']))             : 0);
-       $daily_registrations    = (!empty($_POST['max_daily_registrations']) ? intval(trim($_POST['max_daily_registrations']))     : 0);
-       $abandon_days           = (!empty($_POST['abandon_days'])            ? intval(trim($_POST['abandon_days']))                : 0);
-
-       $register_text          = (!empty($_POST['register_text'])           ? strip_tags(trim($_POST['register_text']))           : '');
-
-       $allowed_sites          = (!empty($_POST['allowed_sites'])           ? Strings::escapeTags(trim($_POST['allowed_sites']))  : '');
-       $allowed_email          = (!empty($_POST['allowed_email'])           ? Strings::escapeTags(trim($_POST['allowed_email']))  : '');
-       $forbidden_nicknames    = (!empty($_POST['forbidden_nicknames'])     ? strtolower(Strings::escapeTags(trim($_POST['forbidden_nicknames']))) : '');
-       $no_oembed_rich_content = !empty($_POST['no_oembed_rich_content']);
-       $allowed_oembed         = (!empty($_POST['allowed_oembed'])          ? Strings::escapeTags(trim($_POST['allowed_oembed'])) : '');
-       $block_public           = !empty($_POST['block_public']);
-       $force_publish          = !empty($_POST['publish_all']);
-       $global_directory       = (!empty($_POST['directory'])               ? Strings::escapeTags(trim($_POST['directory']))      : '');
-       $newuser_private        = !empty($_POST['newuser_private']);
-       $enotify_no_content     = !empty($_POST['enotify_no_content']);
-       $private_addons         = !empty($_POST['private_addons']);
-       $disable_embedded       = !empty($_POST['disable_embedded']);
-       $allow_users_remote_self = !empty($_POST['allow_users_remote_self']);
-       $explicit_content       = !empty($_POST['explicit_content']);
-
-       $no_multi_reg           = !empty($_POST['no_multi_reg']);
-       $no_openid              = !empty($_POST['no_openid']);
-       $no_regfullname         = !empty($_POST['no_regfullname']);
-       $community_page_style   = (!empty($_POST['community_page_style']) ? intval(trim($_POST['community_page_style'])) : 0);
-       $max_author_posts_community_page = (!empty($_POST['max_author_posts_community_page']) ? intval(trim($_POST['max_author_posts_community_page'])) : 0);
-
-       $verifyssl              = !empty($_POST['verifyssl']);
-       $proxyuser              = (!empty($_POST['proxyuser'])              ? Strings::escapeTags(trim($_POST['proxyuser'])) : '');
-       $proxy                  = (!empty($_POST['proxy'])                  ? Strings::escapeTags(trim($_POST['proxy']))     : '');
-       $timeout                = (!empty($_POST['timeout'])                ? intval(trim($_POST['timeout']))                : 60);
-       $maxloadavg             = (!empty($_POST['maxloadavg'])             ? intval(trim($_POST['maxloadavg']))             : 20);
-       $maxloadavg_frontend    = (!empty($_POST['maxloadavg_frontend'])    ? intval(trim($_POST['maxloadavg_frontend']))    : 50);
-       $min_memory             = (!empty($_POST['min_memory'])             ? intval(trim($_POST['min_memory']))             : 0);
-       $optimize_max_tablesize = (!empty($_POST['optimize_max_tablesize']) ? intval(trim($_POST['optimize_max_tablesize'])) : 100);
-       $optimize_fragmentation = (!empty($_POST['optimize_fragmentation']) ? intval(trim($_POST['optimize_fragmentation'])) : 30);
-       $poco_completion        = (!empty($_POST['poco_completion'])        ? intval(trim($_POST['poco_completion']))        : false);
-       $poco_requery_days      = (!empty($_POST['poco_requery_days'])      ? intval(trim($_POST['poco_requery_days']))      : 7);
-       $poco_discovery         = (!empty($_POST['poco_discovery'])         ? intval(trim($_POST['poco_discovery']))         : PortableContact::DISABLED);
-       $poco_discovery_since   = (!empty($_POST['poco_discovery_since'])   ? intval(trim($_POST['poco_discovery_since']))   : 30);
-       $poco_local_search      = !empty($_POST['poco_local_search']);
-       $nodeinfo               = !empty($_POST['nodeinfo']);
-       $dfrn_only              = !empty($_POST['dfrn_only']);
-       $ostatus_disabled       = !empty($_POST['ostatus_disabled']);
-       $ostatus_full_threads   = !empty($_POST['ostatus_full_threads']);
-       $diaspora_enabled       = !empty($_POST['diaspora_enabled']);
-       $ssl_policy             = (!empty($_POST['ssl_policy'])             ? intval($_POST['ssl_policy'])                    : 0);
-       $force_ssl              = !empty($_POST['force_ssl']);
-       $hide_help              = !empty($_POST['hide_help']);
-       $dbclean                = !empty($_POST['dbclean']);
-       $dbclean_expire_days    = (!empty($_POST['dbclean_expire_days'])    ? intval($_POST['dbclean_expire_days'])           : 0);
-       $dbclean_unclaimed      = (!empty($_POST['dbclean_unclaimed'])      ? intval($_POST['dbclean_unclaimed'])             : 0);
-       $dbclean_expire_conv    = (!empty($_POST['dbclean_expire_conv'])    ? intval($_POST['dbclean_expire_conv'])           : 0);
-       $suppress_tags          = !empty($_POST['suppress_tags']);
-       $itemcache              = (!empty($_POST['itemcache'])              ? Strings::escapeTags(trim($_POST['itemcache']))  : '');
-       $itemcache_duration     = (!empty($_POST['itemcache_duration'])     ? intval($_POST['itemcache_duration'])            : 0);
-       $max_comments           = (!empty($_POST['max_comments'])           ? intval($_POST['max_comments'])                  : 0);
-       $temppath               = (!empty($_POST['temppath'])               ? Strings::escapeTags(trim($_POST['temppath']))   : '');
-       $singleuser             = (!empty($_POST['singleuser'])             ? Strings::escapeTags(trim($_POST['singleuser'])) : '');
-       $proxy_disabled         = !empty($_POST['proxy_disabled']);
-       $only_tag_search        = !empty($_POST['only_tag_search']);
-       $rino                   = (!empty($_POST['rino'])                   ? intval($_POST['rino'])                          : 0);
-       $check_new_version_url  = (!empty($_POST['check_new_version_url'])  ? Strings::escapeTags(trim($_POST['check_new_version_url'])) : 'none');
-
-       $worker_queues    = (!empty($_POST['worker_queues'])                ? intval($_POST['worker_queues'])                 : 10);
-       $worker_dont_fork = !empty($_POST['worker_dont_fork']);
-       $worker_fastlane  = !empty($_POST['worker_fastlane']);
-       $worker_frontend  = !empty($_POST['worker_frontend']);
-
-       $relay_directly    = !empty($_POST['relay_directly']);
-       $relay_server      = (!empty($_POST['relay_server'])      ? Strings::escapeTags(trim($_POST['relay_server']))       : '');
-       $relay_subscribe   = !empty($_POST['relay_subscribe']);
-       $relay_scope       = (!empty($_POST['relay_scope'])       ? Strings::escapeTags(trim($_POST['relay_scope']))        : '');
-       $relay_server_tags = (!empty($_POST['relay_server_tags']) ? Strings::escapeTags(trim($_POST['relay_server_tags']))  : '');
-       $relay_user_tags   = !empty($_POST['relay_user_tags']);
-       $active_panel      = (!empty($_POST['active_panel'])      ? "#" . Strings::escapeTags(trim($_POST['active_panel'])) : '');
-
-       /**
-        * @var $storagebackend \Friendica\Model\Storage\IStorage
-        */
-       $storagebackend    = Strings::escapeTags(trim(defaults($_POST, 'storagebackend', '')));
-
-       // save storage backend form
-       if (!is_null($storagebackend) && $storagebackend != "") {
-               if (StorageManager::setBackend($storagebackend)) {
-                       $storage_opts = $storagebackend::getOptions();
-                       $storage_form_prefix = preg_replace('|[^a-zA-Z0-9]|', '', $storagebackend);
-                       $storage_opts_data = [];
-                       foreach ($storage_opts as $name => $info) {
-                               $fieldname = $storage_form_prefix . '_' . $name;
-                               switch ($info[0]) { // type
-                                       case 'checkbox':
-                                       case 'yesno':
-                                               $value = !empty($_POST[$fieldname]);
-                                               break;
-                                       default:
-                                               $value = defaults($_POST, $fieldname, '');
-                               }
-                               $storage_opts_data[$name] = $value;
-                       }
-                       unset($name);
-                       unset($info);
-
-                       $storage_form_errors = $storagebackend::saveOptions($storage_opts_data);
-                       if (count($storage_form_errors)) {
-                               foreach ($storage_form_errors as $name => $err) {
-                                       notice('Storage backend, ' . $storage_opts[$name][1] . ': ' . $err);
-                               }
-                               $a->internalRedirect('admin/site' . $active_panel);
-                       }
-               } else {
-                       info(L10n::t('Invalid storage backend setting value.'));
-               }
-       }
-
-
-
-       // Has the directory url changed? If yes, then resubmit the existing profiles there
-       if ($global_directory != Config::get('system', 'directory') && ($global_directory != '')) {
-               Config::set('system', 'directory', $global_directory);
-               Worker::add(PRIORITY_LOW, 'Directory');
-       }
-
-       if ($a->getURLPath() != "") {
-               $diaspora_enabled = false;
-       }
-       if ($ssl_policy != intval(Config::get('system', 'ssl_policy'))) {
-               if ($ssl_policy == BaseURL::SSL_POLICY_FULL) {
-                       q("UPDATE `contact` SET
-                               `url`     = REPLACE(`url`    , 'http:' , 'https:'),
-                               `photo`   = REPLACE(`photo`  , 'http:' , 'https:'),
-                               `thumb`   = REPLACE(`thumb`  , 'http:' , 'https:'),
-                               `micro`   = REPLACE(`micro`  , 'http:' , 'https:'),
-                               `request` = REPLACE(`request`, 'http:' , 'https:'),
-                               `notify`  = REPLACE(`notify` , 'http:' , 'https:'),
-                               `poll`    = REPLACE(`poll`   , 'http:' , 'https:'),
-                               `confirm` = REPLACE(`confirm`, 'http:' , 'https:'),
-                               `poco`    = REPLACE(`poco`   , 'http:' , 'https:')
-                               WHERE `self` = 1"
-                       );
-                       q("UPDATE `profile` SET
-                               `photo`   = REPLACE(`photo`  , 'http:' , 'https:'),
-                               `thumb`   = REPLACE(`thumb`  , 'http:' , 'https:')
-                               WHERE 1 "
-                       );
-               } elseif ($ssl_policy == BaseURL::SSL_POLICY_SELFSIGN) {
-                       q("UPDATE `contact` SET
-                               `url`     = REPLACE(`url`    , 'https:' , 'http:'),
-                               `photo`   = REPLACE(`photo`  , 'https:' , 'http:'),
-                               `thumb`   = REPLACE(`thumb`  , 'https:' , 'http:'),
-                               `micro`   = REPLACE(`micro`  , 'https:' , 'http:'),
-                               `request` = REPLACE(`request`, 'https:' , 'http:'),
-                               `notify`  = REPLACE(`notify` , 'https:' , 'http:'),
-                               `poll`    = REPLACE(`poll`   , 'https:' , 'http:'),
-                               `confirm` = REPLACE(`confirm`, 'https:' , 'http:'),
-                               `poco`    = REPLACE(`poco`   , 'https:' , 'http:')
-                               WHERE `self` = 1"
-                       );
-                       q("UPDATE `profile` SET
-                               `photo`   = REPLACE(`photo`  , 'https:' , 'http:'),
-                               `thumb`   = REPLACE(`thumb`  , 'https:' , 'http:')
-                               WHERE 1 "
-                       );
-               }
-       }
-       Config::set('system', 'ssl_policy'            , $ssl_policy);
-       Config::set('system', 'maxloadavg'            , $maxloadavg);
-       Config::set('system', 'maxloadavg_frontend'   , $maxloadavg_frontend);
-       Config::set('system', 'min_memory'            , $min_memory);
-       Config::set('system', 'optimize_max_tablesize', $optimize_max_tablesize);
-       Config::set('system', 'optimize_fragmentation', $optimize_fragmentation);
-       Config::set('system', 'poco_completion'       , $poco_completion);
-       Config::set('system', 'poco_requery_days'     , $poco_requery_days);
-       Config::set('system', 'poco_discovery'        , $poco_discovery);
-       Config::set('system', 'poco_discovery_since'  , $poco_discovery_since);
-       Config::set('system', 'poco_local_search'     , $poco_local_search);
-       Config::set('system', 'nodeinfo'              , $nodeinfo);
-       Config::set('config', 'sitename'              , $sitename);
-       Config::set('config', 'sender_email'          , $sender_email);
-       Config::set('system', 'suppress_tags'         , $suppress_tags);
-       Config::set('system', 'shortcut_icon'         , $shortcut_icon);
-       Config::set('system', 'touch_icon'            , $touch_icon);
-
-       if ($banner == "") {
-               Config::delete('system', 'banner');
-       } else {
-               Config::set('system', 'banner', $banner);
-       }
-
-       if (empty($additional_info)) {
-               Config::delete('config', 'info');
-       } else {
-               Config::set('config', 'info', $additional_info);
-       }
-       Config::set('system', 'language', $language);
-       Config::set('system', 'theme', $theme);
-       Theme::install($theme);
-
-       if ($theme_mobile == '---') {
-               Config::delete('system', 'mobile-theme');
-       } else {
-               Config::set('system', 'mobile-theme', $theme_mobile);
-       }
-       if ($singleuser == '---') {
-               Config::delete('system', 'singleuser');
-       } else {
-               Config::set('system', 'singleuser', $singleuser);
-       }
-       Config::set('system', 'maximagesize'           , $maximagesize);
-       Config::set('system', 'max_image_length'       , $maximagelength);
-       Config::set('system', 'jpeg_quality'           , $jpegimagequality);
-
-       Config::set('config', 'register_policy'        , $register_policy);
-       Config::set('system', 'max_daily_registrations', $daily_registrations);
-       Config::set('system', 'account_abandon_days'   , $abandon_days);
-       Config::set('config', 'register_text'          , $register_text);
-       Config::set('system', 'allowed_sites'          , $allowed_sites);
-       Config::set('system', 'allowed_email'          , $allowed_email);
-       Config::set('system', 'forbidden_nicknames'    , $forbidden_nicknames);
-       Config::set('system', 'no_oembed_rich_content' , $no_oembed_rich_content);
-       Config::set('system', 'allowed_oembed'         , $allowed_oembed);
-       Config::set('system', 'block_public'           , $block_public);
-       Config::set('system', 'publish_all'            , $force_publish);
-       Config::set('system', 'newuser_private'        , $newuser_private);
-       Config::set('system', 'enotify_no_content'     , $enotify_no_content);
-       Config::set('system', 'disable_embedded'       , $disable_embedded);
-       Config::set('system', 'allow_users_remote_self', $allow_users_remote_self);
-       Config::set('system', 'explicit_content'       , $explicit_content);
-       Config::set('system', 'check_new_version_url'  , $check_new_version_url);
-
-       Config::set('system', 'block_extended_register', $no_multi_reg);
-       Config::set('system', 'no_openid'              , $no_openid);
-       Config::set('system', 'no_regfullname'         , $no_regfullname);
-       Config::set('system', 'community_page_style'   , $community_page_style);
-       Config::set('system', 'max_author_posts_community_page', $max_author_posts_community_page);
-       Config::set('system', 'verifyssl'              , $verifyssl);
-       Config::set('system', 'proxyuser'              , $proxyuser);
-       Config::set('system', 'proxy'                  , $proxy);
-       Config::set('system', 'curl_timeout'           , $timeout);
-       Config::set('system', 'dfrn_only'              , $dfrn_only);
-       Config::set('system', 'ostatus_disabled'       , $ostatus_disabled);
-       Config::set('system', 'ostatus_full_threads'   , $ostatus_full_threads);
-       Config::set('system', 'diaspora_enabled'       , $diaspora_enabled);
-
-       Config::set('config', 'private_addons'         , $private_addons);
-
-       Config::set('system', 'force_ssl'              , $force_ssl);
-       Config::set('system', 'hide_help'              , $hide_help);
-
-       Config::set('system', 'dbclean'                , $dbclean);
-       Config::set('system', 'dbclean-expire-days'    , $dbclean_expire_days);
-       Config::set('system', 'dbclean_expire_conversation', $dbclean_expire_conv);
-
-       if ($dbclean_unclaimed == 0) {
-               $dbclean_unclaimed = $dbclean_expire_days;
-       }
-
-       Config::set('system', 'dbclean-expire-unclaimed', $dbclean_unclaimed);
-
-       if ($itemcache != '') {
-               $itemcache = BasePath::getRealPath($itemcache);
-       }
-
-       Config::set('system', 'itemcache', $itemcache);
-       Config::set('system', 'itemcache_duration', $itemcache_duration);
-       Config::set('system', 'max_comments', $max_comments);
-
-       if ($temppath != '') {
-               $temppath = BasePath::getRealPath($temppath);
-       }
-
-       Config::set('system', 'temppath', $temppath);
-
-       Config::set('system', 'proxy_disabled'   , $proxy_disabled);
-       Config::set('system', 'only_tag_search'  , $only_tag_search);
-
-       Config::set('system', 'worker_queues'    , $worker_queues);
-       Config::set('system', 'worker_dont_fork' , $worker_dont_fork);
-       Config::set('system', 'worker_fastlane'  , $worker_fastlane);
-       Config::set('system', 'frontend_worker'  , $worker_frontend);
-
-       Config::set('system', 'relay_directly'   , $relay_directly);
-       Config::set('system', 'relay_server'     , $relay_server);
-       Config::set('system', 'relay_subscribe'  , $relay_subscribe);
-       Config::set('system', 'relay_scope'      , $relay_scope);
-       Config::set('system', 'relay_server_tags', $relay_server_tags);
-       Config::set('system', 'relay_user_tags'  , $relay_user_tags);
-
-       Config::set('system', 'rino_encrypt'     , $rino);
-
-       info(L10n::t('Site settings updated.') . EOL);
-
-       $a->internalRedirect('admin/site' . $active_panel);
-       return; // NOTREACHED
-}
-
-/**
- * @brief Generate Admin Site subpage
- *
- * This function generates the main configuration page of the admin panel.
- *
- * @param  App $a
- * @return string
- * @throws \Friendica\Network\HTTPException\InternalServerErrorException
- */
-function admin_page_site(App $a)
-{
-       /* Installed langs */
-       $lang_choices = L10n::getAvailableLanguages();
-
-       if (strlen(Config::get('system', 'directory_submit_url')) &&
-               !strlen(Config::get('system', 'directory'))) {
-               Config::set('system', 'directory', dirname(Config::get('system', 'directory_submit_url')));
-               Config::delete('system', 'directory_submit_url');
-       }
-
-       /* Installed themes */
-       $theme_choices = [];
-       $theme_choices_mobile = [];
-       $theme_choices_mobile["---"] = L10n::t("No special theme for mobile devices");
-       $files = glob('view/theme/*');
-       if (is_array($files)) {
-               $allowed_theme_list = Config::get('system', 'allowed_themes');
-
-               foreach ($files as $file) {
-                       if (intval(file_exists($file . '/unsupported'))) {
-                               continue;
-                       }
-
-                       $f = basename($file);
-
-                       // Only show allowed themes here
-                       if (($allowed_theme_list != '') && !strstr($allowed_theme_list, $f)) {
-                               continue;
-                       }
-
-                       $theme_name = ((file_exists($file . '/experimental')) ? sprintf("%s - \x28Experimental\x29", $f) : $f);
-
-                       if (file_exists($file . '/mobile')) {
-                               $theme_choices_mobile[$f] = $theme_name;
-                       } else {
-                               $theme_choices[$f] = $theme_name;
-                       }
-               }
-       }
-
-       /* Community page style */
-       $community_page_style_choices = [
-               CP_NO_INTERNAL_COMMUNITY => L10n::t("No community page for local users"),
-               CP_NO_COMMUNITY_PAGE => L10n::t("No community page"),
-               CP_USERS_ON_SERVER => L10n::t("Public postings from users of this site"),
-               CP_GLOBAL_COMMUNITY => L10n::t("Public postings from the federated network"),
-               CP_USERS_AND_GLOBAL => L10n::t("Public postings from local users and the federated network")
-       ];
-
-       $poco_discovery_choices = [
-               PortableContact::DISABLED => L10n::t("Disabled"),
-               PortableContact::USERS => L10n::t("Users"),
-               PortableContact::USERS_GCONTACTS => L10n::t("Users, Global Contacts"),
-               PortableContact::USERS_GCONTACTS_FALLBACK => L10n::t("Users, Global Contacts/fallback"),
-       ];
-
-       $poco_discovery_since_choices = [
-               "30" => L10n::t("One month"),
-               "91" => L10n::t("Three months"),
-               "182" => L10n::t("Half a year"),
-               "365" => L10n::t("One year"),
-       ];
-
-       /* get user names to make the install a personal install of X */
-       $user_names = [];
-       $user_names['---'] = L10n::t('Multi user instance');
-       $users = q("SELECT `username`, `nickname` FROM `user`");
-
-       foreach ($users as $user) {
-               $user_names[$user['nickname']] = $user['username'];
-       }
-
-       /* Banner */
-       $banner = Config::get('system', 'banner');
-
-       if ($banner == false) {
-               $banner = '<a href="https://friendi.ca"><img id="logo-img" src="images/friendica-32.png" alt="logo" /></a><span id="logo-text"><a href="https://friendi.ca">Friendica</a></span>';
-       }
-
-       $additional_info = Config::get('config', 'info');
-
-       // Automatically create temporary paths
-       get_temppath();
-       get_itemcachepath();
-
-       //echo "<pre>"; var_dump($lang_choices); die("</pre>");
-
-       /* Register policy */
-       $register_choices = [
-               Module\Register::CLOSED => L10n::t("Closed"),
-               Module\Register::APPROVE => L10n::t("Requires approval"),
-               Module\Register::OPEN => L10n::t("Open")
-       ];
-
-       $ssl_choices = [
-               BaseURL::SSL_POLICY_NONE => L10n::t("No SSL policy, links will track page SSL state"),
-               BaseURL::SSL_POLICY_FULL => L10n::t("Force all links to use SSL"),
-               BaseURL::SSL_POLICY_SELFSIGN => L10n::t("Self-signed certificate, use SSL for local links only \x28discouraged\x29")
-       ];
-
-       $check_git_version_choices = [
-               "none" => L10n::t("Don't check"),
-               "master" => L10n::t("check the stable version"),
-               "develop" => L10n::t("check the development version")
-       ];
-
-       $diaspora_able = ($a->getURLPath() == "");
-
-       $optimize_max_tablesize = Config::get('system', 'optimize_max_tablesize', -1);
-
-       if ($optimize_max_tablesize <= 0) {
-               $optimize_max_tablesize = -1;
-       }
-
-       /* storage backend */
-       $storage_backends = StorageManager::listBackends();
-       /**
-        * @var $storage_current_backend \Friendica\Model\Storage\IStorage
-        */
-       $storage_current_backend = StorageManager::getBackend();
-
-       $storage_backends_choices = [];
-
-       // show legacy option only if it is the current backend:
-       // once changed can't be selected anymore
-       if ($storage_current_backend == '') {
-               $storage_backends_choices[''] = L10n::t('Database (legacy)');
-       };
-
-       foreach ($storage_backends as $name => $class) {
-               $storage_backends_choices[$class] = $name;
-       }
-       unset($storage_backends);
-
-       // build storage config form,
-       $storage_form_prefix=preg_replace('|[^a-zA-Z0-9]|' ,'', $storage_current_backend);
-
-       $storage_form = [];
-       if (!is_null($storage_current_backend) && $storage_current_backend != "") {
-               foreach ($storage_current_backend::getOptions() as $name => $info) {
-                       $type = $info[0];
-                       $info[0] = $storage_form_prefix . '_' . $name;
-                       $info['type'] = $type;
-                       $info['field'] = 'field_' . $type . '.tpl';
-                       $storage_form[$name] = $info;
-               }
-       }
-
-
-       $t = Renderer::getMarkupTemplate('admin/site.tpl');
-       return Renderer::replaceMacros($t, [
-               '$title'             => L10n::t('Administration'),
-               '$page'              => L10n::t('Site'),
-               '$submit'            => L10n::t('Save Settings'),
-               '$republish'         => L10n::t('Republish users to directory'),
-               '$registration'      => L10n::t('Registration'),
-               '$upload'            => L10n::t('File upload'),
-               '$corporate'         => L10n::t('Policies'),
-               '$advanced'          => L10n::t('Advanced'),
-               '$portable_contacts' => L10n::t('Auto Discovered Contact Directory'),
-               '$performance'       => L10n::t('Performance'),
-               '$worker_title'      => L10n::t('Worker'),
-               '$relay_title'       => L10n::t('Message Relay'),
-               '$relocate'          => L10n::t('Relocate Instance'),
-               '$relocate_warning'  => L10n::t('Warning! Advanced function. Could make this server unreachable.'),
-               '$baseurl'           => System::baseUrl(true),
-
-               // name, label, value, help string, extra data...
-               '$sitename'         => ['sitename', L10n::t("Site name"), Config::get('config', 'sitename'), ''],
-               '$sender_email'     => ['sender_email', L10n::t("Sender Email"), Config::get('config', 'sender_email'), L10n::t("The email address your server shall use to send notification emails from."), "", "", "email"],
-               '$banner'           => ['banner', L10n::t("Banner/Logo"), $banner, ""],
-               '$shortcut_icon'    => ['shortcut_icon', L10n::t("Shortcut icon"), Config::get('system', 'shortcut_icon'), L10n::t("Link to an icon that will be used for browsers.")],
-               '$touch_icon'       => ['touch_icon', L10n::t("Touch icon"), Config::get('system', 'touch_icon'), L10n::t("Link to an icon that will be used for tablets and mobiles.")],
-               '$additional_info'  => ['additional_info', L10n::t('Additional Info'), $additional_info, L10n::t('For public servers: you can add additional information here that will be listed at %s/servers.', get_server())],
-               '$language'         => ['language', L10n::t("System language"), Config::get('system', 'language'), "", $lang_choices],
-               '$theme'            => ['theme', L10n::t("System theme"), Config::get('system', 'theme'), L10n::t("Default system theme - may be over-ridden by user profiles - <a href='#' id='cnftheme'>change theme settings</a>"), $theme_choices],
-               '$theme_mobile'     => ['theme_mobile', L10n::t("Mobile system theme"), Config::get('system', 'mobile-theme', '---'), L10n::t("Theme for mobile devices"), $theme_choices_mobile],
-               '$ssl_policy'       => ['ssl_policy', L10n::t("SSL link policy"), (string)intval(Config::get('system', 'ssl_policy')), L10n::t("Determines whether generated links should be forced to use SSL"), $ssl_choices],
-               '$force_ssl'        => ['force_ssl', L10n::t("Force SSL"), Config::get('system', 'force_ssl'), L10n::t("Force all Non-SSL requests to SSL - Attention: on some systems it could lead to endless loops.")],
-               '$hide_help'        => ['hide_help', L10n::t("Hide help entry from navigation menu"), Config::get('system', 'hide_help'), L10n::t("Hides the menu entry for the Help pages from the navigation menu. You can still access it calling /help directly.")],
-               '$singleuser'       => ['singleuser', L10n::t("Single user instance"), Config::get('system', 'singleuser', '---'), L10n::t("Make this instance multi-user or single-user for the named user"), $user_names],
-
-               '$storagebackend'   => ['storagebackend', L10n::t("File storage backend"), $storage_current_backend, L10n::t('The backend used to store uploaded data. If you change the storage backend, you can manually move the existing files. If you do not do so, the files uploaded before the change will still be available at the old backend. Please see <a href="/help/Settings#1_2_3_1">the settings documentation</a> for more information about the choices and the moving procedure.'), $storage_backends_choices],
-               '$storageform'      => $storage_form,
-               '$maximagesize'     => ['maximagesize', L10n::t("Maximum image size"), Config::get('system', 'maximagesize'), L10n::t("Maximum size in bytes of uploaded images. Default is 0, which means no limits.")],
-               '$maximagelength'   => ['maximagelength', L10n::t("Maximum image length"), Config::get('system', 'max_image_length'), L10n::t("Maximum length in pixels of the longest side of uploaded images. Default is -1, which means no limits.")],
-               '$jpegimagequality' => ['jpegimagequality', L10n::t("JPEG image quality"), Config::get('system', 'jpeg_quality'), L10n::t("Uploaded JPEGS will be saved at this quality setting [0-100]. Default is 100, which is full quality.")],
-
-               '$register_policy'        => ['register_policy', L10n::t("Register policy"), Config::get('config', 'register_policy'), "", $register_choices],
-               '$daily_registrations'    => ['max_daily_registrations', L10n::t("Maximum Daily Registrations"), Config::get('system', 'max_daily_registrations'), L10n::t("If registration is permitted above, this sets the maximum number of new user registrations to accept per day.  If register is set to closed, this setting has no effect.")],
-               '$register_text'          => ['register_text', L10n::t("Register text"), Config::get('config', 'register_text'), L10n::t("Will be displayed prominently on the registration page. You can use BBCode here.")],
-               '$forbidden_nicknames'    => ['forbidden_nicknames', L10n::t('Forbidden Nicknames'), Config::get('system', 'forbidden_nicknames'), L10n::t('Comma separated list of nicknames that are forbidden from registration. Preset is a list of role names according RFC 2142.')],
-               '$abandon_days'           => ['abandon_days', L10n::t('Accounts abandoned after x days'), Config::get('system', 'account_abandon_days'), L10n::t('Will not waste system resources polling external sites for abandonded accounts. Enter 0 for no time limit.')],
-               '$allowed_sites'          => ['allowed_sites', L10n::t("Allowed friend domains"), Config::get('system', 'allowed_sites'), L10n::t("Comma separated list of domains which are allowed to establish friendships with this site. Wildcards are accepted. Empty to allow any domains")],
-               '$allowed_email'          => ['allowed_email', L10n::t("Allowed email domains"), Config::get('system', 'allowed_email'), L10n::t("Comma separated list of domains which are allowed in email addresses for registrations to this site. Wildcards are accepted. Empty to allow any domains")],
-               '$no_oembed_rich_content' => ['no_oembed_rich_content', L10n::t("No OEmbed rich content"), Config::get('system', 'no_oembed_rich_content'), L10n::t("Don't show the rich content \x28e.g. embedded PDF\x29, except from the domains listed below.")],
-               '$allowed_oembed'         => ['allowed_oembed', L10n::t("Allowed OEmbed domains"), Config::get('system', 'allowed_oembed'), L10n::t("Comma separated list of domains which oembed content is allowed to be displayed. Wildcards are accepted.")],
-               '$block_public'           => ['block_public', L10n::t("Block public"), Config::get('system', 'block_public'), L10n::t("Check to block public access to all otherwise public personal pages on this site unless you are currently logged in.")],
-               '$force_publish'          => ['publish_all', L10n::t("Force publish"), Config::get('system', 'publish_all'), L10n::t("Check to force all profiles on this site to be listed in the site directory.") . '<strong>' . L10n::t('Enabling this may violate privacy laws like the GDPR') . '</strong>'],
-               '$global_directory'       => ['directory', L10n::t("Global directory URL"), Config::get('system', 'directory', 'https://dir.friendica.social'), L10n::t("URL to the global directory. If this is not set, the global directory is completely unavailable to the application.")],
-               '$newuser_private'        => ['newuser_private', L10n::t("Private posts by default for new users"), Config::get('system', 'newuser_private'), L10n::t("Set default post permissions for all new members to the default privacy group rather than public.")],
-               '$enotify_no_content'     => ['enotify_no_content', L10n::t("Don't include post content in email notifications"), Config::get('system', 'enotify_no_content'), L10n::t("Don't include the content of a post/comment/private message/etc. in the email notifications that are sent out from this site, as a privacy measure.")],
-               '$private_addons'         => ['private_addons', L10n::t("Disallow public access to addons listed in the apps menu."), Config::get('config', 'private_addons'), L10n::t("Checking this box will restrict addons listed in the apps menu to members only.")],
-               '$disable_embedded'       => ['disable_embedded', L10n::t("Don't embed private images in posts"), Config::get('system', 'disable_embedded'), L10n::t("Don't replace locally-hosted private photos in posts with an embedded copy of the image. This means that contacts who receive posts containing private photos will have to authenticate and load each image, which may take a while.")],
-               '$explicit_content'       => ['explicit_content', L10n::t('Explicit Content'), Config::get('system', 'explicit_content', false), L10n::t('Set this to announce that your node is used mostly for explicit content that might not be suited for minors. This information will be published in the node information and might be used, e.g. by the global directory, to filter your node from listings of nodes to join. Additionally a note about this will be shown at the user registration page.')],
-               '$allow_users_remote_self'=> ['allow_users_remote_self', L10n::t('Allow Users to set remote_self'), Config::get('system', 'allow_users_remote_self'), L10n::t('With checking this, every user is allowed to mark every contact as a remote_self in the repair contact dialog. Setting this flag on a contact causes mirroring every posting of that contact in the users stream.')],
-               '$no_multi_reg'           => ['no_multi_reg', L10n::t("Block multiple registrations"), Config::get('system', 'block_extended_register'), L10n::t("Disallow users to register additional accounts for use as pages.")],
-               '$no_openid'              => ['no_openid', L10n::t("Disable OpenID"), Config::get('system', 'no_openid'), L10n::t("Disable OpenID support for registration and logins.")],
-               '$no_regfullname'         => ['no_regfullname', L10n::t("No Fullname check"), Config::get('system', 'no_regfullname'), L10n::t("Allow users to register without a space between the first name and the last name in their full name.")],
-               '$community_page_style'   => ['community_page_style', L10n::t("Community pages for visitors"), Config::get('system', 'community_page_style'), L10n::t("Which community pages should be available for visitors. Local users always see both pages."), $community_page_style_choices],
-               '$max_author_posts_community_page' => ['max_author_posts_community_page', L10n::t("Posts per user on community page"), Config::get('system', 'max_author_posts_community_page'), L10n::t("The maximum number of posts per user on the community page. \x28Not valid for 'Global Community'\x29")],
-               '$ostatus_disabled'       => ['ostatus_disabled', L10n::t("Disable OStatus support"), Config::get('system', 'ostatus_disabled'), L10n::t("Disable built-in OStatus (StatusNet, GNU Social etc.) compatibility. All communications in OStatus are public, so privacy warnings will be occasionally displayed.")],
-               '$ostatus_full_threads'   => ['ostatus_full_threads', L10n::t("Only import OStatus/ActivityPub threads from our contacts"), Config::get('system', 'ostatus_full_threads'), L10n::t("Normally we import every content from our OStatus and ActivityPub contacts. With this option we only store threads that are started by a contact that is known on our system.")],
-               '$ostatus_not_able'       => L10n::t("OStatus support can only be enabled if threading is enabled."),
-               '$diaspora_able'          => $diaspora_able,
-               '$diaspora_not_able'      => L10n::t("Diaspora support can't be enabled because Friendica was installed into a sub directory."),
-               '$diaspora_enabled'       => ['diaspora_enabled', L10n::t("Enable Diaspora support"), Config::get('system', 'diaspora_enabled', $diaspora_able), L10n::t("Provide built-in Diaspora network compatibility.")],
-               '$dfrn_only'              => ['dfrn_only', L10n::t('Only allow Friendica contacts'), Config::get('system', 'dfrn_only'), L10n::t("All contacts must use Friendica protocols. All other built-in communication protocols disabled.")],
-               '$verifyssl'              => ['verifyssl', L10n::t("Verify SSL"), Config::get('system', 'verifyssl'), L10n::t("If you wish, you can turn on strict certificate checking. This will mean you cannot connect \x28at all\x29 to self-signed SSL sites.")],
-               '$proxyuser'              => ['proxyuser', L10n::t("Proxy user"), Config::get('system', 'proxyuser'), ""],
-               '$proxy'                  => ['proxy', L10n::t("Proxy URL"), Config::get('system', 'proxy'), ""],
-               '$timeout'                => ['timeout', L10n::t("Network timeout"), Config::get('system', 'curl_timeout', 60), L10n::t("Value is in seconds. Set to 0 for unlimited \x28not recommended\x29.")],
-               '$maxloadavg'             => ['maxloadavg', L10n::t("Maximum Load Average"), Config::get('system', 'maxloadavg', 20), L10n::t("Maximum system load before delivery and poll processes are deferred - default %d.", 20)],
-               '$maxloadavg_frontend'    => ['maxloadavg_frontend', L10n::t("Maximum Load Average \x28Frontend\x29"), Config::get('system', 'maxloadavg_frontend', 50), L10n::t("Maximum system load before the frontend quits service - default 50.")],
-               '$min_memory'             => ['min_memory', L10n::t("Minimal Memory"), Config::get('system', 'min_memory', 0), L10n::t("Minimal free memory in MB for the worker. Needs access to /proc/meminfo - default 0 \x28deactivated\x29.")],
-               '$optimize_max_tablesize' => ['optimize_max_tablesize', L10n::t("Maximum table size for optimization"), $optimize_max_tablesize, L10n::t("Maximum table size \x28in MB\x29 for the automatic optimization. Enter -1 to disable it.")],
-               '$optimize_fragmentation' => ['optimize_fragmentation', L10n::t("Minimum level of fragmentation"), Config::get('system', 'optimize_fragmentation', 30), L10n::t("Minimum fragmenation level to start the automatic optimization - default value is 30%.")],
-
-               '$poco_completion'        => ['poco_completion', L10n::t("Periodical check of global contacts"), Config::get('system', 'poco_completion'), L10n::t("If enabled, the global contacts are checked periodically for missing or outdated data and the vitality of the contacts and servers.")],
-               '$poco_requery_days'      => ['poco_requery_days', L10n::t("Days between requery"), Config::get('system', 'poco_requery_days'), L10n::t("Number of days after which a server is requeried for his contacts.")],
-               '$poco_discovery'         => ['poco_discovery', L10n::t("Discover contacts from other servers"), (string)intval(Config::get('system', 'poco_discovery')), L10n::t("Periodically query other servers for contacts. You can choose between 'users': the users on the remote system, 'Global Contacts': active contacts that are known on the system. The fallback is meant for Redmatrix servers and older friendica servers, where global contacts weren't available. The fallback increases the server load, so the recommended setting is 'Users, Global Contacts'."), $poco_discovery_choices],
-               '$poco_discovery_since'   => ['poco_discovery_since', L10n::t("Timeframe for fetching global contacts"), (string)intval(Config::get('system', 'poco_discovery_since')), L10n::t("When the discovery is activated, this value defines the timeframe for the activity of the global contacts that are fetched from other servers."), $poco_discovery_since_choices],
-               '$poco_local_search'      => ['poco_local_search', L10n::t("Search the local directory"), Config::get('system', 'poco_local_search'), L10n::t("Search the local directory instead of the global directory. When searching locally, every search will be executed on the global directory in the background. This improves the search results when the search is repeated.")],
-
-               '$nodeinfo'               => ['nodeinfo', L10n::t("Publish server information"), Config::get('system', 'nodeinfo'), L10n::t("If enabled, general server and usage data will be published. The data contains the name and version of the server, number of users with public profiles, number of posts and the activated protocols and connectors. See <a href='http://the-federation.info/'>the-federation.info</a> for details.")],
-
-               '$check_new_version_url'  => ['check_new_version_url', L10n::t("Check upstream version"), Config::get('system', 'check_new_version_url'), L10n::t("Enables checking for new Friendica versions at github. If there is a new version, you will be informed in the admin panel overview."), $check_git_version_choices],
-               '$suppress_tags'          => ['suppress_tags', L10n::t("Suppress Tags"), Config::get('system', 'suppress_tags'), L10n::t("Suppress showing a list of hashtags at the end of the posting.")],
-               '$dbclean'                => ['dbclean', L10n::t("Clean database"), Config::get('system', 'dbclean', false), L10n::t("Remove old remote items, orphaned database records and old content from some other helper tables.")],
-               '$dbclean_expire_days'    => ['dbclean_expire_days', L10n::t("Lifespan of remote items"), Config::get('system', 'dbclean-expire-days', 0), L10n::t("When the database cleanup is enabled, this defines the days after which remote items will be deleted. Own items, and marked or filed items are always kept. 0 disables this behaviour.")],
-               '$dbclean_unclaimed'      => ['dbclean_unclaimed', L10n::t("Lifespan of unclaimed items"), Config::get('system', 'dbclean-expire-unclaimed', 90), L10n::t("When the database cleanup is enabled, this defines the days after which unclaimed remote items (mostly content from the relay) will be deleted. Default value is 90 days. Defaults to the general lifespan value of remote items if set to 0.")],
-               '$dbclean_expire_conv'    => ['dbclean_expire_conv', L10n::t("Lifespan of raw conversation data"), Config::get('system', 'dbclean_expire_conversation', 90), L10n::t("The conversation data is used for ActivityPub and OStatus, as well as for debug purposes. It should be safe to remove it after 14 days, default is 90 days.")],
-               '$itemcache'              => ['itemcache', L10n::t("Path to item cache"), Config::get('system', 'itemcache'), L10n::t("The item caches buffers generated bbcode and external images.")],
-               '$itemcache_duration'     => ['itemcache_duration', L10n::t("Cache duration in seconds"), Config::get('system', 'itemcache_duration'), L10n::t("How long should the cache files be hold? Default value is 86400 seconds \x28One day\x29. To disable the item cache, set the value to -1.")],
-               '$max_comments'           => ['max_comments', L10n::t("Maximum numbers of comments per post"), Config::get('system', 'max_comments'), L10n::t("How much comments should be shown for each post? Default value is 100.")],
-               '$temppath'               => ['temppath', L10n::t("Temp path"), Config::get('system', 'temppath'), L10n::t("If you have a restricted system where the webserver can't access the system temp path, enter another path here.")],
-               '$proxy_disabled'         => ['proxy_disabled', L10n::t("Disable picture proxy"), Config::get('system', 'proxy_disabled'), L10n::t("The picture proxy increases performance and privacy. It shouldn't be used on systems with very low bandwidth.")],
-               '$only_tag_search'        => ['only_tag_search', L10n::t("Only search in tags"), Config::get('system', 'only_tag_search'), L10n::t("On large systems the text search can slow down the system extremely.")],
-
-               '$relocate_url'           => ['relocate_url', L10n::t("New base url"), System::baseUrl(), L10n::t("Change base url for this server. Sends relocate message to all Friendica and Diaspora* contacts of all users.")],
-
-               '$rino'                   => ['rino', L10n::t("RINO Encryption"), intval(Config::get('system', 'rino_encrypt')), L10n::t("Encryption layer between nodes."), [0 => L10n::t("Disabled"), 1 => L10n::t("Enabled")]],
-
-               '$worker_queues'          => ['worker_queues', L10n::t("Maximum number of parallel workers"), Config::get('system', 'worker_queues'), L10n::t("On shared hosters set this to %d. On larger systems, values of %d are great. Default value is %d.", 5, 20, 10)],
-               '$worker_dont_fork'       => ['worker_dont_fork', L10n::t("Don't use 'proc_open' with the worker"), Config::get('system', 'worker_dont_fork'), L10n::t("Enable this if your system doesn't allow the use of 'proc_open'. This can happen on shared hosters. If this is enabled you should increase the frequency of worker calls in your crontab.")],
-               '$worker_fastlane'        => ['worker_fastlane', L10n::t("Enable fastlane"), Config::get('system', 'worker_fastlane'), L10n::t("When enabed, the fastlane mechanism starts an additional worker if processes with higher priority are blocked by processes of lower priority.")],
-               '$worker_frontend'        => ['worker_frontend', L10n::t('Enable frontend worker'), Config::get('system', 'frontend_worker'), L10n::t("When enabled the Worker process is triggered when backend access is performed \x28e.g. messages being delivered\x29. On smaller sites you might want to call %s/worker on a regular basis via an external cron job. You should only enable this option if you cannot utilize cron/scheduled jobs on your server.", System::baseUrl())],
-
-               '$relay_subscribe'        => ['relay_subscribe', L10n::t("Subscribe to relay"), Config::get('system', 'relay_subscribe'), L10n::t("Enables the receiving of public posts from the relay. They will be included in the search, subscribed tags and on the global community page.")],
-               '$relay_server'           => ['relay_server', L10n::t("Relay server"), Config::get('system', 'relay_server', 'https://relay.diasp.org'), L10n::t("Address of the relay server where public posts should be send to. For example https://relay.diasp.org")],
-               '$relay_directly'         => ['relay_directly', L10n::t("Direct relay transfer"), Config::get('system', 'relay_directly'), L10n::t("Enables the direct transfer to other servers without using the relay servers")],
-               '$relay_scope'            => ['relay_scope', L10n::t("Relay scope"), Config::get('system', 'relay_scope'), L10n::t("Can be 'all' or 'tags'. 'all' means that every public post should be received. 'tags' means that only posts with selected tags should be received."), ['' => L10n::t('Disabled'), 'all' => L10n::t('all'), 'tags' => L10n::t('tags')]],
-               '$relay_server_tags'      => ['relay_server_tags', L10n::t("Server tags"), Config::get('system', 'relay_server_tags'), L10n::t("Comma separated list of tags for the 'tags' subscription.")],
-               '$relay_user_tags'        => ['relay_user_tags', L10n::t("Allow user tags"), Config::get('system', 'relay_user_tags', true), L10n::t("If enabled, the tags from the saved searches will used for the 'tags' subscription in addition to the 'relay_server_tags'.")],
-
-               '$form_security_token'    => BaseModule::getFormSecurityToken("admin_site"),
-               '$relocate_button'        => L10n::t('Start Relocation'),
-       ]);
-}
-
-/**
- * @brief Generates admin panel subpage for DB syncronization
- *
- * This page checks if the database of friendica is in sync with the specs.
- * Should this not be the case, it attemps to sync the structure and notifies
- * the admin if the automatic process was failing.
- *
- * The returned string holds the HTML code of the page.
- *
- * @param App $a
- * @return string
- * @throws \Friendica\Network\HTTPException\InternalServerErrorException
- */
-function admin_page_dbsync(App $a)
-{
-       $o = '';
-
-       if ($a->argc > 3 && intval($a->argv[3]) && $a->argv[2] === 'mark') {
-               Config::set('database', 'update_' . intval($a->argv[3]), 'success');
-               $curr = Config::get('system', 'build');
-               if (intval($curr) == intval($a->argv[3])) {
-                       Config::set('system', 'build', intval($curr) + 1);
-               }
-               info(L10n::t('Update has been marked successful') . EOL);
-               $a->internalRedirect('admin/dbsync');
-       }
-
-       if (($a->argc > 2) && (intval($a->argv[2]) || ($a->argv[2] === 'check'))) {
-               $retval = DBStructure::update($a->getBasePath(), false, true);
-               if ($retval === '') {
-                       $o .= L10n::t("Database structure update %s was successfully applied.", DB_UPDATE_VERSION) . "<br />";
-                       Config::set('database', 'last_successful_update', DB_UPDATE_VERSION);
-                       Config::set('database', 'last_successful_update_time', time());
-               } else {
-                       $o .= L10n::t("Executing of database structure update %s failed with error: %s", DB_UPDATE_VERSION, $retval) . "<br />";
-               }
-               if ($a->argv[2] === 'check') {
-                       return $o;
-               }
-       }
-
-       if ($a->argc > 2 && intval($a->argv[2])) {
-               require_once 'update.php';
-
-               $func = 'update_' . intval($a->argv[2]);
-
-               if (function_exists($func)) {
-                       $retval = $func();
-
-                       if ($retval === Update::FAILED) {
-                               $o .= L10n::t("Executing %s failed with error: %s", $func, $retval);
-                       } elseif ($retval === Update::SUCCESS) {
-                               $o .= L10n::t('Update %s was successfully applied.', $func);
-                               Config::set('database', $func, 'success');
-                       } else {
-                               $o .= L10n::t('Update %s did not return a status. Unknown if it succeeded.', $func);
-                       }
-               } else {
-                       $o .= L10n::t('There was no additional update function %s that needed to be called.', $func) . "<br />";
-                       Config::set('database', $func, 'success');
-               }
-
-               return $o;
-       }
-
-       $failed = [];
-       $r = q("SELECT `k`, `v` FROM `config` WHERE `cat` = 'database' ");
-
-       if (DBA::isResult($r)) {
-               foreach ($r as $rr) {
-                       $upd = intval(substr($rr['k'], 7));
-                       if ($upd < 1139 || $rr['v'] === 'success') {
-                               continue;
-                       }
-                       $failed[] = $upd;
-               }
-       }
-
-       if (!count($failed)) {
-               $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('structure_check.tpl'), [
-                       '$base' => System::baseUrl(true),
-                       '$banner' => L10n::t('No failed updates.'),
-                       '$check' => L10n::t('Check database structure'),
-               ]);
-       } else {
-               $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('failed_updates.tpl'), [
-                       '$base' => System::baseUrl(true),
-                       '$banner' => L10n::t('Failed Updates'),
-                       '$desc' => L10n::t('This does not include updates prior to 1139, which did not return a status.'),
-                       '$mark' => L10n::t("Mark success \x28if update was manually applied\x29"),
-                       '$apply' => L10n::t('Attempt to execute this update step automatically'),
-                       '$failed' => $failed
-               ]);
-       }
-
-       return $o;
-}
-
-/**
- * @brief Process data send by Users admin page
- *
- * @param App $a
- * @throws \Friendica\Network\HTTPException\InternalServerErrorException
- */
-function admin_page_users_post(App $a)
-{
-       $pending     = defaults($_POST, 'pending'          , []);
-       $users       = defaults($_POST, 'user'             , []);
-       $nu_name     = defaults($_POST, 'new_user_name'    , '');
-       $nu_nickname = defaults($_POST, 'new_user_nickname', '');
-       $nu_email    = defaults($_POST, 'new_user_email'   , '');
-       $nu_language = Config::get('system', 'language');
-
-       BaseModule::checkFormSecurityTokenRedirectOnError('/admin/users', 'admin_users');
-
-       if (!($nu_name === "") && !($nu_email === "") && !($nu_nickname === "")) {
-               try {
-                       $result = User::create([
-                               'username' => $nu_name,
-                               'email' => $nu_email,
-                               'nickname' => $nu_nickname,
-                               'verified' => 1,
-                               'language' => $nu_language
-                       ]);
-               } catch (Exception $ex) {
-                       notice($ex->getMessage());
-                       return;
-               }
-
-               $user = $result['user'];
-               $preamble = Strings::deindent(L10n::t('
-                       Dear %1$s,
-                               the administrator of %2$s has set up an account for you.'));
-               $body = Strings::deindent(L10n::t('
-                       The login details are as follows:
-
-                       Site Location:  %1$s
-                       Login Name:             %2$s
-                       Password:               %3$s
-
-                       You may change your password from your account "Settings" page after logging
-                       in.
-
-                       Please take a few moments to review the other account settings on that page.
-
-                       You may also wish to add some basic information to your default profile
-                       ' . "\x28" . 'on the "Profiles" page' . "\x29" . ' so that other people can easily find you.
-
-                       We recommend setting your full name, adding a profile photo,
-                       adding some profile "keywords" ' . "\x28" . 'very useful in making new friends' . "\x29" . ' - and
-                       perhaps what country you live in; if you do not wish to be more specific
-                       than that.
-
-                       We fully respect your right to privacy, and none of these items are necessary.
-                       If you are new and do not know anybody here, they may help
-                       you to make some new and interesting friends.
-
-                       If you ever want to delete your account, you can do so at %1$s/removeme
-
-                       Thank you and welcome to %4$s.'));
-
-               $preamble = sprintf($preamble, $user['username'], Config::get('config', 'sitename'));
-               $body = sprintf($body, System::baseUrl(), $user['nickname'], $result['password'], Config::get('config', 'sitename'));
-
-               notification([
-                       'type'     => SYSTEM_EMAIL,
-                       'language' => $user['language'],
-                       'to_name'  => $user['username'],
-                       'to_email' => $user['email'],
-                       'uid'      => $user['uid'],
-                       'subject'  => L10n::t('Registration details for %s', Config::get('config', 'sitename')),
-                       'preamble' => $preamble,
-                       'body'     => $body]);
-       }
-
-       if (!empty($_POST['page_users_block'])) {
-               foreach ($users as $uid) {
-                       q("UPDATE `user` SET `blocked` = 1-`blocked` WHERE `uid` = %s", intval($uid)
-                       );
-               }
-               notice(L10n::tt("%s user blocked/unblocked", "%s users blocked/unblocked", count($users)));
-       }
-       if (!empty($_POST['page_users_delete'])) {
-               foreach ($users as $uid) {
-                       if (local_user() != $uid) {
-                               User::remove($uid);
-                       } else {
-                               notice(L10n::t('You can\'t remove yourself'));
-                       }
-               }
-               notice(L10n::tt("%s user deleted", "%s users deleted", count($users)));
-       }
-
-       if (!empty($_POST['page_users_approve'])) {
-               require_once "mod/regmod.php";
-               foreach ($pending as $hash) {
-                       user_allow($hash);
-               }
-       }
-       if (!empty($_POST['page_users_deny'])) {
-               require_once "mod/regmod.php";
-               foreach ($pending as $hash) {
-                       user_deny($hash);
-               }
-       }
-       $a->internalRedirect('admin/users');
-       return; // NOTREACHED
-}
-
-/**
- * @brief Admin panel subpage for User management
- *
- * This function generates the admin panel page for user management of the
- * node. It offers functionality to add/block/delete users and offers some
- * statistics about the userbase.
- *
- * The returned string holds the HTML code of the page.
- *
- * @param App $a
- * @return string
- * @throws \Friendica\Network\HTTPException\InternalServerErrorException
- */
-function admin_page_users(App $a)
-{
-       if ($a->argc > 2) {
-               $uid = $a->argv[3];
-               $user = DBA::selectFirst('user', ['username', 'blocked'], ['uid' => $uid]);
-               if (!DBA::isResult($user)) {
-                       notice('User not found' . EOL);
-                       $a->internalRedirect('admin/users');
-                       return ''; // NOTREACHED
-               }
-               switch ($a->argv[2]) {
-                       case "delete":
-                               if (local_user() != $uid) {
-                                       BaseModule::checkFormSecurityTokenRedirectOnError('/admin/users', 'admin_users', 't');
-                                       // delete user
-                                       User::remove($uid);
-
-                                       notice(L10n::t("User '%s' deleted", $user['username']));
-                               } else {
-                                       notice(L10n::t('You can\'t remove yourself'));
-                               }
-                               break;
-                       case "block":
-                               BaseModule::checkFormSecurityTokenRedirectOnError('/admin/users', 'admin_users', 't');
-                               q("UPDATE `user` SET `blocked` = %d WHERE `uid` = %s",
-                                       intval(1 - $user['blocked']),
-                                       intval($uid)
-                               );
-                               notice(sprintf(($user['blocked'] ? L10n::t("User '%s' unblocked") : L10n::t("User '%s' blocked")), $user['username']) . EOL);
-                               break;
-               }
-               $a->internalRedirect('admin/users');
-               return ''; // NOTREACHED
-       }
-
-       /* get pending */
-       $pending = Register::getPending();
-
-       $pager = new Pager($a->query_string, 100);
-
-       /* ordering */
-       $valid_orders = [
-               'contact.name',
-               'user.email',
-               'user.register_date',
-               'user.login_date',
-               'lastitem_date',
-               'user.page-flags'
-       ];
-
-       $order = "contact.name";
-       $order_direction = "+";
-       if (!empty($_GET['o'])) {
-               $new_order = $_GET['o'];
-               if ($new_order[0] === "-") {
-                       $order_direction = "-";
-                       $new_order = substr($new_order, 1);
-               }
-
-               if (in_array($new_order, $valid_orders)) {
-                       $order = $new_order;
-               }
-       }
-       $sql_order = "`" . str_replace('.', '`.`', $order) . "`";
-       $sql_order_direction = ($order_direction === "+") ? "ASC" : "DESC";
-
-       $users = q("SELECT `user`.*, `contact`.`name`, `contact`.`url`, `contact`.`micro`, `user`.`account_expired`, `contact`.`last-item` AS `lastitem_date`
-                               FROM `user`
-                               INNER JOIN `contact` ON `contact`.`uid` = `user`.`uid` AND `contact`.`self`
-                               WHERE `user`.`verified`
-                               ORDER BY $sql_order $sql_order_direction LIMIT %d, %d", $pager->getStart(), $pager->getItemsPerPage()
-       );
-
-       $adminlist = explode(",", str_replace(" ", "", Config::get('config', 'admin_email')));
-       $_setup_users = function ($e) use ($adminlist) {
-               $page_types = [
-                       User::PAGE_FLAGS_NORMAL    => L10n::t('Normal Account Page'),
-                       User::PAGE_FLAGS_SOAPBOX   => L10n::t('Soapbox Page'),
-                       User::PAGE_FLAGS_COMMUNITY => L10n::t('Public Forum'),
-                       User::PAGE_FLAGS_FREELOVE  => L10n::t('Automatic Friend Page'),
-                       User::PAGE_FLAGS_PRVGROUP  => L10n::t('Private Forum')
-               ];
-               $account_types = [
-                       User::ACCOUNT_TYPE_PERSON       => L10n::t('Personal Page'),
-                       User::ACCOUNT_TYPE_ORGANISATION => L10n::t('Organisation Page'),
-                       User::ACCOUNT_TYPE_NEWS         => L10n::t('News Page'),
-                       User::ACCOUNT_TYPE_COMMUNITY    => L10n::t('Community Forum'),
-                       User::ACCOUNT_TYPE_RELAY        => L10n::t('Relay'),
-               ];
-
-               $e['page_flags_raw'] = $e['page-flags'];
-               $e['page-flags'] = $page_types[$e['page-flags']];
-
-               $e['account_type_raw'] = ($e['page_flags_raw'] == 0) ? $e['account-type'] : -1;
-               $e['account-type'] = ($e['page_flags_raw'] == 0) ? $account_types[$e['account-type']] : "";
-
-               $e['register_date'] = Temporal::getRelativeDate($e['register_date']);
-               $e['login_date'] = Temporal::getRelativeDate($e['login_date']);
-               $e['lastitem_date'] = Temporal::getRelativeDate($e['lastitem_date']);
-               $e['is_admin'] = in_array($e['email'], $adminlist);
-               $e['is_deletable'] = (intval($e['uid']) != local_user());
-               $e['deleted'] = ($e['account_removed'] ? Temporal::getRelativeDate($e['account_expires_on']) : False);
-
-               return $e;
-       };
-
-       $users = array_map($_setup_users, $users);
-
-
-       // Get rid of dashes in key names, Smarty3 can't handle them
-       // and extracting deleted users
-
-       $tmp_users = [];
-       $deleted = [];
-
-       while (count($users)) {
-               $new_user = [];
-               foreach (array_pop($users) as $k => $v) {
-                       $k = str_replace('-', '_', $k);
-                       $new_user[$k] = $v;
-               }
-               if ($new_user['deleted']) {
-                       array_push($deleted, $new_user);
-               } else {
-                       array_push($tmp_users, $new_user);
-               }
-       }
-       //Reversing the two array, and moving $tmp_users to $users
-       array_reverse($deleted);
-       while (count($tmp_users)) {
-               array_push($users, array_pop($tmp_users));
-       }
-
-       $th_users = array_map(null, [L10n::t('Name'), L10n::t('Email'), L10n::t('Register date'), L10n::t('Last login'), L10n::t('Last item'), L10n::t('Type')], $valid_orders);
-
-       $t = Renderer::getMarkupTemplate('admin/users.tpl');
-       $o = Renderer::replaceMacros($t, [
-               // strings //
-               '$title' => L10n::t('Administration'),
-               '$page' => L10n::t('Users'),
-               '$submit' => L10n::t('Add User'),
-               '$select_all' => L10n::t('select all'),
-               '$h_pending' => L10n::t('User registrations waiting for confirm'),
-               '$h_deleted' => L10n::t('User waiting for permanent deletion'),
-               '$th_pending' => [L10n::t('Request date'), L10n::t('Name'), L10n::t('Email')],
-               '$no_pending' => L10n::t('No registrations.'),
-               '$pendingnotetext' => L10n::t('Note from the user'),
-               '$approve' => L10n::t('Approve'),
-               '$deny' => L10n::t('Deny'),
-               '$delete' => L10n::t('Delete'),
-               '$block' => L10n::t('Block'),
-               '$blocked' => L10n::t('User blocked'),
-               '$unblock' => L10n::t('Unblock'),
-               '$siteadmin' => L10n::t('Site admin'),
-               '$accountexpired' => L10n::t('Account expired'),
-
-               '$h_users' => L10n::t('Users'),
-               '$h_newuser' => L10n::t('New User'),
-               '$th_deleted' => [L10n::t('Name'), L10n::t('Email'), L10n::t('Register date'), L10n::t('Last login'), L10n::t('Last item'), L10n::t('Permanent deletion')],
-               '$th_users' => $th_users,
-               '$order_users' => $order,
-               '$order_direction_users' => $order_direction,
-
-               '$confirm_delete_multi' => L10n::t('Selected users will be deleted!\n\nEverything these users had posted on this site will be permanently deleted!\n\nAre you sure?'),
-               '$confirm_delete' => L10n::t('The user {0} will be deleted!\n\nEverything this user has posted on this site will be permanently deleted!\n\nAre you sure?'),
-
-               '$form_security_token' => BaseModule::getFormSecurityToken("admin_users"),
-
-               // values //
-               '$baseurl' => $a->getBaseURL(true),
-
-               '$pending' => $pending,
-               'deleted' => $deleted,
-               '$users' => $users,
-               '$newusername' => ['new_user_name', L10n::t("Name"), '', L10n::t("Name of the new user.")],
-               '$newusernickname' => ['new_user_nickname', L10n::t("Nickname"), '', L10n::t("Nickname of the new user.")],
-               '$newuseremail' => ['new_user_email', L10n::t("Email"), '', L10n::t("Email address of the new user."), '', '', 'email'],
-       ]);
-       $o .= $pager->renderFull(DBA::count('user'));
-       return $o;
-}
-
-/**
- * @brief Addons admin page
- *
- * This function generates the admin panel page for managing addons on the
- * friendica node. If an addon name is given a single page showing the details
- * for this addon is generated. If no name is given, a list of available
- * addons is shown.
- *
- * The template used for displaying the list of addons and the details of the
- * addon are the same as used for the templates.
- *
- * The returned string returned hulds the HTML code of the page.
- *
- * @param App   $a
- * @param array $addons_admin A list of admin addon names
- * @return string
- * @throws \Friendica\Network\HTTPException\InternalServerErrorException
- */
-function admin_page_addons(App $a, array $addons_admin)
-{
-       /*
-        * Single addon
-        */
-       if ($a->argc == 3) {
-               $addon = $a->argv[2];
-               if (!is_file("addon/$addon/$addon.php")) {
-                       notice(L10n::t("Item not found."));
-                       return '';
-               }
-
-               if (defaults($_GET, 'a', '') == "t") {
-                       BaseModule::checkFormSecurityTokenRedirectOnError('/admin/addons', 'admin_themes', 't');
-
-                       // Toggle addon status
-                       if (Addon::isEnabled($addon)) {
-                               Addon::uninstall($addon);
-                               info(L10n::t("Addon %s disabled.", $addon));
-                       } else {
-                               Addon::install($addon);
-                               info(L10n::t("Addon %s enabled.", $addon));
-                       }
-
-                       Addon::saveEnabledList();
-                       $a->internalRedirect('admin/addons');
-                       return ''; // NOTREACHED
-               }
-
-               // display addon details
-               if (Addon::isEnabled($addon)) {
-                       $status = "on";
-                       $action = L10n::t("Disable");
-               } else {
-                       $status = "off";
-                       $action = L10n::t("Enable");
-               }
-
-               $readme = null;
-               if (is_file("addon/$addon/README.md")) {
-                       $readme = Markdown::convert(file_get_contents("addon/$addon/README.md"), false);
-               } elseif (is_file("addon/$addon/README")) {
-                       $readme = "<pre>" . file_get_contents("addon/$addon/README") . "</pre>";
-               }
-
-               $admin_form = "";
-               if (in_array($addon, $addons_admin)) {
-                       require_once "addon/$addon/$addon.php";
-                       $func = $addon . '_addon_admin';
-                       $func($a, $admin_form);
-               }
-
-               $t = Renderer::getMarkupTemplate('admin/addon_details.tpl');
-
-               return Renderer::replaceMacros($t, [
-                       '$title' => L10n::t('Administration'),
-                       '$page' => L10n::t('Addons'),
-                       '$toggle' => L10n::t('Toggle'),
-                       '$settings' => L10n::t('Settings'),
-                       '$baseurl' => $a->getBaseURL(true),
-
-                       '$addon' => $addon,
-                       '$status' => $status,
-                       '$action' => $action,
-                       '$info' => Addon::getInfo($addon),
-                       '$str_author' => L10n::t('Author: '),
-                       '$str_maintainer' => L10n::t('Maintainer: '),
-
-                       '$admin_form' => $admin_form,
-                       '$function' => 'addons',
-                       '$screenshot' => '',
-                       '$readme' => $readme,
-
-                       '$form_security_token' => BaseModule::getFormSecurityToken("admin_themes"),
-               ]);
-       }
-
-       /*
-        * List addons
-        */
-       if (!empty($_GET['a']) && $_GET['a'] == "r") {
-               BaseModule::checkFormSecurityTokenRedirectOnError($a->getBaseURL() . '/admin/addons', 'admin_themes', 't');
-               Addon::reload();
-               info("Addons reloaded");
-               $a->internalRedirect('admin/addons');
-       }
-
-       $addons = [];
-       $files = glob("addon/*/");
-       if (is_array($files)) {
-               foreach ($files as $file) {
-                       if (is_dir($file)) {
-                               list($tmp, $id) = array_map("trim", explode("/", $file));
-                               $info = Addon::getInfo($id);
-                               $show_addon = true;
-
-                               // If the addon is unsupported, then only show it, when it is enabled
-                               if ((strtolower($info["status"]) == "unsupported") && !Addon::isEnabled($id)) {
-                                       $show_addon = false;
-                               }
-
-                               // Override the above szenario, when the admin really wants to see outdated stuff
-                               if (Config::get("system", "show_unsupported_addons")) {
-                                       $show_addon = true;
-                               }
-
-                               if ($show_addon) {
-                                       $addons[] = [$id, (Addon::isEnabled($id) ? "on" : "off"), $info];
-                               }
-                       }
-               }
-       }
-
-       $t = Renderer::getMarkupTemplate('admin/addons.tpl');
-       return Renderer::replaceMacros($t, [
-               '$title' => L10n::t('Administration'),
-               '$page' => L10n::t('Addons'),
-               '$submit' => L10n::t('Save Settings'),
-               '$reload' => L10n::t('Reload active addons'),
-               '$baseurl' => System::baseUrl(true),
-               '$function' => 'addons',
-               '$addons' => $addons,
-               '$pcount' => count($addons),
-               '$noplugshint' => L10n::t('There are currently no addons available on your node. You can find the official addon repository at %1$s and might find other interesting addons in the open addon registry at %2$s', 'https://github.com/friendica/friendica-addons', 'http://addons.friendi.ca'),
-               '$form_security_token' => BaseModule::getFormSecurityToken("admin_themes"),
-       ]);
-}
-
-/**
- * @param array  $themes
- * @param string $th
- * @param int    $result
- */
-function toggle_theme(&$themes, $th, &$result)
-{
-       $count = count($themes);
-       for ($x = 0; $x < $count; $x++) {
-               if ($themes[$x]['name'] === $th) {
-                       if ($themes[$x]['allowed']) {
-                               $themes[$x]['allowed'] = 0;
-                               $result = 0;
-                       } else {
-                               $themes[$x]['allowed'] = 1;
-                               $result = 1;
-                       }
-               }
-       }
-}
-
-/**
- * @param array  $themes
- * @param string $th
- * @return int
- */
-function theme_status($themes, $th)
-{
-       $count = count($themes);
-       for ($x = 0; $x < $count; $x++) {
-               if ($themes[$x]['name'] === $th) {
-                       if ($themes[$x]['allowed']) {
-                               return 1;
-                       } else {
-                               return 0;
-                       }
-               }
-       }
-       return 0;
-}
-
-/**
- * @param array $themes
- * @return string
- */
-function rebuild_theme_table($themes)
-{
-       $o = '';
-       if (count($themes)) {
-               foreach ($themes as $th) {
-                       if ($th['allowed']) {
-                               if (strlen($o)) {
-                                       $o .= ',';
-                               }
-                               $o .= $th['name'];
-                       }
-               }
-       }
-       return $o;
-}
-
-/**
- * @brief Themes admin page
- *
- * This function generates the admin panel page to control the themes available
- * on the friendica node. If the name of a theme is given as parameter a page
- * with the details for the theme is shown. Otherwise a list of available
- * themes is generated.
- *
- * The template used for displaying the list of themes and the details of the
- * themes are the same as used for the addons.
- *
- * The returned string contains the HTML code of the admin panel page.
- *
- * @param App $a
- * @return string
- * @throws \Friendica\Network\HTTPException\InternalServerErrorException
- */
-function admin_page_themes(App $a)
-{
-       $allowed_themes_str = Config::get('system', 'allowed_themes');
-       $allowed_themes_raw = explode(',', $allowed_themes_str);
-       $allowed_themes = [];
-       if (count($allowed_themes_raw)) {
-               foreach ($allowed_themes_raw as $x) {
-                       if (strlen(trim($x))) {
-                               $allowed_themes[] = trim($x);
-                       }
-               }
-       }
-
-       $themes = [];
-       $files = glob('view/theme/*');
-       if (is_array($files)) {
-               foreach ($files as $file) {
-                       $f = basename($file);
-
-                       // Is there a style file?
-                       $theme_files = glob('view/theme/' . $f . '/style.*');
-
-                       // If not then quit
-                       if (count($theme_files) == 0) {
-                               continue;
-                       }
-
-                       $is_experimental = intval(file_exists($file . '/experimental'));
-                       $is_supported = 1 - (intval(file_exists($file . '/unsupported')));
-                       $is_allowed = intval(in_array($f, $allowed_themes));
-
-                       if ($is_allowed || $is_supported || Config::get("system", "show_unsupported_themes")) {
-                               $themes[] = ['name' => $f, 'experimental' => $is_experimental, 'supported' => $is_supported, 'allowed' => $is_allowed];
-                       }
-               }
-       }
-
-       if (!count($themes)) {
-               notice(L10n::t('No themes found.'));
-               return '';
-       }
-
-       /*
-        * Single theme
-        */
-
-       if ($a->argc == 3) {
-               $theme = $a->argv[2];
-               if (!is_dir("view/theme/$theme")) {
-                       notice(L10n::t("Item not found."));
-                       return '';
-               }
-
-               if (!empty($_GET['a']) && $_GET['a'] == "t") {
-                       BaseModule::checkFormSecurityTokenRedirectOnError('/admin/themes', 'admin_themes', 't');
-
-                       // Toggle theme status
-
-                       toggle_theme($themes, $theme, $result);
-                       $s = rebuild_theme_table($themes);
-                       if ($result) {
-                               Theme::install($theme);
-                               info(sprintf('Theme %s enabled.', $theme));
-                       } else {
-                               Theme::uninstall($theme);
-                               info(sprintf('Theme %s disabled.', $theme));
-                       }
-
-                       Config::set('system', 'allowed_themes', $s);
-                       $a->internalRedirect('admin/themes');
-                       return ''; // NOTREACHED
-               }
-
-               // display theme details
-               if (theme_status($themes, $theme)) {
-                       $status = "on";
-                       $action = L10n::t("Disable");
-               } else {
-                       $status = "off";
-                       $action = L10n::t("Enable");
-               }
-
-               $readme = null;
-
-               if (is_file("view/theme/$theme/README.md")) {
-                       $readme = Markdown::convert(file_get_contents("view/theme/$theme/README.md"), false);
-               } elseif (is_file("view/theme/$theme/README")) {
-                       $readme = "<pre>" . file_get_contents("view/theme/$theme/README") . "</pre>";
-               }
-
-               $admin_form = '';
-               if (is_file("view/theme/$theme/config.php")) {
-                       require_once "view/theme/$theme/config.php";
-
-                       if (function_exists('theme_admin')) {
-                               $admin_form = theme_admin($a);
-                       }
-               }
-
-               $screenshot = [Theme::getScreenshot($theme), L10n::t('Screenshot')];
-               if (!stristr($screenshot[0], $theme)) {
-                       $screenshot = null;
-               }
-
-               $t = Renderer::getMarkupTemplate('admin/addon_details.tpl');
-               return Renderer::replaceMacros($t, [
-                       '$title' => L10n::t('Administration'),
-                       '$page' => L10n::t('Themes'),
-                       '$toggle' => L10n::t('Toggle'),
-                       '$settings' => L10n::t('Settings'),
-                       '$baseurl' => System::baseUrl(true),
-                       '$addon' => $theme . (!empty($_GET['mode']) ? '?mode=' . $_GET['mode'] : ''),
-                       '$status' => $status,
-                       '$action' => $action,
-                       '$info' => Theme::getInfo($theme),
-                       '$function' => 'themes',
-                       '$admin_form' => $admin_form,
-                       '$str_author' => L10n::t('Author: '),
-                       '$str_maintainer' => L10n::t('Maintainer: '),
-                       '$screenshot' => $screenshot,
-                       '$readme' => $readme,
-
-                       '$form_security_token' => BaseModule::getFormSecurityToken("admin_themes"),
-               ]);
-       }
-
-       // reload active themes
-       if (!empty($_GET['a']) && $_GET['a'] == "r") {
-               BaseModule::checkFormSecurityTokenRedirectOnError(System::baseUrl() . '/admin/themes', 'admin_themes', 't');
-               foreach ($themes as $th) {
-                       if ($th['allowed']) {
-                               Theme::uninstall($th['name']);
-                               Theme::install($th['name']);
-                       }
-               }
-               info("Themes reloaded");
-               $a->internalRedirect('admin/themes');
-       }
-
-       /*
-        * List themes
-        */
-
-       $addons = [];
-       foreach ($themes as $th) {
-               $addons[] = [$th['name'], (($th['allowed']) ? "on" : "off"), Theme::getInfo($th['name'])];
-       }
-
-       $t = Renderer::getMarkupTemplate('admin/addons.tpl');
-       return Renderer::replaceMacros($t, [
-               '$title'               => L10n::t('Administration'),
-               '$page'                => L10n::t('Themes'),
-               '$submit'              => L10n::t('Save Settings'),
-               '$reload'              => L10n::t('Reload active themes'),
-               '$baseurl'             => System::baseUrl(true),
-               '$function'            => 'themes',
-               '$addons'             => $addons,
-               '$pcount'              => count($themes),
-               '$noplugshint'         => L10n::t('No themes found on the system. They should be placed in %1$s', '<code>/view/themes</code>'),
-               '$experimental'        => L10n::t('[Experimental]'),
-               '$unsupported'         => L10n::t('[Unsupported]'),
-               '$form_security_token' => BaseModule::getFormSecurityToken("admin_themes"),
-       ]);
-}
-
-/**
- * @brief Prosesses data send by Logs admin page
- *
- * @param App $a
- * @throws \Friendica\Network\HTTPException\InternalServerErrorException
- */
-function admin_page_logs_post(App $a)
-{
-       if (!empty($_POST['page_logs'])) {
-               BaseModule::checkFormSecurityTokenRedirectOnError('/admin/logs', 'admin_logs');
-
-               $logfile   = (!empty($_POST['logfile']) ? Strings::escapeTags(trim($_POST['logfile'])) : '');
-               $debugging = !empty($_POST['debugging']);
-               $loglevel  = defaults($_POST, 'loglevel', LogLevel::ERROR);
-
-               Config::set('system', 'logfile', $logfile);
-               Config::set('system', 'debugging', $debugging);
-               Config::set('system', 'loglevel', $loglevel);
-       }
-
-       info(L10n::t("Log settings updated."));
-       $a->internalRedirect('admin/logs');
-       return; // NOTREACHED
-}
-
-/**
- * @brief Generates admin panel subpage for configuration of the logs
- *
- * This function take the view/templates/admin_logs.tpl file and generates a
- * page where admin can configure the logging of friendica.
- *
- * Displaying the log is separated from the log config as the logfile can get
- * big depending on the settings and changing settings regarding the logs can
- * thus waste bandwidth.
- *
- * The string returned contains the content of the template file with replaced
- * macros.
- *
- * @param App $a
- * @return string
- * @throws \Friendica\Network\HTTPException\InternalServerErrorException
- */
-function admin_page_logs(App $a)
-{
-       $log_choices = [
-               LogLevel::ERROR   => 'Error',
-               LogLevel::WARNING => 'Warning',
-               LogLevel::NOTICE  => 'Notice',
-               LogLevel::INFO    => 'Info',
-               LogLevel::DEBUG   => 'Debug',
-       ];
-
-       if (ini_get('log_errors')) {
-               $phplogenabled = L10n::t('PHP log currently enabled.');
-       } else {
-               $phplogenabled = L10n::t('PHP log currently disabled.');
-       }
-
-       $t = Renderer::getMarkupTemplate('admin/logs.tpl');
-
-       return Renderer::replaceMacros($t, [
-               '$title' => L10n::t('Administration'),
-               '$page' => L10n::t('Logs'),
-               '$submit' => L10n::t('Save Settings'),
-               '$clear' => L10n::t('Clear'),
-               '$baseurl' => System::baseUrl(true),
-               '$logname' => Config::get('system', 'logfile'),
-               // name, label, value, help string, extra data...
-               '$debugging' => ['debugging', L10n::t("Enable Debugging"), Config::get('system', 'debugging'), ""],
-               '$logfile' => ['logfile', L10n::t("Log file"), Config::get('system', 'logfile'), L10n::t("Must be writable by web server. Relative to your Friendica top-level directory.")],
-               '$loglevel' => ['loglevel', L10n::t("Log level"), Config::get('system', 'loglevel'), "", $log_choices],
-               '$form_security_token' => BaseModule::getFormSecurityToken("admin_logs"),
-               '$phpheader' => L10n::t("PHP logging"),
-               '$phphint' => L10n::t("To temporarily enable logging of PHP errors and warnings you can prepend the following to the index.php file of your installation. The filename set in the 'error_log' line is relative to the friendica top-level directory and must be writeable by the web server. The option '1' for 'log_errors' and 'display_errors' is to enable these options, set to '0' to disable them."),
-               '$phplogcode' => "error_reporting(E_ERROR | E_WARNING | E_PARSE);\nini_set('error_log','php.out');\nini_set('log_errors','1');\nini_set('display_errors', '1');",
-               '$phplogenabled' => $phplogenabled,
-       ]);
-}
-
-/**
- * @brief Generates admin panel subpage to view the Friendica log
- *
- * This function loads the template view/templates/admin_viewlogs.tpl to
- * display the systemlog content. The filename for the systemlog of friendica
- * is relative to the base directory and taken from the config entry 'logfile'
- * in the 'system' category.
- *
- * Displaying the log is separated from the log config as the logfile can get
- * big depending on the settings and changing settings regarding the logs can
- * thus waste bandwidth.
- *
- * The string returned contains the content of the template file with replaced
- * macros.
- *
- * @param App $a
- * @return string
- * @throws \Friendica\Network\HTTPException\InternalServerErrorException
- */
-function admin_page_viewlogs(App $a)
-{
-       $t = Renderer::getMarkupTemplate('admin/viewlogs.tpl');
-       $f = Config::get('system', 'logfile');
-       $data = '';
-
-       if (!file_exists($f)) {
-               $data = L10n::t('Error trying to open <strong>%1$s</strong> log file.\r\n<br/>Check to see if file %1$s exist and is readable.', $f);
-       } else {
-               $fp = fopen($f, 'r');
-               if (!$fp) {
-                       $data = L10n::t('Couldn\'t open <strong>%1$s</strong> log file.\r\n<br/>Check to see if file %1$s is readable.', $f);
-               } else {
-                       $fstat = fstat($fp);
-                       $size = $fstat['size'];
-                       if ($size != 0) {
-                               if ($size > 5000000 || $size < 0) {
-                                       $size = 5000000;
-                               }
-                               $seek = fseek($fp, 0 - $size, SEEK_END);
-                               if ($seek === 0) {
-                                       $data = Strings::escapeHtml(fread($fp, $size));
-                                       while (!feof($fp)) {
-                                               $data .= Strings::escapeHtml(fread($fp, 4096));
-                                       }
-                               }
-                       }
-                       fclose($fp);
-               }
-       }
-       return Renderer::replaceMacros($t, [
-               '$title' => L10n::t('Administration'),
-               '$page' => L10n::t('View Logs'),
-               '$data' => $data,
-               '$logname' => Config::get('system', 'logfile')
-       ]);
-}
-
-/**
- * @brief Prosesses data send by the features admin page
- *
- * @param App $a
- * @throws \Friendica\Network\HTTPException\InternalServerErrorException
- */
-function admin_page_features_post(App $a)
-{
-       BaseModule::checkFormSecurityTokenRedirectOnError('/admin/features', 'admin_manage_features');
-
-       Logger::log('postvars: ' . print_r($_POST, true), Logger::DATA);
-
-       $features = Feature::get(false);
-
-       foreach ($features as $fname => $fdata) {
-               foreach (array_slice($fdata, 1) as $f) {
-                       $feature = $f[0];
-                       $feature_state = 'feature_' . $feature;
-                       $featurelock = 'featurelock_' . $feature;
-
-                       if (!empty($_POST[$feature_state])) {
-                               $val = intval($_POST[$feature_state]);
-                       } else {
-                               $val = 0;
-                       }
-                       Config::set('feature', $feature, $val);
-
-                       if (!empty($_POST[$featurelock])) {
-                               Config::set('feature_lock', $feature, $val);
-                       } else {
-                               Config::delete('feature_lock', $feature);
-                       }
-               }
-       }
-
-       $a->internalRedirect('admin/features');
-       return; // NOTREACHED
-}
-
-/**
- * @brief Subpage for global additional feature management
- *
- * This functin generates the subpage 'Manage Additional Features'
- * for the admin panel. At this page the admin can set preferences
- * for the user settings of the 'additional features'. If needed this
- * preferences can be locked through the admin.
- *
- * The returned string contains the HTML code of the subpage 'Manage
- * Additional Features'
- *
- * @param App $a
- * @return string
- * @throws \Friendica\Network\HTTPException\InternalServerErrorException
- */
-function admin_page_features(App $a)
-{
-       if (($a->argc > 1) && ($a->getArgumentValue(1) === 'features')) {
-               $arr = [];
-               $features = Feature::get(false);
-
-               foreach ($features as $fname => $fdata) {
-                       $arr[$fname] = [];
-                       $arr[$fname][0] = $fdata[0];
-                       foreach (array_slice($fdata, 1) as $f) {
-                               $set = Config::get('feature', $f[0], $f[3]);
-                               $arr[$fname][1][] = [
-                                       ['feature_' . $f[0], $f[1], $set, $f[2], [L10n::t('Off'), L10n::t('On')]],
-                                       ['featurelock_' . $f[0], L10n::t('Lock feature %s', $f[1]), (($f[4] !== false) ? "1" : ''), '', [L10n::t('Off'), L10n::t('On')]]
-                               ];
-                       }
-               }
-
-               $tpl = Renderer::getMarkupTemplate('admin/settings_features.tpl');
-               $o = Renderer::replaceMacros($tpl, [
-                       '$form_security_token' => BaseModule::getFormSecurityToken("admin_manage_features"),
-                       '$title' => L10n::t('Manage Additional Features'),
-                       '$features' => $arr,
-                       '$submit' => L10n::t('Save Settings'),
-               ]);
-
-               return $o;
-       }
-}
-
-function admin_page_server_vital()
-{
-       // Fetch the host-meta to check if this really is a vital server
-       return Network::curl(System::baseUrl() . '/.well-known/host-meta')->isSuccess();
-}
diff --git a/mod/allfriends.php b/mod/allfriends.php
deleted file mode 100644 (file)
index ce648cc..0000000
+++ /dev/null
@@ -1,106 +0,0 @@
-<?php
-/**
- * @file mod/allfriends.php
- */
-
-use Friendica\App;
-use Friendica\Content\ContactSelector;
-use Friendica\Content\Pager;
-use Friendica\Core\L10n;
-use Friendica\Core\Renderer;
-use Friendica\Core\System;
-use Friendica\Database\DBA;
-use Friendica\Model;
-use Friendica\Module;
-use Friendica\Util\Proxy as ProxyUtils;
-
-
-function allfriends_content(App $a)
-{
-       $o = '';
-       if (!local_user()) {
-               notice(L10n::t('Permission denied.') . EOL);
-               return;
-       }
-
-       $cid = 0;
-       if ($a->argc > 1) {
-               $cid = intval($a->argv[1]);
-       }
-
-       if (!$cid) {
-               return;
-       }
-
-       $uid = $a->user['uid'];
-
-       $contact = DBA::selectFirst('contact', ['name', 'url', 'photo', 'uid', 'id'], ['id' => $cid, 'uid' => local_user()]);
-
-       if (!DBA::isResult($contact)) {
-               return;
-       }
-
-       $a->page['aside'] = "";
-       Model\Profile::load($a, "", 0, Model\Contact::getDetailsByURL($contact["url"]));
-
-       $total = Model\GContact::countAllFriends(local_user(), $cid);
-
-       $pager = new Pager($a->query_string);
-
-       $r = Model\GContact::allFriends(local_user(), $cid, $pager->getStart(), $pager->getItemsPerPage());
-       if (!DBA::isResult($r)) {
-               $o .= L10n::t('No friends to display.');
-               return $o;
-       }
-
-       $id = 0;
-
-       $entries = [];
-       foreach ($r as $rr) {
-               //get further details of the contact
-               $contact_details = Model\Contact::getDetailsByURL($rr['url'], $uid, $rr);
-
-               $connlnk = '';
-               // $rr[cid] is only available for common contacts. So if the contact is a common one, use contact_photo_menu to generate the photo_menu
-               // If the contact is not common to the user, Connect/Follow' will be added to the photo menu
-               if ($rr['cid']) {
-                       $rr['id'] = $rr['cid'];
-                       $photo_menu = Model\Contact::photoMenu($rr);
-               } else {
-                       $connlnk = System::baseUrl() . '/follow/?url=' . $rr['url'];
-                       $photo_menu = [
-                               'profile' => [L10n::t("View Profile"), Model\Contact::magicLink($rr['url'])],
-                               'follow' => [L10n::t("Connect/Follow"), $connlnk]
-                       ];
-               }
-
-               $entry = [
-                       'url'          => Model\Contact::magicLink($rr['url']),
-                       'itemurl'      => defaults($contact_details, 'addr', $rr['url']),
-                       'name'         => $contact_details['name'],
-                       'thumb'        => ProxyUtils::proxifyUrl($contact_details['thumb'], false, ProxyUtils::SIZE_THUMB),
-                       'img_hover'    => $contact_details['name'],
-                       'details'      => $contact_details['location'],
-                       'tags'         => $contact_details['keywords'],
-                       'about'        => $contact_details['about'],
-                       'account_type' => Model\Contact::getAccountType($contact_details),
-                       'network'      => ContactSelector::networkToName($contact_details['network'], $contact_details['url']),
-                       'photo_menu'   => $photo_menu,
-                       'conntxt'      => L10n::t('Connect'),
-                       'connlnk'      => $connlnk,
-                       'id'           => ++$id,
-               ];
-               $entries[] = $entry;
-       }
-
-       $tab_str = Module\Contact::getTabsHTML($a, $contact, 4);
-
-       $tpl = Renderer::getMarkupTemplate('viewcontact_template.tpl');
-       $o .= Renderer::replaceMacros($tpl, [
-               '$tab_str' => $tab_str,
-               '$contacts' => $entries,
-               '$paginate' => $pager->renderFull($total),
-       ]);
-
-       return $o;
-}
diff --git a/mod/amcd.php b/mod/amcd.php
deleted file mode 100644 (file)
index ca5aa07..0000000
+++ /dev/null
@@ -1,49 +0,0 @@
-<?php
-
-function amcd_content()
-{
-       echo <<< JSON
-{
-  "version":1,
-  "sessionstatus":{
-    "method":"GET",
-    "path":"/session"
-  },
-  "auth-methods": {
-    "username-password-form": {
-      "connect": {
-        "method":"POST",
-        "path":"/login",
-        "params": {
-          "username":"login-name",
-          "password":"password"
-        },
-        "onsuccess": { "action":"reload" }
-      },
-      "disconnect": {
-        "method":"GET",
-        "path":"\/logout"
-      }
-    }
-  }
-  "methods": {
-    "username-password-form": {
-      "connect": {
-        "method":"POST",
-        "path":"\/login",
-        "params": {
-          "username":"login-name",
-          "password":"password"
-        },
-        "onsuccess": { "action":"reload" }
-      },
-      "disconnect": {
-        "method":"GET",
-        "path":"\/logout"
-      }
-    }
-  }
-}
-JSON;
-       exit();
-}
diff --git a/mod/bookmarklet.php b/mod/bookmarklet.php
deleted file mode 100644 (file)
index 1c4d191..0000000
+++ /dev/null
@@ -1,59 +0,0 @@
-<?php
-/**
- * @file mod/bookmarklet.php
- */
-
-use Friendica\App;
-use Friendica\Core\ACL;
-use Friendica\Core\Config;
-use Friendica\Core\L10n;
-use Friendica\Core\System;
-use Friendica\Module\Login;
-use Friendica\Util\Strings;
-
-function bookmarklet_init()
-{
-       $_GET["mode"] = "minimal";
-}
-
-function bookmarklet_content(App $a)
-{
-       if (!local_user()) {
-               $o = '<h2>' . L10n::t('Login') . '</h2>';
-               $o .= Login::form($a->query_string, intval(Config::get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? false : true);
-               return $o;
-       }
-
-       $referer = Strings::normaliseLink(defaults($_SERVER, 'HTTP_REFERER', ''));
-       $page = Strings::normaliseLink(System::baseUrl() . "/bookmarklet");
-
-       if (!strstr($referer, $page)) {
-               if (empty($_REQUEST["url"])) {
-                       System::httpExit(400, ["title" => L10n::t('Bad Request')]);
-               }
-
-               $content = add_page_info($_REQUEST["url"]);
-
-               $x = [
-                       'is_owner' => true,
-                       'allow_location' => $a->user['allow_location'],
-                       'default_location' => $a->user['default-location'],
-                       'nickname' => $a->user['nickname'],
-                       'lockstate' => ((is_array($a->user) && ((strlen($a->user['allow_cid'])) || (strlen($a->user['allow_gid'])) || (strlen($a->user['deny_cid'])) || (strlen($a->user['deny_gid'])))) ? 'lock' : 'unlock'),
-                       'default_perms' => ACL::getDefaultUserPermissions($a->user),
-                       'acl' => ACL::getFullSelectorHTML($a->user, true),
-                       'bang' => '',
-                       'visitor' => 'block',
-                       'profile_uid' => local_user(),
-                       'title' => trim(defaults($_REQUEST, 'title', ''), "*"),
-                       'content' => $content
-               ];
-               $o = status_editor($a, $x, 0, false);
-               $o .= "<script>window.resizeTo(800,550);</script>";
-       } else {
-               $o = '<h2>' . L10n::t('The post was created') . '</h2>';
-               $o .= "<script>window.close()</script>";
-       }
-
-       return $o;
-}
index 5baffec8a8f423cbfaf30d45739ecbf9f9bcc180..e93341583a53df4ab42e75b4f4f282e4958ab13b 100644 (file)
@@ -31,11 +31,11 @@ function cal_init(App $a)
        }
 
        if (Config::get('system', 'block_public') && !local_user() && !remote_user()) {
-               System::httpExit(403, ['title' => L10n::t('Access denied.')]);
+               throw new \Friendica\Network\HTTPException\ForbiddenException(L10n::t('Access denied.'));
        }
 
        if ($a->argc < 2) {
-               System::httpExit(403, ['title' => L10n::t('Access denied.')]);
+               throw new \Friendica\Network\HTTPException\ForbiddenException(L10n::t('Access denied.'));
        }
 
        Nav::setSelected('events');
@@ -43,7 +43,7 @@ function cal_init(App $a)
        $nick = $a->argv[1];
        $user = DBA::selectFirst('user', [], ['nickname' => $nick, 'blocked' => false]);
        if (!DBA::isResult($user)) {
-               System::httpExit(404, ['title' => L10n::t('Page not found.')]);
+               throw new \Slim\Exception\NotFoundException();
        }
 
        $a->data['user'] = $user;
@@ -90,7 +90,6 @@ function cal_content(App $a)
 
        $htpl = Renderer::getMarkupTemplate('event_head.tpl');
        $a->page['htmlhead'] .= Renderer::replaceMacros($htpl, [
-               '$baseurl' => System::baseUrl(),
                '$module_url' => '/cal/' . $a->data['user']['nickname'],
                '$modparams' => 2,
                '$i18n' => $i18n,
@@ -268,7 +267,6 @@ function cal_content(App $a)
                }
 
                $o = Renderer::replaceMacros($tpl, [
-                       '$baseurl' => System::baseUrl(),
                        '$tabs' => $tabs,
                        '$title' => L10n::t('Events'),
                        '$view' => L10n::t('View'),
index 745411a8ef89ec10f9f8263fda1db1a30f3355d0..1a9f98fa33103f8f411a9ebd6d12dca36bee812d 100644 (file)
@@ -29,7 +29,7 @@ function dfrn_notify_post(App $a) {
 
                        $user = DBA::selectFirst('user', [], ['nickname' => $nick, 'account_expired' => false, 'account_removed' => false]);
                        if (!DBA::isResult($user)) {
-                               System::httpExit(500);
+                               throw new \Friendica\Network\HTTPException\InternalServerErrorException();
                        }
                        dfrn_dispatch_private($user, $postdata);
                } elseif (!dfrn_dispatch_public($postdata)) {
index 5b72c0bf940cec4fa7d4ac0c643430c9b1e4c425..6c849cb807fa6b28059991e51e6207cb9a85aa84 100644 (file)
@@ -50,7 +50,7 @@ function dfrn_poll_init(App $a)
 
        if (($dfrn_id === '') && empty($_POST['dfrn_id'])) {
                if (Config::get('system', 'block_public') && !local_user() && !remote_user()) {
-                       System::httpExit(403);
+                       throw new \Friendica\Network\HTTPException\ForbiddenException();
                }
 
                $user = '';
@@ -59,7 +59,7 @@ function dfrn_poll_init(App $a)
                                DBA::escape($a->argv[1])
                        );
                        if (!$r) {
-                               System::httpExit(404);
+                               throw new \Friendica\Network\HTTPException\NotFoundException();
                        }
 
                        $hidewall = ($r[0]['hidewall'] && !local_user());
@@ -483,7 +483,7 @@ function dfrn_poll_content(App $a)
                        // heluecht: I don't know why we don't fail immediately when the user or contact hadn't been found.
                        // Since it doesn't make sense to continue from this point on, we now fail here. This should be safe.
                        if (!DBA::isResult($r)) {
-                               System::httpExit(404, ["title" => L10n::t('Page not found.')]);
+                               throw new \Friendica\Network\HTTPException\NotFoundException();
                        }
 
                        // URL reply
diff --git a/mod/directory.php b/mod/directory.php
deleted file mode 100644 (file)
index 256c9bb..0000000
+++ /dev/null
@@ -1,230 +0,0 @@
-<?php
-/**
- * @file mod/directory.php
- */
-
-use Friendica\App;
-use Friendica\Content\Nav;
-use Friendica\Content\Pager;
-use Friendica\Content\Widget;
-use Friendica\Core\Config;
-use Friendica\Core\Hook;
-use Friendica\Core\L10n;
-use Friendica\Core\Renderer;
-use Friendica\Database\DBA;
-use Friendica\Model\Contact;
-use Friendica\Model\Profile;
-use Friendica\Util\Proxy as ProxyUtils;
-use Friendica\Util\Strings;
-
-function directory_init(App $a)
-{
-       if (local_user()) {
-               $a->page['aside'] .= Widget::findPeople();
-               $a->page['aside'] .= Widget::follow();
-       } else {
-               unset($_SESSION['theme']);
-               unset($_SESSION['mobile-theme']);
-       }
-}
-
-function directory_post(App $a)
-{
-       if (!empty($_POST['search'])) {
-               $a->data['search'] = $_POST['search'];
-       }
-}
-
-function directory_content(App $a)
-{
-       if ((Config::get('system', 'block_public') && !local_user() && !remote_user())
-               || (Config::get('system', 'block_local_dir') && !local_user() && !remote_user())
-       ) {
-               notice(L10n::t('Public access denied.') . EOL);
-               return;
-       }
-
-       $o = '';
-       $entries = [];
-
-       Nav::setSelected('directory');
-
-       if (!empty($a->data['search'])) {
-               $search = Strings::escapeTags(trim($a->data['search']));
-       } else {
-               $search = (!empty($_GET['search']) ? Strings::escapeTags(trim(rawurldecode($_GET['search']))) : '');
-       }
-
-       $gdirpath = '';
-       $dirurl = Config::get('system', 'directory');
-       if (strlen($dirurl)) {
-               $gdirpath = Profile::zrl($dirurl, true);
-       }
-
-       if ($search) {
-               $search = DBA::escape($search);
-
-               $sql_extra = " AND ((`profile`.`name` LIKE '%$search%') OR
-                               (`user`.`nickname` LIKE '%$search%') OR
-                               (`profile`.`pdesc` LIKE '%$search%') OR
-                               (`profile`.`locality` LIKE '%$search%') OR
-                               (`profile`.`region` LIKE '%$search%') OR
-                               (`profile`.`country-name` LIKE '%$search%') OR
-                               (`profile`.`gender` LIKE '%$search%') OR
-                               (`profile`.`marital` LIKE '%$search%') OR
-                               (`profile`.`sexual` LIKE '%$search%') OR
-                               (`profile`.`about` LIKE '%$search%') OR
-                               (`profile`.`romance` LIKE '%$search%') OR
-                               (`profile`.`work` LIKE '%$search%') OR
-                               (`profile`.`education` LIKE '%$search%') OR
-                               (`profile`.`pub_keywords` LIKE '%$search%') OR
-                               (`profile`.`prv_keywords` LIKE '%$search%'))";
-       } else {
-               $sql_extra = '';
-       }
-
-       $publish = (Config::get('system', 'publish_all') ? '' : " AND `publish` = 1 " );
-
-
-       $total = 0;
-       $cnt = DBA::fetchFirst("SELECT COUNT(*) AS `total` FROM `profile`
-                               LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
-                               WHERE `is-default` $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed` $sql_extra");
-       if (DBA::isResult($cnt)) {
-               $total = $cnt['total'];
-       }
-       $pager = new Pager($a->query_string, 60);
-
-       $order = " ORDER BY `name` ASC ";
-
-       $limit = $pager->getStart()."," . $pager->getItemsPerPage();
-
-       $r = DBA::p("SELECT `profile`.*, `profile`.`uid` AS `profile_uid`, `user`.`nickname`, `user`.`timezone` , `user`.`page-flags`,
-                       `contact`.`addr`, `contact`.`url` AS `profile_url` FROM `profile`
-                       LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
-                       LEFT JOIN `contact` ON `contact`.`uid` = `user`.`uid`
-                       WHERE `is-default` $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed` AND `contact`.`self`
-                       $sql_extra $order LIMIT $limit"
-       );
-       if (DBA::isResult($r)) {
-               if (in_array('small', $a->argv)) {
-                       $photo = 'thumb';
-               } else {
-                       $photo = 'photo';
-               }
-
-               while ($rr = DBA::fetch($r)) {
-                       $entries[] = format_directory_entry($rr, $photo);
-               }
-               DBA::close($r);
-       } else {
-               info(L10n::t("No entries \x28some entries may be hidden\x29.") . EOL);
-       }
-
-       $tpl = Renderer::getMarkupTemplate('directory_header.tpl');
-
-       $o .= Renderer::replaceMacros($tpl, [
-               '$search'    => $search,
-               '$globaldir' => L10n::t('Global Directory'),
-               '$gdirpath'  => $gdirpath,
-               '$desc'      => L10n::t('Find on this site'),
-               '$contacts'  => $entries,
-               '$finding'   => L10n::t('Results for:'),
-               '$findterm'  => (strlen($search) ? $search : ""),
-               '$title'     => L10n::t('Site Directory'),
-               '$search_mod' => 'directory',
-               '$submit'    => L10n::t('Find'),
-               '$paginate'  => $pager->renderFull($total),
-       ]);
-
-       return $o;
-}
-
-/**
- * Format contact/profile/user data from the database into an usable
- * array for displaying directory entries.
- * 
- * @param array $arr The directory entry from the database.
- * @param string $photo_size Avatar size (thumb, photo or micro).
- * 
- * @return array
- */
-function format_directory_entry(array $arr, $photo_size = 'photo')
-{
-       $itemurl = (($arr['addr'] != "") ? $arr['addr'] : $arr['profile_url']);
-
-       $profile_link = $arr['profile_url'];
-
-       $pdesc = (($arr['pdesc']) ? $arr['pdesc'] . '<br />' : '');
-
-       $details = '';
-       if (strlen($arr['locality'])) {
-               $details .= $arr['locality'];
-       }
-       if (strlen($arr['region'])) {
-               if (strlen($arr['locality'])) {
-                       $details .= ', ';
-               }
-               $details .= $arr['region'];
-       }
-       if (strlen($arr['country-name'])) {
-               if (strlen($details)) {
-                       $details .= ', ';
-               }
-               $details .= $arr['country-name'];
-       }
-
-       $profile = $arr;
-
-       if (!empty($profile['address'])
-               || !empty($profile['locality'])
-               || !empty($profile['region'])
-               || !empty($profile['postal-code'])
-               || !empty($profile['country-name'])
-       ) {
-               $location = L10n::t('Location:');
-       } else {
-               $location = '';
-       }
-
-       $gender   = (!empty($profile['gender'])   ? L10n::t('Gender:')   : false);
-       $marital  = (!empty($profile['marital'])  ? L10n::t('Status:')   : false);
-       $homepage = (!empty($profile['homepage']) ? L10n::t('Homepage:') : false);
-       $about    = (!empty($profile['about'])    ? L10n::t('About:')    : false);
-
-       $location_e = $location;
-
-       $photo_menu = [
-               'profile' => [L10n::t("View Profile"), Contact::magicLink($profile_link)]
-       ];
-
-       $entry = [
-               'id'           => $arr['id'],
-               'url'          => Contact::magicLInk($profile_link),
-               'itemurl'      => $itemurl,
-               'thumb'        => ProxyUtils::proxifyUrl($arr[$photo_size], false, ProxyUtils::SIZE_THUMB),
-               'img_hover'    => $arr['name'],
-               'name'         => $arr['name'],
-               'details'      => $details,
-               'account_type' => Contact::getAccountType($arr),
-               'profile'      => $profile,
-               'location'     => $location_e,
-               'tags'         => $arr['pub_keywords'],
-               'gender'       => $gender,
-               'pdesc'        => $pdesc,
-               'marital'      => $marital,
-               'homepage'     => $homepage,
-               'about'        => $about,
-               'photo_menu'   => $photo_menu,
-
-       ];
-
-       $hook = ['contact' => $arr, 'entry' => $entry];
-
-       Hook::callAll('directory_item', $hook);
-
-       unset($profile);
-       unset($location);
-
-       return $hook['entry'];
-}
index acc2a5b0901540466009bb60e6066c28fc63e274..fa5b2e1962d3d0df161315f6010a4074d52f3f64 100644 (file)
@@ -20,6 +20,7 @@ use Friendica\Model\Group;
 use Friendica\Model\Item;
 use Friendica\Model\Profile;
 use Friendica\Module\Objects;
+use Friendica\Network\HTTPException;
 use Friendica\Protocol\ActivityPub;
 use Friendica\Protocol\DFRN;
 use Friendica\Util\Strings;
@@ -76,7 +77,7 @@ function display_init(App $a)
        }
 
        if (!DBA::isResult($item)) {
-               System::httpExit(404);
+               return;
        }
 
        if ($a->argc >= 3 && $nick == 'feed-item') {
@@ -200,8 +201,7 @@ function display_fetchauthor($a, $item)
 function display_content(App $a, $update = false, $update_uid = 0)
 {
        if (Config::get('system','block_public') && !local_user() && !remote_user()) {
-               notice(L10n::t('Public access denied.') . EOL);
-               return;
+               throw new HTTPException\ForbiddenException(L10n::t('Public access denied.'));
        }
 
        $o = '';
@@ -254,7 +254,7 @@ function display_content(App $a, $update = false, $update_uid = 0)
        }
 
        if (!$item_id) {
-               System::httpExit(404);
+               throw new HTTPException\NotFoundException(L10n::t('The requested item doesn\'t exist or has been deleted.'));
        }
 
        // We are displaying an "alternate" link if that post was public. See issue 2864
@@ -303,8 +303,7 @@ function display_content(App $a, $update = false, $update_uid = 0)
        $is_owner = (local_user() && (in_array($a->profile['profile_uid'], [local_user(), 0])) ? true : false);
 
        if (!empty($a->profile['hidewall']) && !$is_owner && !$is_remote_contact) {
-               notice(L10n::t('Access to this profile has been restricted.') . EOL);
-               return;
+               throw new HTTPException\ForbiddenException(L10n::t('Access to this profile has been restricted.'));
        }
 
        // We need the editor here to be able to reshare an item.
@@ -340,7 +339,7 @@ function display_content(App $a, $update = false, $update_uid = 0)
        $item = Item::selectFirstForUser(local_user(), $fields, $condition);
 
        if (!DBA::isResult($item)) {
-               System::httpExit(404);
+               throw new HTTPException\NotFoundException(L10n::t('The requested item doesn\'t exist or has been deleted.'));
        }
 
        $item['uri'] = $item['parent-uri'];
@@ -415,7 +414,7 @@ function displayShowFeed($item_id, $conversation)
 {
        $xml = DFRN::itemFeed($item_id, $conversation);
        if ($xml == '') {
-               System::httpExit(500);
+               throw new HTTPException\InternalServerErrorException(L10n::t('The feed for this item is unavailable.'));
        }
        header("Content-type: application/atom+xml");
        echo $xml;
index c1c0d16d7fd712497476e6c7742a23624dac119d..e14baffa28aca2cad4f483c097cc38487a9194c1 100644 (file)
@@ -8,7 +8,6 @@ use Friendica\Content\Feature;
 use Friendica\Core\Hook;
 use Friendica\Core\L10n;
 use Friendica\Core\Renderer;
-use Friendica\Core\System;
 use Friendica\Model\FileTag;
 use Friendica\Model\Item;
 use Friendica\Database\DBA;
@@ -48,7 +47,6 @@ function editpost_content(App $a)
 
        $tpl = Renderer::getMarkupTemplate('jot-header.tpl');
        $a->page['htmlhead'] .= Renderer::replaceMacros($tpl, [
-               '$baseurl' => System::baseUrl(),
                '$ispublic' => '&nbsp;', // L10n::t('Visible to <strong>everybody</strong>'),
                '$geotag' => $geotag,
                '$nickname' => $a->user['nickname']
@@ -91,7 +89,6 @@ function editpost_content(App $a)
                '$posttype' => $item['post-type'],
                '$content' => undo_post_tagging($item['body']),
                '$post_id' => $post_id,
-               '$baseurl' => System::baseUrl(),
                '$defloc' => $a->user['default-location'],
                '$visitor' => 'none',
                '$pvisit' => 'none',
index 008cf643ceac1a670814ff90f15bfb85cea3b742..6569653a063f01779e411c2f84a696a7632e2a62 100644 (file)
@@ -237,7 +237,6 @@ function events_content(App $a)
 
        $htpl = Renderer::getMarkupTemplate('event_head.tpl');
        $a->page['htmlhead'] .= Renderer::replaceMacros($htpl, [
-               '$baseurl' => System::baseUrl(),
                '$module_url' => '/events',
                '$modparams' => 1,
                '$i18n' => $i18n,
@@ -379,7 +378,6 @@ function events_content(App $a)
                }
 
                $o = Renderer::replaceMacros($tpl, [
-                       '$baseurl'   => System::baseUrl(),
                        '$tabs'      => $tabs,
                        '$title'     => L10n::t('Events'),
                        '$view'      => L10n::t('View'),
index 559896acb13932ea6c690b4dd93d6dca0a385ef2..f2bccb085a6f0d4d93c9a981728d94698b1727cd 100644 (file)
@@ -11,6 +11,7 @@ use Friendica\Core\Renderer;
 use Friendica\Core\System;
 use Friendica\Database\DBA;
 use Friendica\Object\Image;
+use Friendica\Util\Strings;
 
 /**
  * @param App $a
@@ -27,6 +28,12 @@ function fbrowser_content(App $a)
                exit();
        }
 
+       // Needed to match the correct template in a module that uses a different theme than the user/site/default
+       $theme = Strings::sanitizeFilePathItem(defaults($_GET, 'theme', null));
+       if ($theme && is_file("view/theme/$theme/config.php")) {
+               $a->setCurrentTheme($theme);
+       }
+
        $template_file = "filebrowser.tpl";
 
        $o = '';
@@ -97,7 +104,6 @@ function fbrowser_content(App $a)
 
                        $o =  Renderer::replaceMacros($tpl, [
                                '$type'     => 'image',
-                               '$baseurl'  => System::baseUrl(),
                                '$path'     => $path,
                                '$folders'  => $albums,
                                '$files'    => $files,
@@ -127,7 +133,6 @@ function fbrowser_content(App $a)
                                $tpl = Renderer::getMarkupTemplate($template_file);
                                $o = Renderer::replaceMacros($tpl, [
                                        '$type'     => 'file',
-                                       '$baseurl'  => System::baseUrl(),
                                        '$path'     => [ [ "", L10n::t("Files")] ],
                                        '$folders'  => false,
                                        '$files'    => $files,
diff --git a/mod/fetch.php b/mod/fetch.php
deleted file mode 100644 (file)
index 3e9c4e6..0000000
+++ /dev/null
@@ -1,62 +0,0 @@
-<?php
-/*
-This file is part of the Diaspora protocol. It is used for fetching single public posts.
-*/
-
-use Friendica\App;
-use Friendica\Core\Protocol;
-use Friendica\Core\System;
-use Friendica\Protocol\Diaspora;
-use Friendica\Model\Item;
-use Friendica\Model\User;
-use Friendica\Util\Strings;
-use Friendica\Database\DBA;
-
-function fetch_init(App $a)
-{
-
-       if (($a->argc != 3) || (!in_array($a->argv[1], ["post", "status_message", "reshare"]))) {
-               System::httpExit(404);
-       }
-
-       $guid = $a->argv[2];
-
-       // Fetch the item
-       $fields = ['uid', 'title', 'body', 'guid', 'contact-id', 'private', 'created', 'app', 'location', 'coord', 'network',
-               'event-id', 'resource-id', 'author-link', 'author-avatar', 'author-name', 'plink', 'owner-link', 'attach'];
-       $condition = ['wall' => true, 'private' => false, 'guid' => $guid, 'network' => [Protocol::DFRN, Protocol::DIASPORA]];
-       $item = Item::selectFirst($fields, $condition);
-       if (!DBA::isResult($item)) {
-               $condition = ['guid' => $guid, 'network' => [Protocol::DFRN, Protocol::DIASPORA]];
-               $item = Item::selectFirst(['author-link'], $condition);
-               if (DBA::isResult($item)) {
-                       $parts = parse_url($item["author-link"]);
-                       $host = $parts["scheme"]."://".$parts["host"];
-
-                       if (Strings::normaliseLink($host) != Strings::normaliseLink(System::baseUrl())) {
-                               $location = $host."/fetch/".$a->argv[1]."/".urlencode($guid);
-
-                               header("HTTP/1.1 301 Moved Permanently");
-                               header("Location:".$location);
-                               exit();
-                       }
-               }
-
-               System::httpExit(404);
-       }
-
-       // Fetch some data from the author (We could combine both queries - but I think this is more readable)
-       $user = User::getOwnerDataById($item["uid"]);
-       if (!$user) {
-               System::httpExit(404);
-       }
-
-       $status = Diaspora::buildStatus($item, $user);
-       $xml = Diaspora::buildPostXml($status["type"], $status["message"]);
-
-       // Send the envelope
-       header("Content-Type: application/magic-envelope+xml; charset=utf-8");
-       echo Diaspora::buildMagicEnvelope($xml, $user);
-
-       exit();
-}
index 48e621f4af8da036b02c0a0530a5b2c21c0143c1..8a00e0559ce3d4132dca07cc3f8084638e981dc7 100644 (file)
@@ -17,7 +17,7 @@ use Friendica\Util\Strings;
 function follow_post(App $a)
 {
        if (!local_user()) {
-               System::httpExit(403, ['title' => L10n::t('Access denied.')]);
+               throw new \Friendica\Network\HTTPException\ForbiddenException(L10n::t('Access denied.'));
        }
 
        if (isset($_REQUEST['cancel'])) {
index cbaebc8ff4819f558a42983c380dddf9cf39d37e..828eeaf0910a3fdd5338d529eb49fbc6bb51283e 100644 (file)
@@ -17,9 +17,7 @@ function hcard_init(App $a)
        if ($a->argc > 1) {
                $which = $a->argv[1];
        } else {
-               notice(L10n::t('No profile') . EOL);
-               $a->error = 404;
-               return;
+               throw new \Friendica\Network\HTTPException\NotFoundException(L10n::t('No profile'));
        }
 
        $profile = 0;
diff --git a/mod/help.php b/mod/help.php
deleted file mode 100644 (file)
index cdfedac..0000000
+++ /dev/null
@@ -1,119 +0,0 @@
-<?php
-/**
- * @file mod/help.php
- */
-
-use Friendica\App;
-use Friendica\Content\Nav;
-use Friendica\Content\Text\Markdown;
-use Friendica\Core\Config;
-use Friendica\Core\L10n;
-use Friendica\Core\Renderer;
-use Friendica\Core\System;
-use Friendica\Util\Strings;
-
-function load_doc_file($s)
-{
-       $lang = Config::get('system', 'language');
-       $b = basename($s);
-       $d = dirname($s);
-       if (file_exists("$d/$lang/$b")) {
-               return file_get_contents("$d/$lang/$b");
-       }
-
-       if (file_exists($s)) {
-               return file_get_contents($s);
-       }
-
-       return '';
-}
-
-function help_content(App $a)
-{
-       Nav::setSelected('help');
-
-       $text = '';
-       $filename = '';
-
-       if ($a->argc > 1) {
-               $path = '';
-               // looping through the argv keys bigger than 0 to build
-               // a path relative to /help
-               for ($x = 1; $x < $a->argc; $x ++) {
-                       if (strlen($path)) {
-                               $path .= '/';
-                       }
-
-                       $path .= $a->getArgumentValue($x);
-               }
-               $title = basename($path);
-               $filename = $path;
-               $text = load_doc_file('doc/' . $path . '.md');
-               $a->page['title'] = L10n::t('Help:') . ' ' . str_replace('-', ' ', Strings::escapeTags($title));
-       }
-
-       $home = load_doc_file('doc/Home.md');
-       if (!$text) {
-               $text = $home;
-               $filename = "Home";
-               $a->page['title'] = L10n::t('Help');
-       } else {
-               $a->page['aside'] = Markdown::convert($home, false);
-       }
-
-       if (!strlen($text)) {
-               header($_SERVER["SERVER_PROTOCOL"] . ' 404 ' . L10n::t('Not Found'));
-               $tpl = Renderer::getMarkupTemplate("404.tpl");
-               return Renderer::replaceMacros($tpl, [
-                       '$message' => L10n::t('Page not found.')
-               ]);
-       }
-
-       $html = Markdown::convert($text, false);
-
-       if ($filename !== "Home") {
-               // create TOC but not for home
-               $lines = explode("\n", $html);
-               $toc = "<h2>TOC</h2><ul id='toc'>";
-               $lastlevel = 1;
-               $idnum = [0, 0, 0, 0, 0, 0, 0];
-               foreach ($lines as &$line) {
-                       if (substr($line, 0, 2) == "<h") {
-                               $level = substr($line, 2, 1);
-                               if ($level != "r") {
-                                       $level = intval($level);
-                                       if ($level < $lastlevel) {
-                                               for ($k = $level; $k < $lastlevel; $k++) {
-                                                       $toc .= "</ul></li>";
-                                               }
-
-                                               for ($k = $level + 1; $k < count($idnum); $k++) {
-                                                       $idnum[$k] = 0;
-                                               }
-                                       }
-
-                                       if ($level > $lastlevel) {
-                                               $toc .= "<li><ul>";
-                                       }
-
-                                       $idnum[$level] ++;
-                                       $id = implode("_", array_slice($idnum, 1, $level));
-                                       $href = System::baseUrl() . "/help/{$filename}#{$id}";
-                                       $toc .= "<li><a href='{$href}'>" . strip_tags($line) . "</a></li>";
-                                       $line = "<a name='{$id}'></a>" . $line;
-                                       $lastlevel = $level;
-                               }
-                       }
-               }
-
-               for ($k = 0; $k < $lastlevel; $k++) {
-                       $toc .= "</ul>";
-               }
-
-               $html = implode("\n", $lines);
-
-               $a->page['aside'] = '<div class="help-aside-wrapper widget"><div id="toc-wrapper">' . $toc . '</div>' . $a->page['aside'] . '</div>';
-       }
-
-       return $html;
-}
diff --git a/mod/home.php b/mod/home.php
deleted file mode 100644 (file)
index 9f18101..0000000
+++ /dev/null
@@ -1,64 +0,0 @@
-<?php
-/**
- * @file mod/home.php
- */
-use Friendica\App;
-use Friendica\Core\Config;
-use Friendica\Core\Hook;
-use Friendica\Core\L10n;
-use Friendica\Core\Renderer;
-use Friendica\Core\System;
-use Friendica\Module\Login;
-
-if(! function_exists('home_init')) {
-function home_init(App $a) {
-
-       $ret = [];
-       Hook::callAll('home_init',$ret);
-
-       if (local_user() && ($a->user['nickname'])) {
-               $a->internalRedirect('network');
-       }
-
-       if (strlen(Config::get('system','singleuser'))) {
-               $a->internalRedirect('profile/' . Config::get('system','singleuser'));
-       }
-
-}}
-
-if(! function_exists('home_content')) {
-function home_content(App $a) {
-
-       if (!empty($_SESSION['theme'])) {
-               unset($_SESSION['theme']);
-       }
-       if (!empty($_SESSION['mobile-theme'])) {
-               unset($_SESSION['mobile-theme']);
-       }
-
-       $customhome = false;
-       $defaultheader = '<h1>' . (Config::get('config', 'sitename') ? L10n::t('Welcome to %s', Config::get('config', 'sitename')) : '') . '</h1>';
-
-       $homefilepath = $a->getBasePath() . "/home.html";
-       $cssfilepath = $a->getBasePath() . "/home.css";
-       if (file_exists($homefilepath)) {
-               $customhome = $homefilepath;
-               if (file_exists($cssfilepath)) {
-                       $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="'.System::baseUrl().'/home.css'.'" media="all" />';
-               }
-       }
-
-       $login = Login::form($a->query_string, intval(Config::get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? 0 : 1);
-
-       $content = '';
-       Hook::callAll("home_content",$content);
-
-
-       $tpl = Renderer::getMarkupTemplate('home.tpl');
-       return Renderer::replaceMacros($tpl, [
-               '$defaultheader' => $defaultheader,
-               '$customhome' => $customhome,
-               '$login' => $login,
-               '$content' => $content
-       ]);
-}}
diff --git a/mod/hostxrd.php b/mod/hostxrd.php
deleted file mode 100644 (file)
index 93a9d83..0000000
+++ /dev/null
@@ -1,34 +0,0 @@
-<?php
-/**
- * @file mod/hostxrd.php
- */
-use Friendica\App;
-use Friendica\Core\Config;
-use Friendica\Core\Renderer;
-use Friendica\Core\System;
-use Friendica\Protocol\Salmon;
-use Friendica\Util\Crypto;
-
-function hostxrd_init(App $a)
-{
-       header('Access-Control-Allow-Origin: *');
-       header("Content-type: text/xml");
-       $pubkey = Config::get('system', 'site_pubkey');
-
-       if (! $pubkey) {
-               $res = Crypto::newKeypair(1024);
-
-               Config::set('system','site_prvkey', $res['prvkey']);
-               Config::set('system','site_pubkey', $res['pubkey']);
-       }
-
-       $tpl = Renderer::getMarkupTemplate('xrd_host.tpl');
-       echo Renderer::replaceMacros($tpl, [
-               '$zhost' => $a->getHostName(),
-               '$zroot' => System::baseUrl(),
-               '$domain' => System::baseUrl(),
-               '$bigkey' => Salmon::salmonKey(Config::get('system', 'site_pubkey'))]
-       );
-
-       exit();
-}
index 603c617ca4874107efb6833db9585405371f1570..ca399196368b71b3151d616924b8e59a8ab19cca 100644 (file)
@@ -31,7 +31,7 @@ function hovercard_content()
 
        // Get out if the system doesn't have public access allowed
        if (intval(Config::get('system', 'block_public'))) {
-               System::httpExit(401);
+               throw new \Friendica\Network\HTTPException\ForbiddenException();
        }
 
        // Return the raw content of the template. We use this to make templates usable for js functions.
diff --git a/mod/invite.php b/mod/invite.php
deleted file mode 100644 (file)
index e8901d0..0000000
+++ /dev/null
@@ -1,158 +0,0 @@
-<?php
-/**
- * Module: invite.php
- *
- * Send email invitations to join social network
- *
- */
-
-use Friendica\App;
-use Friendica\BaseModule;
-use Friendica\Core\Config;
-use Friendica\Core\L10n;
-use Friendica\Core\PConfig;
-use Friendica\Core\Renderer;
-use Friendica\Core\System;
-use Friendica\Module\Register;
-use Friendica\Protocol\Email;
-use Friendica\Util\Strings;
-
-function invite_post(App $a)
-{
-       if (! local_user()) {
-               notice(L10n::t('Permission denied.') . EOL);
-               return;
-       }
-
-       BaseModule::checkFormSecurityTokenRedirectOnError('/', 'send_invite');
-
-       $max_invites = intval(Config::get('system', 'max_invites'));
-       if (! $max_invites) {
-               $max_invites = 50;
-       }
-
-       $current_invites = intval(PConfig::get(local_user(), 'system', 'sent_invites'));
-       if ($current_invites > $max_invites) {
-               notice(L10n::t('Total invitation limit exceeded.') . EOL);
-               return;
-       }
-
-
-       $recipients  = !empty($_POST['recipients']) ? explode("\n", $_POST['recipients']) : [];
-       $message     = !empty($_POST['message'])    ? Strings::escapeTags(trim($_POST['message']))     : '';
-
-       $total = 0;
-       $invitation_only = false;
-       $invites_remaining = null;
-
-       if (Config::get('system', 'invitation_only')) {
-               $invitation_only = true;
-               $invites_remaining = PConfig::get(local_user(), 'system', 'invites_remaining');
-               if ((! $invites_remaining) && (! is_site_admin())) {
-                       return;
-               }
-       }
-
-       foreach ($recipients as $recipient) {
-               $recipient = trim($recipient);
-
-               if (!filter_var($recipient, FILTER_VALIDATE_EMAIL)) {
-                       notice(L10n::t('%s : Not a valid email address.', $recipient) . EOL);
-                       continue;
-               }
-
-               if ($invitation_only && ($invites_remaining || is_site_admin())) {
-                       $code = Friendica\Model\Register::createForInvitation();
-                       $nmessage = str_replace('$invite_code', $code, $message);
-
-                       if (! is_site_admin()) {
-                               $invites_remaining --;
-                               if ($invites_remaining >= 0) {
-                                       PConfig::set(local_user(), 'system', 'invites_remaining', $invites_remaining);
-                               } else {
-                                       return;
-                               }
-                       }
-               } else {
-                       $nmessage = $message;
-               }
-
-               $additional_headers = 'From: ' . $a->user['email'] . "\n"
-                       . 'Sender: ' . $a->getSenderEmailAddress() . "\n"
-                       . 'Content-type: text/plain; charset=UTF-8' . "\n"
-                       . 'Content-transfer-encoding: 8bit';
-
-               $res = mail(
-                       $recipient,
-                       Email::encodeHeader(L10n::t('Please join us on Friendica'), 'UTF-8'),
-                       $nmessage,
-                       $additional_headers);
-
-               if ($res) {
-                       $total ++;
-                       $current_invites ++;
-                       PConfig::set(local_user(), 'system', 'sent_invites', $current_invites);
-                       if ($current_invites > $max_invites) {
-                               notice(L10n::t('Invitation limit exceeded. Please contact your site administrator.') . EOL);
-                               return;
-                       }
-               } else {
-                       notice(L10n::t('%s : Message delivery failed.', $recipient) . EOL);
-               }
-
-       }
-       notice(L10n::tt("%d message sent.", "%d messages sent.", $total) . EOL);
-       return;
-}
-
-function invite_content(App $a) {
-
-       if (! local_user()) {
-               notice(L10n::t('Permission denied.') . EOL);
-               return;
-       }
-
-       $tpl = Renderer::getMarkupTemplate('invite.tpl');
-       $invonly = false;
-
-       if (Config::get('system', 'invitation_only')) {
-               $invonly = true;
-               $x = PConfig::get(local_user(), 'system', 'invites_remaining');
-               if ((! $x) && (! is_site_admin())) {
-                       notice(L10n::t('You have no more invitations available') . EOL);
-                       return '';
-               }
-       }
-
-       $dirloc = Config::get('system', 'directory');
-       if (strlen($dirloc)) {
-               if (intval(Config::get('config', 'register_policy')) === Register::CLOSED) {
-                       $linktxt = L10n::t('Visit %s for a list of public sites that you can join. Friendica members on other sites can all connect with each other, as well as with members of many other social networks.', $dirloc . '/servers');
-               } else {
-                       $linktxt = L10n::t('To accept this invitation, please visit and register at %s or any other public Friendica website.', System::baseUrl())
-                       . "\r\n" . "\r\n" . L10n::t('Friendica sites all inter-connect to create a huge privacy-enhanced social web that is owned and controlled by its members. They can also connect with many traditional social networks. See %s for a list of alternate Friendica sites you can join.', $dirloc . '/servers');
-               }
-       } else { // there is no global directory URL defined
-               if (intval(Config::get('config', 'register_policy')) === Register::CLOSED) {
-                       $o = L10n::t('Our apologies. This system is not currently configured to connect with other public sites or invite members.');
-                       return $o;
-               } else {
-                       $linktxt = L10n::t('To accept this invitation, please visit and register at %s.', System::baseUrl()
-                       . "\r\n" . "\r\n" . L10n::t('Friendica sites all inter-connect to create a huge privacy-enhanced social web that is owned and controlled by its members. They can also connect with many traditional social networks.'));
-               }
-       }
-
-       $o = Renderer::replaceMacros($tpl, [
-               '$form_security_token' => BaseModule::getFormSecurityToken("send_invite"),
-               '$title'               => L10n::t('Send invitations'),
-               '$recipients'          => ['recipients', L10n::t('Enter email addresses, one per line:')],
-               '$message'             => ['message', L10n::t('Your message:'),L10n::t('You are cordially invited to join me and other close friends on Friendica - and help us to create a better social web.') . "\r\n" . "\r\n"
-                       . $linktxt
-                       . "\r\n" . "\r\n" . (($invonly) ? L10n::t('You will need to supply this invitation code: $invite_code') . "\r\n" . "\r\n" : '') .L10n::t('Once you have registered, please connect with me via my profile page at:')
-                       . "\r\n" . "\r\n" . System::baseUrl() . '/profile/' . $a->user['nickname']
-                       . "\r\n" . "\r\n" . L10n::t('For more information about the Friendica project and why we feel it is important, please visit http://friendi.ca') . "\r\n" . "\r\n"],
-               '$submit'              => L10n::t('Submit')
-       ]);
-
-       return $o;
-}
diff --git a/mod/like.php b/mod/like.php
deleted file mode 100644 (file)
index 7fc7b2b..0000000
+++ /dev/null
@@ -1,48 +0,0 @@
-<?php
-
-use Friendica\App;
-use Friendica\Model\Item;
-use Friendica\Util\Strings;
-
-function like_content(App $a) {
-       if (!local_user() && !remote_user()) {
-               return false;
-       }
-
-
-       $verb = Strings::escapeTags(trim($_GET['verb']));
-
-       if (!$verb) {
-               $verb = 'like';
-       }
-
-       $item_id = (($a->argc > 1) ? Strings::escapeTags(trim($a->argv[1])) : 0);
-
-       $r = Item::performLike($item_id, $verb);
-       if (!$r) {
-               return;
-       }
-
-       // See if we've been passed a return path to redirect to
-       $return_path = defaults($_REQUEST, 'return', '');
-
-       like_content_return($a, $return_path);
-       exit();
-}
-
-
-// Decide how to return. If we were called with a 'return' argument,
-// then redirect back to the calling page. If not, just quietly end
-
-function like_content_return(App $a, $return_path) {
-       if ($return_path) {
-               $rand = '_=' . time();
-               if (strpos($return_path, '?')) {
-                       $rand = "&$rand";
-               } else {
-                       $rand = "?$rand";
-               }
-
-               $a->internalRedirect($return_path . $rand);
-       }
-}
index 548cea185cb943ac3c3f1e7cda039045f7514b12..01e84268b4300b7f0a0fe48cf64eae0300817366 100644 (file)
@@ -139,7 +139,6 @@ function lostpass_generate_password($user)
                        '$lbl5'    => '<a href="' . System::baseUrl() . '">' . L10n::t('click here to login') . '</a>.',
                        '$lbl6'    => L10n::t('Your password may be changed from the <em>Settings</em> page after successful login.'),
                        '$newpass' => $new_password,
-                       '$baseurl' => System::baseUrl()
                ]);
 
                info("Your password has been reset." . EOL);
diff --git a/mod/nogroup.php b/mod/nogroup.php
deleted file mode 100644 (file)
index 20dbd23..0000000
+++ /dev/null
@@ -1,23 +0,0 @@
-<?php
-/**
- * @file mod/nogroup.php
- */
-use Friendica\App;
-use Friendica\Core\L10n;
-
-function nogroup_init(App $a)
-{
-       if (! local_user()) {
-               return;
-       }
-}
-
-function nogroup_content(App $a)
-{
-       if (! local_user()) {
-               notice(L10n::t('Permission denied.') . EOL);
-               return '';
-       }
-
-       $a->internalRedirect('group/none');
-}
index 1a584000c72d86eee8560391b8c6ad910033bdf9..b0a6a543912d71e656ed0b403695a293b4654fa7 100644 (file)
@@ -16,8 +16,7 @@ function notice_init(App $a)
                $nick = $r[0]['nickname'];
                $a->internalRedirect('display/' . $nick . '/' . $id);
        } else {
-               $a->error = 404;
-               notice(L10n::t('Item not found.') . EOL);
+               throw new \Friendica\Network\HTTPException\NotFoundException(L10n::t('Item not found.'));
        }
 
        return;
index 87035817841d637b957037051ca087b34a9551ba..7f9974d30a1e5737b1d61ddc4dd089a29641c70e 100644 (file)
@@ -26,18 +26,6 @@ function notify_init(App $a)
                $note = $nm->getByID($a->argv[2]);
                if ($note) {
                        $nm->setSeen($note);
-
-                       // The friendica client has problems with the GUID. this is some workaround
-                       if ($a->isFriendicaApp()) {
-                               require_once("include/items.php");
-                               $urldata = parse_url($note['link']);
-                               $guid = basename($urldata["path"]);
-                               $itemdata = Item::getIdAndNickByGuid($guid, local_user());
-                               if ($itemdata["id"] != 0) {
-                                       $note['link'] = System::baseUrl().'/display/'.$itemdata["nick"].'/'.$itemdata["id"];
-                               }
-                       }
-
                        System::externalRedirect($note['link']);
                }
 
index 2057f0b5d60579155de31336d1990da404d5e3a9..0744157e5310b99a8334cfe8cc97b3477b79169b 100644 (file)
@@ -2,7 +2,6 @@
 
 use Friendica\App;
 use Friendica\Core\Renderer;
-use Friendica\Core\System;
 
 function opensearch_content(App $a) {
 
@@ -11,7 +10,6 @@ function opensearch_content(App $a) {
        header("Content-type: application/opensearchdescription+xml");
 
        $o = Renderer::replaceMacros($tpl, [
-               '$baseurl' => System::baseUrl(),
                '$nodename' => $a->getHostName(),
        ]);
 
index 137e0adb563218b312b51fc3b0dc021899df677f..db9beb6685fa8e712386ca830700a3983c75cfce 100644 (file)
@@ -47,16 +47,14 @@ function photos_init(App $a) {
 
        if ($a->argc > 1) {
                $nick = $a->argv[1];
-               $user = q("SELECT * FROM `user` WHERE `nickname` = '%s' AND `blocked` = 0 LIMIT 1",
-                       DBA::escape($nick)
-               );
+               $user = DBA::selectFirst('user', [], ['nickname' => $nick, 'blocked' => false]);
 
                if (!DBA::isResult($user)) {
                        return;
                }
 
-               $a->data['user'] = $user[0];
-               $a->profile_uid = $user[0]['uid'];
+               $a->data['user'] = $user;
+               $a->profile_uid = $user['uid'];
                $is_owner = (local_user() && (local_user() == $a->profile_uid));
 
                $profile = Profile::getByNickname($nick, $a->profile_uid);
@@ -115,7 +113,6 @@ function photos_init(App $a) {
                                '$title'    => L10n::t('Photo Albums'),
                                '$recent'   => L10n::t('Recent Photos'),
                                '$albums'   => $ret['albums'],
-                               '$baseurl'  => System::baseUrl(),
                                '$upload'   => [L10n::t('Upload New Photos'), 'photos/' . $a->data['user']['nickname'] . '/upload'],
                                '$can_post' => $can_post
                        ]);
@@ -170,12 +167,7 @@ function photos_post(App $a)
                }
 
                if ($contact_id > 0) {
-                       $r = q("SELECT `uid` FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `id` = %d AND `uid` = %d LIMIT 1",
-                               intval($contact_id),
-                               intval($page_owner_uid)
-                       );
-
-                       if (DBA::isResult($r)) {
+                       if (DBA::exists('contact', ['id' => $contact_id, 'uid' => $page_owner_uid, 'blocked' => false, 'pending' => false])) {
                                $can_post = true;
                                $visitor = $contact_id;
                        }
@@ -235,36 +227,12 @@ function photos_post(App $a)
                }
 
                /*
-                * DELETE photo album and all its photos
+                * DELETE all photos filed in a given album
                 */
-
-               if ($_POST['dropalbum'] == L10n::t('Delete Album')) {
-                       // Check if we should do HTML-based delete confirmation
-                       if (!empty($_REQUEST['confirm'])) {
-                               $drop_url = $a->query_string;
-
-                               $extra_inputs = [
-                                       ['name' => 'albumname', 'value' => $_POST['albumname']],
-                               ];
-
-                               $a->page['content'] = Renderer::replaceMacros(Renderer::getMarkupTemplate('confirm.tpl'), [
-                                       '$method' => 'post',
-                                       '$message' => L10n::t('Do you really want to delete this photo album and all its photos?'),
-                                       '$extra_inputs' => $extra_inputs,
-                                       '$confirm' => L10n::t('Delete Album'),
-                                       '$confirm_url' => $drop_url,
-                                       '$confirm_name' => 'dropalbum', // Needed so that confirmation will bring us back into this if statement
-                                       '$cancel' => L10n::t('Cancel'),
-                               ]);
-
-                               $a->error = 1; // Set $a->error so the other module functions don't execute
-                               return;
-                       }
-
+               if (!empty($_POST['dropalbum'])) {
                        $res = [];
 
                        // get the list of photos we are about to delete
-
                        if ($visitor) {
                                $r = q("SELECT distinct(`resource-id`) as `rid` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d AND `album` = '%s'",
                                        intval($visitor),
@@ -282,77 +250,57 @@ function photos_post(App $a)
                                foreach ($r as $rr) {
                                        $res[] = $rr['rid'];
                                }
-                       } else {
-                               $a->internalRedirect($_SESSION['photo_return']);
-                               return; // NOTREACHED
-                       }
 
-                       // remove the associated photos
-                       Photo::delete(['resource-id' => $res, 'uid' => $page_owner_uid]);
+                               // remove the associated photos
+                               Photo::delete(['resource-id' => $res, 'uid' => $page_owner_uid]);
 
-                       // find and delete the corresponding item with all the comments and likes/dislikes
-                       Item::deleteForUser(['resource-id' => $res, 'uid' => $page_owner_uid], $page_owner_uid);
+                               // find and delete the corresponding item with all the comments and likes/dislikes
+                               Item::deleteForUser(['resource-id' => $res, 'uid' => $page_owner_uid], $page_owner_uid);
 
-                       // Update the photo albums cache
-                       Photo::clearAlbumCache($page_owner_uid);
+                               // Update the photo albums cache
+                               Photo::clearAlbumCache($page_owner_uid);
+                               notice(L10n::t('Album successfully deleted'));
+                       } else {
+                               notice(L10n::t('Album was empty.'));
+                       }
                }
 
-               $a->internalRedirect('photos/' . $a->data['user']['nickname']);
-               return; // NOTREACHED
+               $a->internalRedirect('photos/' . $a->argv[1]);
        }
 
+       if ($a->argc > 3 && $a->argv[2] === 'image') {
+               // Check if the user has responded to a delete confirmation query for a single photo
+               if (!empty($_POST['canceled'])) {
+                       $a->internalRedirect('photos/' . $a->argv[1] . '/image/' . $a->argv[3]);
+               }
 
-       // Check if the user has responded to a delete confirmation query for a single photo
-       if ($a->argc > 2 && !empty($_REQUEST['canceled'])) {
-               $a->internalRedirect($_SESSION['photo_return']);
-       }
-
-       if ($a->argc > 2 && defaults($_POST, 'delete', '') === L10n::t('Delete Photo')) {
-
-               // same as above but remove single photo
-
-               // Check if we should do HTML-based delete confirmation
-               if (!empty($_REQUEST['confirm'])) {
-                       $drop_url = $a->query_string;
+               if (!empty($_POST['delete'])) {
+                       // same as above but remove single photo
+                       if ($visitor) {
+                               $condition = ['contact-id' => $visitor, 'uid' => $page_owner_uid, 'resource-id' => $a->argv[3]];
 
-                       $a->page['content'] = Renderer::replaceMacros(Renderer::getMarkupTemplate('confirm.tpl'), [
-                               '$method' => 'post',
-                               '$message' => L10n::t('Do you really want to delete this photo?'),
-                               '$extra_inputs' => [],
-                               '$confirm' => L10n::t('Delete Photo'),
-                               '$confirm_url' => $drop_url,
-                               '$confirm_name' => 'delete', // Needed so that confirmation will bring us back into this if statement
-                               '$cancel' => L10n::t('Cancel'),
-                       ]);
+                       } else {
+                               $condition = ['uid' => local_user(), 'resource-id' => $a->argv[3]];
+                       }
 
-                       $a->error = 1; // Set $a->error so the other module functions don't execute
-                       return;
-               }
+                       $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
 
-               if ($visitor) {
-                       $r = q("SELECT `id`, `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d AND `resource-id` = '%s' LIMIT 1",
-                               intval($visitor),
-                               intval($page_owner_uid),
-                               DBA::escape($a->argv[2])
-                       );
-               } else {
-                       $r = q("SELECT `id`, `resource-id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' LIMIT 1",
-                               intval(local_user()),
-                               DBA::escape($a->argv[2])
-                       );
-               }
+                       if (DBA::isResult($photo)) {
+                               Photo::delete(['uid' => $page_owner_uid, 'resource-id' => $photo['resource-id']]);
 
-               if (DBA::isResult($r)) {
-                       Photo::delete(['uid' => $page_owner_uid, 'resource-id' => $r[0]['resource-id']]);
+                               Item::deleteForUser(['resource-id' => $photo['resource-id'], 'uid' => $page_owner_uid], $page_owner_uid);
 
-                       Item::deleteForUser(['resource-id' => $r[0]['resource-id'], 'uid' => $page_owner_uid], $page_owner_uid);
+                               // Update the photo albums cache
+                               Photo::clearAlbumCache($page_owner_uid);
+                               notice('Successfully deleted the photo.');
+                       } else {
+                               notice('Failed to delete the photo.');
+                               $a->internalRedirect('photos/' . $a->argv[1] . '/image/' . $a->argv[3]);
+                       }
 
-                       // Update the photo albums cache
-                       Photo::clearAlbumCache($page_owner_uid);
+                       $a->internalRedirect('photos/' . $a->argv[1]);
+                       return; // NOTREACHED
                }
-
-               $a->internalRedirect('photos/' . $a->data['user']['nickname']);
-               return; // NOTREACHED
        }
 
        if ($a->argc > 2 && (!empty($_POST['desc']) || !empty($_POST['newtag']) || isset($_POST['albname']))) {
@@ -493,6 +441,7 @@ function photos_post(App $a)
                                foreach ($tags as $tag) {
                                        if (strpos($tag, '@') === 0) {
                                                $profile = '';
+                                               $contact = null;
                                                $name = substr($tag,1);
 
                                                if ((strpos($name, '@')) || (strpos($name, 'http://'))) {
@@ -527,34 +476,26 @@ function photos_post(App $a)
                                                        }
 
                                                        if ($tagcid) {
-                                                               $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
-                                                                       intval($tagcid),
-                                                                       intval($page_owner_uid)
-                                                               );
+                                                               $contact = DBA::selectFirst('contact', [], ['id' => $tagcid, 'uid' => $page_owner_uid]);
                                                        } else {
                                                                $newname = str_replace('_',' ',$name);
 
                                                                //select someone from this user's contacts by name
-                                                               $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `uid` = %d LIMIT 1",
-                                                                               DBA::escape($newname),
-                                                                               intval($page_owner_uid)
-                                                               );
-
-                                                               if (!DBA::isResult($r)) {
+                                                               $contact = DBA::selectFirst('contact', [], ['name' => $newname, 'uid' => $page_owner_uid]);
+                                                               if (!DBA::isResult($contact)) {
                                                                        //select someone by attag or nick and the name passed in
-                                                                       $r = q("SELECT * FROM `contact` WHERE `attag` = '%s' OR `nick` = '%s' AND `uid` = %d ORDER BY `attag` DESC LIMIT 1",
-                                                                                       DBA::escape($name),
-                                                                                       DBA::escape($name),
-                                                                                       intval($page_owner_uid)
+                                                                       $contact = DBA::selectFirst('contact', [],
+                                                                               ['(`attag` = ? OR `nick` = ?) AND `uid` = ?', $name, $name, $page_owner_uid],
+                                                                               ['order' => ['attag' => true]]
                                                                        );
                                                                }
                                                        }
 
-                                                       if (DBA::isResult($r)) {
-                                                               $newname = $r[0]['name'];
-                                                               $profile = $r[0]['url'];
+                                                       if (DBA::isResult($contact)) {
+                                                               $newname = $contact['name'];
+                                                               $profile = $contact['url'];
 
-                                                               $notify = 'cid:' . $r[0]['id'];
+                                                               $notify = 'cid:' . $contact['id'];
                                                                if (strlen($inform)) {
                                                                        $inform .= ',';
                                                                }
@@ -563,8 +504,8 @@ function photos_post(App $a)
                                                }
 
                                                if ($profile) {
-                                                       if (substr($notify, 0, 4) === 'cid:') {
-                                                               $taginfo[] = [$newname, $profile, $notify, $r[0], '@[url=' . str_replace(',','%2c',$profile) . ']' . $newname . '[/url]'];
+                                                       if (!empty($contact)) {
+                                                               $taginfo[] = [$newname, $profile, $notify, $contact, '@[url=' . str_replace(',', '%2c', $profile) . ']' . $newname . '[/url]'];
                                                        } else {
                                                                $taginfo[] = [$newname, $profile, $notify, null, $str_tags .= '@[url=' . $profile . ']' . $newname . '[/url]'];
                                                        }
@@ -896,8 +837,10 @@ function photos_content(App $a)
        // photos/name/upload/xxxxx (xxxxx is album name)
        // photos/name/album/xxxxx
        // photos/name/album/xxxxx/edit
+       // photos/name/album/xxxxx/drop
        // photos/name/image/xxxxx
        // photos/name/image/xxxxx/edit
+       // photos/name/image/xxxxx/drop
 
        if (Config::get('system', 'block_public') && !local_user() && !remote_user()) {
                notice(L10n::t('Public access denied.') . EOL);
@@ -936,7 +879,8 @@ function photos_content(App $a)
        $contact        = null;
        $remote_contact = false;
        $contact_id     = 0;
-       $edit           = false;
+       $edit           = '';
+       $drop           = '';
 
        $owner_uid = $a->data['user']['uid'];
 
@@ -954,15 +898,12 @@ function photos_content(App $a)
                                        }
                                }
                        }
+
                        if ($contact_id) {
+                               $contact = DBA::selectFirst('contact', [], ['id' => $contact_id, 'uid' => $owner_uid, 'blocked' => false, 'pending' => false]);
 
-                               $r = q("SELECT `uid` FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `id` = %d AND `uid` = %d LIMIT 1",
-                                       intval($contact_id),
-                                       intval($owner_uid)
-                               );
-                               if (DBA::isResult($r)) {
+                               if (DBA::isResult($contact)) {
                                        $can_post = true;
-                                       $contact = $r[0];
                                        $remote_contact = true;
                                        $visitor = $contact_id;
                                }
@@ -983,16 +924,13 @@ function photos_content(App $a)
                                }
                        }
                }
+
                if ($contact_id) {
                        $groups = Group::getIdsByContactId($contact_id);
-                       $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `id` = %d AND `uid` = %d LIMIT 1",
-                               intval($contact_id),
-                               intval($owner_uid)
-                       );
-                       if (DBA::isResult($r)) {
-                               $contact = $r[0];
-                               $remote_contact = true;
-                       }
+
+                       $contact = DBA::selectFirst('contact', [], ['id' => $contact_id, 'uid' => $owner_uid, 'blocked' => false, 'pending' => false]);
+
+                       $remote_contact = DBA::isResult($contact);
                }
        }
 
@@ -1121,6 +1059,24 @@ function photos_content(App $a)
                        $pager->getItemsPerPage()
                );
 
+               if ($cmd === 'drop') {
+                       $drop_url = $a->query_string;
+
+                       $extra_inputs = [
+                               ['name' => 'albumname', 'value' => $_POST['albumname']],
+                       ];
+
+                       return Renderer::replaceMacros(Renderer::getMarkupTemplate('confirm.tpl'), [
+                               '$method' => 'post',
+                               '$message' => L10n::t('Do you really want to delete this photo album and all its photos?'),
+                               '$extra_inputs' => $extra_inputs,
+                               '$confirm' => L10n::t('Delete Album'),
+                               '$confirm_url' => $drop_url,
+                               '$confirm_name' => 'dropalbum',
+                               '$cancel' => L10n::t('Cancel'),
+                       ]);
+               }
+
                // edit album name
                if ($cmd === 'edit') {
                        if (($album !== L10n::t('Profile Photos')) && ($album !== 'Contact Photos') && ($album !== L10n::t('Contact Photos'))) {
@@ -1142,6 +1098,7 @@ function photos_content(App $a)
                } else {
                        if (($album !== L10n::t('Profile Photos')) && ($album !== 'Contact Photos') && ($album !== L10n::t('Contact Photos')) && $can_post) {
                                $edit = [L10n::t('Edit Album'), 'photos/' . $a->data['user']['nickname'] . '/album/' . bin2hex($album) . '/edit'];
+                               $drop = [L10n::t('Drop Album'), 'photos/' . $a->data['user']['nickname'] . '/album/' . bin2hex($album) . '/drop'];
                        }
                }
 
@@ -1187,6 +1144,7 @@ function photos_content(App $a)
                        '$upload' => [L10n::t('Upload New Photos'), 'photos/' . $a->data['user']['nickname'] . '/upload/' . bin2hex($album)],
                        '$order' => $order,
                        '$edit' => $edit,
+                       '$drop' => $drop,
                        '$paginate' => $pager->renderFull($total),
                ]);
 
@@ -1204,12 +1162,7 @@ function photos_content(App $a)
                );
 
                if (!DBA::isResult($ph)) {
-                       $ph = q("SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'
-                               LIMIT 1",
-                               intval($owner_uid),
-                               DBA::escape($datum)
-                       );
-                       if (DBA::isResult($ph)) {
+                       if (DBA::exists('photo', ['resource-id' => $datum, 'uid' => $owner_uid])) {
                                notice(L10n::t('Permission denied. Access to this item may be restricted.'));
                        } else {
                                notice(L10n::t('Photo not available') . EOL);
@@ -1217,6 +1170,20 @@ function photos_content(App $a)
                        return;
                }
 
+               if ($cmd === 'drop') {
+                       $drop_url = $a->query_string;
+
+                       return Renderer::replaceMacros(Renderer::getMarkupTemplate('confirm.tpl'), [
+                               '$method' => 'post',
+                               '$message' => L10n::t('Do you really want to delete this photo?'),
+                               '$extra_inputs' => [],
+                               '$confirm' => L10n::t('Delete Photo'),
+                               '$confirm_url' => $drop_url,
+                               '$confirm_name' => 'delete',
+                               '$cancel' => L10n::t('Cancel'),
+                       ]);
+               }
+
                $prevlink = '';
                $nextlink = '';
 
@@ -1225,7 +1192,7 @@ function photos_content(App $a)
                 * The query leads to a really intense used index.
                 * By now we hide it if someone wants to.
                 */
-               if (!Config::get('system', 'no_count', false)) {
+               if ($cmd === 'view' && !Config::get('system', 'no_count', false)) {
                        $order_field = defaults($_GET, 'order', '');
 
                        if ($order_field === 'posted') {
@@ -1256,12 +1223,26 @@ function photos_content(App $a)
                                                break;
                                        }
                                }
-                               $edit_suffix = ((($cmd === 'edit') && $can_post) ? '/edit' : '');
+
                                if (!is_null($prv)) {
-                                       $prevlink = 'photos/' . $a->data['user']['nickname'] . '/image/' . $prvnxt[$prv]['resource-id'] . $edit_suffix . ($order_field === 'posted' ? '?f=&order=posted' : '');
+                                       $prevlink = 'photos/' . $a->data['user']['nickname'] . '/image/' . $prvnxt[$prv]['resource-id'] . ($order_field === 'posted' ? '?f=&order=posted' : '');
                                }
                                if (!is_null($nxt)) {
-                                       $nextlink = 'photos/' . $a->data['user']['nickname'] . '/image/' . $prvnxt[$nxt]['resource-id'] . $edit_suffix . ($order_field === 'posted' ? '?f=&order=posted' : '');
+                                       $nextlink = 'photos/' . $a->data['user']['nickname'] . '/image/' . $prvnxt[$nxt]['resource-id'] . ($order_field === 'posted' ? '?f=&order=posted' : '');
+                               }
+
+                               $tpl = Renderer::getMarkupTemplate('photo_edit_head.tpl');
+                               $a->page['htmlhead'] .= Renderer::replaceMacros($tpl,[
+                                       '$prevlink' => $prevlink,
+                                       '$nextlink' => $nextlink
+                               ]);
+
+                               if ($prevlink) {
+                                       $prevlink = [$prevlink, '<div class="icon prev"></div>'];
+                               }
+
+                               if ($nextlink) {
+                                       $nextlink = [$nextlink, '<div class="icon next"></div>'];
                                }
                        }
                }
@@ -1283,33 +1264,23 @@ function photos_content(App $a)
                $album_link = 'photos/' . $a->data['user']['nickname'] . '/album/' . bin2hex($ph[0]['album']);
 
                $tools = null;
-               $lock = null;
 
                if ($can_post && ($ph[0]['uid'] == $owner_uid)) {
-                       $tools = [
-                               'edit'  => ['photos/' . $a->data['user']['nickname'] . '/image/' . $datum . (($cmd === 'edit') ? '' : '/edit'), (($cmd === 'edit') ? L10n::t('View photo') : L10n::t('Edit photo'))],
-                               'profile'=>['profile_photo/use/'.$ph[0]['resource-id'], L10n::t('Use as profile photo')],
-                       ];
-
-                       // lock
-                       $lock = ((($ph[0]['uid'] == local_user()) && (strlen($ph[0]['allow_cid']) || strlen($ph[0]['allow_gid'])
-                                       || strlen($ph[0]['deny_cid']) || strlen($ph[0]['deny_gid'])))
-                                       ? L10n::t('Private Message')
-                                       : Null);
-
-
-               }
-
-               if ($cmd === 'edit') {
-                       $tpl = Renderer::getMarkupTemplate('photo_edit_head.tpl');
-                       $a->page['htmlhead'] .= Renderer::replaceMacros($tpl,[
-                               '$prevlink' => $prevlink,
-                               '$nextlink' => $nextlink
-                       ]);
-               }
+                       $tools = [];
+                       if ($cmd === 'edit') {
+                               $tools['view'] = ['photos/' . $a->data['user']['nickname'] . '/image/' . $datum, L10n::t('View photo')];
+                       } else {
+                               $tools['edit'] = ['photos/' . $a->data['user']['nickname'] . '/image/' . $datum . '/edit', L10n::t('Edit photo')];
+                               $tools['delete'] = ['photos/' . $a->data['user']['nickname'] . '/image/' . $datum . '/drop', L10n::t('Delete photo')];
+                               $tools['profile'] = ['profile_photo/use/'.$ph[0]['resource-id'], L10n::t('Use as profile photo')];
+                       }
 
-               if ($prevlink) {
-                       $prevlink = [$prevlink, '<div class="icon prev"></div>'];
+                       if (
+                               $ph[0]['uid'] == local_user()
+                               && (strlen($ph[0]['allow_cid']) || strlen($ph[0]['allow_gid']) || strlen($ph[0]['deny_cid']) || strlen($ph[0]['deny_gid']))
+                       ) {
+                               $tools['lock'] = L10n::t('Private Photo');
+                       }
                }
 
                $photo = [
@@ -1322,11 +1293,6 @@ function photos_content(App $a)
                        'filename' => $hires['filename'],
                ];
 
-               if ($nextlink) {
-                       $nextlink = [$nextlink, '<div class="icon next"></div>'];
-               }
-
-
                // Do we have an item for this photo?
 
                // FIXME! - replace following code to display the conversation with our normal
@@ -1431,7 +1397,7 @@ function photos_content(App $a)
                        $tpl = Renderer::getMarkupTemplate('photo_item.tpl');
                        $return_path = $a->cmd;
 
-                       if ($can_post || Security::canWriteToUserWall($owner_uid)) {
+                       if ($cmd === 'view' && ($can_post || Security::canWriteToUserWall($owner_uid))) {
                                $like_tpl = Renderer::getMarkupTemplate('like_noshare.tpl');
                                $likebuttons = Renderer::replaceMacros($like_tpl, [
                                        '$id' => $link_item['id'],
@@ -1510,7 +1476,7 @@ function photos_content(App $a)
                                                continue;
                                        }
 
-                                       $profile_url = Contact::MagicLinkById($item['author-id']);
+                                       $profile_url = Contact::magicLinkbyId($item['author-id']);
                                        if (strpos($profile_url, 'redir/') === 0) {
                                                $sparkle = ' sparkle';
                                        } else {
@@ -1574,7 +1540,6 @@ function photos_content(App $a)
                        '$id' => $ph[0]['id'],
                        '$album' => [$album_link, $ph[0]['album']],
                        '$tools' => $tools,
-                       '$lock' => $lock,
                        '$photo' => $photo,
                        '$prevlink' => $prevlink,
                        '$nextlink' => $nextlink,
diff --git a/mod/phpinfo.php b/mod/phpinfo.php
deleted file mode 100644 (file)
index 3228d25..0000000
+++ /dev/null
@@ -1,14 +0,0 @@
-<?php
-/**
- * @file mod/phpinfo.php
- */
-
-function phpinfo_content()
-{
-       if (!is_site_admin()) {
-               return false;
-       }
-
-       phpinfo();
-       exit();
-}
index b89cb9246c29b45c5fe9656c0c569ee4b140d924..9b844cc48ddc02ad7ce52f3753e20f3d74cd08ce 100644 (file)
@@ -313,14 +313,7 @@ function ping_init(App $a)
                usort($notifs, $sort_function);
 
                if (DBA::isResult($notifs)) {
-                       // Are the nofications called from the regular process or via the friendica app?
-                       $regularnotifications = (!empty($_GET['uid']) && !empty($_GET['_']));
-
                        foreach ($notifs as $notif) {
-                               if ($a->isFriendicaApp() || !$regularnotifications) {
-                                       $notif['message'] = str_replace("{0}", $notif['name'], $notif['message']);
-                               }
-
                                $contact = Contact::getDetailsByURL($notif['url']);
                                if (isset($contact['micro'])) {
                                        $notif['photo'] = ProxyUtils::proxifyUrl($contact['micro'], false, ProxyUtils::SIZE_MICRO);
index 064e0e9a85f919178aefcd6372a4092efd324a69..c288f6b6393bf8a7bf3eb082b8714cb3dc4a914a 100644 (file)
@@ -22,7 +22,7 @@ function poco_init(App $a) {
        $system_mode = false;
 
        if (intval(Config::get('system', 'block_public')) || (Config::get('system', 'block_local_dir'))) {
-               System::httpExit(401);
+               throw new \Friendica\Network\HTTPException\ForbiddenException();
        }
 
        if ($a->argc > 1) {
@@ -31,7 +31,7 @@ function poco_init(App $a) {
        if (empty($nickname)) {
                $c = q("SELECT * FROM `pconfig` WHERE `cat` = 'system' AND `k` = 'suggestme' AND `v` = 1");
                if (!DBA::isResult($c)) {
-                       System::httpExit(401);
+                       throw new \Friendica\Network\HTTPException\ForbiddenException();
                }
                $system_mode = true;
        }
@@ -73,7 +73,7 @@ function poco_init(App $a) {
                        DBA::escape($nickname)
                );
                if (! DBA::isResult($users) || $users[0]['hidewall'] || $users[0]['hide-friends']) {
-                       System::httpExit(404);
+                       throw new \Friendica\Network\HTTPException\NotFoundException();
                }
 
                $user = $users[0];
@@ -371,8 +371,9 @@ function poco_init(App $a) {
                        $ret['entry'][] = [];
                }
        } else {
-               System::httpExit(500);
+               throw new \Friendica\Network\HTTPException\InternalServerErrorException();
        }
+
        Logger::log("End of poco", Logger::DEBUG);
 
        if ($format === 'xml') {
@@ -385,6 +386,6 @@ function poco_init(App $a) {
                echo json_encode($ret);
                exit();
        } else {
-               System::httpExit(500);
+               throw new \Friendica\Network\HTTPException\InternalServerErrorException();
        }
 }
index b8a1ba7bfd1fcee0b935d10ff4d45ed04addb2ac..e8ddf86cd3ad3abc4f527f2a7a0bcf19e440d046 100644 (file)
@@ -154,15 +154,11 @@ function poke_content(App $a)
        $name = $contact['name'];
        $id = $contact['id'];
 
-       $base = System::baseUrl();
-
        $head_tpl = Renderer::getMarkupTemplate('poke_head.tpl');
        $a->page['htmlhead'] .= Renderer::replaceMacros($head_tpl,[
                '$baseurl' => System::baseUrl(true),
-               '$base' => $base
        ]);
 
-
        $parent = (!empty($_GET['parent']) ? intval($_GET['parent']) : '0');
 
 
index e120ce17246dbbc37647842494e5c80b4d419ee4..7fc3a92899f78be6314116e23775b0389189c366 100644 (file)
@@ -10,9 +10,9 @@ use Friendica\Network\Probe;
 function probe_content(App $a)
 {
        if (!local_user()) {
-               System::httpExit(403, ["title" => L10n::t("Public access denied."),
-                       "description" => L10n::t("Only logged in users are permitted to perform a probing.")]);
-               exit();
+               $e = new \Friendica\Network\HTTPException\ForbiddenException(L10n::t("Only logged in users are permitted to perform a probing."));
+               $e->httpdesc = L10n::t("Public access denied.");
+               throw $e;
        }
 
        $o = '<div class="generic-page-wrapper">';
index c5744f399b2443565525eb0293ef090f1a7875a0..e5ede6c80a3792da91512c2d95f8db61d52dd51d 100644 (file)
@@ -12,10 +12,9 @@ use Friendica\Core\System;
 function hub_return($valid, $body)
 {
        if ($valid) {
-               header($_SERVER["SERVER_PROTOCOL"] . ' 200 OK');
                echo $body;
        } else {
-               System::httpExit(404);
+               throw new \Friendica\Network\HTTPException\NotFoundException();
        }
        exit();
 }
@@ -24,7 +23,7 @@ function hub_return($valid, $body)
 
 function hub_post_return()
 {
-       System::httpExit(200);
+       throw new \Friendica\Network\HTTPException\OKException();
 }
 
 function pubsub_init(App $a)
index 342facd1076fa8b2c03cd56e9c5fb2d090c68c42..f71984ec1826cfce2a5df6492f17bdc4b841f759 100644 (file)
@@ -17,7 +17,7 @@ function pubsubhubbub_init(App $a) {
        // PuSH subscription must be considered "public" so just block it
        // if public access isn't enabled.
        if (Config::get('system', 'block_public')) {
-               System::httpExit(403);
+               throw new \Friendica\Network\HTTPException\ForbiddenException();
        }
 
        // Subscription request from subscriber
@@ -44,7 +44,7 @@ function pubsubhubbub_init(App $a) {
                        $subscribe = 0;
                } else {
                        Logger::log("Invalid hub_mode=$hub_mode, ignoring.");
-                       System::httpExit(404);
+                       throw new \Friendica\Network\HTTPException\NotFoundException();
                }
 
                Logger::log("$hub_mode request from " . $_SERVER['REMOTE_ADDR']);
@@ -61,7 +61,7 @@ function pubsubhubbub_init(App $a) {
 
                if (!$nick) {
                        Logger::log('Bad hub_topic=$hub_topic, ignoring.');
-                       System::httpExit(404);
+                       throw new \Friendica\Network\HTTPException\NotFoundException();
                }
 
                // fetch user from database given the nickname
@@ -69,13 +69,13 @@ function pubsubhubbub_init(App $a) {
                $owner = DBA::selectFirst('user', ['uid', 'hidewall', 'nickname'], $condition);
                if (!DBA::isResult($owner)) {
                        Logger::log('Local account not found: ' . $nick . ' - topic: ' . $hub_topic . ' - callback: ' . $hub_callback);
-                       System::httpExit(404);
+                       throw new \Friendica\Network\HTTPException\NotFoundException();
                }
 
                // abort if user's wall is supposed to be private
                if ($owner['hidewall']) {
                        Logger::log('Local user ' . $nick . 'has chosen to hide wall, ignoring.');
-                       System::httpExit(403);
+                       throw new \Friendica\Network\HTTPException\ForbiddenException();
                }
 
                // get corresponding row from contact table
@@ -84,7 +84,7 @@ function pubsubhubbub_init(App $a) {
                $contact = DBA::selectFirst('contact', ['poll'], $condition);
                if (!DBA::isResult($contact)) {
                        Logger::log('Self contact for user ' . $owner['uid'] . ' not found.');
-                       System::httpExit(404);
+                       throw new \Friendica\Network\HTTPException\NotFoundException();
                }
 
                // sanity check that topic URLs are the same
@@ -93,7 +93,7 @@ function pubsubhubbub_init(App $a) {
 
                if (!Strings::compareLink($hub_topic, $contact['poll']) && !Strings::compareLink($hub_topic2, $contact['poll']) && !Strings::compareLink($hub_topic, $self)) {
                        Logger::log('Hub topic ' . $hub_topic . ' != ' . $contact['poll']);
-                       System::httpExit(404);
+                       throw new \Friendica\Network\HTTPException\NotFoundException();
                }
 
                // do subscriber verification according to the PuSH protocol
@@ -121,19 +121,19 @@ function pubsubhubbub_init(App $a) {
                // give up if the HTTP return code wasn't a success (2xx)
                if ($ret < 200 || $ret > 299) {
                        Logger::log("Subscriber verification for $hub_topic at $hub_callback returned $ret, ignoring.");
-                       System::httpExit(404);
+                       throw new \Friendica\Network\HTTPException\NotFoundException();
                }
 
                // check that the correct hub_challenge code was echoed back
                if (trim($body) !== $hub_challenge) {
                        Logger::log("Subscriber did not echo back hub.challenge, ignoring.");
                        Logger::log("\"$hub_challenge\" != \"".trim($body)."\"");
-                       System::httpExit(404);
+                       throw new \Friendica\Network\HTTPException\NotFoundException();
                }
 
                PushSubscriber::renew($owner['uid'], $nick, $subscribe, $hub_callback, $hub_topic, $hub_secret);
 
-               System::httpExit(202);
+               throw new \Friendica\Network\HTTPException\AcceptedException();
        }
        exit();
 }
index b0258acbd71803b0ac4286cafd31eb5c465d065b..db1287ea6f1f804a8b6b784710ce5e01409beb07 100644 (file)
@@ -22,7 +22,7 @@ function receive_post(App $a)
        $enabled = intval(Config::get('system', 'diaspora_enabled'));
        if (!$enabled) {
                Logger::log('mod-diaspora: disabled');
-               System::httpExit(500);
+               throw new \Friendica\Network\HTTPException\InternalServerErrorException();
        }
 
        if (($a->argc == 2) && ($a->argv[1] === 'public')) {
@@ -32,13 +32,13 @@ function receive_post(App $a)
                $public = false;
 
                if ($a->argc != 3 || $a->argv[1] !== 'users') {
-                       System::httpExit(500);
+                       throw new \Friendica\Network\HTTPException\InternalServerErrorException();
                }
                $guid = $a->argv[2];
 
                $importer = DBA::selectFirst('user', [], ['guid' => $guid, 'account_expired' => false, 'account_removed' => false]);
                if (!DBA::isResult($importer)) {
-                       System::httpExit(500);
+                       throw new \Friendica\Network\HTTPException\InternalServerErrorException();
                }
        }
 
@@ -49,7 +49,7 @@ function receive_post(App $a)
        if (empty($_POST['xml'])) {
                $postdata = file_get_contents("php://input");
                if ($postdata == '') {
-                       System::httpExit(500);
+                       throw new \Friendica\Network\HTTPException\InternalServerErrorException();
                }
 
                Logger::log('mod-diaspora: message is in the new format', Logger::DEBUG);
@@ -71,7 +71,7 @@ function receive_post(App $a)
        Logger::log('mod-diaspora: decoded msg: ' . print_r($msg, true), Logger::DATA);
 
        if (!is_array($msg)) {
-               System::httpExit(500);
+               throw new \Friendica\Network\HTTPException\InternalServerErrorException();
        }
 
        Logger::log('mod-diaspora: dispatching', Logger::DEBUG);
@@ -83,6 +83,9 @@ function receive_post(App $a)
                $ret = Diaspora::dispatch($importer, $msg);
        }
 
-       System::httpExit(($ret) ? 200 : 500);
-       // NOTREACHED
+       if ($ret) {
+               throw new \Friendica\Network\HTTPException\OKException();
+       } else {
+               throw new \Friendica\Network\HTTPException\InternalServerErrorException();
+       }
 }
diff --git a/mod/rsd_xml.php b/mod/rsd_xml.php
deleted file mode 100644 (file)
index 84dedd6..0000000
+++ /dev/null
@@ -1,26 +0,0 @@
-<?php
-
-use Friendica\App;
-use Friendica\Core\System;
-
-function rsd_xml_content(App $a)
-{
-       header ("Content-Type: text/xml");
-       echo '<?xml version="1.0" encoding="UTF-8"?>
-<rsd version="1.0" xmlns="http://archipelago.phrasewise.com/rsd">
-  <service>
-    <engineName>Friendica</engineName>
-    <engineLink>http://friendica.com/</engineLink>
-    <apis>
-      <api name="Twitter" preferred="true" apiLink="'.System::baseUrl().'/api/" blogID="">
-        <settings>
-          <docs>http://status.net/wiki/TwitterCompatibleAPI</docs>
-          <setting name="OAuth">false</setting>
-        </settings>
-      </api>
-    </apis>
-  </service>
-</rsd>';
-
-       exit();
-}
index 84d2942d5332dd5d8e042bff24a73569d7100eb4..ba1bc8d46513e54caf0c58be55487e5a0387b79c 100644 (file)
@@ -28,7 +28,7 @@ function salmon_post(App $a, $xml = '') {
                DBA::escape($nick)
        );
        if (! DBA::isResult($r)) {
-               System::httpExit(500);
+               throw new \Friendica\Network\HTTPException\InternalServerErrorException();
        }
 
        $importer = $r[0];
@@ -49,7 +49,7 @@ function salmon_post(App $a, $xml = '') {
 
        if (empty($base)) {
                Logger::log('unable to locate salmon data in xml ');
-               System::httpExit(400);
+               throw new \Friendica\Network\HTTPException\BadRequestException();
        }
 
        // Stash the signature away for now. We have to find their key or it won't be good for anything.
@@ -87,7 +87,7 @@ function salmon_post(App $a, $xml = '') {
 
        if(! $author_link) {
                Logger::log('Could not retrieve author URI.');
-               System::httpExit(400);
+               throw new \Friendica\Network\HTTPException\BadRequestException();
        }
 
        // Once we have the author URI, go to the web and try to find their public key
@@ -98,7 +98,7 @@ function salmon_post(App $a, $xml = '') {
 
        if(! $key) {
                Logger::log('Could not retrieve author key.');
-               System::httpExit(400);
+               throw new \Friendica\Network\HTTPException\BadRequestException();
        }
 
        $key_info = explode('.',$key);
@@ -130,7 +130,7 @@ function salmon_post(App $a, $xml = '') {
 
        if (! $verify) {
                Logger::log('Message did not verify. Discarding.');
-               System::httpExit(400);
+               throw new \Friendica\Network\HTTPException\BadRequestException();
        }
 
        Logger::log('Message verified with mode '.$mode);
@@ -177,8 +177,7 @@ function salmon_post(App $a, $xml = '') {
        //if((DBA::isResult($r)) && (($r[0]['readonly']) || ($r[0]['rel'] == Contact::FOLLOWER) || ($r[0]['blocked']))) {
        if (DBA::isResult($r) && $r[0]['blocked']) {
                Logger::log('Ignoring this author.');
-               System::httpExit(202);
-               // NOTREACHED
+               throw new \Friendica\Network\HTTPException\AcceptedException();
        }
 
        // Placeholder for hub discovery.
@@ -188,5 +187,5 @@ function salmon_post(App $a, $xml = '') {
 
        OStatus::import($data, $importer, $contact_rec, $hub);
 
-       System::httpExit(200);
+       throw new \Friendica\Network\HTTPException\OKException();
 }
index 9a70bcac908d179d3512761284bd8dd64b431a17..1416f1d89f52d34edb82e9a94da5af8e91353779 100644 (file)
@@ -98,12 +98,9 @@ function search_content(App $a) {
        }
 
        if (Config::get('system','local_search') && !local_user() && !remote_user()) {
-               System::httpExit(403,
-                               ["title" => L10n::t("Public access denied."),
-                                       "description" => L10n::t("Only logged in users are permitted to perform a search.")]);
-               exit();
-               //notice(L10n::t('Public access denied.').EOL);
-               //return;
+               $e = new \Friendica\Network\HTTPException\ForbiddenException(L10n::t("Only logged in users are permitted to perform a search."));
+               $e->httpdesc = L10n::t("Public access denied.");
+               throw $e;
        }
 
        if (Config::get('system','permit_crawling') && !local_user() && !remote_user()) {
@@ -123,10 +120,7 @@ function search_content(App $a) {
                if (!is_null($result)) {
                        $resultdata = json_decode($result);
                        if (($resultdata->time > (time() - $crawl_permit_period)) && ($resultdata->accesses > $free_crawls)) {
-                               System::httpExit(429,
-                                               ["title" => L10n::t("Too Many Requests"),
-                                                       "description" => L10n::t("Only one search per minute is permitted for not logged in users.")]);
-                               exit();
+                               throw new \Friendica\Network\HTTPException\TooManyRequestsException(L10n::t("Only one search per minute is permitted for not logged in users."));
                        }
                        Cache::set("remote_search:".$remote, json_encode(["time" => time(), "accesses" => $resultdata->accesses + 1]), Cache::HOUR);
                } else
index 23ebf4fe4858f40a7f46f2bde0a6251852edb09d..9fa1a410d37130eff5ad646e84f840c0c1011ba5 100644 (file)
@@ -87,7 +87,7 @@ function subthread_content(App $a) {
 
        $post_type = (($item['resource-id']) ? L10n::t('photo') : L10n::t('status'));
        $objtype = (($item['resource-id']) ? ACTIVITY_OBJ_IMAGE : ACTIVITY_OBJ_NOTE );
-       $link = XML::escape('<link rel="alternate" type="text/html" href="' . System::baseUrl() . '/display/' . $owner['nickname'] . '/' . $item['id'] . '" />' . "\n");
+       $link = XML::escape('<link rel="alternate" type="text/html" href="' . System::baseUrl() . '/display/' . $item['guid'] . '" />' . "\n");
        $body = $item['body'];
 
        $obj = <<< EOT
@@ -128,7 +128,7 @@ EOT;
 
        $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
        $alink = '[url=' . $item['author-link'] . ']' . $item['author-name'] . '[/url]';
-       $plink = '[url=' . System::baseUrl() . '/display/' . $owner['nickname'] . '/' . $item['id'] . ']' . $post_type . '[/url]';
+       $plink = '[url=' . System::baseUrl() . '/display/' . $item['guid'] . ']' . $post_type . '[/url]';
        $arr['body'] =  sprintf( $bodyverb, $ulink, $alink, $plink );
 
        $arr['verb'] = $activity;
index bca2694d37360ebb9e7055114d91df6995eeca61..4b67dd6eb8e7930b6d217c7dc46024d55707956f 100644 (file)
@@ -19,39 +19,16 @@ function suggest_init(App $a)
        if (! local_user()) {
                return;
        }
+}
 
-       if (!empty($_GET['ignore'])) {
-               // Check if we should do HTML-based delete confirmation
-               if ($_REQUEST['confirm']) {
-                       // <form> can't take arguments in its "action" parameter
-                       // so add any arguments as hidden inputs
-                       $query = explode_querystring($a->query_string);
-                       $inputs = [];
-                       foreach ($query['args'] as $arg) {
-                               if (strpos($arg, 'confirm=') === false) {
-                                       $arg_parts = explode('=', $arg);
-                                       $inputs[] = ['name' => $arg_parts[0], 'value' => $arg_parts[1]];
-                               }
-                       }
-
-                       $a->page['content'] = Renderer::replaceMacros(Renderer::getMarkupTemplate('confirm.tpl'), [
-                               '$method' => 'get',
-                               '$message' => L10n::t('Do you really want to delete this suggestion?'),
-                               '$extra_inputs' => $inputs,
-                               '$confirm' => L10n::t('Yes'),
-                               '$confirm_url' => $query['base'],
-                               '$confirm_name' => 'confirmed',
-                               '$cancel' => L10n::t('Cancel'),
-                       ]);
-                       $a->error = 1; // Set $a->error so the other module functions don't execute
-                       return;
-               }
-               // Now check how the user responded to the confirmation query
-               if (!$_REQUEST['canceled']) {
-                       DBA::insert('gcign', ['uid' => local_user(), 'gcid' => $_GET['ignore']]);
-               }
+function suggest_post(App $a)
+{
+       if (!empty($_POST['ignore']) && !empty($_POST['confirm'])) {
+               DBA::insert('gcign', ['uid' => local_user(), 'gcid' => $_POST['ignore']]);
+               notice(L10n::t('Contact suggestion successfully ignored.'));
        }
 
+       $a->internalRedirect('suggest');
 }
 
 function suggest_content(App $a)
@@ -76,11 +53,34 @@ function suggest_content(App $a)
                return $o;
        }
 
+
+       if (!empty($_GET['ignore'])) {
+               // <form> can't take arguments in its "action" parameter
+               // so add any arguments as hidden inputs
+               $query = explode_querystring($a->query_string);
+               $inputs = [];
+               foreach ($query['args'] as $arg) {
+                       if (strpos($arg, 'confirm=') === false) {
+                               $arg_parts = explode('=', $arg);
+                               $inputs[] = ['name' => $arg_parts[0], 'value' => $arg_parts[1]];
+                       }
+               }
+
+               return Renderer::replaceMacros(Renderer::getMarkupTemplate('confirm.tpl'), [
+                       '$method' => 'post',
+                       '$message' => L10n::t('Do you really want to delete this suggestion?'),
+                       '$extra_inputs' => $inputs,
+                       '$confirm' => L10n::t('Yes'),
+                       '$confirm_url' => $query['base'],
+                       '$confirm_name' => 'confirm',
+                       '$cancel' => L10n::t('Cancel'),
+               ]);
+       }
+
        $id = 0;
        $entries = [];
 
        foreach ($r as $rr) {
-
                $connlnk = System::baseUrl() . '/follow/?url=' . (($rr['connect']) ? $rr['connect'] : $rr['url']);
                $ignlnk = System::baseUrl() . '/suggest?ignore=' . $rr['id'];
                $photo_menu = [
index 7cb43e330c951989b94e61cb7375dfe9836e20f0..5d3d1923e4425958b4d53a00e3ea436cd8553c76 100644 (file)
@@ -40,14 +40,12 @@ function tagger_content(App $a) {
        }
 
        $owner_uid = $item['uid'];
-       $owner_nick = '';
        $blocktags = 0;
 
-       $r = q("select `nickname`,`blocktags` from user where uid = %d limit 1",
+       $r = q("select `blocktags` from user where uid = %d limit 1",
                intval($owner_uid)
        );
        if (DBA::isResult($r)) {
-               $owner_nick = $r[0]['nickname'];
                $blocktags = $r[0]['blocktags'];
        }
 
@@ -69,12 +67,7 @@ function tagger_content(App $a) {
        $xterm = XML::escape($term);
        $post_type = (($item['resource-id']) ? L10n::t('photo') : L10n::t('status'));
        $targettype = (($item['resource-id']) ? ACTIVITY_OBJ_IMAGE : ACTIVITY_OBJ_NOTE );
-
-       if ($owner_nick) {
-               $href = System::baseUrl() . '/display/' . $owner_nick . '/' . $item['id'];
-       } else {
-               $href = System::baseUrl() . '/display/' . $item['guid'];
-       }
+       $href = System::baseUrl() . '/display/' . $item['guid'];
 
        $link = XML::escape('<link rel="alternate" type="text/html" href="'. $href . '" />' . "\n");
 
index 2821e0a646bef02e3e6297d22a1d57d861c251b7..d1a26b3ca21ae9cfb3c59a2d31432ad197a5c142 100644 (file)
@@ -1,7 +1,6 @@
 <?php
 
 use Friendica\App;
-use Friendica\Core\System;
 
 function toggle_mobile_init(App $a) {
 
index 17715ac35fcda08224265518760207f4aff63f14..c91309e74c37fec9eb4077a25dda78defc6da4ca 100644 (file)
@@ -49,7 +49,6 @@ function uexport_content(App $a) {
 
        $tpl = Renderer::getMarkupTemplate("uexport.tpl");
        return Renderer::replaceMacros($tpl, [
-               '$baseurl' => System::baseUrl(),
                '$title' => L10n::t('Export personal data'),
                '$options' => $options
        ]);
index 4120c136f177c009562fe385047b6ea82d59549c..728a71bb5d70495bd6810c2a143e77f71294b78d 100644 (file)
@@ -67,9 +67,7 @@ function videos_init(App $a)
                $a->page['aside'] .= $vcard_widget;
 
                $tpl = Renderer::getMarkupTemplate("videos_head.tpl");
-               $a->page['htmlhead'] .= Renderer::replaceMacros($tpl,[
-                       '$baseurl' => System::baseUrl(),
-               ]);
+               $a->page['htmlhead'] .= Renderer::replaceMacros($tpl);
        }
 
        return;
@@ -84,33 +82,6 @@ function videos_post(App $a)
        }
 
        if (($a->argc == 2) && !empty($_POST['delete']) && !empty($_POST['id'])) {
-               // Check if we should do HTML-based delete confirmation
-               if (empty($_REQUEST['confirm'])) {
-                       if (!empty($_REQUEST['canceled'])) {
-                               $a->internalRedirect('videos/' . $a->data['user']['nickname']);
-                       }
-
-                       $drop_url = $a->query_string;
-
-                       $a->page['content'] = Renderer::replaceMacros(Renderer::getMarkupTemplate('confirm.tpl'), [
-                               '$method' => 'post',
-                               '$message' => L10n::t('Do you really want to delete this video?'),
-                               '$extra_inputs' => [
-                                       ['name' => 'id'    , 'value' => $_POST['id']],
-                                       ['name' => 'delete', 'value' => 'x']
-                               ],
-                               '$confirm' => L10n::t('Delete Video'),
-                               '$confirm_url' => $drop_url,
-                               '$confirm_name' => 'confirm', // Needed so that confirmation will bring us back into this if statement
-                               '$cancel' => L10n::t('Cancel'),
-
-                       ]);
-
-                       $a->error = 1; // Set $a->error so the other module functions don't execute
-
-                       return;
-               }
-
                $video_id = $_POST['id'];
 
                if (Attach::exists(['id' => $video_id, 'uid' => local_user()])) {
index 7c2b96fad1bb796cd0b8fe32d2eb23fe5db3d3aa..14919820dd2f280b3024fcc03814e8740c35e8d2 100644 (file)
@@ -20,18 +20,18 @@ use Friendica\Util\Proxy as ProxyUtils;
 function viewcontacts_init(App $a)
 {
        if (Config::get('system', 'block_public') && !local_user() && !remote_user()) {
-               System::httpExit(403, ["title" => L10n::t('Access denied.')]);
+               throw new \Friendica\Network\HTTPException\ForbiddenException(L10n::t('Access denied.'));
        }
 
        if ($a->argc < 2) {
-               System::httpExit(403, ["title" => L10n::t('Access denied.')]);
+               throw new \Friendica\Network\HTTPException\ForbiddenException(L10n::t('Access denied.'));
        }
 
        Nav::setSelected('home');
 
        $user = DBA::selectFirst('user', [], ['nickname' => $a->argv[1], 'blocked' => false]);
        if (!DBA::isResult($user)) {
-               System::httpExit(404, ["title" => L10n::t('Page not found.')]);
+               throw new \Friendica\Network\HTTPException\NotFoundException();
        }
 
        $a->data['user'] = $user;
index f05996d2fbcf22ef9fb59724248548a4c370bcd6..55eb0b990c06ca5f2e44978b1e01450162f86fd9 100644 (file)
@@ -18,9 +18,7 @@ function viewsrc_content(App $a)
        $item_id = (($a->argc > 1) ? intval($a->argv[1]) : 0);
 
        if (!$item_id) {
-               $a->error = 404;
-               notice(L10n::t('Item not found.') . EOL);
-               return;
+               throw new \Friendica\Network\HTTPException\NotFoundException(L10n::t('Item not found.'));
        }
 
        $item = Item::selectFirst(['body'], ['uid' => local_user(), 'id' => $item_id]);
diff --git a/mod/webfinger.php b/mod/webfinger.php
deleted file mode 100644 (file)
index b22b1ee..0000000
+++ /dev/null
@@ -1,42 +0,0 @@
-<?php
-/**
- * @file mod/webfinger.php
- */
-use Friendica\App;
-use Friendica\Core\L10n;
-use Friendica\Core\System;
-use Friendica\Network\Probe;
-
-function webfinger_content(App $a)
-{
-       if (!local_user()) {
-               System::httpExit(
-                       403,
-                       [
-                               "title" => L10n::t("Public access denied."),
-                               "description" => L10n::t("Only logged in users are permitted to perform a probing.")
-                       ]
-               );
-               exit();
-       }
-
-       $o = '<div class="generic-page-wrapper">';
-       $o .= '<h3>Webfinger Diagnostic</h3>';
-
-       $o .= '<form action="webfinger" method="get">';
-       $o .= 'Lookup address: <input type="text" style="width: 250px;" name="addr" value="' . defaults($_GET, 'addr', '') .'" />';
-       $o .= '<input type="submit" name="submit" value="Submit" /></form>';
-
-       $o .= '<br /><br />';
-
-       if (!empty($_GET['addr'])) {
-               $addr = trim($_GET['addr']);
-               $res = Probe::lrdd($addr);
-               $o .= '<pre>';
-               $o .= str_replace("\n", '<br />', print_r($res, true));
-               $o .= '</pre>';
-       }
-       $o .= '</div>';
-
-       return $o;
-}
diff --git a/mod/xrd.php b/mod/xrd.php
deleted file mode 100644 (file)
index b4cb60a..0000000
+++ /dev/null
@@ -1,134 +0,0 @@
-<?php
-/**
- * @file mod/xrd.php
- */
-
-use Friendica\App;
-use Friendica\Core\Hook;
-use Friendica\Core\Renderer;
-use Friendica\Core\System;
-use Friendica\Database\DBA;
-use Friendica\Protocol\Salmon;
-use Friendica\Util\Strings;
-
-function xrd_init(App $a)
-{
-       if ($a->argv[0] == 'xrd') {
-               if (empty($_GET['uri'])) {
-                       System::httpExit(404);
-               }
-
-               $uri = urldecode(Strings::escapeTags(trim($_GET['uri'])));
-               if (defaults($_SERVER, 'HTTP_ACCEPT', '') == 'application/jrd+json') {
-                       $mode = 'json';
-               } else {
-                       $mode = 'xml';
-               }
-       } else {
-               if (empty($_GET['resource'])) {
-                       System::httpExit(404);
-               }
-
-               $uri = urldecode(Strings::escapeTags(trim($_GET['resource'])));
-               if (defaults($_SERVER, 'HTTP_ACCEPT', '') == 'application/xrd+xml') {
-                       $mode = 'xml';
-               } else {
-                       $mode = 'json';
-               }
-       }
-
-       if (substr($uri, 0, 4) === 'http') {
-               $name = ltrim(basename($uri), '~');
-       } else {
-               $local = str_replace('acct:', '', $uri);
-               if (substr($local, 0, 2) == '//') {
-                       $local = substr($local, 2);
-               }
-
-               $name = substr($local, 0, strpos($local, '@'));
-       }
-
-       $user = DBA::selectFirst('user', [], ['nickname' => $name]);
-       if (!DBA::isResult($user)) {
-               System::httpExit(404);
-       }
-
-       $profile_url = System::baseUrl().'/profile/'.$user['nickname'];
-
-       $alias = str_replace('/profile/', '/~', $profile_url);
-
-       $addr = 'acct:'.$user['nickname'].'@'.$a->getHostName();
-       if ($a->getURLPath()) {
-               $addr .= '/'.$a->getURLPath();
-       }
-
-       if ($mode == 'xml') {
-               xrd_xml($addr, $alias, $profile_url, $user);
-       } else {
-               xrd_json($addr, $alias, $profile_url, $user);
-       }
-}
-
-function xrd_json($uri, $alias, $profile_url, $r)
-{
-       $salmon_key = Salmon::salmonKey($r['spubkey']);
-
-       header('Access-Control-Allow-Origin: *');
-       header("Content-type: application/json; charset=utf-8");
-
-       $json = ['subject' => $uri,
-               'aliases' => [$alias, $profile_url],
-               'links' => [
-                       ['rel' => NAMESPACE_DFRN, 'href' => $profile_url],
-                       ['rel' => NAMESPACE_FEED, 'type' => 'application/atom+xml', 'href' => System::baseUrl().'/dfrn_poll/'.$r['nickname']],
-                       ['rel' => 'http://webfinger.net/rel/profile-page', 'type' => 'text/html', 'href' => $profile_url],
-                       ['rel' => 'self', 'type' => 'application/activity+json', 'href' => $profile_url],
-                       ['rel' => 'http://microformats.org/profile/hcard', 'type' => 'text/html', 'href' => System::baseUrl().'/hcard/'.$r['nickname']],
-                       ['rel' => NAMESPACE_POCO, 'href' => System::baseUrl().'/poco/'.$r['nickname']],
-                       ['rel' => 'http://webfinger.net/rel/avatar', 'type' => 'image/jpeg', 'href' => System::baseUrl().'/photo/profile/'.$r['uid'].'.jpg'],
-                       ['rel' => 'http://joindiaspora.com/seed_location', 'type' => 'text/html', 'href' => System::baseUrl()],
-                       ['rel' => 'salmon', 'href' => System::baseUrl().'/salmon/'.$r['nickname']],
-                       ['rel' => 'http://salmon-protocol.org/ns/salmon-replies', 'href' => System::baseUrl().'/salmon/'.$r['nickname']],
-                       ['rel' => 'http://salmon-protocol.org/ns/salmon-mention', 'href' => System::baseUrl().'/salmon/'.$r['nickname'].'/mention'],
-                       ['rel' => 'http://ostatus.org/schema/1.0/subscribe', 'template' => System::baseUrl().'/follow?url={uri}'],
-                       ['rel' => 'magic-public-key', 'href' => 'data:application/magic-public-key,'.$salmon_key],
-                       ['rel' => 'http://purl.org/openwebauth/v1', 'type' => 'application/x-zot+json', 'href' => System::baseUrl().'/owa']
-               ]
-       ];
-
-       echo json_encode($json);
-       exit();
-}
-
-function xrd_xml($uri, $alias, $profile_url, $r)
-{
-       $salmon_key = Salmon::salmonKey($r['spubkey']);
-
-       header('Access-Control-Allow-Origin: *');
-       header("Content-type: text/xml");
-
-       $tpl = Renderer::getMarkupTemplate('xrd_person.tpl');
-
-       $o = Renderer::replaceMacros($tpl, [
-               '$nick'        => $r['nickname'],
-               '$accturi'     => $uri,
-               '$alias'       => $alias,
-               '$profile_url' => $profile_url,
-               '$hcard_url'   => System::baseUrl() . '/hcard/'         . $r['nickname'],
-               '$atom'        => System::baseUrl() . '/dfrn_poll/'     . $r['nickname'],
-               '$poco_url'    => System::baseUrl() . '/poco/'          . $r['nickname'],
-               '$photo'       => System::baseUrl() . '/photo/profile/' . $r['uid']      . '.jpg',
-               '$baseurl'     => System::baseUrl(),
-               '$salmon'      => System::baseUrl() . '/salmon/'        . $r['nickname'],
-               '$salmen'      => System::baseUrl() . '/salmon/'        . $r['nickname'] . '/mention',
-               '$subscribe'   => System::baseUrl() . '/follow?url={uri}',
-               '$openwebauth' => System::baseUrl() . '/owa',
-               '$modexp'      => 'data:application/magic-public-key,'  . $salmon_key]
-       );
-
-       $arr = ['user' => $r, 'xml' => $o];
-       Hook::callAll('personal_xrd', $arr);
-
-       echo $arr['xml'];
-       exit();
-}
index 9cde12499859cf5878910a87931f292374ae0725..017661c4ca666081ad997b5e5d97ad7ce3ed4d08 100644 (file)
@@ -14,7 +14,7 @@ use Friendica\Core\Hook;
 use Friendica\Core\Theme;
 use Friendica\Database\DBA;
 use Friendica\Model\Profile;
-use Friendica\Network\HTTPException\InternalServerErrorException;
+use Friendica\Network\HTTPException;
 use Friendica\Util\BaseURL;
 use Friendica\Util\Config\ConfigFileLoader;
 use Friendica\Util\HTTPSignature;
@@ -49,7 +49,6 @@ class App
        public $page_contact;
        public $content;
        public $data = [];
-       public $error = false;
        public $cmd = '';
        public $argv;
        public $argc;
@@ -88,11 +87,6 @@ class App
         */
        private $baseURL;
 
-       /**
-        * @var bool true, if the call is from the Friendica APP, otherwise false
-        */
-       private $isFriendicaApp;
-
        /**
         * @var bool true, if the call is from an backend node (f.e. worker)
         */
@@ -258,8 +252,6 @@ class App
                $this->profiler = $profiler;
                $this->logger   = $logger;
 
-               $this->checkFriendicaApp();
-
                $this->profiler->reset();
 
                $this->reload();
@@ -406,8 +398,6 @@ class App
         * @param bool $ssl Whether to append http or https under BaseURL::SSL_POLICY_SELFSIGN
         *
         * @return string Friendica server base URL
-        *
-        * @deprecated 2019.06 - use BaseURL->get($ssl) instead
         */
        public function getBaseURL($ssl = false)
        {
@@ -509,7 +499,6 @@ class App
                 * being first
                 */
                $this->page['htmlhead'] = Core\Renderer::replaceMacros($tpl, [
-                       '$baseurl'         => $this->getBaseURL(),
                        '$local_user'      => local_user(),
                        '$generator'       => 'Friendica' . ' ' . FRIENDICA_VERSION,
                        '$delitem'         => Core\L10n::t('Delete this item?'),
@@ -562,7 +551,6 @@ class App
 
                $tpl = Core\Renderer::getMarkupTemplate('footer.tpl');
                $this->page['footer'] = Core\Renderer::replaceMacros($tpl, [
-                       '$baseurl' => $this->getBaseURL(),
                        '$footerScripts' => $this->footerScripts,
                ]) . $this->page['footer'];
        }
@@ -573,7 +561,7 @@ class App
         * @param string $origURL
         *
         * @return string The cleaned url
-        * @throws InternalServerErrorException
+        * @throws HTTPException\InternalServerErrorException
         */
        public function removeBaseURL($origURL)
        {
@@ -594,7 +582,7 @@ class App
         * Returns the current UserAgent as a String
         *
         * @return string the UserAgent as a String
-        * @throws InternalServerErrorException
+        * @throws HTTPException\InternalServerErrorException
         */
        public function getUserAgent()
        {
@@ -606,28 +594,6 @@ class App
                        $this->getBaseURL();
        }
 
-       /**
-        * Checks, if the call is from the Friendica App
-        *
-        * Reason:
-        * The friendica client has problems with the GUID in the notify. this is some workaround
-        */
-       private function checkFriendicaApp()
-       {
-               // Friendica-Client
-               $this->isFriendicaApp = isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)';
-       }
-
-       /**
-        *      Is the call via the Friendica app? (not a "normale" call)
-        *
-        * @return bool true if it's from the Friendica app
-        */
-       public function isFriendicaApp()
-       {
-               return $this->isFriendicaApp;
-       }
-
        /**
         * @brief Checks if the site is called via a backend process
         *
@@ -724,7 +690,7 @@ class App
         * @brief Checks if the minimal memory is reached
         *
         * @return bool Is the memory limit reached?
-        * @throws InternalServerErrorException
+        * @throws HTTPException\InternalServerErrorException
         */
        public function isMinMemoryReached()
        {
@@ -769,7 +735,7 @@ class App
         * @brief Checks if the maximum load is reached
         *
         * @return bool Is the load reached?
-        * @throws InternalServerErrorException
+        * @throws HTTPException\InternalServerErrorException
         */
        public function isMaxLoadReached()
        {
@@ -802,7 +768,7 @@ class App
         *
         * @param string $command The command to execute
         * @param array  $args    Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
-        * @throws InternalServerErrorException
+        * @throws HTTPException\InternalServerErrorException
         */
        public function proc_run($command, $args)
        {
@@ -843,7 +809,7 @@ class App
         * Generates the site's default sender email address
         *
         * @return string
-        * @throws InternalServerErrorException
+        * @throws HTTPException\InternalServerErrorException
         */
        public function getSenderEmailAddress()
        {
@@ -864,7 +830,7 @@ class App
         * Returns the current theme name.
         *
         * @return string the name of the current theme
-        * @throws InternalServerErrorException
+        * @throws HTTPException\InternalServerErrorException
         */
        public function getCurrentTheme()
        {
@@ -945,7 +911,7 @@ class App
         * Provide a sane default if nothing is chosen or the specified theme does not exist.
         *
         * @return string
-        * @throws InternalServerErrorException
+        * @throws HTTPException\InternalServerErrorException
         */
        public function getCurrentThemeStylesheetPath()
        {
@@ -1011,7 +977,9 @@ class App
        {
                // Missing DB connection: ERROR
                if ($this->getMode()->has(App\Mode::LOCALCONFIGPRESENT) && !$this->getMode()->has(App\Mode::DBAVAILABLE)) {
-                       Core\System::httpExit(500, ['title' => 'Error 500 - Internal Server Error', 'description' => 'Apologies but the website is unavailable at the moment.']);
+                       Module\Special\HTTPException::rawContent(
+                               new HTTPException\InternalServerErrorException('Apologies but the website is unavailable at the moment.')
+                       );
                }
 
                // Max Load Average reached: ERROR
@@ -1019,11 +987,15 @@ class App
                        header('Retry-After: 120');
                        header('Refresh: 120; url=' . $this->getBaseURL() . "/" . $this->query_string);
 
-                       Core\System::httpExit(503, ['title' => 'Error 503 - Service Temporarily Unavailable', 'description' => 'Core\System is currently overloaded. Please try again later.']);
+                       Module\Special\HTTPException::rawContent(
+                               new HTTPException\ServiceUnavaiableException('The node is currently overloaded. Please try again later.')
+                       );
                }
 
                if (strstr($this->query_string, '.well-known/host-meta') && ($this->query_string != '.well-known/host-meta')) {
-                       Core\System::httpExit(404);
+                       Module\Special\HTTPException::rawContent(
+                               new HTTPException\NotFoundException()
+                       );
                }
 
                if (!$this->getMode()->isInstall()) {
@@ -1074,7 +1046,9 @@ class App
                                        // Someone came with an invalid parameter, maybe as a DDoS attempt
                                        // We simply stop processing here
                                        Core\Logger::log("Invalid ZRL parameter " . $_GET['zrl'], Core\Logger::DEBUG);
-                                       Core\System::httpExit(403, ['title' => '403 Forbidden']);
+                                       Module\Special\HTTPException::rawContent(
+                                               new HTTPException\ForbiddenException()
+                                       );
                                }
                        }
                }
@@ -1127,123 +1101,110 @@ class App
                        'title' => ''
                ];
 
-               if (strlen($this->module)) {
-                       // Compatibility with the Android Diaspora client
-                       if ($this->module == 'stream') {
-                               $this->internalRedirect('network?f=&order=post');
-                       }
+               // Compatibility with the Android Diaspora client
+               if ($this->module == 'stream') {
+                       $this->internalRedirect('network?f=&order=post');
+               }
 
-                       if ($this->module == 'conversations') {
-                               $this->internalRedirect('message');
-                       }
+               if ($this->module == 'conversations') {
+                       $this->internalRedirect('message');
+               }
 
-                       if ($this->module == 'commented') {
-                               $this->internalRedirect('network?f=&order=comment');
-                       }
+               if ($this->module == 'commented') {
+                       $this->internalRedirect('network?f=&order=comment');
+               }
 
-                       if ($this->module == 'liked') {
-                               $this->internalRedirect('network?f=&order=comment');
-                       }
+               if ($this->module == 'liked') {
+                       $this->internalRedirect('network?f=&order=comment');
+               }
 
-                       if ($this->module == 'activity') {
-                               $this->internalRedirect('network/?f=&conv=1');
-                       }
+               if ($this->module == 'activity') {
+                       $this->internalRedirect('network/?f=&conv=1');
+               }
 
-                       if (($this->module == 'status_messages') && ($this->cmd == 'status_messages/new')) {
-                               $this->internalRedirect('bookmarklet');
-                       }
+               if (($this->module == 'status_messages') && ($this->cmd == 'status_messages/new')) {
+                       $this->internalRedirect('bookmarklet');
+               }
 
-                       if (($this->module == 'user') && ($this->cmd == 'user/edit')) {
-                               $this->internalRedirect('settings');
-                       }
+               if (($this->module == 'user') && ($this->cmd == 'user/edit')) {
+                       $this->internalRedirect('settings');
+               }
 
-                       if (($this->module == 'tag_followings') && ($this->cmd == 'tag_followings/manage')) {
-                               $this->internalRedirect('search');
-                       }
+               if (($this->module == 'tag_followings') && ($this->cmd == 'tag_followings/manage')) {
+                       $this->internalRedirect('search');
+               }
 
-                       // Compatibility with the Firefox App
-                       if (($this->module == "users") && ($this->cmd == "users/sign_in")) {
-                               $this->module = "login";
-                       }
+               // Compatibility with the Firefox App
+               if (($this->module == "users") && ($this->cmd == "users/sign_in")) {
+                       $this->module = "login";
+               }
 
-                       /*
-                        * ROUTING
-                        *
-                        * From the request URL, routing consists of obtaining the name of a BaseModule-extending class of which the
-                        * post() and/or content() static methods can be respectively called to produce a data change or an output.
-                        */
+               /*
+                * ROUTING
+                *
+                * From the request URL, routing consists of obtaining the name of a BaseModule-extending class of which the
+                * post() and/or content() static methods can be respectively called to produce a data change or an output.
+                */
 
-                       // First we try explicit routes defined in App\Router
-                       $this->router->collectRoutes();
+               // First we try explicit routes defined in App\Router
+               $this->router->collectRoutes();
 
-                       $data = $this->router->getRouteCollector();
-                       Hook::callAll('route_collection', $data);
+               $data = $this->router->getRouteCollector();
+               Hook::callAll('route_collection', $data);
 
-                       $this->module_class = $this->router->getModuleClass($this->cmd);
+               $this->module_class = $this->router->getModuleClass($this->cmd);
 
-                       // Then we try addon-provided modules that we wrap in the LegacyModule class
-                       if (!$this->module_class && Core\Addon::isEnabled($this->module) && file_exists("addon/{$this->module}/{$this->module}.php")) {
-                               //Check if module is an app and if public access to apps is allowed or not
-                               $privateapps = $this->config->get('config', 'private_addons', false);
-                               if ((!local_user()) && Core\Hook::isAddonApp($this->module) && $privateapps) {
-                                       info(Core\L10n::t("You must be logged in to use addons. "));
-                               } else {
-                                       include_once "addon/{$this->module}/{$this->module}.php";
-                                       if (function_exists($this->module . '_module')) {
-                                               LegacyModule::setModuleFile("addon/{$this->module}/{$this->module}.php");
-                                               $this->module_class = 'Friendica\\LegacyModule';
-                                       }
+               // Then we try addon-provided modules that we wrap in the LegacyModule class
+               if (!$this->module_class && Core\Addon::isEnabled($this->module) && file_exists("addon/{$this->module}/{$this->module}.php")) {
+                       //Check if module is an app and if public access to apps is allowed or not
+                       $privateapps = $this->config->get('config', 'private_addons', false);
+                       if ((!local_user()) && Core\Hook::isAddonApp($this->module) && $privateapps) {
+                               info(Core\L10n::t("You must be logged in to use addons. "));
+                       } else {
+                               include_once "addon/{$this->module}/{$this->module}.php";
+                               if (function_exists($this->module . '_module')) {
+                                       LegacyModule::setModuleFile("addon/{$this->module}/{$this->module}.php");
+                                       $this->module_class = LegacyModule::class;
                                }
                        }
+               }
 
-                       // Then we try name-matching a Friendica\Module class
-                       if (!$this->module_class && class_exists('Friendica\\Module\\' . ucfirst($this->module))) {
-                               $this->module_class = 'Friendica\\Module\\' . ucfirst($this->module);
-                       }
+               /* Finally, we look for a 'standard' program module in the 'mod' directory
+                * We emulate a Module class through the LegacyModule class
+                */
+               if (!$this->module_class && file_exists("mod/{$this->module}.php")) {
+                       LegacyModule::setModuleFile("mod/{$this->module}.php");
+                       $this->module_class = LegacyModule::class;
+               }
 
-                       /* Finally, we look for a 'standard' program module in the 'mod' directory
-                        * We emulate a Module class through the LegacyModule class
-                        */
-                       if (!$this->module_class && file_exists("mod/{$this->module}.php")) {
-                               LegacyModule::setModuleFile("mod/{$this->module}.php");
-                               $this->module_class = 'Friendica\\LegacyModule';
+               /* The URL provided does not resolve to a valid module.
+                *
+                * On Dreamhost sites, quite often things go wrong for no apparent reason and they send us to '/internal_error.html'.
+                * We don't like doing this, but as it occasionally accounts for 10-20% or more of all site traffic -
+                * we are going to trap this and redirect back to the requested page. As long as you don't have a critical error on your page
+                * this will often succeed and eventually do the right thing.
+                *
+                * Otherwise we are going to emit a 404 not found.
+                */
+               if (!$this->module_class) {
+                       // Stupid browser tried to pre-fetch our Javascript img template. Don't log the event or return anything - just quietly exit.
+                       if (!empty($_SERVER['QUERY_STRING']) && preg_match('/{[0-9]}/', $_SERVER['QUERY_STRING']) !== 0) {
+                               exit();
                        }
 
-                       /* The URL provided does not resolve to a valid module.
-                        *
-                        * On Dreamhost sites, quite often things go wrong for no apparent reason and they send us to '/internal_error.html'.
-                        * We don't like doing this, but as it occasionally accounts for 10-20% or more of all site traffic -
-                        * we are going to trap this and redirect back to the requested page. As long as you don't have a critical error on your page
-                        * this will often succeed and eventually do the right thing.
-                        *
-                        * Otherwise we are going to emit a 404 not found.
-                        */
-                       if (!$this->module_class) {
-                               // Stupid browser tried to pre-fetch our Javascript img template. Don't log the event or return anything - just quietly exit.
-                               if (!empty($_SERVER['QUERY_STRING']) && preg_match('/{[0-9]}/', $_SERVER['QUERY_STRING']) !== 0) {
-                                       exit();
-                               }
-
-                               if (!empty($_SERVER['QUERY_STRING']) && ($_SERVER['QUERY_STRING'] === 'q=internal_error.html') && isset($dreamhost_error_hack)) {
-                                       Core\Logger::log('index.php: dreamhost_error_hack invoked. Original URI =' . $_SERVER['REQUEST_URI']);
-                                       $this->internalRedirect($_SERVER['REQUEST_URI']);
-                               }
+                       if (!empty($_SERVER['QUERY_STRING']) && ($_SERVER['QUERY_STRING'] === 'q=internal_error.html') && isset($dreamhost_error_hack)) {
+                               Core\Logger::log('index.php: dreamhost_error_hack invoked. Original URI =' . $_SERVER['REQUEST_URI']);
+                               $this->internalRedirect($_SERVER['REQUEST_URI']);
+                       }
 
-                               Core\Logger::log('index.php: page not found: ' . $_SERVER['REQUEST_URI'] . ' ADDRESS: ' . $_SERVER['REMOTE_ADDR'] . ' QUERY: ' . $_SERVER['QUERY_STRING'], Core\Logger::DEBUG);
+                       Core\Logger::log('index.php: page not found: ' . $_SERVER['REQUEST_URI'] . ' ADDRESS: ' . $_SERVER['REMOTE_ADDR'] . ' QUERY: ' . $_SERVER['QUERY_STRING'], Core\Logger::DEBUG);
 
-                               header($_SERVER["SERVER_PROTOCOL"] . ' 404 ' . Core\L10n::t('Not Found'));
-                               $tpl = Core\Renderer::getMarkupTemplate("404.tpl");
-                               $this->page['content'] = Core\Renderer::replaceMacros($tpl, [
-                                       '$message' =>  Core\L10n::t('Page not found.')
-                               ]);
-                       }
+                       $this->module_class = Module\PageNotFound::class;
                }
 
-               $content = '';
-
                // Initialize module that can set the current theme in the init() method, either directly or via App->profile_uid
-               if ($this->module_class) {
-                       $this->page['page_title'] = $this->module;
+               $this->page['page_title'] = $this->module;
+               try {
                        $placeholder = '';
 
                        Core\Hook::callAll($this->module . '_mod_init', $placeholder);
@@ -1252,41 +1213,41 @@ class App
 
                        // "rawContent" is especially meant for technical endpoints.
                        // This endpoint doesn't need any theme initialization or other comparable stuff.
-                       if (!$this->error) {
-                               call_user_func([$this->module_class, 'rawContent']);
-                       }
-               }
+                       call_user_func([$this->module_class, 'rawContent']);
 
-               // Load current theme info after module has been initialized as theme could have been set in module
-               $theme_info_file = 'view/theme/' . $this->getCurrentTheme() . '/theme.php';
-               if (file_exists($theme_info_file)) {
-                       require_once $theme_info_file;
-               }
+                       // Load current theme info after module has been initialized as theme could have been set in module
+                       $theme_info_file = 'view/theme/' . $this->getCurrentTheme() . '/theme.php';
+                       if (file_exists($theme_info_file)) {
+                               require_once $theme_info_file;
+                       }
 
-               if (function_exists(str_replace('-', '_', $this->getCurrentTheme()) . '_init')) {
-                       $func = str_replace('-', '_', $this->getCurrentTheme()) . '_init';
-                       $func($this);
-               }
+                       if (function_exists(str_replace('-', '_', $this->getCurrentTheme()) . '_init')) {
+                               $func = str_replace('-', '_', $this->getCurrentTheme()) . '_init';
+                               $func($this);
+                       }
 
-               if ($this->module_class) {
-                       if (! $this->error && $_SERVER['REQUEST_METHOD'] === 'POST') {
+                       if ($_SERVER['REQUEST_METHOD'] === 'POST') {
                                Core\Hook::callAll($this->module . '_mod_post', $_POST);
                                call_user_func([$this->module_class, 'post']);
                        }
 
-                       if (! $this->error) {
-                               Core\Hook::callAll($this->module . '_mod_afterpost', $placeholder);
-                               call_user_func([$this->module_class, 'afterpost']);
-                       }
+                       Core\Hook::callAll($this->module . '_mod_afterpost', $placeholder);
+                       call_user_func([$this->module_class, 'afterpost']);
+               } catch(HTTPException $e) {
+                       Module\Special\HTTPException::rawContent($e);
+               }
 
-                       if (! $this->error) {
-                               $arr = ['content' => $content];
-                               Core\Hook::callAll($this->module . '_mod_content', $arr);
-                               $content = $arr['content'];
-                               $arr = ['content' => call_user_func([$this->module_class, 'content'])];
-                               Core\Hook::callAll($this->module . '_mod_aftercontent', $arr);
-                               $content .= $arr['content'];
-                       }
+               $content = '';
+
+               try {
+                       $arr = ['content' => $content];
+                       Core\Hook::callAll($this->module . '_mod_content', $arr);
+                       $content = $arr['content'];
+                       $arr = ['content' => call_user_func([$this->module_class, 'content'])];
+                       Core\Hook::callAll($this->module . '_mod_aftercontent', $arr);
+                       $content .= $arr['content'];
+               } catch(HTTPException $e) {
+                       $content = Module\Special\HTTPException::content($e);
                }
 
                // initialise content region
@@ -1310,13 +1271,6 @@ class App
                 */
                $this->initFooter();
 
-               /* now that we've been through the module content, see if the page reported
-                * a permission problem and if so, a 403 response would seem to be in order.
-                */
-               if (stristr(implode("", $_SESSION['sysmsg']), Core\L10n::t('Permission denied'))) {
-                       header($_SERVER["SERVER_PROTOCOL"] . ' 403 ' . Core\L10n::t('Permission denied.'));
-               }
-
                if (!$this->isAjax()) {
                        Core\Hook::callAll('page_end', $this->page['content']);
                }
@@ -1408,12 +1362,12 @@ class App
         * @param string $toUrl The destination URL (Default is empty, which is the default page of the Friendica node)
         * @param bool $ssl if true, base URL will try to get called with https:// (works just for relative paths)
         *
-        * @throws InternalServerErrorException In Case the given URL is not relative to the Friendica node
+        * @throws HTTPException\InternalServerErrorException In Case the given URL is not relative to the Friendica node
         */
        public function internalRedirect($toUrl = '', $ssl = false)
        {
                if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
-                       throw new InternalServerErrorException("'$toUrl is not a relative path, please use System::externalRedirectTo");
+                       throw new HTTPException\InternalServerErrorException("'$toUrl is not a relative path, please use System::externalRedirectTo");
                }
 
                $redirectTo = $this->getBaseURL($ssl) . '/' . ltrim($toUrl, '/');
@@ -1425,7 +1379,7 @@ class App
         * Should only be used if it isn't clear if the URL is either internal or external
         *
         * @param string $toUrl The target URL
-        * @throws InternalServerErrorException
+        * @throws HTTPException\InternalServerErrorException
         */
        public function redirect($toUrl)
        {
index be85fcd9dc33cf49a4c3c9bc1237ca44f3a6e3f1..1dffb6b406f0d3b22bd75880710bd56a5eee8437 100644 (file)
-<?php\r
-\r
-namespace Friendica\App;\r
-\r
-\r
-use FastRoute\DataGenerator\GroupCountBased;\r
-use FastRoute\Dispatcher;\r
-use FastRoute\RouteCollector;\r
-use FastRoute\RouteParser\Std;\r
-use Friendica\Module;\r
-\r
-/**\r
- * Wrapper for FastRoute\Router\r
- *\r
- * This wrapper only makes use of a subset of the router features, mainly parses a route rule to return the relevant\r
- * module class.\r
- *\r
- * Actual routes are defined in App->collectRoutes.\r
- *\r
- * @package Friendica\App\r
- */\r
-class Router\r
-{\r
-       /** @var RouteCollector */\r
-       protected $routeCollector;\r
-\r
-       /**\r
-        * Static declaration of Friendica routes.\r
-        *\r
-        * Supports:\r
-        * - Route groups\r
-        * - Variable parts\r
-        * Disregards:\r
-        * - HTTP method other than GET\r
-        * - Named parameters\r
-        *\r
-        * Handler must be the name of a class extending Friendica\BaseModule.\r
-        *\r
-        * @brief Static declaration of Friendica routes.\r
-        */\r
-       public function collectRoutes()\r
-       {\r
-               $this->routeCollector->addRoute(['GET', 'POST'], '/itemsource[/{guid}]', Module\Itemsource::class);\r
-       }\r
-\r
-       public function __construct(RouteCollector $routeCollector = null)\r
-       {\r
-               if (!$routeCollector) {\r
-                       $routeCollector = new RouteCollector(new Std(), new GroupCountBased());\r
-               }\r
-\r
-               $this->routeCollector = $routeCollector;\r
-       }\r
-\r
-       public function getRouteCollector()\r
-       {\r
-               return $this->routeCollector;\r
-       }\r
-\r
-       /**\r
-        * Returns the relevant module class name for the given page URI or NULL if no route rule matched.\r
-        *\r
-        * @param string $cmd The path component of the request URL without the query string\r
-        * @return string|null A Friendica\BaseModule-extending class name if a route rule matched\r
-        */\r
-       public function getModuleClass($cmd)\r
-       {\r
-               $cmd = '/' . ltrim($cmd, '/');\r
-\r
-               $dispatcher = new \FastRoute\Dispatcher\GroupCountBased($this->routeCollector->getData());\r
-\r
-               $moduleClass = null;\r
-\r
-               // @TODO: Enable method-specific modules\r
-               $httpMethod = 'GET';\r
-               $routeInfo = $dispatcher->dispatch($httpMethod, $cmd);\r
-               if ($routeInfo[0] === Dispatcher::FOUND) {\r
-                       $moduleClass = $routeInfo[1];\r
-               }\r
-\r
-               return $moduleClass;\r
-       }\r
-}\r
+<?php
+
+namespace Friendica\App;
+
+
+use FastRoute\DataGenerator\GroupCountBased;
+use FastRoute\Dispatcher;
+use FastRoute\RouteCollector;
+use FastRoute\RouteParser\Std;
+use Friendica\Module;
+
+/**
+ * Wrapper for FastRoute\Router
+ *
+ * This wrapper only makes use of a subset of the router features, mainly parses a route rule to return the relevant
+ * module class.
+ *
+ * Actual routes are defined in App->collectRoutes.
+ *
+ * @package Friendica\App
+ */
+class Router
+{
+       /** @var RouteCollector */
+       protected $routeCollector;
+
+       /**
+        * Static declaration of Friendica routes.
+        *
+        * Supports:
+        * - Route groups
+        * - Variable parts
+        * Disregards:
+        * - HTTP method other than GET
+        * - Named parameters
+        *
+        * Handler must be the name of a class extending Friendica\BaseModule.
+        *
+        * @brief Static declaration of Friendica routes.
+        */
+       public function collectRoutes()
+       {
+               $this->routeCollector->addRoute(['GET'],         '[/]',               Module\Home::class);
+               $this->routeCollector->addGroup('/.well-known', function (RouteCollector $collector) {
+                       $collector->addRoute(['GET'], '/host-meta'       , Module\WellKnown\HostMeta::class);
+                       $collector->addRoute(['GET'], '/nodeinfo[/1.0]'  , Module\NodeInfo::class);
+                       $collector->addRoute(['GET'], '/webfinger'       , Module\Xrd::class);
+                       $collector->addRoute(['GET'], '/x-social-relay'  , Module\WellKnown\XSocialRelay::class);
+               });
+               $this->routeCollector->addGroup('/admin', function (RouteCollector $collector) {
+                       $collector->addRoute(['GET']        , '[/]'                     , Module\Admin\Summary::class);
+
+                       $collector->addRoute(['GET', 'POST'], '/addons'                 , Module\Admin\Addons\Index::class);
+                       $collector->addRoute(['GET', 'POST'], '/addons/{addon}'         , Module\Admin\Addons\Details::class);
+
+                       $collector->addRoute(['GET', 'POST'], '/blocklist/contact'      , Module\Admin\Blocklist\Contact::class);
+                       $collector->addRoute(['GET', 'POST'], '/blocklist/server'       , Module\Admin\Blocklist\Server::class);
+
+                       $collector->addRoute(['GET']        , '/dbsync[/check]'         , Module\Admin\DBSync::class);
+                       $collector->addRoute(['GET']        , '/dbsync/{update:\d+}'    , Module\Admin\DBSync::class);
+                       $collector->addRoute(['GET']        , '/dbsync/mark/{update:\d+}', Module\Admin\DBSync::class);
+
+                       $collector->addRoute(['GET', 'POST'], '/features'               , Module\Admin\Features::class);
+                       $collector->addRoute(['GET']        , '/federation'             , Module\Admin\Federation::class);
+
+                       $collector->addRoute(['GET', 'POST'], '/item/delete'            , Module\Admin\Item\Delete::class);
+                       $collector->addRoute(['GET', 'POST'], '/item/source[/{guid}]'   , Module\Admin\Item\Source::class);
+
+                       $collector->addRoute(['GET']        , '/logs/view'              , Module\Admin\Logs\View::class);
+                       $collector->addRoute(['GET', 'POST'], '/logs'                   , Module\Admin\Logs\Settings::class);
+
+                       $collector->addRoute(['GET']        , '/phpinfo'                , Module\Admin\PhpInfo::class);
+
+                       $collector->addRoute(['GET']        , '/queue[/deferred]'       , Module\Admin\Queue::class);
+
+                       $collector->addRoute(['GET', 'POST'], '/site'                   , Module\Admin\Site::class);
+
+                       $collector->addRoute(['GET', 'POST'], '/themes'                 , Module\Admin\Themes\Index::class);
+                       $collector->addRoute(['GET', 'POST'], '/themes/{theme}'         , Module\Admin\Themes\Details::class);
+                       $collector->addRoute(['GET', 'POST'], '/themes/{theme}/embed'   , Module\Admin\Themes\Embed::class);
+
+                       $collector->addRoute(['GET', 'POST'], '/tos'                    , Module\Admin\Tos::class);
+
+                       $collector->addRoute(['GET', 'POST'], '/users[/{action}/{uid}]' , Module\Admin\Users::class);
+               });
+               $this->routeCollector->addRoute(['GET'],         '/amcd',                Module\AccountManagementControlDocument::class);
+               $this->routeCollector->addRoute(['GET'],         '/acctlink',            Module\Acctlink::class);
+               $this->routeCollector->addRoute(['GET'],         '/allfriends/{id:\d+}', Module\AllFriends::class);
+               $this->routeCollector->addRoute(['GET'],         '/apps',                Module\Apps::class);
+               $this->routeCollector->addRoute(['GET'],         '/attach/{item:\d+}',   Module\Attach::class);
+               $this->routeCollector->addRoute(['GET'],         '/babel',               Module\Babel::class);
+               $this->routeCollector->addRoute(['GET'],         '/bookmarklet',         Module\BookMarklet::class);
+               $this->routeCollector->addGroup('/contact', function (RouteCollector $collector) {
+                       $collector->addRoute(['GET'], '[/]',                                 Module\Contact::class);
+                       $collector->addRoute(['GET'], '/{id:\d+}[/posts|conversations]',     Module\Contact::class);
+               });
+               $this->routeCollector->addRoute(['GET'],         '/credits',             Module\Credits::class);
+               $this->routeCollector->addGroup('/feed', function (RouteCollector $collector) {
+                       $collector->addRoute(['GET'], '/{nickname}',                         Module\Feed::class);
+                       $collector->addRoute(['GET'], '/{nickname}/posts',                   Module\Feed::class);
+                       $collector->addRoute(['GET'], '/{nickname}/comments',                Module\Feed::class);
+                       $collector->addRoute(['GET'], '/{nickname}/replies',                 Module\Feed::class);
+                       $collector->addRoute(['GET'], '/{nickname}/activity',                Module\Feed::class);
+               });
+               $this->routeCollector->addRoute(['GET'],         '/directory',           Module\Directory::class);
+               $this->routeCollector->addRoute(['GET'],         '/feedtest',            Module\Feedtest::class);
+               $this->routeCollector->addGroup('/fetch', function (RouteCollector $collector) {
+                       $collector->addRoute(['GET'], '/{guid}/post',                        Module\Diaspora\Fetch::class);
+                       $collector->addRoute(['GET'], '/{guid}/status_message',              Module\Diaspora\Fetch::class);
+                       $collector->addRoute(['GET'], '/{guid}/reshare',                     Module\Diaspora\Fetch::class);
+               });
+               $this->routeCollector->addRoute(['GET'],         '/filer[/{id:\d+}]',    Module\Filer::class);
+               $this->routeCollector->addRoute(['GET'],         '/followers/{owner}',   Module\Followers::class);
+               $this->routeCollector->addRoute(['GET'],         '/following/{owner}',   Module\Following::class);
+               $this->routeCollector->addGroup('/group', function (RouteCollector $collector) {
+                       $collector->addRoute(['GET', 'POST'], '[/]',                         Module\Group::class);
+                       $collector->addRoute(['GET', 'POST'], '/{group:\d+}',                Module\Group::class);
+                       $collector->addRoute(['GET', 'POST'], '/none',                       Module\Group::class);
+                       $collector->addRoute(['GET', 'POST'], '/new',                        Module\Group::class);
+                       $collector->addRoute(['GET', 'POST'], '/drop/{group:\d+}',           Module\Group::class);
+                       $collector->addRoute(['GET', 'POST'], '/{group:\d+}/{contact:\d+}',  Module\Group::class);
+
+                       $collector->addRoute(['POST'], '/{group:\d+}/add/{contact:\d+}',     Module\Group::class);
+                       $collector->addRoute(['POST'], '/{group:\d+}/remove/{contact:\d+}',  Module\Group::class);
+               });
+               $this->routeCollector->addRoute(['GET'],         '/hashtag',             Module\Hashtag::class);
+               $this->routeCollector->addRoute(['GET'],         '/home',                Module\Home::class);
+               $this->routeCollector->addRoute(['GET'],         '/help[/{doc:.+}]',     Module\Help::class);
+               $this->routeCollector->addRoute(['GET'],         '/inbox[/{nickname}]',  Module\Inbox::class);
+               $this->routeCollector->addRoute(['GET', 'POST'], '/invite',              Module\Invite::class);
+               $this->routeCollector->addGroup('/install', function (RouteCollector $collector) {
+                       $collector->addRoute(['GET', 'POST'], '[/]',                         Module\Install::class);
+                       $collector->addRoute(['GET'],         '/testrewrite',                Module\Install::class);
+               });
+               $this->routeCollector->addRoute(['GET', 'POST'], '/itemsource[/{guid}]', Module\Itemsource::class);
+               $this->routeCollector->addRoute(['GET'],         '/like/{item:\d+}',     Module\Like::class);
+               $this->routeCollector->addRoute(['GET', 'POST'], '/localtime',           Module\Localtime::class);
+               $this->routeCollector->addRoute(['GET', 'POST'], '/login',               Module\Login::class);
+               $this->routeCollector->addRoute(['GET', 'POST'], '/logout',              Module\Logout::class);
+               $this->routeCollector->addRoute(['GET'],         '/magic',               Module\Magic::class);
+               $this->routeCollector->addRoute(['GET'],         '/manifest',            Module\Manifest::class);
+               $this->routeCollector->addRoute(['GET'],         '/nodeinfo/1.0',        Module\NodeInfo::class);
+               $this->routeCollector->addRoute(['GET'],         '/nogroup',             Module\Group::class);
+               $this->routeCollector->addRoute(['GET'],         '/objects/{guid}',      Module\Objects::class);
+               $this->routeCollector->addGroup('/oembed', function (RouteCollector $collector) {
+                       $collector->addRoute(['GET'], '/[b2h|h2b]',                          Module\Oembed::class);
+                       $collector->addRoute(['GET'], '/{hash}',                             Module\Oembed::class);
+               });
+               $this->routeCollector->addRoute(['GET'],         '/outbox/{owner}',      Module\Outbox::class);
+               $this->routeCollector->addRoute(['GET'],         '/owa',                 Module\Owa::class);
+               $this->routeCollector->addGroup('/photo', function (RouteCollector $collector) {
+                       $collector->addRoute(['GET'], '/{name}',                             Module\Photo::class);
+                       $collector->addRoute(['GET'], '/{type}/{name}',                      Module\Photo::class);
+                       $collector->addRoute(['GET'], '/{type}/{customize}/{name}',          Module\Photo::class);
+               });
+               $this->routeCollector->addGroup('/profile', function (RouteCollector $collector) {
+                       $collector->addRoute(['GET'], '/{nickname}',                         Module\Profile::class);
+                       $collector->addRoute(['GET'], '/{profile:\d+}/view',                 Module\Profile::class);
+               });
+               $this->routeCollector->addGroup('/proxy', function (RouteCollector $collector) {
+                       $collector->addRoute(['GET'], '[/]'                                , Module\Proxy::class);
+                       $collector->addRoute(['GET'], '/{url}'                             , Module\Proxy::class);
+                       $collector->addRoute(['GET'], '/{sub1}/{url}'                      , Module\Proxy::class);
+                       $collector->addRoute(['GET'], '/{sub1}/{sub2}/{url}'               , Module\Proxy::class);
+               });
+               $this->routeCollector->addRoute(['GET', 'POST'], '/register',            Module\Register::class);
+               $this->routeCollector->addRoute(['GET'],         '/rsd.xml',             Module\ReallySimpleDiscovery::class);
+               $this->routeCollector->addRoute(['GET'],         '/statistics.json',     Module\Statistics::class);
+               $this->routeCollector->addRoute(['GET'],         '/tos',                 Module\Tos::class);
+               $this->routeCollector->addRoute(['GET'],         '/webfinger',           Module\WebFinger::class);
+               $this->routeCollector->addRoute(['GET'],         '/xrd',                 Module\Xrd::class);
+       }
+
+       public function __construct(RouteCollector $routeCollector = null)
+       {
+               if (!$routeCollector) {
+                       $routeCollector = new RouteCollector(new Std(), new GroupCountBased());
+               }
+
+               $this->routeCollector = $routeCollector;
+       }
+
+       public function getRouteCollector()
+       {
+               return $this->routeCollector;
+       }
+
+       /**
+        * Returns the relevant module class name for the given page URI or NULL if no route rule matched.
+        *
+        * @param string $cmd The path component of the request URL without the query string
+        * @return string|null A Friendica\BaseModule-extending class name if a route rule matched
+        */
+       public function getModuleClass($cmd)
+       {
+               $cmd = '/' . ltrim($cmd, '/');
+
+               $dispatcher = new \FastRoute\Dispatcher\GroupCountBased($this->routeCollector->getData());
+
+               $moduleClass = null;
+
+               // @TODO: Enable method-specific modules
+               $httpMethod = 'GET';
+               $routeInfo = $dispatcher->dispatch($httpMethod, $cmd);
+               if ($routeInfo[0] === Dispatcher::FOUND) {
+                       $moduleClass = $routeInfo[1];
+               }
+
+               return $moduleClass;
+       }
+}
index 3878d150734720d8d2b6d42b16245ec04e6088d8..dd9059bfba0db063fa3732b1969eacd42620da73 100644 (file)
@@ -153,7 +153,7 @@ abstract class BaseModule extends BaseObject
                        Logger::log('checkFormSecurityToken failed: user ' . $a->user['guid'] . ' - form element ' . $typename);
                        Logger::log('checkFormSecurityToken failed: _REQUEST data: ' . print_r($_REQUEST, true), Logger::DATA);
 
-                       System::httpExit(403);
+                       throw new \Friendica\Network\HTTPException\ForbiddenException();
                }
        }
 }
diff --git a/src/Console/ArchiveContact.php b/src/Console/ArchiveContact.php
new file mode 100644 (file)
index 0000000..cf177cf
--- /dev/null
@@ -0,0 +1,75 @@
+<?php
+
+namespace Friendica\Console;
+
+use Friendica\Core\L10n;
+use Friendica\Database\DBA;
+use Friendica\Util\Strings;
+use RuntimeException;
+
+/**
+ * @brief tool to archive a contact on the server
+ *
+ * With this tool you can archive a contact when you know that it isn't existing anymore.
+ * Normally this does happen automatically after a few days.
+ *
+ * License: AGPLv3 or later, same as Friendica
+ *
+ */
+class ArchiveContact extends \Asika\SimpleConsole\Console
+{
+       protected $helpOptions = ['h', 'help', '?'];
+
+       protected function getHelp()
+       {
+               $help = <<<HELP
+console archivecontact - archive a contact
+Usage
+       bin/console archivecontact <profile_url> [-h|--help|-?] [-v]
+
+Description
+       Archive a contact when you know that it isn't existing anymore. Normally this does happen automatically after a few days.
+
+Options
+    -h|--help|-? Show help information
+    -v           Show more debug information.
+HELP;
+               return $help;
+       }
+
+       protected function doExecute()
+       {
+               $a = \Friendica\BaseObject::getApp();
+
+               if ($this->getOption('v')) {
+                       $this->out('Class: ' . __CLASS__);
+                       $this->out('Arguments: ' . var_export($this->args, true));
+                       $this->out('Options: ' . var_export($this->options, true));
+               }
+
+               if (count($this->args) == 0) {
+                       $this->out($this->getHelp());
+                       return 0;
+               }
+
+               if (count($this->args) > 1) {
+                       throw new \Asika\SimpleConsole\CommandArgsException('Too many arguments');
+               }
+
+               if ($a->getMode()->isInstall()) {
+                       throw new RuntimeException('Friendica isn\'t properly installed yet.');
+               }
+
+               $nurl = Strings::normaliseLink($this->getArgument(0));
+               if (!DBA::exists('contact', ['nurl' => $nurl, 'archive' => false])) {
+                       throw new RuntimeException(L10n::t('Could not find any unarchived contact entry for this URL (%s)', $nurl));
+               }
+               if (DBA::update('contact', ['archive' => true], ['nurl' => $nurl])) {
+                       $this->out(L10n::t('The contact entries have been archived'));
+               } else {
+                       throw new RuntimeException('The contact archival failed.');
+               }
+
+               return 0;
+       }
+}
diff --git a/src/Console/AutomaticInstallation.php b/src/Console/AutomaticInstallation.php
new file mode 100644 (file)
index 0000000..718573d
--- /dev/null
@@ -0,0 +1,265 @@
+<?php
+
+namespace Friendica\Console;
+
+use Asika\SimpleConsole\Console;
+use Friendica\BaseObject;
+use Friendica\Core\Config;
+use Friendica\Core\Installer;
+use Friendica\Core\Theme;
+use Friendica\Util\BasePath;
+use Friendica\Util\BaseURL;
+use Friendica\Util\Config\ConfigFileLoader;
+use RuntimeException;
+
+class AutomaticInstallation extends Console
+{
+       protected function getHelp()
+       {
+               return <<<HELP
+Installation - Install Friendica automatically
+Synopsis
+       bin/console autoinstall [-h|--help|-?] [-v] [-a] [-f]
+
+Description
+    Installs Friendica with data based on the local.config.php file or environment variables
+
+Notes
+    Not checking .htaccess/URL-Rewrite during CLI installation.
+
+Options
+    -h|--help|-?            Show help information
+    -v                      Show more debug information.
+    -a                      All setup checks are required (except .htaccess)
+    -f|--file <config>      prepared config file (e.g. "config/local.config.php" itself) which will override every other config option - except the environment variables)
+    -s|--savedb               Save the DB credentials to the file (if environment variables is used)
+    -H|--dbhost <host>        The host of the mysql/mariadb database (env MYSQL_HOST)
+    -p|--dbport <port>        The port of the mysql/mariadb database (env MYSQL_PORT)
+    -d|--dbdata <database>    The name of the mysql/mariadb database (env MYSQL_DATABASE)
+    -U|--dbuser <username>    The username of the mysql/mariadb database login (env MYSQL_USER or MYSQL_USERNAME)
+    -P|--dbpass <password>    The password of the mysql/mariadb database login (env MYSQL_PASSWORD)
+    -U|--url <url>            The full base URL of Friendica - f.e. 'https://friendica.local/sub' (env FRIENDICA_URL) 
+    -B|--phppath <php_path>   The path of the PHP binary (env FRIENDICA_PHP_PATH)
+    -b|--basepath <base_path> The basepath of Friendica (env FRIENDICA_BASE_PATH)
+    -t|--tz <timezone>        The timezone of Friendica (env FRIENDICA_TZ)
+    -L|--lang <language>      The language of Friendica (env FRIENDICA_LANG)
+Environment variables
+   MYSQL_HOST                  The host of the mysql/mariadb database (mandatory if mysql and environment is used)
+   MYSQL_PORT                  The port of the mysql/mariadb database
+   MYSQL_USERNAME|MYSQL_USER   The username of the mysql/mariadb database login (MYSQL_USERNAME is for mysql, MYSQL_USER for mariadb)
+   MYSQL_PASSWORD              The password of the mysql/mariadb database login
+   MYSQL_DATABASE              The name of the mysql/mariadb database
+   FRIENDICA_URL               The full base URL of Friendica - f.e. 'https://friendica.local/sub'
+   FRIENDICA_PHP_PATH          The path of the PHP binary - leave empty for auto detection
+   FRIENDICA_BASE_PATH         The basepath of Friendica - leave empty for auto detection
+   FRIENDICA_ADMIN_MAIL        The admin email address of Friendica (this email will be used for admin access)
+   FRIENDICA_TZ                The timezone of Friendica
+   FRIENDICA_LANG              The langauge of Friendica
+   
+Examples
+       bin/console autoinstall -f 'input.config.php
+               Installs Friendica with the prepared 'input.config.php' file
+
+       bin/console autoinstall --savedb
+               Installs Friendica with environment variables and saves them to the 'config/local.config.php' file
+
+       bin/console autoinstall -h localhost -p 3365 -U user -P passwort1234 -d friendica
+               Installs Friendica with a local mysql database with credentials
+HELP;
+       }
+
+       protected function doExecute()
+       {
+               // Initialise the app
+               $this->out("Initializing setup...\n");
+
+               $a = BaseObject::getApp();
+
+               $installer = new Installer();
+
+               $configCache = $a->getConfigCache();
+               $installer->setUpCache($configCache, BasePath::create($a->getBasePath(), $_SERVER));
+
+               $this->out(" Complete!\n\n");
+
+               // Check Environment
+               $this->out("Checking environment...\n");
+
+               $installer->resetChecks();
+
+               if (!$this->runBasicChecks($installer, $configCache)) {
+                       $errorMessage = $this->extractErrors($installer->getChecks());
+                       throw new RuntimeException($errorMessage);
+               }
+
+               $this->out(" Complete!\n\n");
+
+               // if a config file is set,
+               $config_file = $this->getOption(['f', 'file']);
+
+               if (!empty($config_file)) {
+                       if ($config_file != 'config' . DIRECTORY_SEPARATOR . 'local.config.php') {
+                               // Copy config file
+                               $this->out("Copying config file...\n");
+                               if (!copy($a->getBasePath() . DIRECTORY_SEPARATOR . $config_file, $a->getBasePath() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.config.php')) {
+                                       throw new RuntimeException("ERROR: Saving config file failed. Please copy '$config_file' to '" . $a->getBasePath() . "'" . DIRECTORY_SEPARATOR . "config" . DIRECTORY_SEPARATOR . "local.config.php' manually.\n");
+                               }
+                       }
+
+                       //reload the config cache
+                       $loader = new ConfigFileLoader($a->getBasePath(), $a->getMode());
+                       $loader->setupCache($configCache);
+
+               } else {
+                       // Creating config file
+                       $this->out("Creating config file...\n");
+
+                       $save_db = $this->getOption(['s', 'savedb'], false);
+
+                       $db_host = $this->getOption(['H', 'dbhost'], ($save_db) ? (getenv('MYSQL_HOST')) : Installer::DEFAULT_HOST);
+                       $db_port = $this->getOption(['p', 'dbport'], ($save_db) ? getenv('MYSQL_PORT') : null);
+                       $configCache->set('database', 'hostname', $db_host . (!empty($db_port) ? ':' . $db_port : ''));
+                       $configCache->set('database', 'database',
+                               $this->getOption(['d', 'dbdata'],
+                                       ($save_db) ? getenv('MYSQL_DATABASE') : ''));
+                       $configCache->set('database', 'username',
+                               $this->getOption(['U', 'dbuser'],
+                                       ($save_db) ? getenv('MYSQL_USER') . getenv('MYSQL_USERNAME') : ''));
+                       $configCache->set('database', 'password',
+                               $this->getOption(['P', 'dbpass'],
+                                       ($save_db) ? getenv('MYSQL_PASSWORD') : ''));
+
+                       $php_path = $this->getOption(['b', 'phppath'], !empty('FRIENDICA_PHP_PATH') ? getenv('FRIENDICA_PHP_PATH') : null);
+                       if (!empty($php_path)) {
+                               $configCache->set('config', 'php_path', $php_path);
+                       } else {
+                               $configCache->set('config', 'php_path', $installer->getPHPPath());
+                       }
+
+                       $configCache->set('config', 'admin_email',
+                               $this->getOption(['A', 'admin'],
+                                       !empty(getenv('FRIENDICA_ADMIN_MAIL')) ? getenv('FRIENDICA_ADMIN_MAIL') : ''));
+                       $configCache->set('system', 'default_timezone',
+                               $this->getOption(['T', 'tz'],
+                                       !empty(getenv('FRIENDICA_TZ')) ? getenv('FRIENDICA_TZ') : Installer::DEFAULT_TZ));
+                       $configCache->set('system', 'language',
+                               $this->getOption(['L', 'lang'],
+                                       !empty(getenv('FRIENDICA_LANG')) ? getenv('FRIENDICA_LANG') : Installer::DEFAULT_LANG));
+
+                       $basepath = $this->getOption(['b', 'basepath'], !empty(getenv('FRIENDICA_BASE_PATH')) ? getenv('FRIENDICA_BASE_PATH') : null);
+                       if (!empty($basepath)) {
+                               $configCache->set('system', 'basepath', $basepath);
+                       }
+
+                       $url = $this->getOption(['U', 'url'], !empty(getenv('FRIENDICA_URL')) ? getenv('FRIENDICA_URL') : null);
+
+                       if (empty($url)) {
+                               $this->out('The Friendica URL has to be set during CLI installation.');
+                               return 1;
+                       } else {
+                               $baseUrl = new BaseURL($a->getConfig(), []);
+                               $baseUrl->saveByURL($url);
+                       }
+
+                       $installer->createConfig($configCache);
+               }
+
+               $this->out(" Complete!\n\n");
+
+               // Check database connection
+               $this->out("Checking database...\n");
+
+               $installer->resetChecks();
+
+               if (!$installer->checkDB($configCache, $a->getProfiler())) {
+                       $errorMessage = $this->extractErrors($installer->getChecks());
+                       throw new RuntimeException($errorMessage);
+               }
+
+               $this->out(" Complete!\n\n");
+
+               // Install database
+               $this->out("Inserting data into database...\n");
+
+               $installer->resetChecks();
+
+               if (!$installer->installDatabase($a->getBasePath())) {
+                       $errorMessage = $this->extractErrors($installer->getChecks());
+                       throw new RuntimeException($errorMessage);
+               }
+
+               $this->out(" Complete!\n\n");
+
+               // Install theme
+               $this->out("Installing theme\n");
+               if (!empty(Config::get('system', 'theme'))) {
+                       Theme::install(Config::get('system', 'theme'));
+                       $this->out(" Complete\n\n");
+               } else {
+                       $this->out(" Theme setting is empty. Please check the file 'config/local.config.php'\n\n");
+               }
+
+               $this->out("\nInstallation is finished\n");
+
+               return 0;
+       }
+
+       /**
+        * @param Installer                 $installer   The Installer instance
+        * @param Config\Cache\IConfigCache $configCache The config cache
+        *
+        * @return bool true if checks were successfully, otherwise false
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        */
+       private function runBasicChecks(Installer $installer, Config\Cache\IConfigCache $configCache)
+       {
+               $checked = true;
+
+               $installer->resetChecks();
+               if (!$installer->checkFunctions())              {
+                       $checked = false;
+               }
+               if (!$installer->checkImagick()) {
+                       $checked = false;
+               }
+               if (!$installer->checkLocalIni()) {
+                       $checked = false;
+               }
+               if (!$installer->checkSmarty3()) {
+                       $checked = false;
+               }
+               if (!$installer->checkKeys()) {
+                       $checked = false;
+               }
+
+               $php_path = $configCache->get('config', 'php_path');
+
+               if (!$installer->checkPHP($php_path, true)) {
+                       $checked = false;
+               }
+
+               $this->out(" NOTICE: Not checking .htaccess/URL-Rewrite during CLI installation.\n");
+
+               return $checked;
+       }
+
+       /**
+        * @param array $results
+        * @return string
+        */
+       private function extractErrors($results)
+       {
+               $errorMessage = '';
+               $allChecksRequired = $this->getOption('a') !== null;
+
+               foreach ($results as $result) {
+                       if (($allChecksRequired || $result['required'] === true) && $result['status'] === false) {
+                               $errorMessage .= "--------\n";
+                               $errorMessage .= $result['title'] . ': ' . $result['help'] . "\n";
+                       }
+               }
+
+               return $errorMessage;
+       }
+}
diff --git a/src/Console/Cache.php b/src/Console/Cache.php
new file mode 100644 (file)
index 0000000..eefb6cc
--- /dev/null
@@ -0,0 +1,178 @@
+<?php
+
+namespace Friendica\Console;
+
+use Asika\SimpleConsole\CommandArgsException;
+use Friendica\App;
+use Friendica\Core;
+use RuntimeException;
+
+/**
+ * @brief tool to access the cache from the CLI
+ *
+ * With this script you can access the cache of your node from the CLI.
+ * You can read current values stored in the cache and set new values
+ * in cache keys.
+ *
+ * @author Hypolite Petovan <hypolite@mrpetovan.com>
+ */
+class Cache extends \Asika\SimpleConsole\Console
+{
+       protected $helpOptions = ['h', 'help', '?'];
+
+       protected function getHelp()
+       {
+               $help = <<<HELP
+console cache - Manage node cache
+Synopsis
+       bin/console cache list [-h|--help|-?] [-v]
+       bin/console cache get <key> [-h|--help|-?] [-v]
+       bin/console cache set <key> <value> [-h|--help|-?] [-v]
+       bin/console cache flush [-h|--help|-?] [-v]
+       bin/console cache clear [-h|--help|-?] [-v]
+
+Description
+       bin/console cache list [<prefix>]
+               List all cache keys, optionally filtered by a prefix
+
+       bin/console cache get <key>
+               Shows the value of the provided cache key
+
+       bin/console cache set <key> <value> [<ttl>]
+               Sets the value of the provided cache key, optionally with the provided TTL (time to live) with a default of five minutes.
+
+       bin/console cache flush
+               Clears expired cache keys
+
+       bin/console cache clear
+               Clears all cache keys
+
+Options
+    -h|--help|-? Show help information
+    -v           Show more debug information.
+HELP;
+               return $help;
+       }
+
+       protected function doExecute()
+       {
+               $a = \Friendica\BaseObject::getApp();
+
+               if ($this->getOption('v')) {
+                       $this->out('Executable: ' . $this->executable);
+                       $this->out('Class: ' . __CLASS__);
+                       $this->out('Arguments: ' . var_export($this->args, true));
+                       $this->out('Options: ' . var_export($this->options, true));
+               }
+
+               if ($a->getMode()->has(App\Mode::DBCONFIGAVAILABLE)) {
+                       $this->out('Database isn\'t ready or populated yet, database cache won\'t be available');
+               }
+
+               Core\Cache::init();
+
+               if ($this->getOption('v')) {
+                       $this->out('Cache Driver Name: ' . Core\Cache::$driver_name);
+                       $this->out('Cache Driver Class: ' . Core\Cache::$driver_class);
+               }
+
+               switch ($this->getArgument(0)) {
+                       case 'list':
+                               $this->executeList();
+                               break;
+                       case 'get':
+                               $this->executeGet();
+                               break;
+                       case 'set':
+                               $this->executeSet();
+                               break;
+                       case 'flush':
+                               $this->executeFlush();
+                               break;
+                       case 'clear':
+                               $this->executeClear();
+                               break;
+               }
+
+               if (count($this->args) == 0) {
+                       $this->out($this->getHelp());
+                       return 0;
+               }
+
+               return 0;
+       }
+
+       private function executeList()
+       {
+               $prefix = $this->getArgument(1);
+               $keys = Core\Cache::getAllKeys($prefix);
+
+               if (empty($prefix)) {
+                       $this->out('Listing all cache keys:');
+               } else {
+                       $this->out('Listing all cache keys starting with "' . $prefix . '":');
+               }
+
+               $count = 0;
+               foreach ($keys as $key) {
+                       $this->out($key);
+                       $count++;
+               }
+
+               $this->out($count . ' keys found');
+       }
+
+       private function executeGet()
+       {
+               if (count($this->args) >= 2) {
+                       $key = $this->getArgument(1);
+                       $value = Core\Cache::get($key);
+
+                       $this->out("{$key} => " . var_export($value, true));
+               } else {
+                       throw new CommandArgsException('Too few arguments for get');
+               }
+       }
+
+       private function executeSet()
+       {
+               if (count($this->args) >= 3) {
+                       $key = $this->getArgument(1);
+                       $value = $this->getArgument(2);
+                       $duration = intval($this->getArgument(3, Core\Cache::FIVE_MINUTES));
+
+                       if (is_array(Core\Cache::get($key))) {
+                               throw new RuntimeException("$key is an array and can't be set using this command.");
+                       }
+
+                       $result = Core\Cache::set($key, $value, $duration);
+                       if ($result) {
+                               $this->out("{$key} <= " . Core\Cache::get($key));
+                       } else {
+                               $this->out("Unable to set {$key}");
+                       }
+               } else {
+                       throw new CommandArgsException('Too few arguments for set');
+               }
+       }
+
+       private function executeFlush()
+       {
+               $result = Core\Cache::clear();
+               if ($result) {
+                       $this->out('Cache successfully flushed');
+               } else {
+                       $this->out('Unable to flush the cache');
+               }
+       }
+
+       private function executeClear()
+       {
+               $result = Core\Cache::clear(false);
+               if ($result) {
+                       $this->out('Cache successfully cleared');
+               } else {
+                       $this->out('Unable to flush the cache');
+               }
+       }
+}
diff --git a/src/Console/Config.php b/src/Console/Config.php
new file mode 100644 (file)
index 0000000..a27ca13
--- /dev/null
@@ -0,0 +1,171 @@
+<?php
+
+namespace Friendica\Console;
+
+use Asika\SimpleConsole\CommandArgsException;
+use Friendica\App;
+use Friendica\Core;
+use RuntimeException;
+
+/**
+ * @brief tool to access the system config from the CLI
+ *
+ * With this script you can access the system configuration of your node from
+ * the CLI. You can do both, reading current values stored in the database and
+ * set new values to config variables.
+ *
+ * Usage:
+ *   If you specify no parameters at the CLI, the script will list all config
+ *   variables defined.
+ *
+ *   If you specify one parameter, the script will list all config variables
+ *   defined in this section of the configuration (e.g. "system").
+ *
+ *   If you specify two parameters, the script will show you the current value
+ *   of the named configuration setting. (e.g. "system loglevel")
+ *
+ *   If you specify three parameters, the named configuration setting will be
+ *   set to the value of the last parameter. (e.g. "system loglevel 0" will
+ *   disable logging)
+ *
+ * @author Tobias Diekershoff <tobias.diekershoff@gmx.net>
+ * @author Hypolite Petovan <hypolite@mrpetovan.com>
+ */
+class Config extends \Asika\SimpleConsole\Console
+{
+       protected $helpOptions = ['h', 'help', '?'];
+
+       protected function getHelp()
+       {
+               $help = <<<HELP
+console config - Manage site configuration
+Synopsis
+       bin/console config [-h|--help|-?] [-v]
+       bin/console config <category> [-h|--help|-?] [-v]
+       bin/console config <category> <key> [-h|--help|-?] [-v]
+       bin/console config <category> <key> <value> [-h|--help|-?] [-v]
+
+Description
+       bin/console config
+               Lists all config values
+
+       bin/console config <category>
+               Lists all config values in the provided category
+
+       bin/console config <category> <key>
+               Shows the value of the provided key in the category
+
+       bin/console config <category> <key> <value>
+               Sets the value of the provided key in the category
+
+Notes:
+       Setting config entries which are manually set in config/local.config.php may result in
+       conflict between database settings and the manual startup settings.
+
+Options
+    -h|--help|-? Show help information
+    -v           Show more debug information.
+HELP;
+               return $help;
+       }
+
+       protected function doExecute()
+       {
+               $a = \Friendica\BaseObject::getApp();
+
+               if ($this->getOption('v')) {
+                       $this->out('Executable: ' . $this->executable);
+                       $this->out('Class: ' . __CLASS__);
+                       $this->out('Arguments: ' . var_export($this->args, true));
+                       $this->out('Options: ' . var_export($this->options, true));
+               }
+
+               if (count($this->args) > 3) {
+                       throw new CommandArgsException('Too many arguments');
+               }
+
+               if (!$a->getMode()->has(App\Mode::DBCONFIGAVAILABLE)) {
+                       $this->out('Database isn\'t ready or populated yet, showing file config only');
+               }
+
+               if (count($this->args) == 3) {
+                       $cat = $this->getArgument(0);
+                       $key = $this->getArgument(1);
+                       $value = $this->getArgument(2);
+
+                       if (is_array(Core\Config::get($cat, $key))) {
+                               throw new RuntimeException("$cat.$key is an array and can't be set using this command.");
+                       }
+
+                       $result = Core\Config::set($cat, $key, $value);
+                       if ($result) {
+                               $this->out("{$cat}.{$key} <= " .
+                                       Core\Config::get($cat, $key));
+                       } else {
+                               $this->out("Unable to set {$cat}.{$key}");
+                       }
+               }
+
+               if (count($this->args) == 2) {
+                       $cat = $this->getArgument(0);
+                       $key = $this->getArgument(1);
+                       $value = Core\Config::get($this->getArgument(0), $this->getArgument(1));
+
+                       if (is_array($value)) {
+                               foreach ($value as $k => $v) {
+                                       $this->out("{$cat}.{$key}[{$k}] => " . (is_array($v) ? implode(', ', $v) : $v));
+                               }
+                       } else {
+                               $this->out("{$cat}.{$key} => " . $value);
+                       }
+               }
+
+               if (count($this->args) == 1) {
+                       $cat = $this->getArgument(0);
+                       Core\Config::load($cat);
+
+                       if ($a->getConfigCache()->get($cat) !== null) {
+                               $this->out("[{$cat}]");
+                               $catVal = $a->getConfigCache()->get($cat);
+                               foreach ($catVal as $key => $value) {
+                                       if (is_array($value)) {
+                                               foreach ($value as $k => $v) {
+                                                       $this->out("{$key}[{$k}] => " . (is_array($v) ? implode(', ', $v) : $v));
+                                               }
+                                       } else {
+                                               $this->out("{$key} => " . $value);
+                                       }
+                               }
+                       } else {
+                               $this->out('Config section ' . $this->getArgument(0) . ' returned nothing');
+                       }
+               }
+
+               if (count($this->args) == 0) {
+                       Core\Config::load();
+
+                       if (Core\Config::get('system', 'config_adapter') == 'jit' && $a->getMode()->has(App\Mode::DBCONFIGAVAILABLE)) {
+                               $this->out('Warning: The JIT (Just In Time) Config adapter doesn\'t support loading the entire configuration, showing file config only');
+                       }
+
+                       $config = $a->getConfigCache()->getAll();
+                       foreach ($config as $cat => $section) {
+                               if (is_array($section)) {
+                                       foreach ($section as $key => $value) {
+                                               if (is_array($value)) {
+                                                       foreach ($value as $k => $v) {
+                                                               $this->out("{$cat}.{$key}[{$k}] => " . (is_array($v) ? implode(', ', $v) : $v));
+                                                       }
+                                               } else {
+                                                       $this->out("{$cat}.{$key} => " . $value);
+                                               }
+                                       }
+                               } else {
+                                       $this->out("config.{$cat} => " . $section);
+                               }
+                       }
+               }
+
+               return 0;
+       }
+}
diff --git a/src/Console/CreateDoxygen.php b/src/Console/CreateDoxygen.php
new file mode 100644 (file)
index 0000000..0196839
--- /dev/null
@@ -0,0 +1,148 @@
+<?php
+
+namespace Friendica\Console;
+
+/**
+ * Description of CreateDoxygen
+ *
+ * @author Hypolite Petovan <hypolite@mrpetovan.com>
+ */
+class CreateDoxygen extends \Asika\SimpleConsole\Console
+{
+       protected $helpOptions = ['h', 'help', '?'];
+
+       protected function getHelp()
+       {
+               $help = <<<HELP
+console createdoxygen - Generate Doxygen headers
+Usage
+       bin/console createdoxygen <file> [-h|--help|-?] [-v]
+
+Description
+       Outputs the provided file with added Doxygen headers to functions
+
+Options
+    -h|--help|-? Show help information
+    -v           Show more debug information.
+HELP;
+               return $help;
+       }
+
+       protected function doExecute()
+       {
+               if ($this->getOption('v')) {
+                       $this->out('Class: ' . __CLASS__);
+                       $this->out('Arguments: ' . var_export($this->args, true));
+                       $this->out('Options: ' . var_export($this->options, true));
+               }
+
+               if (count($this->args) == 0) {
+                       $this->out($this->getHelp());
+                       return 0;
+               }
+
+               if (count($this->args) > 1) {
+                       throw new \Asika\SimpleConsole\CommandArgsException('Too many arguments');
+               }
+
+               $file = $this->getArgument(0);
+               if (!file_exists($file)) {
+                       throw new \RuntimeException('Unable to find specified file.');
+               }
+
+               $data = file_get_contents($file);
+
+               $lines = explode("\n", $data);
+
+               $previous = "";
+
+               foreach ($lines AS $line) {
+                       $line = rtrim(trim($line, "\r"));
+
+                       if (strstr(strtolower($line), "function")) {
+                               $detect = strtolower(trim($line));
+                               $detect = implode(" ", explode(" ", $detect));
+
+                               $found = false;
+
+                               if (substr($detect, 0, 9) == "function ") {
+                                       $found = true;
+                               }
+
+                               if (substr($detect, 0, 19) == "protected function ") {
+                                       $found = true;
+                               }
+
+                               if (substr($detect, 0, 17) == "private function ") {
+                                       $found = true;
+                               }
+
+                               if (substr($detect, 0, 23) == "public static function ") {
+                                       $found = true;
+                               }
+
+                               if (substr($detect, 0, 24) == "private static function ") {
+                                       $found = true;
+                               }
+
+                               if (substr($detect, 0, 10) == "function (") {
+                                       $found = false;
+                               }
+
+                               if ($found && ( trim($previous) == "*/")) {
+                                       $found = false;
+                               }
+
+                               if ($found) {
+                                       $this->out($this->addDocumentation($line));
+                               }
+                       }
+                       $this->out($line);
+                       $previous = $line;
+               }
+
+               return 0;
+       }
+
+       /**
+        * @brief Adds a doxygen header
+        *
+        * @param string $line The current line of the document
+        *
+        * @return string added doxygen header
+        */
+       private function addDocumentation($line)
+       {
+               $trimmed = ltrim($line);
+               $length = strlen($line) - strlen($trimmed);
+               $space = substr($line, 0, $length);
+
+               $block = $space . "/**\n" .
+                       $space . " * @brief \n" .
+                       $space . " *\n"; /**/
+
+
+               $left = strpos($line, "(");
+               $line = substr($line, $left + 1);
+
+               $right = strpos($line, ")");
+               $line = trim(substr($line, 0, $right));
+
+               if ($line != "") {
+                       $parameters = explode(",", $line);
+                       foreach ($parameters AS $parameter) {
+                               $parameter = trim($parameter);
+                               $splitted = explode("=", $parameter);
+
+                               $block .= $space . " * @param " . trim($splitted[0], "& ") . "\n";
+                       }
+                       if (count($parameters) > 0) $block .= $space . " *\n";
+               }
+
+               $block .= $space . " * @return \n" .
+                       $space . " */\n";
+
+               return $block;
+       }
+
+}
diff --git a/src/Console/DatabaseStructure.php b/src/Console/DatabaseStructure.php
new file mode 100644 (file)
index 0000000..3feaa64
--- /dev/null
@@ -0,0 +1,94 @@
+<?php
+
+namespace Friendica\Console;
+
+use Friendica\Core;
+use Friendica\Core\Update;
+use Friendica\Database\DBA;
+use Friendica\Database\DBStructure;
+use RuntimeException;
+
+/**
+ * @brief Performs database updates from the command line
+ *
+ * @author Hypolite Petovan <hypolite@mrpetovan.com>
+ */
+class DatabaseStructure extends \Asika\SimpleConsole\Console
+{
+       protected $helpOptions = ['h', 'help', '?'];
+
+       protected function getHelp()
+       {
+               $help = <<<HELP
+console dbstructure - Performs database updates
+Usage
+       bin/console dbstructure <command> [-h|--help|-?] |-f|--force] [-v]
+
+Commands
+       dryrun   Show database update schema queries without running them
+       update   Update database schema
+       dumpsql  Dump database schema
+       toinnodb Convert all tables from MyISAM to InnoDB
+
+Options
+    -h|--help|-?       Show help information
+    -v                 Show more debug information.
+    -f|--force         Force the update command (Even if the database structure matches)
+    -o|--override      Override running or stalling updates
+HELP;
+               return $help;
+       }
+
+       protected function doExecute()
+       {
+               if ($this->getOption('v')) {
+                       $this->out('Class: ' . __CLASS__);
+                       $this->out('Arguments: ' . var_export($this->args, true));
+                       $this->out('Options: ' . var_export($this->options, true));
+               }
+
+               if (count($this->args) == 0) {
+                       $this->out($this->getHelp());
+                       return 0;
+               }
+
+               if (count($this->args) > 1) {
+                       throw new \Asika\SimpleConsole\CommandArgsException('Too many arguments');
+               }
+
+               if (!DBA::connected()) {
+                       throw new RuntimeException('Unable to connect to database');
+               }
+
+               Core\Config::load();
+
+               $a = get_app();
+
+               switch ($this->getArgument(0)) {
+                       case "dryrun":
+                               $output = DBStructure::update($a->getBasePath(), true, false);
+                               break;
+                       case "update":
+                               $force    = $this->getOption(['f', 'force'], false);
+                               $override = $this->getOption(['o', 'override'], false);
+                               $output = Update::run($a->getBasePath(), $force, $override,true, false);
+                               break;
+                       case "dumpsql":
+                               ob_start();
+                               DBStructure::printStructure($a->getBasePath());
+                               $output = ob_get_clean();
+                               break;
+                       case "toinnodb":
+                               ob_start();
+                               DBStructure::convertToInnoDB();
+                               $output = ob_get_clean();
+                               break;
+                       default:
+                               $output = 'Unknown command: ' . $this->getArgument(0);
+               }
+
+               $this->out($output);
+
+               return 0;
+       }
+}
diff --git a/src/Console/DocBloxErrorChecker.php b/src/Console/DocBloxErrorChecker.php
new file mode 100644 (file)
index 0000000..4393e99
--- /dev/null
@@ -0,0 +1,186 @@
+<?php
+
+namespace Friendica\Console;
+
+/**
+ * When I installed docblox, I had the experience that it does not generate any output at all.
+ * This script may be used to find that kind of problems with the documentation build process.
+ * If docblox generates output, use another approach for debugging.
+ *
+ * Basically, docblox takes a list of files to build documentation from. This script assumes there is a file or set of files
+ * breaking the build when it is included in that list. It tries to calculate the smallest list containing these files.
+ * Unfortunatly, the original problem is NP-complete, so what the script does is a best guess only.
+ *
+ * So it starts with a list of all files in the project.
+ * If that list can't be build, it cuts it in two parts and tries both parts independently. If only one of them breaks,
+ * it takes that one and tries the same independently. If both break, it assumes this is the smallest set. This assumption
+ * is not necessarily true. Maybe the smallest set consists of two files and both of them were in different parts when
+ * the list was divided, but by now it is my best guess. To make this assumption better, the list is shuffled after every step.
+ *
+ * After that, the script tries to remove a file from the list. It tests if the list breaks and if so, it
+ * assumes that the file it removed belongs to the set of erroneous files.
+ * This is done for all files, so, in the end removing one file leads to a working doc build.
+ *
+ * @author Alexander Kampmann
+ * @author Hypolite Petovan <hypolite@mrpetovan.com>
+ */
+class DocBloxErrorChecker extends \Asika\SimpleConsole\Console
+{
+
+       protected $helpOptions = ['h', 'help', '?'];
+
+       protected function getHelp()
+       {
+               $help = <<<HELP
+console docbloxerrorchecker - Checks the file tree for docblox errors
+Usage
+       bin/console docbloxerrorchecker [-h|--help|-?] [-v]
+
+Options
+    -h|--help|-? Show help information
+    -v           Show more debug information.
+HELP;
+               return $help;
+       }
+
+       protected function doExecute()
+       {
+               if ($this->getOption('v')) {
+                       $this->out('Class: ' . __CLASS__);
+                       $this->out('Arguments: ' . var_export($this->args, true));
+                       $this->out('Options: ' . var_export($this->options, true));
+               }
+
+               if (count($this->args) > 0) {
+                       throw new \Asika\SimpleConsole\CommandArgsException('Too many arguments');
+               }
+
+               if (!$this->commandExists('docblox')) {
+                       throw new \RuntimeException('DocBlox isn\'t available.');
+               }
+
+               $dir = \get_app()->getBasePath();
+
+               //stack for dirs to search
+               $dirstack = [];
+               //list of source files
+               $filelist = [];
+
+               //loop over all files in $dir
+               while ($dh = opendir($dir)) {
+                       while ($file = readdir($dh)) {
+                               if (is_dir($dir . "/" . $file)) {
+                                       //add to directory stack
+                                       if (strpos($file, '.') !== 0) {
+                                               array_push($dirstack, $dir . "/" . $file);
+                                               $this->out('dir ' . $dir . '/' . $file);
+                                       }
+                               } else {
+                                       //test if it is a source file and add to filelist
+                                       if (substr($file, strlen($file) - 4) == ".php") {
+                                               array_push($filelist, $dir . "/" . $file);
+                                               $this->out($dir . '/' . $file);
+                                       }
+                               }
+                       }
+                       //look at the next dir
+                       $dir = array_pop($dirstack);
+               }
+
+               //check the entire set
+               if ($this->runs($filelist)) {
+                       throw new \RuntimeException("I can not detect a problem.");
+               }
+
+               //check half of the set and discard if that half is okay
+               $res = $filelist;
+               $i = count($res);
+               do {
+                       $this->out($i . '/' . count($filelist) . ' elements remaining.');
+                       $res = $this->reduce($res, count($res) / 2);
+                       shuffle($res);
+                       $i = count($res);
+               } while (count($res) < $i);
+
+               //check one file after another
+               $needed = [];
+
+               while (count($res) != 0) {
+                       $file = array_pop($res);
+
+                       if ($this->runs(array_merge($res, $needed))) {
+                               $this->out('needs: ' . $file . ' and file count ' . count($needed));
+                               array_push($needed, $file);
+                       }
+               }
+
+               $this->out('Smallest Set is: ' . $this->namesList($needed) . ' with ' . count($needed) . ' files. ');
+
+               return 0;
+       }
+
+       private function commandExists($command)
+       {
+               $prefix = strpos(strtolower(PHP_OS),'win') > -1 ? 'where' : 'which';
+               exec("{$prefix} {$command}", $output, $returnVal);
+               return $returnVal === 0;
+       }
+
+       /**
+        * This function generates a comma separated list of file names.
+        *
+        * @param array $fileset Set of file names
+        *
+        * @return string comma-separated list of the file names
+        */
+       private function namesList($fileset)
+       {
+               return implode(',', $fileset);
+       }
+
+       /**
+        * This functions runs phpdoc on the provided list of files
+        *
+        * @param array $fileset Set of filenames
+        *
+        * @return bool true, if that set can be built
+        */
+       private function runs($fileset)
+       {
+               $fsParam = $this->namesList($fileset);
+               $this->exec('docblox -t phpdoc_out -f ' . $fsParam);
+               if (file_exists("phpdoc_out/index.html")) {
+                       $this->out('Subset ' . $fsParam . ' is okay.');
+                       $this->exec('rm -r phpdoc_out');
+                       return true;
+               } else {
+                       $this->out('Subset ' . $fsParam . ' failed.');
+                       return false;
+               }
+       }
+
+       /**
+        * This functions cuts down a fileset by removing files until it finally works.
+        * it was meant to be recursive, but php's maximum stack size is to small. So it just simulates recursion.
+        *
+        * In that version, it does not necessarily generate the smallest set, because it may not alter the elements order enough.
+        *
+        * @param array $fileset set of filenames
+        * @param int $ps number of files in subsets
+        *
+        * @return array a part of $fileset, that crashes
+        */
+       private function reduce($fileset, $ps)
+       {
+               //split array...
+               $parts = array_chunk($fileset, $ps);
+               //filter working subsets...
+               $parts = array_filter($parts, [$this, 'runs']);
+               //melt remaining parts together
+               if (is_array($parts)) {
+                       return array_reduce($parts, "array_merge", []);
+               }
+               return [];
+       }
+
+}
diff --git a/src/Console/Extract.php b/src/Console/Extract.php
new file mode 100644 (file)
index 0000000..7fac598
--- /dev/null
@@ -0,0 +1,140 @@
+<?php
+
+namespace Friendica\Console;
+
+/**
+ * Extracts translation strings from the Friendica project's files to be exported
+ * to Transifex for translation.
+ *
+ * Outputs a PHP file with language strings used by Friendica
+ *
+ * @author Hypolite Petovan <hypolite@mrpetovan.com>
+ */
+class Extract extends \Asika\SimpleConsole\Console
+{
+       protected $helpOptions = ['h', 'help', '?'];
+
+       protected function getHelp()
+       {
+               $help = <<<HELP
+console extract - Generate translation string file for the Friendica project (deprecated)
+Usage
+       bin/console extract [-h|--help|-?] [-v]
+
+Description
+       This script was used to generate the translation string file to be exported to Transifex,
+       please use bin/run_xgettext.sh instead
+
+Options
+    -h|--help|-? Show help information
+    -v           Show more debug information.
+HELP;
+               return $help;
+       }
+
+       protected function doExecute()
+       {
+               if ($this->getOption('v')) {
+                       $this->out('Class: ' . __CLASS__);
+                       $this->out('Arguments: ' . var_export($this->args, true));
+                       $this->out('Options: ' . var_export($this->options, true));
+               }
+
+               if (count($this->args) > 0) {
+                       throw new \Asika\SimpleConsole\CommandArgsException('Too many arguments');
+               }
+
+               $s = '<?php' . PHP_EOL;
+               $s .= '
+               function string_plural_select($n){
+                       return ($n != 1);
+               }
+
+               ';
+
+               $arr = [];
+
+               $files = array_merge(
+                       ['index.php', 'boot.php'],
+                       glob('mod/*'),
+                       glob('include/*'),
+                       glob('addon/*/*'),
+                       $this->globRecursive('src')
+               );
+
+               foreach ($files as $file) {
+                       $str = file_get_contents($file);
+
+                       $pat = '|L10n::t\(([^\)]*+)[\)]|';
+                       $patt = '|L10n::tt\(([^\)]*+)[\)]|';
+
+                       $matches = [];
+                       $matchestt = [];
+
+                       preg_match_all($pat, $str, $matches);
+                       preg_match_all($patt, $str, $matchestt);
+
+                       if (count($matches) || count($matchestt)) {
+                               $s .= '// ' . $file . PHP_EOL;
+                       }
+
+                       if (!empty($matches[1])) {
+                               foreach ($matches[1] as $long_match) {
+                                       $match_arr = preg_split('/(?<=[\'"])\s*,/', $long_match);
+                                       $match = $match_arr[0];
+                                       if (!in_array($match, $arr)) {
+                                               if (substr($match, 0, 1) == '$') {
+                                                       continue;
+                                               }
+
+                                               $arr[] = $match;
+
+                                               $s .= '$a->strings[' . $match . '] = ' . $match . ';' . "\n";
+                                       }
+                               }
+                       }
+                       if (!empty($matchestt[1])) {
+                               foreach ($matchestt[1] as $match) {
+                                       $matchtkns = preg_split("|[ \t\r\n]*,[ \t\r\n]*|", $match);
+                                       if (count($matchtkns) == 3 && !in_array($matchtkns[0], $arr)) {
+                                               if (substr($matchtkns[1], 0, 1) == '$') {
+                                                       continue;
+                                               }
+
+                                               $arr[] = $matchtkns[0];
+
+                                               $s .= '$a->strings[' . $matchtkns[0] . "] = array(\n";
+                                               $s .= "\t0 => " . $matchtkns[0] . ",\n";
+                                               $s .= "\t1 => " . $matchtkns[1] . ",\n";
+                                               $s .= ");\n";
+                                       }
+                               }
+                       }
+               }
+
+               $s .= '// Timezones' . PHP_EOL;
+
+               $zones = timezone_identifiers_list();
+               foreach ($zones as $zone) {
+                       $s .= '$a->strings[\'' . $zone . '\'] = \'' . $zone . '\';' . "\n";
+               }
+
+               $this->out($s);
+
+               return 0;
+       }
+
+       private function globRecursive($path) {
+               $dir_iterator = new \RecursiveDirectoryIterator($path);
+               $iterator = new \RecursiveIteratorIterator($dir_iterator, \RecursiveIteratorIterator::SELF_FIRST);
+
+               $return = [];
+               foreach ($iterator as $file) {
+                       if ($file->getBasename() != '.' && $file->getBasename() != '..') {
+                               $return[] = $file->getPathname();
+                       }
+               }
+
+               return $return;
+       }
+}
diff --git a/src/Console/GlobalCommunityBlock.php b/src/Console/GlobalCommunityBlock.php
new file mode 100644 (file)
index 0000000..bc067da
--- /dev/null
@@ -0,0 +1,75 @@
+<?php
+
+namespace Friendica\Console;
+
+use Friendica\Core\L10n;
+use Friendica\Model\Contact;
+
+/**
+ * @brief tool to block an account from the node
+ *
+ * With this tool, you can block an account in such a way, that no postings
+ * or comments this account writes are accepted to the node.
+ *
+ * License: AGPLv3 or later, same as Friendica
+ *
+ * @author Tobias Diekershoff <tobias.diekershoff@gmx.net>
+ * @author Hypolite Petovan <hypolite@mrpetovan.com>
+ */
+class GlobalCommunityBlock extends \Asika\SimpleConsole\Console
+{
+       protected $helpOptions = ['h', 'help', '?'];
+
+       protected function getHelp()
+       {
+               $help = <<<HELP
+console globalcommunityblock - Block remote profile from interacting with this node
+Usage
+       bin/console globalcommunityblock <profile_url> [-h|--help|-?] [-v]
+
+Description
+       Blocks an account in such a way that no postings or comments this account writes are accepted to this node.
+
+Options
+    -h|--help|-? Show help information
+    -v           Show more debug information.
+HELP;
+               return $help;
+       }
+
+       protected function doExecute()
+       {
+               $a = \get_app();
+
+               if ($this->getOption('v')) {
+                       $this->out('Class: ' . __CLASS__);
+                       $this->out('Arguments: ' . var_export($this->args, true));
+                       $this->out('Options: ' . var_export($this->options, true));
+               }
+
+               if (count($this->args) == 0) {
+                       $this->out($this->getHelp());
+                       return 0;
+               }
+
+               if (count($this->args) > 1) {
+                       throw new \Asika\SimpleConsole\CommandArgsException('Too many arguments');
+               }
+
+               if ($a->getMode()->isInstall()) {
+                       throw new \RuntimeException('Database isn\'t ready or populated yet');
+               }
+
+               $contact_id = Contact::getIdForURL($this->getArgument(0));
+               if (!$contact_id) {
+                       throw new \RuntimeException(L10n::t('Could not find any contact entry for this URL (%s)', $this->getArgument(0)));
+               }
+               if(Contact::block($contact_id)) {
+                       $this->out(L10n::t('The contact has been blocked from the node'));
+               } else {
+                       throw new \RuntimeException('The contact block failed.');
+               }
+
+               return 0;
+       }
+}
diff --git a/src/Console/GlobalCommunitySilence.php b/src/Console/GlobalCommunitySilence.php
new file mode 100644 (file)
index 0000000..daaf551
--- /dev/null
@@ -0,0 +1,92 @@
+<?php
+
+namespace Friendica\Console;
+
+use Friendica\Core\Protocol;
+use Friendica\Database\DBA;
+use Friendica\Network\Probe;
+use Friendica\Util\Strings;
+use RuntimeException;
+
+/**
+ * @brief tool to silence accounts on the global community page
+ *
+ * With this tool, you can silence an account on the global community page.
+ * Postings from silenced accounts will not be displayed on the community
+ * page. This silencing does only affect the display on the community page,
+ * accounts following the silenced accounts will still get their postings.
+ *
+ * License: AGPLv3 or later, same as Friendica
+ *
+ * @author Tobias Diekershoff <tobias.diekershoff@gmx.net>
+ * @author Hypolite Petovan <hypolite@mrpetovan.com>
+ */
+class GlobalCommunitySilence extends \Asika\SimpleConsole\Console
+{
+       protected $helpOptions = ['h', 'help', '?'];
+
+       protected function getHelp()
+       {
+               $help = <<<HELP
+console globalcommunitysilence - Silence remote profile from global community page
+Usage
+       bin/console globalcommunitysilence <profile_url> [-h|--help|-?] [-v]
+
+Description
+       With this tool, you can silence an account on the global community page.
+       Postings from silenced accounts will not be displayed on the community page.
+       This silencing does only affect the display on the community page, accounts
+       following the silenced accounts will still get their postings.
+
+Options
+    -h|--help|-? Show help information
+    -v           Show more debug information.
+HELP;
+               return $help;
+       }
+
+       protected function doExecute()
+       {
+               $a = \get_app();
+
+               if ($this->getOption('v')) {
+                       $this->out('Class: ' . __CLASS__);
+                       $this->out('Arguments: ' . var_export($this->args, true));
+                       $this->out('Options: ' . var_export($this->options, true));
+               }
+
+               if (count($this->args) == 0) {
+                       $this->out($this->getHelp());
+                       return 0;
+               }
+
+               if (count($this->args) > 1) {
+                       throw new \Asika\SimpleConsole\CommandArgsException('Too many arguments');
+               }
+
+               if ($a->getMode()->isInstall()) {
+                       throw new RuntimeException('Database isn\'t ready or populated yet');
+               }
+
+               /**
+                * 1. make nurl from last parameter
+                * 2. check DB (contact) if there is a contact with uid=0 and that nurl, get the ID
+                * 3. set the flag hidden=1 for the contact entry with the found ID
+                * */
+               $net = Probe::uri($this->getArgument(0));
+               if (in_array($net['network'], [Protocol::PHANTOM, Protocol::MAIL])) {
+                       throw new RuntimeException('This account seems not to exist.');
+               }
+
+               $nurl = Strings::normaliseLink($net['url']);
+               $contact = DBA::selectFirst("contact", ["id"], ["nurl" => $nurl, "uid" => 0]);
+               if (DBA::isResult($contact)) {
+                       DBA::update("contact", ["hidden" => true], ["id" => $contact["id"]]);
+                       $this->out('NOTICE: The account should be silenced from the global community page');
+               } else {
+                       throw new RuntimeException('NOTICE: Could not find any entry for this URL (' . $nurl . ')');
+               }
+
+               return 0;
+       }
+}
diff --git a/src/Console/Maintenance.php b/src/Console/Maintenance.php
new file mode 100644 (file)
index 0000000..080eb09
--- /dev/null
@@ -0,0 +1,95 @@
+<?php
+
+namespace Friendica\Console;
+
+use Friendica\Core;
+
+/**
+ * @brief Sets maintenance mode for this node
+ *
+ * @author Hypolite Petovan <hypolite@mrpetovan.com>
+ */
+class Maintenance extends \Asika\SimpleConsole\Console
+{
+       protected $helpOptions = ['h', 'help', '?'];
+
+       protected function getHelp()
+       {
+               $help = <<<HELP
+console maintenance - Sets maintenance mode for this node
+Usage
+       bin/console maintenance <enable> [<reason>] [-h|--help|-?] [-v]
+
+Description
+       <enable> cen be either 0 or 1 to disabled or enable the maintenance mode on this node.
+
+       <reason> is a quote-enclosed string with the optional reason for the maintenance mode.
+
+Examples
+       bin/console maintenance 1
+               Enables the maintenance mode without setting a reason message
+
+       bin/console maintenance 1 "SSL certification update"
+               Enables the maintenance mode with setting a reason message
+
+       bin/console maintenance 0
+               Disables the maintenance mode
+
+Options
+    -h|--help|-? Show help information
+    -v           Show more debug information.
+HELP;
+               return $help;
+       }
+
+       protected function doExecute()
+       {
+               $a = \Friendica\BaseObject::getApp();
+
+               if ($this->getOption('v')) {
+                       $this->out('Class: ' . __CLASS__);
+                       $this->out('Arguments: ' . var_export($this->args, true));
+                       $this->out('Options: ' . var_export($this->options, true));
+               }
+
+               if (count($this->args) == 0) {
+                       $this->out($this->getHelp());
+                       return 0;
+               }
+
+               if (count($this->args) > 2) {
+                       throw new \Asika\SimpleConsole\CommandArgsException('Too many arguments');
+               }
+
+               if ($a->getMode()->isInstall()) {
+                       throw new \RuntimeException('Database isn\'t ready or populated yet');
+               }
+
+               $enabled = intval($this->getArgument(0));
+
+               Core\Config::set('system', 'maintenance', $enabled);
+
+               $reason = $this->getArgument(1);
+
+               if ($enabled && $this->getArgument(1)) {
+                       Core\Config::set('system', 'maintenance_reason', $this->getArgument(1));
+               } else {
+                       Core\Config::set('system', 'maintenance_reason', '');
+               }
+
+               if ($enabled) {
+                       $mode_str = "maintenance mode";
+               } else {
+                       $mode_str = "normal mode";
+               }
+
+               $this->out('System set in ' . $mode_str);
+
+               if ($enabled && $reason != '') {
+                       $this->out('Maintenance reason: ' . $reason);
+               }
+
+               return 0;
+       }
+
+}
diff --git a/src/Console/NewPassword.php b/src/Console/NewPassword.php
new file mode 100644 (file)
index 0000000..dc69438
--- /dev/null
@@ -0,0 +1,90 @@
+<?php
+
+namespace Friendica\Console;
+
+use Friendica\Core\L10n;
+use Friendica\Database\DBA;
+use Friendica\Model\User;
+use RuntimeException;
+
+/**
+ * @brief tool to set a new password for a user
+ *
+ * With this tool, you can set a new password for a user
+ *
+ * License: AGPLv3 or later, same as Friendica
+ *
+ * @author Michael Vogel <heluecht@pirati.ca>
+ */
+class NewPassword extends \Asika\SimpleConsole\Console
+{
+       protected $helpOptions = ['h', 'help', '?'];
+
+       protected function getHelp()
+       {
+               $help = <<<HELP
+console newpassword - Creates a new password for a given user
+Usage
+       bin/console newpassword <nickname> [<password>] [-h|--help|-?] [-v]
+
+Description
+       Creates a new password for a user without using the "forgot password" functionality.
+
+Options
+    -h|--help|-? Show help information
+    -v           Show more debug information.
+HELP;
+               return $help;
+       }
+
+       protected function doExecute()
+       {
+               $a = \get_app();
+
+               if ($this->getOption('v')) {
+                       $this->out('Class: ' . __CLASS__);
+                       $this->out('Arguments: ' . var_export($this->args, true));
+                       $this->out('Options: ' . var_export($this->options, true));
+               }
+
+               if (count($this->args) == 0) {
+                       $this->out($this->getHelp());
+                       return 0;
+               }
+
+               if (count($this->args) > 2) {
+                       throw new \Asika\SimpleConsole\CommandArgsException('Too many arguments');
+               }
+
+               if ($a->getMode()->isInstall()) {
+                       throw new RuntimeException('Database isn\'t ready or populated yet');
+               }
+
+               $nick = $this->getArgument(0);
+
+               $user = DBA::selectFirst('user', ['uid'], ['nickname' => $nick]);
+               if (!DBA::isResult($user)) {
+                       throw new RuntimeException(L10n::t('User not found'));
+               }
+
+               $password = $this->getArgument(1);
+               if (is_null($password)) {
+                       $this->out(L10n::t('Enter new password: '), false);
+                       $password = \Seld\CliPrompt\CliPrompt::hiddenPrompt(true);
+               }
+
+               try {
+                       $result = User::updatePassword($user['uid'], $password);
+
+                       if (!DBA::isResult($result)) {
+                               throw new \Exception(L10n::t('Password update failed. Please try again.'));
+                       }
+
+                       $this->out(L10n::t('Password changed.'));
+               } catch (\Exception $e) {
+                       throw new RuntimeException($e->getMessage(), $e->getCode(), $e);
+               }
+
+               return 0;
+       }
+}
diff --git a/src/Console/PhpToPo.php b/src/Console/PhpToPo.php
new file mode 100644 (file)
index 0000000..d73c7f4
--- /dev/null
@@ -0,0 +1,237 @@
+<?php
+
+namespace Friendica\Console;
+
+/**
+ * Read a strings.php file and create messages.po in the same directory
+ *
+ * @author Hypolite Petovan <hypolite@mrpetovan.com>
+ */
+class PhpToPo extends \Asika\SimpleConsole\Console
+{
+
+       protected $helpOptions = ['h', 'help', '?'];
+
+       private $normBaseMsgIds = [];
+       const NORM_REGEXP = "|[\\\]|";
+
+       protected function getHelp()
+       {
+               $help = <<<HELP
+console php2po - Generate a messages.po file from a strings.php file
+Usage
+       bin/console php2po [-p <n>] [--base <file>] <path/to/strings.php> [-h|--help|-?] [-v]
+
+Description
+       Read a strings.php file and create the according messages.po in the same directory
+
+Options
+       -p <n>        Number of plural forms. Default: 2
+       --base <file> Path to base messages.po file. Default: view/lang/C/messages.po
+       -h|--help|-?  Show help information
+       -v            Show more debug information.
+HELP;
+               return $help;
+       }
+
+       protected function doExecute()
+       {
+               if ($this->getOption('v')) {
+                       $this->out('Class: ' . __CLASS__);
+                       $this->out('Arguments: ' . var_export($this->args, true));
+                       $this->out('Options: ' . var_export($this->options, true));
+               }
+
+               if (count($this->args) == 0) {
+                       $this->out($this->getHelp());
+                       return 0;
+               }
+
+               if (count($this->args) > 1) {
+                       throw new \Asika\SimpleConsole\CommandArgsException('Too many arguments');
+               }
+
+               $a = \get_app();
+
+               $phpfile = realpath($this->getArgument(0));
+
+               if (!file_exists($phpfile)) {
+                       throw new \RuntimeException('Supplied file path doesn\'t exist.');
+               }
+
+               if (!is_writable(dirname($phpfile))) {
+                       throw new \RuntimeException('Supplied directory isn\'t writable.');
+               }
+
+               $pofile = dirname($phpfile) . DIRECTORY_SEPARATOR . 'messages.po';
+
+               // start !
+               include_once($phpfile);
+
+               $out = '';
+               $out .= "# FRIENDICA Distributed Social Network\n";
+               $out .= "# Copyright (C) 2010, 2011, 2012, 2013 the Friendica Project\n";
+               $out .= "# This file is distributed under the same license as the Friendica package.\n";
+               $out .= "# \n";
+               $out .= 'msgid ""' . "\n";
+               $out .= 'msgstr ""' . "\n";
+               $out .= '"Project-Id-Version: friendica\n"' . "\n";
+               $out .= '"Report-Msgid-Bugs-To: \n"' . "\n";
+               $out .= '"POT-Creation-Date: ' . date("Y-m-d H:i:sO") . '\n"' . "\n";
+               $out .= '"MIME-Version: 1.0\n"' . "\n";
+               $out .= '"Content-Type: text/plain; charset=UTF-8\n"' . "\n";
+               $out .= '"Content-Transfer-Encoding: 8bit\n"' . "\n";
+
+               // search for plural info
+               $lang = "";
+               $lang_logic = "";
+               $lang_pnum = $this->getOption('p', 2);
+
+               $infile = file($phpfile);
+               foreach ($infile as $l) {
+                       $l = trim($l);
+                       if ($this->startsWith($l, 'function string_plural_select_')) {
+                               $lang = str_replace('function string_plural_select_', '', str_replace('($n){', '', $l));
+                       }
+                       if ($this->startsWith($l, 'return')) {
+                               $lang_logic = str_replace('$', '', trim(str_replace('return ', '', $l), ';'));
+                               break;
+                       }
+               }
+
+               $this->out('Language: ' . $lang);
+               $this->out('Plural forms: ' . $lang_pnum);
+               $this->out('Plural forms: ' . $lang_logic);
+
+               $out .= sprintf('"Language: %s\n"', $lang) . "\n";
+               $out .= sprintf('"Plural-Forms: nplurals=%s; plural=%s;\n"', $lang_pnum, $lang_logic) . "\n";
+               $out .= "\n";
+
+               $base_path = $this->getOption('base', 'view/lang/C/messages.po');
+
+               // load base messages.po and extract msgids
+               $base_msgids = [];
+               $base_f = file($base_path);
+               if (!$base_f) {
+                       throw new \RuntimeException('The base ' . $base_path . ' file is missing or unavailable to read.');
+               }
+
+               $this->out('Loading base file ' . $base_path . '...');
+
+               $_f = 0;
+               $_mid = "";
+               $_mids = [];
+               foreach ($base_f as $l) {
+                       $l = trim($l);
+
+                       if ($this->startsWith($l, 'msgstr')) {
+                               if ($_mid != '""') {
+                                       $base_msgids[$_mid] = $_mids;
+                                       $this->normBaseMsgIds[preg_replace(self::NORM_REGEXP, "", $_mid)] = $_mid;
+                               }
+
+                               $_f = 0;
+                               $_mid = "";
+                               $_mids = [];
+                       }
+
+                       if ($this->startsWith($l, '"') && $_f == 2) {
+                               $_mids[count($_mids) - 1] .= "\n" . $l;
+                       }
+                       if ($this->startsWith($l, 'msgid_plural ')) {
+                               $_f = 2;
+                               $_mids[] = str_replace('msgid_plural ', '', $l);
+                       }
+
+                       if ($this->startsWith($l, '"') && $_f == 1) {
+                               $_mid .= "\n" . $l;
+                               $_mids[count($_mids) - 1] .= "\n" . $l;
+                       }
+                       if ($this->startsWith($l, 'msgid ')) {
+                               $_f = 1;
+                               $_mid = str_replace('msgid ', '', $l);
+                               $_mids = [$_mid];
+                       }
+               }
+
+               $this->out('Creating ' . $pofile . '...');
+
+               // create msgid and msgstr
+               $warnings = "";
+               foreach ($a->strings as $key => $str) {
+                       $msgid = $this->massageString($key);
+
+                       if (preg_match("|%[sd0-9](\$[sn])*|", $msgid)) {
+                               $out .= "#, php-format\n";
+                       }
+                       $msgid = $this->findOriginalMsgId($msgid);
+                       $out .= 'msgid ' . $msgid . "\n";
+
+                       if (is_array($str)) {
+                               if (array_key_exists($msgid, $base_msgids) && isset($base_msgids[$msgid][1])) {
+                                       $out .= 'msgid_plural ' . $base_msgids[$msgid][1] . "\n";
+                               } else {
+                                       $out .= 'msgid_plural ' . $msgid . "\n";
+                                       $warnings .= "[W] No source plural form for msgid:\n" . str_replace("\n", "\n\t", $msgid) . "\n\n";
+                               }
+                               foreach ($str as $n => $msgstr) {
+                                       $out .= 'msgstr[' . $n . '] ' . $this->massageString($msgstr) . "\n";
+                               }
+                       } else {
+                               $out .= 'msgstr ' . $this->massageString($str) . "\n";
+                       }
+
+                       $out .= "\n";
+               }
+
+               if (!file_put_contents($pofile, $out)) {
+                       throw new \RuntimeException('Unable to write to ' . $pofile);
+               }
+
+               if ($warnings != '') {
+                       $this->out($warnings);
+               }
+
+               return 0;
+       }
+
+       private function startsWith($haystack, $needle)
+       {
+               // search backwards starting from haystack length characters from the end
+               return $needle === "" || strrpos($haystack, $needle, -strlen($haystack)) !== FALSE;
+       }
+
+       /**
+        * Get a string and retun a message.po ready text
+        * - replace " with \"
+        * - replace tab char with \t
+        * - manage multiline strings
+        *
+        * @param string $str
+        * @return string
+        */
+       private function massageString($str)
+       {
+               $str = str_replace('\\', '\\\\', $str);
+               $str = str_replace('"', '\"', $str);
+               $str = str_replace("\t", '\t', $str);
+               $str = str_replace("\n", '\n"' . "\n" . '"', $str);
+               if (strpos($str, "\n") !== false && $str[0] !== '"') {
+                       $str = '"' . "\n" . $str;
+               }
+
+               $str = preg_replace("|\n([^\"])|", "\n\"$1", $str);
+               return sprintf('"%s"', $str);
+       }
+
+       private function findOriginalMsgId($str)
+       {
+               $norm_str = preg_replace(self::NORM_REGEXP, "", $str);
+               if (array_key_exists($norm_str, $this->normBaseMsgIds)) {
+                       return $this->normBaseMsgIds[$norm_str];
+               }
+
+               return $str;
+       }
+
+}
diff --git a/src/Console/PoToPhp.php b/src/Console/PoToPhp.php
new file mode 100644 (file)
index 0000000..c4ba42c
--- /dev/null
@@ -0,0 +1,198 @@
+<?php
+
+namespace Friendica\Console;
+
+/**
+ * Read a messages.po file and create strings.php in the same directory
+ *
+ * @author Hypolite Petovan <hypolite@mrpetovan.com>
+ */
+class PoToPhp extends \Asika\SimpleConsole\Console
+{
+       protected $helpOptions = ['h', 'help', '?'];
+
+       const DQ_ESCAPE = "__DQ__";
+
+       protected function getHelp()
+       {
+               $help = <<<HELP
+console php2po - Generate a strings.php file from a messages.po file
+Usage
+       bin/console php2po <path/to/messages.po> [-h|--help|-?] [-v]
+
+Description
+       Read a messages.po file and create the according strings.php in the same directory
+
+Options
+       -h|--help|-?  Show help information
+       -v            Show more debug information.
+HELP;
+               return $help;
+       }
+
+       protected function doExecute()
+       {
+               if ($this->getOption('v')) {
+                       $this->out('Class: ' . __CLASS__);
+                       $this->out('Arguments: ' . var_export($this->args, true));
+                       $this->out('Options: ' . var_export($this->options, true));
+               }
+
+               if (count($this->args) == 0) {
+                       $this->out($this->getHelp());
+                       return 0;
+               }
+
+               if (count($this->args) > 1) {
+                       throw new \Asika\SimpleConsole\CommandArgsException('Too many arguments');
+               }
+
+               $pofile = realpath($this->getArgument(0));
+
+               if (!file_exists($pofile)) {
+                       throw new \RuntimeException('Supplied file path doesn\'t exist.');
+               }
+
+               if (!is_writable(dirname($pofile))) {
+                       throw new \RuntimeException('Supplied directory isn\'t writable.');
+               }
+
+               $outfile = dirname($pofile) . DIRECTORY_SEPARATOR . 'strings.php';
+
+               if (basename(dirname($pofile)) == 'C') {
+                       $lang = 'en';
+               } else {
+                       $lang = str_replace('-', '_', basename(dirname($pofile)));
+               }
+
+               $this->out('Out to ' . $outfile);
+
+               $out = "<?php\n\n";
+
+               $infile = file($pofile);
+               $k = '';
+               $v = '';
+               $arr = false;
+               $ink = false;
+               $inv = false;
+               $escape_s_exp = '|[^\\\\]\$[a-z]|';
+
+               foreach ($infile as $l) {
+                       $l = str_replace('\"', self::DQ_ESCAPE, $l);
+                       $len = strlen($l);
+                       if ($l[0] == "#") {
+                               $l = "";
+                       }
+
+                       if (substr($l, 0, 15) == '"Plural-Forms: ') {
+                               $match = [];
+                               preg_match("|nplurals=([0-9]*); *plural=(.*)[;\\\\]|", $l, $match);
+                               $cond = str_replace('n', '$n', $match[2]);
+                               // define plural select function if not already defined
+                               $fnname = 'string_plural_select_' . $lang;
+                               $out .= 'if(! function_exists("' . $fnname . '")) {' . "\n";
+                               $out .= 'function ' . $fnname . '($n){' . "\n";
+                               $out .= '       $n = intval($n);' . "\n";
+                               $out .= '       return ' . $cond . ';' . "\n";
+                               $out .= '}}' . "\n";
+                       }
+
+                       if ($k != '' && substr($l, 0, 7) == 'msgstr ') {
+                               if ($ink) {
+                                       $ink = false;
+                                       $out .= '$a->strings["' . $k . '"] = ';
+                               }
+
+                               if ($inv) {
+                                       $out .= '"' . $v . '"';
+                               }
+
+                               $v = substr($l, 8, $len - 10);
+                               $v = preg_replace_callback($escape_s_exp, [$this, 'escapeDollar'], $v);
+
+                               $inv = true;
+                       }
+
+                       if ($k != "" && substr($l, 0, 7) == 'msgstr[') {
+                               if ($ink) {
+                                       $ink = false;
+                                       $out .= '$a->strings["' . $k . '"] = ';
+                               }
+                               if ($inv) {
+                                       $inv = false;
+                                       $out .= '"' . $v . '"';
+                               }
+
+                               if (!$arr) {
+                                       $arr = true;
+                                       $out .= "[\n";
+                               }
+
+                               $match = [];
+                               preg_match("|\[([0-9]*)\] (.*)|", $l, $match);
+                               $out .= "\t"
+                                       . preg_replace_callback($escape_s_exp, [$this, 'escapeDollar'], $match[1])
+                                       . ' => '
+                                       . preg_replace_callback($escape_s_exp, [$this, 'escapeDollar'], $match[2])
+                                       . ",\n";
+                       }
+
+                       if (substr($l, 0, 6) == 'msgid_') {
+                               $ink = false;
+                               $out .= '$a->strings["' . $k . '"] = ';
+                       }
+
+                       if ($ink) {
+                               $k .= trim($l, "\"\r\n");
+                               $k = preg_replace_callback($escape_s_exp, [$this, 'escapeDollar'], $k);
+                       }
+
+                       if (substr($l, 0, 6) == 'msgid ') {
+                               if ($inv) {
+                                       $inv = false;
+                                       $out .= '"' . $v . '"';
+                               }
+
+                               if ($k != "") {
+                                       $out .= ($arr) ? "];\n" : ";\n";
+                               }
+
+                               $arr = false;
+                               $k = str_replace("msgid ", "", $l);
+                               if ($k != '""') {
+                                       $k = trim($k, "\"\r\n");
+                               } else {
+                                       $k = '';
+                               }
+
+                               $k = preg_replace_callback($escape_s_exp, [$this, 'escapeDollar'], $k);
+                               $ink = true;
+                       }
+
+                       if ($inv && substr($l, 0, 6) != "msgstr") {
+                               $v .= trim($l, "\"\r\n");
+                               $v = preg_replace_callback($escape_s_exp, [$this, 'escapeDollar'], $v);
+                       }
+               }
+
+               if ($inv) {
+                       $out .= '"' . $v . '"';
+               }
+
+               if ($k != '') {
+                       $out .= ($arr ? "];\n" : ";\n");
+               }
+
+               $out = str_replace(self::DQ_ESCAPE, '\"', $out);
+               if (!file_put_contents($outfile, $out)) {
+                       throw new \RuntimeException('Unable to write to ' . $outfile);
+               }
+
+               return 0;
+       }
+
+       private function escapeDollar($match)
+       {
+               return str_replace('$', '\$', $match[0]);
+       }
+}
diff --git a/src/Console/PostUpdate.php b/src/Console/PostUpdate.php
new file mode 100644 (file)
index 0000000..4d7246d
--- /dev/null
@@ -0,0 +1,72 @@
+<?php
+
+namespace Friendica\Console;
+
+use Friendica\Core\Config;
+use Friendica\Core\L10n;
+use Friendica\Core\Update;
+
+/**
+ * Performs database post updates
+ *
+ * License: AGPLv3 or later, same as Friendica
+ *
+ * @author Tobias Diekershoff <tobias.diekershoff@gmx.net>
+ * @author Hypolite Petovan <hypolite@mrpetovan.com>
+ */
+class PostUpdate extends \Asika\SimpleConsole\Console
+{
+        protected $helpOptions = ['h', 'help', '?'];
+
+        protected function getHelp()
+        {
+                $help = <<<HELP
+console postupdate - Performs database post updates
+Usage
+        bin/console postupdate [-h|--help|-?] [--reset <version>]
+
+Options
+    -h|--help|-?      Show help information
+    --reset <version> Reset the post update version
+HELP;
+                return $help;
+        }
+
+       protected function doExecute()
+       {
+               $a = \Friendica\BaseObject::getApp();
+
+               if ($this->getOption($this->helpOptions)) {
+                       $this->out($this->getHelp());
+                       return 0;
+               }
+
+               $reset_version = $this->getOption('reset');
+               if (is_bool($reset_version)) {
+                       $this->out($this->getHelp());
+                       return 0;
+               } elseif ($reset_version) {
+                       Config::set('system', 'post_update_version', $reset_version);
+                       echo L10n::t('Post update version number has been set to %s.', $reset_version) . "\n";
+                       return 0;
+               }
+
+               if ($a->getMode()->isInstall()) {
+                       throw new \RuntimeException('Database isn\'t ready or populated yet');
+               }
+
+               echo L10n::t('Check for pending update actions.') . "\n";
+               Update::run($a->getBasePath(), true, false, true, false);
+               echo L10n::t('Done.') . "\n";
+
+               echo L10n::t('Execute pending post updates.') . "\n";
+
+               while (!\Friendica\Database\PostUpdate::update()) {
+                       echo '.';
+               }
+
+               echo "\n" . L10n::t('All pending post updates are done.') . "\n";
+
+               return 0;
+       }
+}
diff --git a/src/Console/ServerBlock.php b/src/Console/ServerBlock.php
new file mode 100644 (file)
index 0000000..7e45f10
--- /dev/null
@@ -0,0 +1,171 @@
+<?php
+
+namespace Friendica\Console;
+
+use Asika\SimpleConsole\CommandArgsException;
+use Asika\SimpleConsole\Console;
+use Console_Table;
+use Friendica\BaseObject;
+use Friendica\Core\Config\Configuration;
+
+/**
+ * @brief Manage blocked servers
+ *
+ * With this tool, you can list the current blocked servers
+ * or you can add / remove a blocked server from the list
+ */
+class ServerBlock extends Console
+{
+       const DEFAULT_REASON = 'blocked';
+
+       protected $helpOptions = ['h', 'help', '?'];
+
+       protected function getHelp()
+       {
+               $help = <<<HELP
+console serverblock - Manage blocked servers
+Usage
+       bin/console serverblock [-h|--help|-?] [-v]
+       bin/console serverblock add <server> <reason> [-h|--help|-?] [-v]
+       bin/console serverblock remove <server> [-h|--help|-?] [-v]
+
+Description
+       With this tool, you can list the current blocked servers
+    or you can add / remove a blocked server from the list
+
+Options
+    -h|--help|-? Show help information
+    -v           Show more debug information.
+HELP;
+               return $help;
+       }
+
+       protected function doExecute()
+       {
+               $a = BaseObject::getApp();
+
+               if (count($this->args) == 0) {
+                       $this->printBlockedServers($a->getConfig());
+                       return 0;
+               }
+
+               switch ($this->getArgument(0)) {
+                       case 'add':
+                               return $this->addBlockedServer($a->getConfig());
+                       case 'remove':
+                               return $this->removeBlockedServer($a->getConfig());
+                       default:
+                               throw new CommandArgsException('Unknown command.');
+                               break;
+               }
+       }
+
+       /**
+        * Prints the whole list of blocked domains including the reason
+        *
+        * @param Configuration $config
+        */
+       private function printBlockedServers(Configuration $config)
+       {
+               $table = new Console_Table();
+               $table->setHeaders(['Domain', 'Reason']);
+               $blocklist = $config->get('system', 'blocklist');
+               foreach ($blocklist as $domain) {
+                       $table->addRow($domain);
+               }
+               $this->out($table->getTable());
+       }
+
+       /**
+        * Adds a server to the blocked list
+        *
+        * @param Configuration $config
+        *
+        * @return int The return code (0 = success, 1 = failed)
+        */
+       private function addBlockedServer(Configuration $config)
+       {
+               if (count($this->args) < 2 || count($this->args) > 3) {
+                       throw new CommandArgsException('Add needs a domain and optional a reason.');
+               }
+
+               $domain = $this->getArgument(1);
+               $reason = (count($this->args) === 3) ? $this->getArgument(2) : self::DEFAULT_REASON;
+
+               $update = false;
+
+               $currBlocklist = $config->get('system', 'blocklist');
+               $newBlockList = [];
+               foreach ($currBlocklist  as $blocked) {
+                       if ($blocked['domain'] === $domain) {
+                               $update = true;
+                               $newBlockList[] = [
+                                       'domain' => $domain,
+                                       'reason' => $reason,
+                               ];
+                       } else {
+                               $newBlockList[] = $blocked;
+                       }
+               }
+
+               if (!$update) {
+                       $newBlockList[] = [
+                               'domain' => $domain,
+                               'reason' => $reason,
+                       ];
+               }
+
+               if ($config->set('system', 'blocklist', $newBlockList)) {
+                       if ($update) {
+                               $this->out(sprintf("The domain '%s' is now updated. (Reason: '%s')", $domain, $reason));
+                       } else {
+                               $this->out(sprintf("The domain '%s' is now blocked. (Reason: '%s')", $domain, $reason));
+                       }
+                       return 0;
+               } else {
+                       $this->out(sprintf("Couldn't save '%s' as blocked server", $domain));
+                       return 1;
+               }
+       }
+
+       /**
+        * Removes a server from the blocked list
+        *
+        * @param Configuration $config
+        *
+        * @return int The return code (0 = success, 1 = failed)
+        */
+       private function removeBlockedServer(Configuration $config)
+       {
+               if (count($this->args) !== 2) {
+                       throw new CommandArgsException('Remove needs a second parameter.');
+               }
+
+               $domain = $this->getArgument(1);
+
+               $found = false;
+
+               $currBlocklist = $config->get('system', 'blocklist');
+               $newBlockList = [];
+               foreach ($currBlocklist as $blocked) {
+                       if ($blocked['domain'] === $domain) {
+                               $found = true;
+                       } else {
+                               $newBlockList[] = $blocked;
+                       }
+               }
+
+               if (!$found) {
+                       $this->out(sprintf("The domain '%s' is not blocked.", $domain));
+                       return 1;
+               }
+
+               if ($config->set('system', 'blocklist', $newBlockList)) {
+                       $this->out(sprintf("The domain '%s' is not more blocked", $domain));
+                       return 0;
+               } else {
+                       $this->out(sprintf("Couldn't remove '%s' from blocked servers", $domain));
+                       return 1;
+               }
+       }
+}
diff --git a/src/Console/Storage.php b/src/Console/Storage.php
new file mode 100644 (file)
index 0000000..30b5567
--- /dev/null
@@ -0,0 +1,147 @@
+<?php
+
+namespace Friendica\Console;
+
+use Asika\SimpleConsole\CommandArgsException;
+use Friendica\Core\StorageManager;
+
+/**
+ * @brief tool to manage storage backend and stored data from CLI
+ *
+ */
+class Storage extends \Asika\SimpleConsole\Console
+{
+       protected $helpOptions = ['h', 'help', '?'];
+
+       protected function getHelp()
+       {
+               $help = <<<HELP
+console storage - manage storage backend and stored data
+Synopsis
+    bin/console storage [-h|--help|-?] [-v]
+        Show this help
+    
+    bin/console storage list
+        List available storage backends
+    
+    bin/console storage set <name>
+        Set current storage backend
+            name        storage backend to use. see "list".
+    
+    bin/console storage move [table] [-n 5000]
+        Move stored data to current storage backend.
+            table       one of "photo" or "attach". default to both
+            -n          limit of processed entry batch size
+HELP;
+               return $help;
+       }
+
+       protected function doExecute()
+       {
+               if ($this->getOption('v')) {
+                       $this->out('Executable: ' . $this->executable);
+                       $this->out('Class: ' . __CLASS__);
+                       $this->out('Arguments: ' . var_export($this->args, true));
+                       $this->out('Options: ' . var_export($this->options, true));
+               }
+
+               if (count($this->args) == 0) {
+                       $this->out($this->getHelp());
+                       return -1;
+               }
+
+               switch ($this->args[0]) {
+                       case 'list':
+                               return $this->doList();
+                               break;
+                       case 'set':
+                               return $this->doSet();
+                               break;
+                       case 'move':
+                               return $this->doMove();
+                               break;
+               }
+
+               $this->out(sprintf('Invalid action "%s"', $this->args[0]));
+               return -1;
+       }
+
+       protected function doList()
+       {
+               $rowfmt = ' %-3s | %-20s';
+               $current = StorageManager::getBackend();
+               $this->out(sprintf($rowfmt, 'Sel', 'Name'));
+               $this->out('-----------------------');
+               $isregisterd = false;
+               foreach (StorageManager::listBackends() as $name => $class) {
+                       $issel = ' ';
+                       if ($current === $class) {
+                               $issel = '*';
+                               $isregisterd = true;
+                       };
+                       $this->out(sprintf($rowfmt, $issel, $name));
+               }
+
+               if ($current === '') {
+                       $this->out();
+                       $this->out('This system is using legacy storage system');
+               }
+               if ($current !== '' && !$isregisterd) {
+                       $this->out();
+                       $this->out('The current storage class (' . $current . ') is not registered!');
+               }
+               return 0;
+       }
+
+       protected function doSet()
+       {
+               if (count($this->args) !== 2) {
+                       throw new CommandArgsException('Invalid arguments');
+               }
+
+               $name = $this->args[1];
+               $class = StorageManager::getByName($name);
+
+               if ($class === '') {
+                       $this->out($name . ' is not a registered backend.');
+                       return -1;
+               }
+
+               if (!StorageManager::setBackend($class)) {
+                       $this->out($class . ' is not a valid backend storage class.');
+                       return -1;
+               }
+
+               return 0;
+       }
+
+       protected function doMove()
+       {
+               $tables = null;
+               if (count($this->args) < 1 || count($this->args) > 2) {
+                       throw new CommandArgsException('Invalid arguments');
+               }
+
+               if (count($this->args) == 2) {
+                       $table = strtolower($this->args[1]);
+                       if (!in_array($table, ['photo', 'attach'])) {
+                               throw new CommandArgsException('Invalid table');
+                       }
+                       $tables = [$table];
+               }
+
+               $current = StorageManager::getBackend();
+               $total = 0;
+
+               do {
+                       $moved = StorageManager::move($current, $tables, $this->getOption('n', 5000));
+                       if ($moved) {
+                               $this->out(date('[Y-m-d H:i:s] ') . sprintf('Moved %d files', $moved));
+                       }
+
+                       $total += $moved;
+               } while ($moved);
+
+               $this->out(sprintf(date('[Y-m-d H:i:s] ') . 'Moved %d files total', $total));
+       }
+}
diff --git a/src/Console/Typo.php b/src/Console/Typo.php
new file mode 100644 (file)
index 0000000..5f5fa0b
--- /dev/null
@@ -0,0 +1,117 @@
+<?php
+
+namespace Friendica\Console;
+
+use Friendica\BaseObject;
+
+/**
+ * Tired of chasing typos and finding them after a commit.
+ * Run this and quickly see if we've got any parse errors in our application files.
+ *
+ * @author Hypolite Petovan <hypolite@mrpetovan.com>
+ */
+class Typo extends \Asika\SimpleConsole\Console
+{
+       protected $helpOptions = ['h', 'help', '?'];
+
+       protected function getHelp()
+       {
+               $help = <<<HELP
+console typo - Checks for parse errors in Friendica files
+Usage
+       bin/console typo [-h|--help|-?] [-v]
+
+Description
+       Checks all PHP files in the Friendica file tree for parse errors
+
+Options
+       -h|--help|-?  Show help information
+       -v            Show more debug information.
+HELP;
+               return $help;
+       }
+
+       protected function doExecute()
+       {
+               if ($this->getOption('v')) {
+                       $this->out('Class: ' . __CLASS__);
+                       $this->out('Arguments: ' . var_export($this->args, true));
+                       $this->out('Options: ' . var_export($this->options, true));
+               }
+
+               if (count($this->args) > 0) {
+                       throw new \Asika\SimpleConsole\CommandArgsException('Too many arguments');
+               }
+
+               $php_path = BaseObject::getApp()->getConfigCache()->get('config', 'php_path', 'php');
+
+               if ($this->getOption('v')) {
+                       $this->out('Directory: src');
+               }
+
+               $Iterator = new \RecursiveDirectoryIterator('src');
+
+               foreach (new \RecursiveIteratorIterator($Iterator) as $file) {
+                       if (substr($file, -4) === '.php') {
+                               $this->checkFile($php_path, $file);
+                       }
+               }
+
+               if ($this->getOption('v')) {
+                       $this->out('Directory: mod');
+               }
+
+               $files = glob('mod/*.php');
+               $this->checkFiles($php_path, $files);
+
+               if ($this->getOption('v')) {
+                       $this->out('Directory: include');
+               }
+
+               $files = glob('include/*.php');
+               $this->checkFiles($php_path, $files);
+
+               if ($this->getOption('v')) {
+                       $this->out('Directory: addon');
+               }
+
+               $dirs = glob('addon/*');
+               foreach ($dirs as $dir) {
+                       $addon = basename($dir);
+                       $files = glob($dir . '/' . $addon . '.php');
+                       $this->checkFiles($php_path, $files);
+               }
+
+               if ($this->getOption('v')) {
+                       $this->out('String files');
+               }
+
+               $files = glob('view/lang/*/strings.php');
+               $this->checkFiles($php_path, $files);
+
+               $this->out('No errors.');
+
+               return 0;
+       }
+
+       private function checkFiles($php_path, array $files)
+       {
+               foreach ($files as $file) {
+                       $this->checkFile($php_path, $file);
+               }
+       }
+
+       private function checkFile($php_path, $file)
+       {
+               if ($this->getOption('v')) {
+                       $this->out('Checking ' . $file);
+               }
+
+               $output = [];
+               $ret = 0;
+               exec("$php_path -l $file", $output, $ret);
+               if ($ret !== 0) {
+                       throw new \RuntimeException('Parse error found in ' . $file . ', scan stopped.');
+               }
+       }
+}
index 1eae2a3e3b4ba98651bfe15e04b38e3c81831111..a63244e856a7ffd0d2b0843750f72552ae7a682a 100644 (file)
@@ -67,7 +67,6 @@ class Nav
                $tpl = Renderer::getMarkupTemplate('nav.tpl');
 
                $nav .= Renderer::replaceMacros($tpl, [
-                       '$baseurl'      => System::baseUrl(),
                        '$sitelocation' => $nav_info['sitelocation'],
                        '$nav'          => $nav_info['nav'],
                        '$banner'       => $nav_info['banner'],
index 0093ba11af38a8e948ab6cca40d5b0c59be0cf40..7190f1ce0ed39cc8b8433b1497947074e566cd6e 100644 (file)
@@ -181,7 +181,6 @@ class OEmbed
                                        $tw = $th * $tr;
                                        $tpl = Renderer::getMarkupTemplate('oembed_video.tpl');
                                        $ret .= Renderer::replaceMacros($tpl, [
-                                               '$baseurl' => System::baseUrl(),
                                                '$embedurl' => $oembed->embed_url,
                                                '$escapedhtml' => base64_encode($oembed->html),
                                                '$tw' => $tw,
index 06a731b2cdd594b4b6cebba0e542e06bd69a01b2..b6f64ad7422f4a451672b4e8cb2d06769c1a691b 100644 (file)
@@ -2,6 +2,7 @@
 /**
  * @file src/Core/Addon.php
  */
+
 namespace Friendica\Core;
 
 use Friendica\BaseObject;
@@ -26,6 +27,61 @@ class Addon extends BaseObject
         */
        private static $addons = [];
 
+       /**
+        * Returns the list of available addons with their current status and info.
+        * This list is made from scanning the addon/ folder.
+        * Unsupported addons are excluded unless they already are enabled or system.show_unsupported_addon is set.
+        *
+        * @return array
+        * @throws \Exception
+        */
+       public static function getAvailableList()
+       {
+               $addons = [];
+               $files = glob('addon/*/');
+               if (is_array($files)) {
+                       foreach ($files as $file) {
+                               if (is_dir($file)) {
+                                       list($tmp, $addon) = array_map('trim', explode('/', $file));
+                                       $info = self::getInfo($addon);
+
+                                       if (Config::get('system', 'show_unsupported_addons')
+                                               || strtolower($info['status']) != 'unsupported'
+                                               || self::isEnabled($addon)
+                                       ) {
+                                               $addons[] = [$addon, (self::isEnabled($addon) ? 'on' : 'off'), $info];
+                                       }
+                               }
+                       }
+               }
+
+               return $addons;
+       }
+
+       /**
+        * Returns a list of addons that can be configured at the node level.
+        * The list is formatted for display in the admin panel aside.
+        *
+        * @return array
+        * @throws \Exception
+        */
+       public static function getAdminList()
+       {
+               $addons_admin = [];
+               $addonsAdminStmt = DBA::select('addon', ['name'], ['plugin_admin' => 1], ['order' => ['name']]);
+               while ($addon = DBA::fetch($addonsAdminStmt)) {
+                       $addons_admin[$addon['name']] = [
+                               'url' => 'admin/addons/' . $addon['name'],
+                               'name' => $addon['name'],
+                               'class' => 'addon'
+                       ];
+               }
+               DBA::close($addonsAdminStmt);
+
+               return $addons_admin;
+       }
+
+
        /**
         * @brief Synchronize addons:
         *
@@ -94,6 +150,8 @@ class Addon extends BaseObject
                }
 
                unset(self::$addons[array_search($addon, self::$addons)]);
+
+               Addon::saveEnabledList();
        }
 
        /**
@@ -136,9 +194,11 @@ class Addon extends BaseObject
                                self::$addons[] = $addon;
                        }
 
+                       Addon::saveEnabledList();
+
                        return true;
                } else {
-                       Logger::error("Addon {addon}: {action} failed", ['action' => 'uninstall', 'addon' => $addon]);
+                       Logger::error("Addon {addon}: {action} failed", ['action' => 'install', 'addon' => $addon]);
                        return false;
                }
        }
@@ -283,11 +343,10 @@ class Addon extends BaseObject
         * Saves the current enabled addon list in the system.addon config key
         *
         * @return boolean
-        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
         */
        public static function saveEnabledList()
        {
-               return Config::set("system", "addon", implode(", ", self::$addons));
+               return Config::set('system', 'addon', implode(',', self::$addons));
        }
 
        /**
index 0cc63a5913fcef016e217a9d44e927c0b27953c4..2893c27b2341e2275b3f2055d84b7e3e4a8b9052 100644 (file)
@@ -2,6 +2,8 @@
 
 namespace Friendica\Core;
 
+use Friendica;
+
 /**
  * Description of Console
  *
@@ -47,24 +49,24 @@ HELP;
        }
 
        protected $subConsoles = [
-               'cache'                  => __NAMESPACE__ . '\Console\Cache',
-               'config'                 => __NAMESPACE__ . '\Console\Config',
-               'createdoxygen'          => __NAMESPACE__ . '\Console\CreateDoxygen',
-               'docbloxerrorchecker'    => __NAMESPACE__ . '\Console\DocBloxErrorChecker',
-               'dbstructure'            => __NAMESPACE__ . '\Console\DatabaseStructure',
-               'extract'                => __NAMESPACE__ . '\Console\Extract',
-               'globalcommunityblock'   => __NAMESPACE__ . '\Console\GlobalCommunityBlock',
-               'globalcommunitysilence' => __NAMESPACE__ . '\Console\GlobalCommunitySilence',
-               'archivecontact'         => __NAMESPACE__ . '\Console\ArchiveContact',
-               'autoinstall'            => __NAMESPACE__ . '\Console\AutomaticInstallation',
-               'maintenance'            => __NAMESPACE__ . '\Console\Maintenance',
-               'newpassword'            => __NAMESPACE__ . '\Console\NewPassword',
-               'php2po'                 => __NAMESPACE__ . '\Console\PhpToPo',
-               'po2php'                 => __NAMESPACE__ . '\Console\PoToPhp',
-               'typo'                   => __NAMESPACE__ . '\Console\Typo',
-               'postupdate'             => __NAMESPACE__ . '\Console\PostUpdate',
-               'serverblock'            => __NAMESPACE__ . '\Console\ServerBlock',
-               'storage'                => __NAMESPACE__ . '\Console\Storage',
+               'cache'                  => Friendica\Console\Cache::class,
+               'config'                 => Friendica\Console\Config::class,
+               'createdoxygen'          => Friendica\Console\CreateDoxygen::class,
+               'docbloxerrorchecker'    => Friendica\Console\DocBloxErrorChecker::class,
+               'dbstructure'            => Friendica\Console\DatabaseStructure::class,
+               'extract'                => Friendica\Console\Extract::class,
+               'globalcommunityblock'   => Friendica\Console\GlobalCommunityBlock::class,
+               'globalcommunitysilence' => Friendica\Console\GlobalCommunitySilence::class,
+               'archivecontact'         => Friendica\Console\ArchiveContact::class,
+               'autoinstall'            => Friendica\Console\AutomaticInstallation::class,
+               'maintenance'            => Friendica\Console\Maintenance::class,
+               'newpassword'            => Friendica\Console\NewPassword::class,
+               'php2po'                 => Friendica\Console\PhpToPo::class,
+               'po2php'                 => Friendica\Console\PoToPhp::class,
+               'typo'                   => Friendica\Console\Typo::class,
+               'postupdate'             => Friendica\Console\PostUpdate::class,
+               'serverblock'            => Friendica\Console\ServerBlock::class,
+               'storage'                => Friendica\Console\Storage::class,
        ];
 
        protected function doExecute()
diff --git a/src/Core/Console/ArchiveContact.php b/src/Core/Console/ArchiveContact.php
deleted file mode 100644 (file)
index b93c079..0000000
+++ /dev/null
@@ -1,75 +0,0 @@
-<?php
-
-namespace Friendica\Core\Console;
-
-use Friendica\Core\L10n;
-use Friendica\Database\DBA;
-use Friendica\Util\Strings;
-use RuntimeException;
-
-/**
- * @brief tool to archive a contact on the server
- *
- * With this tool you can archive a contact when you know that it isn't existing anymore.
- * Normally this does happen automatically after a few days.
- *
- * License: AGPLv3 or later, same as Friendica
- *
- */
-class ArchiveContact extends \Asika\SimpleConsole\Console
-{
-       protected $helpOptions = ['h', 'help', '?'];
-
-       protected function getHelp()
-       {
-               $help = <<<HELP
-console archivecontact - archive a contact
-Usage
-       bin/console archivecontact <profile_url> [-h|--help|-?] [-v]
-
-Description
-       Archive a contact when you know that it isn't existing anymore. Normally this does happen automatically after a few days.
-
-Options
-    -h|--help|-? Show help information
-    -v           Show more debug information.
-HELP;
-               return $help;
-       }
-
-       protected function doExecute()
-       {
-               $a = \Friendica\BaseObject::getApp();
-
-               if ($this->getOption('v')) {
-                       $this->out('Class: ' . __CLASS__);
-                       $this->out('Arguments: ' . var_export($this->args, true));
-                       $this->out('Options: ' . var_export($this->options, true));
-               }
-
-               if (count($this->args) == 0) {
-                       $this->out($this->getHelp());
-                       return 0;
-               }
-
-               if (count($this->args) > 1) {
-                       throw new \Asika\SimpleConsole\CommandArgsException('Too many arguments');
-               }
-
-               if ($a->getMode()->isInstall()) {
-                       throw new RuntimeException('Friendica isn\'t properly installed yet.');
-               }
-
-               $nurl = Strings::normaliseLink($this->getArgument(0));
-               if (!DBA::exists('contact', ['nurl' => $nurl, 'archive' => false])) {
-                       throw new RuntimeException(L10n::t('Could not find any unarchived contact entry for this URL (%s)', $nurl));
-               }
-               if (DBA::update('contact', ['archive' => true], ['nurl' => $nurl])) {
-                       $this->out(L10n::t('The contact entries have been archived'));
-               } else {
-                       throw new RuntimeException('The contact archival failed.');
-               }
-
-               return 0;
-       }
-}
diff --git a/src/Core/Console/AutomaticInstallation.php b/src/Core/Console/AutomaticInstallation.php
deleted file mode 100644 (file)
index e2857d6..0000000
+++ /dev/null
@@ -1,265 +0,0 @@
-<?php
-
-namespace Friendica\Core\Console;
-
-use Asika\SimpleConsole\Console;
-use Friendica\BaseObject;
-use Friendica\Core\Config;
-use Friendica\Core\Installer;
-use Friendica\Core\Theme;
-use Friendica\Util\BasePath;
-use Friendica\Util\BaseURL;
-use Friendica\Util\Config\ConfigFileLoader;
-use RuntimeException;
-
-class AutomaticInstallation extends Console
-{
-       protected function getHelp()
-       {
-               return <<<HELP
-Installation - Install Friendica automatically
-Synopsis
-       bin/console autoinstall [-h|--help|-?] [-v] [-a] [-f]
-
-Description
-    Installs Friendica with data based on the local.config.php file or environment variables
-
-Notes
-    Not checking .htaccess/URL-Rewrite during CLI installation.
-
-Options
-    -h|--help|-?            Show help information
-    -v                      Show more debug information.
-    -a                      All setup checks are required (except .htaccess)
-    -f|--file <config>      prepared config file (e.g. "config/local.config.php" itself) which will override every other config option - except the environment variables)
-    -s|--savedb               Save the DB credentials to the file (if environment variables is used)
-    -H|--dbhost <host>        The host of the mysql/mariadb database (env MYSQL_HOST)
-    -p|--dbport <port>        The port of the mysql/mariadb database (env MYSQL_PORT)
-    -d|--dbdata <database>    The name of the mysql/mariadb database (env MYSQL_DATABASE)
-    -U|--dbuser <username>    The username of the mysql/mariadb database login (env MYSQL_USER or MYSQL_USERNAME)
-    -P|--dbpass <password>    The password of the mysql/mariadb database login (env MYSQL_PASSWORD)
-    -U|--url <url>            The full base URL of Friendica - f.e. 'https://friendica.local/sub' (env FRIENDICA_URL) 
-    -B|--phppath <php_path>   The path of the PHP binary (env FRIENDICA_PHP_PATH)
-    -b|--basepath <base_path> The basepath of Friendica (env FRIENDICA_BASE_PATH)
-    -t|--tz <timezone>        The timezone of Friendica (env FRIENDICA_TZ)
-    -L|--lang <language>      The language of Friendica (env FRIENDICA_LANG)
-Environment variables
-   MYSQL_HOST                  The host of the mysql/mariadb database (mandatory if mysql and environment is used)
-   MYSQL_PORT                  The port of the mysql/mariadb database
-   MYSQL_USERNAME|MYSQL_USER   The username of the mysql/mariadb database login (MYSQL_USERNAME is for mysql, MYSQL_USER for mariadb)
-   MYSQL_PASSWORD              The password of the mysql/mariadb database login
-   MYSQL_DATABASE              The name of the mysql/mariadb database
-   FRIENDICA_URL               The full base URL of Friendica - f.e. 'https://friendica.local/sub'
-   FRIENDICA_PHP_PATH          The path of the PHP binary - leave empty for auto detection
-   FRIENDICA_BASE_PATH         The basepath of Friendica - leave empty for auto detection
-   FRIENDICA_ADMIN_MAIL        The admin email address of Friendica (this email will be used for admin access)
-   FRIENDICA_TZ                The timezone of Friendica
-   FRIENDICA_LANG              The langauge of Friendica
-   
-Examples
-       bin/console autoinstall -f 'input.config.php
-               Installs Friendica with the prepared 'input.config.php' file
-
-       bin/console autoinstall --savedb
-               Installs Friendica with environment variables and saves them to the 'config/local.config.php' file
-
-       bin/console autoinstall -h localhost -p 3365 -U user -P passwort1234 -d friendica
-               Installs Friendica with a local mysql database with credentials
-HELP;
-       }
-
-       protected function doExecute()
-       {
-               // Initialise the app
-               $this->out("Initializing setup...\n");
-
-               $a = BaseObject::getApp();
-
-               $installer = new Installer();
-
-               $configCache = $a->getConfigCache();
-               $installer->setUpCache($configCache, BasePath::create($a->getBasePath(), $_SERVER));
-
-               $this->out(" Complete!\n\n");
-
-               // Check Environment
-               $this->out("Checking environment...\n");
-
-               $installer->resetChecks();
-
-               if (!$this->runBasicChecks($installer, $configCache)) {
-                       $errorMessage = $this->extractErrors($installer->getChecks());
-                       throw new RuntimeException($errorMessage);
-               }
-
-               $this->out(" Complete!\n\n");
-
-               // if a config file is set,
-               $config_file = $this->getOption(['f', 'file']);
-
-               if (!empty($config_file)) {
-                       if ($config_file != 'config' . DIRECTORY_SEPARATOR . 'local.config.php') {
-                               // Copy config file
-                               $this->out("Copying config file...\n");
-                               if (!copy($a->getBasePath() . DIRECTORY_SEPARATOR . $config_file, $a->getBasePath() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.config.php')) {
-                                       throw new RuntimeException("ERROR: Saving config file failed. Please copy '$config_file' to '" . $a->getBasePath() . "'" . DIRECTORY_SEPARATOR . "config" . DIRECTORY_SEPARATOR . "local.config.php' manually.\n");
-                               }
-                       }
-
-                       //reload the config cache
-                       $loader = new ConfigFileLoader($a->getBasePath(), $a->getMode());
-                       $loader->setupCache($configCache);
-
-               } else {
-                       // Creating config file
-                       $this->out("Creating config file...\n");
-
-                       $save_db = $this->getOption(['s', 'savedb'], false);
-
-                       $db_host = $this->getOption(['H', 'dbhost'], ($save_db) ? (getenv('MYSQL_HOST')) : Installer::DEFAULT_HOST);
-                       $db_port = $this->getOption(['p', 'dbport'], ($save_db) ? getenv('MYSQL_PORT') : null);
-                       $configCache->set('database', 'hostname', $db_host . (!empty($db_port) ? ':' . $db_port : ''));
-                       $configCache->set('database', 'database',
-                               $this->getOption(['d', 'dbdata'],
-                                       ($save_db) ? getenv('MYSQL_DATABASE') : ''));
-                       $configCache->set('database', 'username',
-                               $this->getOption(['U', 'dbuser'],
-                                       ($save_db) ? getenv('MYSQL_USER') . getenv('MYSQL_USERNAME') : ''));
-                       $configCache->set('database', 'password',
-                               $this->getOption(['P', 'dbpass'],
-                                       ($save_db) ? getenv('MYSQL_PASSWORD') : ''));
-
-                       $php_path = $this->getOption(['b', 'phppath'], !empty('FRIENDICA_PHP_PATH') ? getenv('FRIENDICA_PHP_PATH') : null);
-                       if (!empty($php_path)) {
-                               $configCache->set('config', 'php_path', $php_path);
-                       } else {
-                               $configCache->set('config', 'php_path', $installer->getPHPPath());
-                       }
-
-                       $configCache->set('config', 'admin_email',
-                               $this->getOption(['A', 'admin'],
-                                       !empty(getenv('FRIENDICA_ADMIN_MAIL')) ? getenv('FRIENDICA_ADMIN_MAIL') : ''));
-                       $configCache->set('system', 'default_timezone',
-                               $this->getOption(['T', 'tz'],
-                                       !empty(getenv('FRIENDICA_TZ')) ? getenv('FRIENDICA_TZ') : Installer::DEFAULT_TZ));
-                       $configCache->set('system', 'language',
-                               $this->getOption(['L', 'lang'],
-                                       !empty(getenv('FRIENDICA_LANG')) ? getenv('FRIENDICA_LANG') : Installer::DEFAULT_LANG));
-
-                       $basepath = $this->getOption(['b', 'basepath'], !empty(getenv('FRIENDICA_BASE_PATH')) ? getenv('FRIENDICA_BASE_PATH') : null);
-                       if (!empty($basepath)) {
-                               $configCache->set('system', 'basepath', $basepath);
-                       }
-
-                       $url = $this->getOption(['U', 'url'], !empty(getenv('FRIENDICA_URL')) ? getenv('FRIENDICA_URL') : null);
-
-                       if (empty($url)) {
-                               $this->out('The Friendica URL has to be set during CLI installation.');
-                               return 1;
-                       } else {
-                               $baseUrl = new BaseURL($a->getConfig(), []);
-                               $baseUrl->saveByURL($url);
-                       }
-
-                       $installer->createConfig($configCache);
-               }
-
-               $this->out(" Complete!\n\n");
-
-               // Check database connection
-               $this->out("Checking database...\n");
-
-               $installer->resetChecks();
-
-               if (!$installer->checkDB($configCache, $a->getProfiler())) {
-                       $errorMessage = $this->extractErrors($installer->getChecks());
-                       throw new RuntimeException($errorMessage);
-               }
-
-               $this->out(" Complete!\n\n");
-
-               // Install database
-               $this->out("Inserting data into database...\n");
-
-               $installer->resetChecks();
-
-               if (!$installer->installDatabase($a->getBasePath())) {
-                       $errorMessage = $this->extractErrors($installer->getChecks());
-                       throw new RuntimeException($errorMessage);
-               }
-
-               $this->out(" Complete!\n\n");
-
-               // Install theme
-               $this->out("Installing theme\n");
-               if (!empty(Config::get('system', 'theme'))) {
-                       Theme::install(Config::get('system', 'theme'));
-                       $this->out(" Complete\n\n");
-               } else {
-                       $this->out(" Theme setting is empty. Please check the file 'config/local.config.php'\n\n");
-               }
-
-               $this->out("\nInstallation is finished\n");
-
-               return 0;
-       }
-
-       /**
-        * @param Installer                 $installer   The Installer instance
-        * @param Config\Cache\IConfigCache $configCache The config cache
-        *
-        * @return bool true if checks were successfully, otherwise false
-        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
-        */
-       private function runBasicChecks(Installer $installer, Config\Cache\IConfigCache $configCache)
-       {
-               $checked = true;
-
-               $installer->resetChecks();
-               if (!$installer->checkFunctions())              {
-                       $checked = false;
-               }
-               if (!$installer->checkImagick()) {
-                       $checked = false;
-               }
-               if (!$installer->checkLocalIni()) {
-                       $checked = false;
-               }
-               if (!$installer->checkSmarty3()) {
-                       $checked = false;
-               }
-               if (!$installer->checkKeys()) {
-                       $checked = false;
-               }
-
-               $php_path = $configCache->get('config', 'php_path');
-
-               if (!$installer->checkPHP($php_path, true)) {
-                       $checked = false;
-               }
-
-               $this->out(" NOTICE: Not checking .htaccess/URL-Rewrite during CLI installation.\n");
-
-               return $checked;
-       }
-
-       /**
-        * @param array $results
-        * @return string
-        */
-       private function extractErrors($results)
-       {
-               $errorMessage = '';
-               $allChecksRequired = $this->getOption('a') !== null;
-
-               foreach ($results as $result) {
-                       if (($allChecksRequired || $result['required'] === true) && $result['status'] === false) {
-                               $errorMessage .= "--------\n";
-                               $errorMessage .= $result['title'] . ': ' . $result['help'] . "\n";
-                       }
-               }
-
-               return $errorMessage;
-       }
-}
diff --git a/src/Core/Console/Cache.php b/src/Core/Console/Cache.php
deleted file mode 100644 (file)
index 510c05b..0000000
+++ /dev/null
@@ -1,178 +0,0 @@
-<?php
-
-namespace Friendica\Core\Console;
-
-use Asika\SimpleConsole\CommandArgsException;
-use Friendica\App;
-use Friendica\Core;
-use RuntimeException;
-
-/**
- * @brief tool to access the cache from the CLI
- *
- * With this script you can access the cache of your node from the CLI.
- * You can read current values stored in the cache and set new values
- * in cache keys.
- *
- * @author Hypolite Petovan <hypolite@mrpetovan.com>
- */
-class Cache extends \Asika\SimpleConsole\Console
-{
-       protected $helpOptions = ['h', 'help', '?'];
-
-       protected function getHelp()
-       {
-               $help = <<<HELP
-console cache - Manage node cache
-Synopsis
-       bin/console cache list [-h|--help|-?] [-v]
-       bin/console cache get <key> [-h|--help|-?] [-v]
-       bin/console cache set <key> <value> [-h|--help|-?] [-v]
-       bin/console cache flush [-h|--help|-?] [-v]
-       bin/console cache clear [-h|--help|-?] [-v]
-
-Description
-       bin/console cache list [<prefix>]
-               List all cache keys, optionally filtered by a prefix
-
-       bin/console cache get <key>
-               Shows the value of the provided cache key
-
-       bin/console cache set <key> <value> [<ttl>]
-               Sets the value of the provided cache key, optionally with the provided TTL (time to live) with a default of five minutes.
-
-       bin/console cache flush
-               Clears expired cache keys
-
-       bin/console cache clear
-               Clears all cache keys
-
-Options
-    -h|--help|-? Show help information
-    -v           Show more debug information.
-HELP;
-               return $help;
-       }
-
-       protected function doExecute()
-       {
-               $a = \Friendica\BaseObject::getApp();
-
-               if ($this->getOption('v')) {
-                       $this->out('Executable: ' . $this->executable);
-                       $this->out('Class: ' . __CLASS__);
-                       $this->out('Arguments: ' . var_export($this->args, true));
-                       $this->out('Options: ' . var_export($this->options, true));
-               }
-
-               if ($a->getMode()->has(App\Mode::DBCONFIGAVAILABLE)) {
-                       $this->out('Database isn\'t ready or populated yet, database cache won\'t be available');
-               }
-
-               Core\Cache::init();
-
-               if ($this->getOption('v')) {
-                       $this->out('Cache Driver Name: ' . Core\Cache::$driver_name);
-                       $this->out('Cache Driver Class: ' . Core\Cache::$driver_class);
-               }
-
-               switch ($this->getArgument(0)) {
-                       case 'list':
-                               $this->executeList();
-                               break;
-                       case 'get':
-                               $this->executeGet();
-                               break;
-                       case 'set':
-                               $this->executeSet();
-                               break;
-                       case 'flush':
-                               $this->executeFlush();
-                               break;
-                       case 'clear':
-                               $this->executeClear();
-                               break;
-               }
-
-               if (count($this->args) == 0) {
-                       $this->out($this->getHelp());
-                       return 0;
-               }
-
-               return 0;
-       }
-
-       private function executeList()
-       {
-               $prefix = $this->getArgument(1);
-               $keys = Core\Cache::getAllKeys($prefix);
-
-               if (empty($prefix)) {
-                       $this->out('Listing all cache keys:');
-               } else {
-                       $this->out('Listing all cache keys starting with "' . $prefix . '":');
-               }
-
-               $count = 0;
-               foreach ($keys as $key) {
-                       $this->out($key);
-                       $count++;
-               }
-
-               $this->out($count . ' keys found');
-       }
-
-       private function executeGet()
-       {
-               if (count($this->args) >= 2) {
-                       $key = $this->getArgument(1);
-                       $value = Core\Cache::get($key);
-
-                       $this->out("{$key} => " . var_export($value, true));
-               } else {
-                       throw new CommandArgsException('Too few arguments for get');
-               }
-       }
-
-       private function executeSet()
-       {
-               if (count($this->args) >= 3) {
-                       $key = $this->getArgument(1);
-                       $value = $this->getArgument(2);
-                       $duration = intval($this->getArgument(3, Core\Cache::FIVE_MINUTES));
-
-                       if (is_array(Core\Cache::get($key))) {
-                               throw new RuntimeException("$key is an array and can't be set using this command.");
-                       }
-
-                       $result = Core\Cache::set($key, $value, $duration);
-                       if ($result) {
-                               $this->out("{$key} <= " . Core\Cache::get($key));
-                       } else {
-                               $this->out("Unable to set {$key}");
-                       }
-               } else {
-                       throw new CommandArgsException('Too few arguments for set');
-               }
-       }
-
-       private function executeFlush()
-       {
-               $result = Core\Cache::clear();
-               if ($result) {
-                       $this->out('Cache successfully flushed');
-               } else {
-                       $this->out('Unable to flush the cache');
-               }
-       }
-
-       private function executeClear()
-       {
-               $result = Core\Cache::clear(false);
-               if ($result) {
-                       $this->out('Cache successfully cleared');
-               } else {
-                       $this->out('Unable to flush the cache');
-               }
-       }
-}
diff --git a/src/Core/Console/Config.php b/src/Core/Console/Config.php
deleted file mode 100644 (file)
index cf5c09f..0000000
+++ /dev/null
@@ -1,171 +0,0 @@
-<?php
-
-namespace Friendica\Core\Console;
-
-use Asika\SimpleConsole\CommandArgsException;
-use Friendica\App;
-use Friendica\Core;
-use RuntimeException;
-
-/**
- * @brief tool to access the system config from the CLI
- *
- * With this script you can access the system configuration of your node from
- * the CLI. You can do both, reading current values stored in the database and
- * set new values to config variables.
- *
- * Usage:
- *   If you specify no parameters at the CLI, the script will list all config
- *   variables defined.
- *
- *   If you specify one parameter, the script will list all config variables
- *   defined in this section of the configuration (e.g. "system").
- *
- *   If you specify two parameters, the script will show you the current value
- *   of the named configuration setting. (e.g. "system loglevel")
- *
- *   If you specify three parameters, the named configuration setting will be
- *   set to the value of the last parameter. (e.g. "system loglevel 0" will
- *   disable logging)
- *
- * @author Tobias Diekershoff <tobias.diekershoff@gmx.net>
- * @author Hypolite Petovan <hypolite@mrpetovan.com>
- */
-class Config extends \Asika\SimpleConsole\Console
-{
-       protected $helpOptions = ['h', 'help', '?'];
-
-       protected function getHelp()
-       {
-               $help = <<<HELP
-console config - Manage site configuration
-Synopsis
-       bin/console config [-h|--help|-?] [-v]
-       bin/console config <category> [-h|--help|-?] [-v]
-       bin/console config <category> <key> [-h|--help|-?] [-v]
-       bin/console config <category> <key> <value> [-h|--help|-?] [-v]
-
-Description
-       bin/console config
-               Lists all config values
-
-       bin/console config <category>
-               Lists all config values in the provided category
-
-       bin/console config <category> <key>
-               Shows the value of the provided key in the category
-
-       bin/console config <category> <key> <value>
-               Sets the value of the provided key in the category
-
-Notes:
-       Setting config entries which are manually set in config/local.config.php may result in
-       conflict between database settings and the manual startup settings.
-
-Options
-    -h|--help|-? Show help information
-    -v           Show more debug information.
-HELP;
-               return $help;
-       }
-
-       protected function doExecute()
-       {
-               $a = \Friendica\BaseObject::getApp();
-
-               if ($this->getOption('v')) {
-                       $this->out('Executable: ' . $this->executable);
-                       $this->out('Class: ' . __CLASS__);
-                       $this->out('Arguments: ' . var_export($this->args, true));
-                       $this->out('Options: ' . var_export($this->options, true));
-               }
-
-               if (count($this->args) > 3) {
-                       throw new CommandArgsException('Too many arguments');
-               }
-
-               if (!$a->getMode()->has(App\Mode::DBCONFIGAVAILABLE)) {
-                       $this->out('Database isn\'t ready or populated yet, showing file config only');
-               }
-
-               if (count($this->args) == 3) {
-                       $cat = $this->getArgument(0);
-                       $key = $this->getArgument(1);
-                       $value = $this->getArgument(2);
-
-                       if (is_array(Core\Config::get($cat, $key))) {
-                               throw new RuntimeException("$cat.$key is an array and can't be set using this command.");
-                       }
-
-                       $result = Core\Config::set($cat, $key, $value);
-                       if ($result) {
-                               $this->out("{$cat}.{$key} <= " .
-                                       Core\Config::get($cat, $key));
-                       } else {
-                               $this->out("Unable to set {$cat}.{$key}");
-                       }
-               }
-
-               if (count($this->args) == 2) {
-                       $cat = $this->getArgument(0);
-                       $key = $this->getArgument(1);
-                       $value = Core\Config::get($this->getArgument(0), $this->getArgument(1));
-
-                       if (is_array($value)) {
-                               foreach ($value as $k => $v) {
-                                       $this->out("{$cat}.{$key}[{$k}] => " . (is_array($v) ? implode(', ', $v) : $v));
-                               }
-                       } else {
-                               $this->out("{$cat}.{$key} => " . $value);
-                       }
-               }
-
-               if (count($this->args) == 1) {
-                       $cat = $this->getArgument(0);
-                       Core\Config::load($cat);
-
-                       if ($a->getConfigCache()->get($cat) !== null) {
-                               $this->out("[{$cat}]");
-                               $catVal = $a->getConfigCache()->get($cat);
-                               foreach ($catVal as $key => $value) {
-                                       if (is_array($value)) {
-                                               foreach ($value as $k => $v) {
-                                                       $this->out("{$key}[{$k}] => " . (is_array($v) ? implode(', ', $v) : $v));
-                                               }
-                                       } else {
-                                               $this->out("{$key} => " . $value);
-                                       }
-                               }
-                       } else {
-                               $this->out('Config section ' . $this->getArgument(0) . ' returned nothing');
-                       }
-               }
-
-               if (count($this->args) == 0) {
-                       Core\Config::load();
-
-                       if (Core\Config::get('system', 'config_adapter') == 'jit' && $a->getMode()->has(App\Mode::DBCONFIGAVAILABLE)) {
-                               $this->out('Warning: The JIT (Just In Time) Config adapter doesn\'t support loading the entire configuration, showing file config only');
-                       }
-
-                       $config = $a->getConfigCache()->getAll();
-                       foreach ($config as $cat => $section) {
-                               if (is_array($section)) {
-                                       foreach ($section as $key => $value) {
-                                               if (is_array($value)) {
-                                                       foreach ($value as $k => $v) {
-                                                               $this->out("{$cat}.{$key}[{$k}] => " . (is_array($v) ? implode(', ', $v) : $v));
-                                                       }
-                                               } else {
-                                                       $this->out("{$cat}.{$key} => " . $value);
-                                               }
-                                       }
-                               } else {
-                                       $this->out("config.{$cat} => " . $section);
-                               }
-                       }
-               }
-
-               return 0;
-       }
-}
diff --git a/src/Core/Console/CreateDoxygen.php b/src/Core/Console/CreateDoxygen.php
deleted file mode 100644 (file)
index 1de2cee..0000000
+++ /dev/null
@@ -1,148 +0,0 @@
-<?php
-
-namespace Friendica\Core\Console;
-
-/**
- * Description of CreateDoxygen
- *
- * @author Hypolite Petovan <hypolite@mrpetovan.com>
- */
-class CreateDoxygen extends \Asika\SimpleConsole\Console
-{
-       protected $helpOptions = ['h', 'help', '?'];
-
-       protected function getHelp()
-       {
-               $help = <<<HELP
-console createdoxygen - Generate Doxygen headers
-Usage
-       bin/console createdoxygen <file> [-h|--help|-?] [-v]
-
-Description
-       Outputs the provided file with added Doxygen headers to functions
-
-Options
-    -h|--help|-? Show help information
-    -v           Show more debug information.
-HELP;
-               return $help;
-       }
-
-       protected function doExecute()
-       {
-               if ($this->getOption('v')) {
-                       $this->out('Class: ' . __CLASS__);
-                       $this->out('Arguments: ' . var_export($this->args, true));
-                       $this->out('Options: ' . var_export($this->options, true));
-               }
-
-               if (count($this->args) == 0) {
-                       $this->out($this->getHelp());
-                       return 0;
-               }
-
-               if (count($this->args) > 1) {
-                       throw new \Asika\SimpleConsole\CommandArgsException('Too many arguments');
-               }
-
-               $file = $this->getArgument(0);
-               if (!file_exists($file)) {
-                       throw new \RuntimeException('Unable to find specified file.');
-               }
-
-               $data = file_get_contents($file);
-
-               $lines = explode("\n", $data);
-
-               $previous = "";
-
-               foreach ($lines AS $line) {
-                       $line = rtrim(trim($line, "\r"));
-
-                       if (strstr(strtolower($line), "function")) {
-                               $detect = strtolower(trim($line));
-                               $detect = implode(" ", explode(" ", $detect));
-
-                               $found = false;
-
-                               if (substr($detect, 0, 9) == "function ") {
-                                       $found = true;
-                               }
-
-                               if (substr($detect, 0, 19) == "protected function ") {
-                                       $found = true;
-                               }
-
-                               if (substr($detect, 0, 17) == "private function ") {
-                                       $found = true;
-                               }
-
-                               if (substr($detect, 0, 23) == "public static function ") {
-                                       $found = true;
-                               }
-
-                               if (substr($detect, 0, 24) == "private static function ") {
-                                       $found = true;
-                               }
-
-                               if (substr($detect, 0, 10) == "function (") {
-                                       $found = false;
-                               }
-
-                               if ($found && ( trim($previous) == "*/")) {
-                                       $found = false;
-                               }
-
-                               if ($found) {
-                                       $this->out($this->addDocumentation($line));
-                               }
-                       }
-                       $this->out($line);
-                       $previous = $line;
-               }
-
-               return 0;
-       }
-
-       /**
-        * @brief Adds a doxygen header
-        *
-        * @param string $line The current line of the document
-        *
-        * @return string added doxygen header
-        */
-       private function addDocumentation($line)
-       {
-               $trimmed = ltrim($line);
-               $length = strlen($line) - strlen($trimmed);
-               $space = substr($line, 0, $length);
-
-               $block = $space . "/**\n" .
-                       $space . " * @brief \n" .
-                       $space . " *\n"; /**/
-
-
-               $left = strpos($line, "(");
-               $line = substr($line, $left + 1);
-
-               $right = strpos($line, ")");
-               $line = trim(substr($line, 0, $right));
-
-               if ($line != "") {
-                       $parameters = explode(",", $line);
-                       foreach ($parameters AS $parameter) {
-                               $parameter = trim($parameter);
-                               $splitted = explode("=", $parameter);
-
-                               $block .= $space . " * @param " . trim($splitted[0], "& ") . "\n";
-                       }
-                       if (count($parameters) > 0) $block .= $space . " *\n";
-               }
-
-               $block .= $space . " * @return \n" .
-                       $space . " */\n";
-
-               return $block;
-       }
-
-}
diff --git a/src/Core/Console/DatabaseStructure.php b/src/Core/Console/DatabaseStructure.php
deleted file mode 100644 (file)
index dededa9..0000000
+++ /dev/null
@@ -1,94 +0,0 @@
-<?php
-
-namespace Friendica\Core\Console;
-
-use Friendica\Core;
-use Friendica\Core\Update;
-use Friendica\Database\DBA;
-use Friendica\Database\DBStructure;
-use RuntimeException;
-
-/**
- * @brief Performs database updates from the command line
- *
- * @author Hypolite Petovan <hypolite@mrpetovan.com>
- */
-class DatabaseStructure extends \Asika\SimpleConsole\Console
-{
-       protected $helpOptions = ['h', 'help', '?'];
-
-       protected function getHelp()
-       {
-               $help = <<<HELP
-console dbstructure - Performs database updates
-Usage
-       bin/console dbstructure <command> [-h|--help|-?] |-f|--force] [-v]
-
-Commands
-       dryrun   Show database update schema queries without running them
-       update   Update database schema
-       dumpsql  Dump database schema
-       toinnodb Convert all tables from MyISAM to InnoDB
-
-Options
-    -h|--help|-?       Show help information
-    -v                 Show more debug information.
-    -f|--force         Force the update command (Even if the database structure matches)
-    -o|--override      Override running or stalling updates
-HELP;
-               return $help;
-       }
-
-       protected function doExecute()
-       {
-               if ($this->getOption('v')) {
-                       $this->out('Class: ' . __CLASS__);
-                       $this->out('Arguments: ' . var_export($this->args, true));
-                       $this->out('Options: ' . var_export($this->options, true));
-               }
-
-               if (count($this->args) == 0) {
-                       $this->out($this->getHelp());
-                       return 0;
-               }
-
-               if (count($this->args) > 1) {
-                       throw new \Asika\SimpleConsole\CommandArgsException('Too many arguments');
-               }
-
-               if (!DBA::connected()) {
-                       throw new RuntimeException('Unable to connect to database');
-               }
-
-               Core\Config::load();
-
-               $a = get_app();
-
-               switch ($this->getArgument(0)) {
-                       case "dryrun":
-                               $output = DBStructure::update($a->getBasePath(), true, false);
-                               break;
-                       case "update":
-                               $force    = $this->getOption(['f', 'force'], false);
-                               $override = $this->getOption(['o', 'override'], false);
-                               $output = Update::run($a->getBasePath(), $force, $override,true, false);
-                               break;
-                       case "dumpsql":
-                               ob_start();
-                               DBStructure::printStructure($a->getBasePath());
-                               $output = ob_get_clean();
-                               break;
-                       case "toinnodb":
-                               ob_start();
-                               DBStructure::convertToInnoDB();
-                               $output = ob_get_clean();
-                               break;
-                       default:
-                               $output = 'Unknown command: ' . $this->getArgument(0);
-               }
-
-               $this->out($output);
-
-               return 0;
-       }
-}
diff --git a/src/Core/Console/DocBloxErrorChecker.php b/src/Core/Console/DocBloxErrorChecker.php
deleted file mode 100644 (file)
index 506e48f..0000000
+++ /dev/null
@@ -1,186 +0,0 @@
-<?php
-
-namespace Friendica\Core\Console;
-
-/**
- * When I installed docblox, I had the experience that it does not generate any output at all.
- * This script may be used to find that kind of problems with the documentation build process.
- * If docblox generates output, use another approach for debugging.
- *
- * Basically, docblox takes a list of files to build documentation from. This script assumes there is a file or set of files
- * breaking the build when it is included in that list. It tries to calculate the smallest list containing these files.
- * Unfortunatly, the original problem is NP-complete, so what the script does is a best guess only.
- *
- * So it starts with a list of all files in the project.
- * If that list can't be build, it cuts it in two parts and tries both parts independently. If only one of them breaks,
- * it takes that one and tries the same independently. If both break, it assumes this is the smallest set. This assumption
- * is not necessarily true. Maybe the smallest set consists of two files and both of them were in different parts when
- * the list was divided, but by now it is my best guess. To make this assumption better, the list is shuffled after every step.
- *
- * After that, the script tries to remove a file from the list. It tests if the list breaks and if so, it
- * assumes that the file it removed belongs to the set of erroneous files.
- * This is done for all files, so, in the end removing one file leads to a working doc build.
- *
- * @author Alexander Kampmann
- * @author Hypolite Petovan <hypolite@mrpetovan.com>
- */
-class DocBloxErrorChecker extends \Asika\SimpleConsole\Console
-{
-
-       protected $helpOptions = ['h', 'help', '?'];
-
-       protected function getHelp()
-       {
-               $help = <<<HELP
-console docbloxerrorchecker - Checks the file tree for docblox errors
-Usage
-       bin/console docbloxerrorchecker [-h|--help|-?] [-v]
-
-Options
-    -h|--help|-? Show help information
-    -v           Show more debug information.
-HELP;
-               return $help;
-       }
-
-       protected function doExecute()
-       {
-               if ($this->getOption('v')) {
-                       $this->out('Class: ' . __CLASS__);
-                       $this->out('Arguments: ' . var_export($this->args, true));
-                       $this->out('Options: ' . var_export($this->options, true));
-               }
-
-               if (count($this->args) > 0) {
-                       throw new \Asika\SimpleConsole\CommandArgsException('Too many arguments');
-               }
-
-               if (!$this->commandExists('docblox')) {
-                       throw new \RuntimeException('DocBlox isn\'t available.');
-               }
-
-               $dir = \get_app()->getBasePath();
-
-               //stack for dirs to search
-               $dirstack = [];
-               //list of source files
-               $filelist = [];
-
-               //loop over all files in $dir
-               while ($dh = opendir($dir)) {
-                       while ($file = readdir($dh)) {
-                               if (is_dir($dir . "/" . $file)) {
-                                       //add to directory stack
-                                       if (strpos($file, '.') !== 0) {
-                                               array_push($dirstack, $dir . "/" . $file);
-                                               $this->out('dir ' . $dir . '/' . $file);
-                                       }
-                               } else {
-                                       //test if it is a source file and add to filelist
-                                       if (substr($file, strlen($file) - 4) == ".php") {
-                                               array_push($filelist, $dir . "/" . $file);
-                                               $this->out($dir . '/' . $file);
-                                       }
-                               }
-                       }
-                       //look at the next dir
-                       $dir = array_pop($dirstack);
-               }
-
-               //check the entire set
-               if ($this->runs($filelist)) {
-                       throw new \RuntimeException("I can not detect a problem.");
-               }
-
-               //check half of the set and discard if that half is okay
-               $res = $filelist;
-               $i = count($res);
-               do {
-                       $this->out($i . '/' . count($filelist) . ' elements remaining.');
-                       $res = $this->reduce($res, count($res) / 2);
-                       shuffle($res);
-                       $i = count($res);
-               } while (count($res) < $i);
-
-               //check one file after another
-               $needed = [];
-
-               while (count($res) != 0) {
-                       $file = array_pop($res);
-
-                       if ($this->runs(array_merge($res, $needed))) {
-                               $this->out('needs: ' . $file . ' and file count ' . count($needed));
-                               array_push($needed, $file);
-                       }
-               }
-
-               $this->out('Smallest Set is: ' . $this->namesList($needed) . ' with ' . count($needed) . ' files. ');
-
-               return 0;
-       }
-
-       private function commandExists($command)
-       {
-               $prefix = strpos(strtolower(PHP_OS),'win') > -1 ? 'where' : 'which';
-               exec("{$prefix} {$command}", $output, $returnVal);
-               return $returnVal === 0;
-       }
-
-       /**
-        * This function generates a comma separated list of file names.
-        *
-        * @param array $fileset Set of file names
-        *
-        * @return string comma-separated list of the file names
-        */
-       private function namesList($fileset)
-       {
-               return implode(',', $fileset);
-       }
-
-       /**
-        * This functions runs phpdoc on the provided list of files
-        *
-        * @param array $fileset Set of filenames
-        *
-        * @return bool true, if that set can be built
-        */
-       private function runs($fileset)
-       {
-               $fsParam = $this->namesList($fileset);
-               $this->exec('docblox -t phpdoc_out -f ' . $fsParam);
-               if (file_exists("phpdoc_out/index.html")) {
-                       $this->out('Subset ' . $fsParam . ' is okay.');
-                       $this->exec('rm -r phpdoc_out');
-                       return true;
-               } else {
-                       $this->out('Subset ' . $fsParam . ' failed.');
-                       return false;
-               }
-       }
-
-       /**
-        * This functions cuts down a fileset by removing files until it finally works.
-        * it was meant to be recursive, but php's maximum stack size is to small. So it just simulates recursion.
-        *
-        * In that version, it does not necessarily generate the smallest set, because it may not alter the elements order enough.
-        *
-        * @param array $fileset set of filenames
-        * @param int $ps number of files in subsets
-        *
-        * @return array a part of $fileset, that crashes
-        */
-       private function reduce($fileset, $ps)
-       {
-               //split array...
-               $parts = array_chunk($fileset, $ps);
-               //filter working subsets...
-               $parts = array_filter($parts, [$this, 'runs']);
-               //melt remaining parts together
-               if (is_array($parts)) {
-                       return array_reduce($parts, "array_merge", []);
-               }
-               return [];
-       }
-
-}
diff --git a/src/Core/Console/Extract.php b/src/Core/Console/Extract.php
deleted file mode 100644 (file)
index e7c751f..0000000
+++ /dev/null
@@ -1,140 +0,0 @@
-<?php
-
-namespace Friendica\Core\Console;
-
-/**
- * Extracts translation strings from the Friendica project's files to be exported
- * to Transifex for translation.
- *
- * Outputs a PHP file with language strings used by Friendica
- *
- * @author Hypolite Petovan <hypolite@mrpetovan.com>
- */
-class Extract extends \Asika\SimpleConsole\Console
-{
-       protected $helpOptions = ['h', 'help', '?'];
-
-       protected function getHelp()
-       {
-               $help = <<<HELP
-console extract - Generate translation string file for the Friendica project (deprecated)
-Usage
-       bin/console extract [-h|--help|-?] [-v]
-
-Description
-       This script was used to generate the translation string file to be exported to Transifex,
-       please use bin/run_xgettext.sh instead
-
-Options
-    -h|--help|-? Show help information
-    -v           Show more debug information.
-HELP;
-               return $help;
-       }
-
-       protected function doExecute()
-       {
-               if ($this->getOption('v')) {
-                       $this->out('Class: ' . __CLASS__);
-                       $this->out('Arguments: ' . var_export($this->args, true));
-                       $this->out('Options: ' . var_export($this->options, true));
-               }
-
-               if (count($this->args) > 0) {
-                       throw new \Asika\SimpleConsole\CommandArgsException('Too many arguments');
-               }
-
-               $s = '<?php' . PHP_EOL;
-               $s .= '
-               function string_plural_select($n){
-                       return ($n != 1);
-               }
-
-               ';
-
-               $arr = [];
-
-               $files = array_merge(
-                       ['index.php', 'boot.php'],
-                       glob('mod/*'),
-                       glob('include/*'),
-                       glob('addon/*/*'),
-                       $this->globRecursive('src')
-               );
-
-               foreach ($files as $file) {
-                       $str = file_get_contents($file);
-
-                       $pat = '|L10n::t\(([^\)]*+)[\)]|';
-                       $patt = '|L10n::tt\(([^\)]*+)[\)]|';
-
-                       $matches = [];
-                       $matchestt = [];
-
-                       preg_match_all($pat, $str, $matches);
-                       preg_match_all($patt, $str, $matchestt);
-
-                       if (count($matches) || count($matchestt)) {
-                               $s .= '// ' . $file . PHP_EOL;
-                       }
-
-                       if (!empty($matches[1])) {
-                               foreach ($matches[1] as $long_match) {
-                                       $match_arr = preg_split('/(?<=[\'"])\s*,/', $long_match);
-                                       $match = $match_arr[0];
-                                       if (!in_array($match, $arr)) {
-                                               if (substr($match, 0, 1) == '$') {
-                                                       continue;
-                                               }
-
-                                               $arr[] = $match;
-
-                                               $s .= '$a->strings[' . $match . '] = ' . $match . ';' . "\n";
-                                       }
-                               }
-                       }
-                       if (!empty($matchestt[1])) {
-                               foreach ($matchestt[1] as $match) {
-                                       $matchtkns = preg_split("|[ \t\r\n]*,[ \t\r\n]*|", $match);
-                                       if (count($matchtkns) == 3 && !in_array($matchtkns[0], $arr)) {
-                                               if (substr($matchtkns[1], 0, 1) == '$') {
-                                                       continue;
-                                               }
-
-                                               $arr[] = $matchtkns[0];
-
-                                               $s .= '$a->strings[' . $matchtkns[0] . "] = array(\n";
-                                               $s .= "\t0 => " . $matchtkns[0] . ",\n";
-                                               $s .= "\t1 => " . $matchtkns[1] . ",\n";
-                                               $s .= ");\n";
-                                       }
-                               }
-                       }
-               }
-
-               $s .= '// Timezones' . PHP_EOL;
-
-               $zones = timezone_identifiers_list();
-               foreach ($zones as $zone) {
-                       $s .= '$a->strings[\'' . $zone . '\'] = \'' . $zone . '\';' . "\n";
-               }
-
-               $this->out($s);
-
-               return 0;
-       }
-
-       private function globRecursive($path) {
-               $dir_iterator = new \RecursiveDirectoryIterator($path);
-               $iterator = new \RecursiveIteratorIterator($dir_iterator, \RecursiveIteratorIterator::SELF_FIRST);
-
-               $return = [];
-               foreach ($iterator as $file) {
-                       if ($file->getBasename() != '.' && $file->getBasename() != '..') {
-                               $return[] = $file->getPathname();
-                       }
-               }
-
-               return $return;
-       }
-}
diff --git a/src/Core/Console/GlobalCommunityBlock.php b/src/Core/Console/GlobalCommunityBlock.php
deleted file mode 100644 (file)
index d99d99c..0000000
+++ /dev/null
@@ -1,75 +0,0 @@
-<?php
-
-namespace Friendica\Core\Console;
-
-use Friendica\Core\L10n;
-use Friendica\Model\Contact;
-
-/**
- * @brief tool to block an account from the node
- *
- * With this tool, you can block an account in such a way, that no postings
- * or comments this account writes are accepted to the node.
- *
- * License: AGPLv3 or later, same as Friendica
- *
- * @author Tobias Diekershoff <tobias.diekershoff@gmx.net>
- * @author Hypolite Petovan <hypolite@mrpetovan.com>
- */
-class GlobalCommunityBlock extends \Asika\SimpleConsole\Console
-{
-       protected $helpOptions = ['h', 'help', '?'];
-
-       protected function getHelp()
-       {
-               $help = <<<HELP
-console globalcommunityblock - Block remote profile from interacting with this node
-Usage
-       bin/console globalcommunityblock <profile_url> [-h|--help|-?] [-v]
-
-Description
-       Blocks an account in such a way that no postings or comments this account writes are accepted to this node.
-
-Options
-    -h|--help|-? Show help information
-    -v           Show more debug information.
-HELP;
-               return $help;
-       }
-
-       protected function doExecute()
-       {
-               $a = \get_app();
-
-               if ($this->getOption('v')) {
-                       $this->out('Class: ' . __CLASS__);
-                       $this->out('Arguments: ' . var_export($this->args, true));
-                       $this->out('Options: ' . var_export($this->options, true));
-               }
-
-               if (count($this->args) == 0) {
-                       $this->out($this->getHelp());
-                       return 0;
-               }
-
-               if (count($this->args) > 1) {
-                       throw new \Asika\SimpleConsole\CommandArgsException('Too many arguments');
-               }
-
-               if ($a->getMode()->isInstall()) {
-                       throw new \RuntimeException('Database isn\'t ready or populated yet');
-               }
-
-               $contact_id = Contact::getIdForURL($this->getArgument(0));
-               if (!$contact_id) {
-                       throw new \RuntimeException(L10n::t('Could not find any contact entry for this URL (%s)', $this->getArgument(0)));
-               }
-               if(Contact::block($contact_id)) {
-                       $this->out(L10n::t('The contact has been blocked from the node'));
-               } else {
-                       throw new \RuntimeException('The contact block failed.');
-               }
-
-               return 0;
-       }
-}
diff --git a/src/Core/Console/GlobalCommunitySilence.php b/src/Core/Console/GlobalCommunitySilence.php
deleted file mode 100644 (file)
index b028124..0000000
+++ /dev/null
@@ -1,92 +0,0 @@
-<?php
-
-namespace Friendica\Core\Console;
-
-use Friendica\Core\Protocol;
-use Friendica\Database\DBA;
-use Friendica\Network\Probe;
-use Friendica\Util\Strings;
-use RuntimeException;
-
-/**
- * @brief tool to silence accounts on the global community page
- *
- * With this tool, you can silence an account on the global community page.
- * Postings from silenced accounts will not be displayed on the community
- * page. This silencing does only affect the display on the community page,
- * accounts following the silenced accounts will still get their postings.
- *
- * License: AGPLv3 or later, same as Friendica
- *
- * @author Tobias Diekershoff <tobias.diekershoff@gmx.net>
- * @author Hypolite Petovan <hypolite@mrpetovan.com>
- */
-class GlobalCommunitySilence extends \Asika\SimpleConsole\Console
-{
-       protected $helpOptions = ['h', 'help', '?'];
-
-       protected function getHelp()
-       {
-               $help = <<<HELP
-console globalcommunitysilence - Silence remote profile from global community page
-Usage
-       bin/console globalcommunitysilence <profile_url> [-h|--help|-?] [-v]
-
-Description
-       With this tool, you can silence an account on the global community page.
-       Postings from silenced accounts will not be displayed on the community page.
-       This silencing does only affect the display on the community page, accounts
-       following the silenced accounts will still get their postings.
-
-Options
-    -h|--help|-? Show help information
-    -v           Show more debug information.
-HELP;
-               return $help;
-       }
-
-       protected function doExecute()
-       {
-               $a = \get_app();
-
-               if ($this->getOption('v')) {
-                       $this->out('Class: ' . __CLASS__);
-                       $this->out('Arguments: ' . var_export($this->args, true));
-                       $this->out('Options: ' . var_export($this->options, true));
-               }
-
-               if (count($this->args) == 0) {
-                       $this->out($this->getHelp());
-                       return 0;
-               }
-
-               if (count($this->args) > 1) {
-                       throw new \Asika\SimpleConsole\CommandArgsException('Too many arguments');
-               }
-
-               if ($a->getMode()->isInstall()) {
-                       throw new RuntimeException('Database isn\'t ready or populated yet');
-               }
-
-               /**
-                * 1. make nurl from last parameter
-                * 2. check DB (contact) if there is a contact with uid=0 and that nurl, get the ID
-                * 3. set the flag hidden=1 for the contact entry with the found ID
-                * */
-               $net = Probe::uri($this->getArgument(0));
-               if (in_array($net['network'], [Protocol::PHANTOM, Protocol::MAIL])) {
-                       throw new RuntimeException('This account seems not to exist.');
-               }
-
-               $nurl = Strings::normaliseLink($net['url']);
-               $contact = DBA::selectFirst("contact", ["id"], ["nurl" => $nurl, "uid" => 0]);
-               if (DBA::isResult($contact)) {
-                       DBA::update("contact", ["hidden" => true], ["id" => $contact["id"]]);
-                       $this->out('NOTICE: The account should be silenced from the global community page');
-               } else {
-                       throw new RuntimeException('NOTICE: Could not find any entry for this URL (' . $nurl . ')');
-               }
-
-               return 0;
-       }
-}
diff --git a/src/Core/Console/Maintenance.php b/src/Core/Console/Maintenance.php
deleted file mode 100644 (file)
index 0cb0da9..0000000
+++ /dev/null
@@ -1,95 +0,0 @@
-<?php
-
-namespace Friendica\Core\Console;
-
-use Friendica\Core;
-
-/**
- * @brief Sets maintenance mode for this node
- *
- * @author Hypolite Petovan <hypolite@mrpetovan.com>
- */
-class Maintenance extends \Asika\SimpleConsole\Console
-{
-       protected $helpOptions = ['h', 'help', '?'];
-
-       protected function getHelp()
-       {
-               $help = <<<HELP
-console maintenance - Sets maintenance mode for this node
-Usage
-       bin/console maintenance <enable> [<reason>] [-h|--help|-?] [-v]
-
-Description
-       <enable> cen be either 0 or 1 to disabled or enable the maintenance mode on this node.
-
-       <reason> is a quote-enclosed string with the optional reason for the maintenance mode.
-
-Examples
-       bin/console maintenance 1
-               Enables the maintenance mode without setting a reason message
-
-       bin/console maintenance 1 "SSL certification update"
-               Enables the maintenance mode with setting a reason message
-
-       bin/console maintenance 0
-               Disables the maintenance mode
-
-Options
-    -h|--help|-? Show help information
-    -v           Show more debug information.
-HELP;
-               return $help;
-       }
-
-       protected function doExecute()
-       {
-               $a = \Friendica\BaseObject::getApp();
-
-               if ($this->getOption('v')) {
-                       $this->out('Class: ' . __CLASS__);
-                       $this->out('Arguments: ' . var_export($this->args, true));
-                       $this->out('Options: ' . var_export($this->options, true));
-               }
-
-               if (count($this->args) == 0) {
-                       $this->out($this->getHelp());
-                       return 0;
-               }
-
-               if (count($this->args) > 2) {
-                       throw new \Asika\SimpleConsole\CommandArgsException('Too many arguments');
-               }
-
-               if ($a->getMode()->isInstall()) {
-                       throw new \RuntimeException('Database isn\'t ready or populated yet');
-               }
-
-               $enabled = intval($this->getArgument(0));
-
-               Core\Config::set('system', 'maintenance', $enabled);
-
-               $reason = $this->getArgument(1);
-
-               if ($enabled && $this->getArgument(1)) {
-                       Core\Config::set('system', 'maintenance_reason', $this->getArgument(1));
-               } else {
-                       Core\Config::set('system', 'maintenance_reason', '');
-               }
-
-               if ($enabled) {
-                       $mode_str = "maintenance mode";
-               } else {
-                       $mode_str = "normal mode";
-               }
-
-               $this->out('System set in ' . $mode_str);
-
-               if ($enabled && $reason != '') {
-                       $this->out('Maintenance reason: ' . $reason);
-               }
-
-               return 0;
-       }
-
-}
diff --git a/src/Core/Console/NewPassword.php b/src/Core/Console/NewPassword.php
deleted file mode 100644 (file)
index 3cd96ad..0000000
+++ /dev/null
@@ -1,90 +0,0 @@
-<?php
-
-namespace Friendica\Core\Console;
-
-use Friendica\Core\L10n;
-use Friendica\Database\DBA;
-use Friendica\Model\User;
-use RuntimeException;
-
-/**
- * @brief tool to set a new password for a user
- *
- * With this tool, you can set a new password for a user
- *
- * License: AGPLv3 or later, same as Friendica
- *
- * @author Michael Vogel <heluecht@pirati.ca>
- */
-class NewPassword extends \Asika\SimpleConsole\Console
-{
-       protected $helpOptions = ['h', 'help', '?'];
-
-       protected function getHelp()
-       {
-               $help = <<<HELP
-console newpassword - Creates a new password for a given user
-Usage
-       bin/console newpassword <nickname> [<password>] [-h|--help|-?] [-v]
-
-Description
-       Creates a new password for a user without using the "forgot password" functionality.
-
-Options
-    -h|--help|-? Show help information
-    -v           Show more debug information.
-HELP;
-               return $help;
-       }
-
-       protected function doExecute()
-       {
-               $a = \get_app();
-
-               if ($this->getOption('v')) {
-                       $this->out('Class: ' . __CLASS__);
-                       $this->out('Arguments: ' . var_export($this->args, true));
-                       $this->out('Options: ' . var_export($this->options, true));
-               }
-
-               if (count($this->args) == 0) {
-                       $this->out($this->getHelp());
-                       return 0;
-               }
-
-               if (count($this->args) > 2) {
-                       throw new \Asika\SimpleConsole\CommandArgsException('Too many arguments');
-               }
-
-               if ($a->getMode()->isInstall()) {
-                       throw new RuntimeException('Database isn\'t ready or populated yet');
-               }
-
-               $nick = $this->getArgument(0);
-
-               $user = DBA::selectFirst('user', ['uid'], ['nickname' => $nick]);
-               if (!DBA::isResult($user)) {
-                       throw new RuntimeException(L10n::t('User not found'));
-               }
-
-               $password = $this->getArgument(1);
-               if (is_null($password)) {
-                       $this->out(L10n::t('Enter new password: '), false);
-                       $password = \Seld\CliPrompt\CliPrompt::hiddenPrompt(true);
-               }
-
-               try {
-                       $result = User::updatePassword($user['uid'], $password);
-
-                       if (!DBA::isResult($result)) {
-                               throw new \Exception(L10n::t('Password update failed. Please try again.'));
-                       }
-
-                       $this->out(L10n::t('Password changed.'));
-               } catch (\Exception $e) {
-                       throw new RuntimeException($e->getMessage(), $e->getCode(), $e);
-               }
-
-               return 0;
-       }
-}
diff --git a/src/Core/Console/PhpToPo.php b/src/Core/Console/PhpToPo.php
deleted file mode 100644 (file)
index 93d8274..0000000
+++ /dev/null
@@ -1,237 +0,0 @@
-<?php
-
-namespace Friendica\Core\Console;
-
-/**
- * Read a strings.php file and create messages.po in the same directory
- *
- * @author Hypolite Petovan <hypolite@mrpetovan.com>
- */
-class PhpToPo extends \Asika\SimpleConsole\Console
-{
-
-       protected $helpOptions = ['h', 'help', '?'];
-
-       private $normBaseMsgIds = [];
-       const NORM_REGEXP = "|[\\\]|";
-
-       protected function getHelp()
-       {
-               $help = <<<HELP
-console php2po - Generate a messages.po file from a strings.php file
-Usage
-       bin/console php2po [-p <n>] [--base <file>] <path/to/strings.php> [-h|--help|-?] [-v]
-
-Description
-       Read a strings.php file and create the according messages.po in the same directory
-
-Options
-       -p <n>        Number of plural forms. Default: 2
-       --base <file> Path to base messages.po file. Default: view/lang/C/messages.po
-       -h|--help|-?  Show help information
-       -v            Show more debug information.
-HELP;
-               return $help;
-       }
-
-       protected function doExecute()
-       {
-               if ($this->getOption('v')) {
-                       $this->out('Class: ' . __CLASS__);
-                       $this->out('Arguments: ' . var_export($this->args, true));
-                       $this->out('Options: ' . var_export($this->options, true));
-               }
-
-               if (count($this->args) == 0) {
-                       $this->out($this->getHelp());
-                       return 0;
-               }
-
-               if (count($this->args) > 1) {
-                       throw new \Asika\SimpleConsole\CommandArgsException('Too many arguments');
-               }
-
-               $a = \get_app();
-
-               $phpfile = realpath($this->getArgument(0));
-
-               if (!file_exists($phpfile)) {
-                       throw new \RuntimeException('Supplied file path doesn\'t exist.');
-               }
-
-               if (!is_writable(dirname($phpfile))) {
-                       throw new \RuntimeException('Supplied directory isn\'t writable.');
-               }
-
-               $pofile = dirname($phpfile) . DIRECTORY_SEPARATOR . 'messages.po';
-
-               // start !
-               include_once($phpfile);
-
-               $out = '';
-               $out .= "# FRIENDICA Distributed Social Network\n";
-               $out .= "# Copyright (C) 2010, 2011, 2012, 2013 the Friendica Project\n";
-               $out .= "# This file is distributed under the same license as the Friendica package.\n";
-               $out .= "# \n";
-               $out .= 'msgid ""' . "\n";
-               $out .= 'msgstr ""' . "\n";
-               $out .= '"Project-Id-Version: friendica\n"' . "\n";
-               $out .= '"Report-Msgid-Bugs-To: \n"' . "\n";
-               $out .= '"POT-Creation-Date: ' . date("Y-m-d H:i:sO") . '\n"' . "\n";
-               $out .= '"MIME-Version: 1.0\n"' . "\n";
-               $out .= '"Content-Type: text/plain; charset=UTF-8\n"' . "\n";
-               $out .= '"Content-Transfer-Encoding: 8bit\n"' . "\n";
-
-               // search for plural info
-               $lang = "";
-               $lang_logic = "";
-               $lang_pnum = $this->getOption('p', 2);
-
-               $infile = file($phpfile);
-               foreach ($infile as $l) {
-                       $l = trim($l);
-                       if ($this->startsWith($l, 'function string_plural_select_')) {
-                               $lang = str_replace('function string_plural_select_', '', str_replace('($n){', '', $l));
-                       }
-                       if ($this->startsWith($l, 'return')) {
-                               $lang_logic = str_replace('$', '', trim(str_replace('return ', '', $l), ';'));
-                               break;
-                       }
-               }
-
-               $this->out('Language: ' . $lang);
-               $this->out('Plural forms: ' . $lang_pnum);
-               $this->out('Plural forms: ' . $lang_logic);
-
-               $out .= sprintf('"Language: %s\n"', $lang) . "\n";
-               $out .= sprintf('"Plural-Forms: nplurals=%s; plural=%s;\n"', $lang_pnum, $lang_logic) . "\n";
-               $out .= "\n";
-
-               $base_path = $this->getOption('base', 'view/lang/C/messages.po');
-
-               // load base messages.po and extract msgids
-               $base_msgids = [];
-               $base_f = file($base_path);
-               if (!$base_f) {
-                       throw new \RuntimeException('The base ' . $base_path . ' file is missing or unavailable to read.');
-               }
-
-               $this->out('Loading base file ' . $base_path . '...');
-
-               $_f = 0;
-               $_mid = "";
-               $_mids = [];
-               foreach ($base_f as $l) {
-                       $l = trim($l);
-
-                       if ($this->startsWith($l, 'msgstr')) {
-                               if ($_mid != '""') {
-                                       $base_msgids[$_mid] = $_mids;
-                                       $this->normBaseMsgIds[preg_replace(self::NORM_REGEXP, "", $_mid)] = $_mid;
-                               }
-
-                               $_f = 0;
-                               $_mid = "";
-                               $_mids = [];
-                       }
-
-                       if ($this->startsWith($l, '"') && $_f == 2) {
-                               $_mids[count($_mids) - 1] .= "\n" . $l;
-                       }
-                       if ($this->startsWith($l, 'msgid_plural ')) {
-                               $_f = 2;
-                               $_mids[] = str_replace('msgid_plural ', '', $l);
-                       }
-
-                       if ($this->startsWith($l, '"') && $_f == 1) {
-                               $_mid .= "\n" . $l;
-                               $_mids[count($_mids) - 1] .= "\n" . $l;
-                       }
-                       if ($this->startsWith($l, 'msgid ')) {
-                               $_f = 1;
-                               $_mid = str_replace('msgid ', '', $l);
-                               $_mids = [$_mid];
-                       }
-               }
-
-               $this->out('Creating ' . $pofile . '...');
-
-               // create msgid and msgstr
-               $warnings = "";
-               foreach ($a->strings as $key => $str) {
-                       $msgid = $this->massageString($key);
-
-                       if (preg_match("|%[sd0-9](\$[sn])*|", $msgid)) {
-                               $out .= "#, php-format\n";
-                       }
-                       $msgid = $this->findOriginalMsgId($msgid);
-                       $out .= 'msgid ' . $msgid . "\n";
-
-                       if (is_array($str)) {
-                               if (array_key_exists($msgid, $base_msgids) && isset($base_msgids[$msgid][1])) {
-                                       $out .= 'msgid_plural ' . $base_msgids[$msgid][1] . "\n";
-                               } else {
-                                       $out .= 'msgid_plural ' . $msgid . "\n";
-                                       $warnings .= "[W] No source plural form for msgid:\n" . str_replace("\n", "\n\t", $msgid) . "\n\n";
-                               }
-                               foreach ($str as $n => $msgstr) {
-                                       $out .= 'msgstr[' . $n . '] ' . $this->massageString($msgstr) . "\n";
-                               }
-                       } else {
-                               $out .= 'msgstr ' . $this->massageString($str) . "\n";
-                       }
-
-                       $out .= "\n";
-               }
-
-               if (!file_put_contents($pofile, $out)) {
-                       throw new \RuntimeException('Unable to write to ' . $pofile);
-               }
-
-               if ($warnings != '') {
-                       $this->out($warnings);
-               }
-
-               return 0;
-       }
-
-       private function startsWith($haystack, $needle)
-       {
-               // search backwards starting from haystack length characters from the end
-               return $needle === "" || strrpos($haystack, $needle, -strlen($haystack)) !== FALSE;
-       }
-
-       /**
-        * Get a string and retun a message.po ready text
-        * - replace " with \"
-        * - replace tab char with \t
-        * - manage multiline strings
-        *
-        * @param string $str
-        * @return string
-        */
-       private function massageString($str)
-       {
-               $str = str_replace('\\', '\\\\', $str);
-               $str = str_replace('"', '\"', $str);
-               $str = str_replace("\t", '\t', $str);
-               $str = str_replace("\n", '\n"' . "\n" . '"', $str);
-               if (strpos($str, "\n") !== false && $str[0] !== '"') {
-                       $str = '"' . "\n" . $str;
-               }
-
-               $str = preg_replace("|\n([^\"])|", "\n\"$1", $str);
-               return sprintf('"%s"', $str);
-       }
-
-       private function findOriginalMsgId($str)
-       {
-               $norm_str = preg_replace(self::NORM_REGEXP, "", $str);
-               if (array_key_exists($norm_str, $this->normBaseMsgIds)) {
-                       return $this->normBaseMsgIds[$norm_str];
-               }
-
-               return $str;
-       }
-
-}
diff --git a/src/Core/Console/PoToPhp.php b/src/Core/Console/PoToPhp.php
deleted file mode 100644 (file)
index d539eae..0000000
+++ /dev/null
@@ -1,198 +0,0 @@
-<?php
-
-namespace Friendica\Core\Console;
-
-/**
- * Read a messages.po file and create strings.php in the same directory
- *
- * @author Hypolite Petovan <hypolite@mrpetovan.com>
- */
-class PoToPhp extends \Asika\SimpleConsole\Console
-{
-       protected $helpOptions = ['h', 'help', '?'];
-
-       const DQ_ESCAPE = "__DQ__";
-
-       protected function getHelp()
-       {
-               $help = <<<HELP
-console php2po - Generate a strings.php file from a messages.po file
-Usage
-       bin/console php2po <path/to/messages.po> [-h|--help|-?] [-v]
-
-Description
-       Read a messages.po file and create the according strings.php in the same directory
-
-Options
-       -h|--help|-?  Show help information
-       -v            Show more debug information.
-HELP;
-               return $help;
-       }
-
-       protected function doExecute()
-       {
-               if ($this->getOption('v')) {
-                       $this->out('Class: ' . __CLASS__);
-                       $this->out('Arguments: ' . var_export($this->args, true));
-                       $this->out('Options: ' . var_export($this->options, true));
-               }
-
-               if (count($this->args) == 0) {
-                       $this->out($this->getHelp());
-                       return 0;
-               }
-
-               if (count($this->args) > 1) {
-                       throw new \Asika\SimpleConsole\CommandArgsException('Too many arguments');
-               }
-
-               $pofile = realpath($this->getArgument(0));
-
-               if (!file_exists($pofile)) {
-                       throw new \RuntimeException('Supplied file path doesn\'t exist.');
-               }
-
-               if (!is_writable(dirname($pofile))) {
-                       throw new \RuntimeException('Supplied directory isn\'t writable.');
-               }
-
-               $outfile = dirname($pofile) . DIRECTORY_SEPARATOR . 'strings.php';
-
-               if (basename(dirname($pofile)) == 'C') {
-                       $lang = 'en';
-               } else {
-                       $lang = str_replace('-', '_', basename(dirname($pofile)));
-               }
-
-               $this->out('Out to ' . $outfile);
-
-               $out = "<?php\n\n";
-
-               $infile = file($pofile);
-               $k = '';
-               $v = '';
-               $arr = false;
-               $ink = false;
-               $inv = false;
-               $escape_s_exp = '|[^\\\\]\$[a-z]|';
-
-               foreach ($infile as $l) {
-                       $l = str_replace('\"', self::DQ_ESCAPE, $l);
-                       $len = strlen($l);
-                       if ($l[0] == "#") {
-                               $l = "";
-                       }
-
-                       if (substr($l, 0, 15) == '"Plural-Forms: ') {
-                               $match = [];
-                               preg_match("|nplurals=([0-9]*); *plural=(.*)[;\\\\]|", $l, $match);
-                               $cond = str_replace('n', '$n', $match[2]);
-                               // define plural select function if not already defined
-                               $fnname = 'string_plural_select_' . $lang;
-                               $out .= 'if(! function_exists("' . $fnname . '")) {' . "\n";
-                               $out .= 'function ' . $fnname . '($n){' . "\n";
-                               $out .= '       $n = intval($n);' . "\n";
-                               $out .= '       return ' . $cond . ';' . "\n";
-                               $out .= '}}' . "\n";
-                       }
-
-                       if ($k != '' && substr($l, 0, 7) == 'msgstr ') {
-                               if ($ink) {
-                                       $ink = false;
-                                       $out .= '$a->strings["' . $k . '"] = ';
-                               }
-
-                               if ($inv) {
-                                       $out .= '"' . $v . '"';
-                               }
-
-                               $v = substr($l, 8, $len - 10);
-                               $v = preg_replace_callback($escape_s_exp, [$this, 'escapeDollar'], $v);
-
-                               $inv = true;
-                       }
-
-                       if ($k != "" && substr($l, 0, 7) == 'msgstr[') {
-                               if ($ink) {
-                                       $ink = false;
-                                       $out .= '$a->strings["' . $k . '"] = ';
-                               }
-                               if ($inv) {
-                                       $inv = false;
-                                       $out .= '"' . $v . '"';
-                               }
-
-                               if (!$arr) {
-                                       $arr = true;
-                                       $out .= "[\n";
-                               }
-
-                               $match = [];
-                               preg_match("|\[([0-9]*)\] (.*)|", $l, $match);
-                               $out .= "\t"
-                                       . preg_replace_callback($escape_s_exp, [$this, 'escapeDollar'], $match[1])
-                                       . ' => '
-                                       . preg_replace_callback($escape_s_exp, [$this, 'escapeDollar'], $match[2])
-                                       . ",\n";
-                       }
-
-                       if (substr($l, 0, 6) == 'msgid_') {
-                               $ink = false;
-                               $out .= '$a->strings["' . $k . '"] = ';
-                       }
-
-                       if ($ink) {
-                               $k .= trim($l, "\"\r\n");
-                               $k = preg_replace_callback($escape_s_exp, [$this, 'escapeDollar'], $k);
-                       }
-
-                       if (substr($l, 0, 6) == 'msgid ') {
-                               if ($inv) {
-                                       $inv = false;
-                                       $out .= '"' . $v . '"';
-                               }
-
-                               if ($k != "") {
-                                       $out .= ($arr) ? "];\n" : ";\n";
-                               }
-
-                               $arr = false;
-                               $k = str_replace("msgid ", "", $l);
-                               if ($k != '""') {
-                                       $k = trim($k, "\"\r\n");
-                               } else {
-                                       $k = '';
-                               }
-
-                               $k = preg_replace_callback($escape_s_exp, [$this, 'escapeDollar'], $k);
-                               $ink = true;
-                       }
-
-                       if ($inv && substr($l, 0, 6) != "msgstr") {
-                               $v .= trim($l, "\"\r\n");
-                               $v = preg_replace_callback($escape_s_exp, [$this, 'escapeDollar'], $v);
-                       }
-               }
-
-               if ($inv) {
-                       $out .= '"' . $v . '"';
-               }
-
-               if ($k != '') {
-                       $out .= ($arr ? "];\n" : ";\n");
-               }
-
-               $out = str_replace(self::DQ_ESCAPE, '\"', $out);
-               if (!file_put_contents($outfile, $out)) {
-                       throw new \RuntimeException('Unable to write to ' . $outfile);
-               }
-
-               return 0;
-       }
-
-       private function escapeDollar($match)
-       {
-               return str_replace('$', '\$', $match[0]);
-       }
-}
diff --git a/src/Core/Console/PostUpdate.php b/src/Core/Console/PostUpdate.php
deleted file mode 100644 (file)
index a903cd7..0000000
+++ /dev/null
@@ -1,72 +0,0 @@
-<?php
-
-namespace Friendica\Core\Console;
-
-use Friendica\Core\Config;
-use Friendica\Core\L10n;
-use Friendica\Core\Update;
-
-/**
- * Performs database post updates
- *
- * License: AGPLv3 or later, same as Friendica
- *
- * @author Tobias Diekershoff <tobias.diekershoff@gmx.net>
- * @author Hypolite Petovan <hypolite@mrpetovan.com>
- */
-class PostUpdate extends \Asika\SimpleConsole\Console
-{
-        protected $helpOptions = ['h', 'help', '?'];
-
-        protected function getHelp()
-        {
-                $help = <<<HELP
-console postupdate - Performs database post updates
-Usage
-        bin/console postupdate [-h|--help|-?] [--reset <version>]
-
-Options
-    -h|--help|-?      Show help information
-    --reset <version> Reset the post update version
-HELP;
-                return $help;
-        }
-
-       protected function doExecute()
-       {
-               $a = \Friendica\BaseObject::getApp();
-
-               if ($this->getOption($this->helpOptions)) {
-                       $this->out($this->getHelp());
-                       return 0;
-               }
-
-               $reset_version = $this->getOption('reset');
-               if (is_bool($reset_version)) {
-                       $this->out($this->getHelp());
-                       return 0;
-               } elseif ($reset_version) {
-                       Config::set('system', 'post_update_version', $reset_version);
-                       echo L10n::t('Post update version number has been set to %s.', $reset_version) . "\n";
-                       return 0;
-               }
-
-               if ($a->getMode()->isInstall()) {
-                       throw new \RuntimeException('Database isn\'t ready or populated yet');
-               }
-
-               echo L10n::t('Check for pending update actions.') . "\n";
-               Update::run($a->getBasePath(), true, false, true, false);
-               echo L10n::t('Done.') . "\n";
-
-               echo L10n::t('Execute pending post updates.') . "\n";
-
-               while (!\Friendica\Database\PostUpdate::update()) {
-                       echo '.';
-               }
-
-               echo "\n" . L10n::t('All pending post updates are done.') . "\n";
-
-               return 0;
-       }
-}
diff --git a/src/Core/Console/ServerBlock.php b/src/Core/Console/ServerBlock.php
deleted file mode 100644 (file)
index 94c97e1..0000000
+++ /dev/null
@@ -1,171 +0,0 @@
-<?php
-
-namespace Friendica\Core\Console;
-
-use Asika\SimpleConsole\CommandArgsException;
-use Asika\SimpleConsole\Console;
-use Console_Table;
-use Friendica\BaseObject;
-use Friendica\Core\Config\Configuration;
-
-/**
- * @brief Manage blocked servers
- *
- * With this tool, you can list the current blocked servers
- * or you can add / remove a blocked server from the list
- */
-class ServerBlock extends Console
-{
-       const DEFAULT_REASON = 'blocked';
-
-       protected $helpOptions = ['h', 'help', '?'];
-
-       protected function getHelp()
-       {
-               $help = <<<HELP
-console serverblock - Manage blocked servers
-Usage
-       bin/console serverblock [-h|--help|-?] [-v]
-       bin/console serverblock add <server> <reason> [-h|--help|-?] [-v]
-       bin/console serverblock remove <server> [-h|--help|-?] [-v]
-
-Description
-       With this tool, you can list the current blocked servers
-    or you can add / remove a blocked server from the list
-
-Options
-    -h|--help|-? Show help information
-    -v           Show more debug information.
-HELP;
-               return $help;
-       }
-
-       protected function doExecute()
-       {
-               $a = BaseObject::getApp();
-
-               if (count($this->args) == 0) {
-                       $this->printBlockedServers($a->getConfig());
-                       return 0;
-               }
-
-               switch ($this->getArgument(0)) {
-                       case 'add':
-                               return $this->addBlockedServer($a->getConfig());
-                       case 'remove':
-                               return $this->removeBlockedServer($a->getConfig());
-                       default:
-                               throw new CommandArgsException('Unknown command.');
-                               break;
-               }
-       }
-
-       /**
-        * Prints the whole list of blocked domains including the reason
-        *
-        * @param Configuration $config
-        */
-       private function printBlockedServers(Configuration $config)
-       {
-               $table = new Console_Table();
-               $table->setHeaders(['Domain', 'Reason']);
-               $blocklist = $config->get('system', 'blocklist');
-               foreach ($blocklist as $domain) {
-                       $table->addRow($domain);
-               }
-               $this->out($table->getTable());
-       }
-
-       /**
-        * Adds a server to the blocked list
-        *
-        * @param Configuration $config
-        *
-        * @return int The return code (0 = success, 1 = failed)
-        */
-       private function addBlockedServer(Configuration $config)
-       {
-               if (count($this->args) < 2 || count($this->args) > 3) {
-                       throw new CommandArgsException('Add needs a domain and optional a reason.');
-               }
-
-               $domain = $this->getArgument(1);
-               $reason = (count($this->args) === 3) ? $this->getArgument(2) : self::DEFAULT_REASON;
-
-               $update = false;
-
-               $currBlocklist = $config->get('system', 'blocklist');
-               $newBlockList = [];
-               foreach ($currBlocklist  as $blocked) {
-                       if ($blocked['domain'] === $domain) {
-                               $update = true;
-                               $newBlockList[] = [
-                                       'domain' => $domain,
-                                       'reason' => $reason,
-                               ];
-                       } else {
-                               $newBlockList[] = $blocked;
-                       }
-               }
-
-               if (!$update) {
-                       $newBlockList[] = [
-                               'domain' => $domain,
-                               'reason' => $reason,
-                       ];
-               }
-
-               if ($config->set('system', 'blocklist', $newBlockList)) {
-                       if ($update) {
-                               $this->out(sprintf("The domain '%s' is now updated. (Reason: '%s')", $domain, $reason));
-                       } else {
-                               $this->out(sprintf("The domain '%s' is now blocked. (Reason: '%s')", $domain, $reason));
-                       }
-                       return 0;
-               } else {
-                       $this->out(sprintf("Couldn't save '%s' as blocked server", $domain));
-                       return 1;
-               }
-       }
-
-       /**
-        * Removes a server from the blocked list
-        *
-        * @param Configuration $config
-        *
-        * @return int The return code (0 = success, 1 = failed)
-        */
-       private function removeBlockedServer(Configuration $config)
-       {
-               if (count($this->args) !== 2) {
-                       throw new CommandArgsException('Remove needs a second parameter.');
-               }
-
-               $domain = $this->getArgument(1);
-
-               $found = false;
-
-               $currBlocklist = $config->get('system', 'blocklist');
-               $newBlockList = [];
-               foreach ($currBlocklist as $blocked) {
-                       if ($blocked['domain'] === $domain) {
-                               $found = true;
-                       } else {
-                               $newBlockList[] = $blocked;
-                       }
-               }
-
-               if (!$found) {
-                       $this->out(sprintf("The domain '%s' is not blocked.", $domain));
-                       return 1;
-               }
-
-               if ($config->set('system', 'blocklist', $newBlockList)) {
-                       $this->out(sprintf("The domain '%s' is not more blocked", $domain));
-                       return 0;
-               } else {
-                       $this->out(sprintf("Couldn't remove '%s' from blocked servers", $domain));
-                       return 1;
-               }
-       }
-}
diff --git a/src/Core/Console/Storage.php b/src/Core/Console/Storage.php
deleted file mode 100644 (file)
index 805ef0a..0000000
+++ /dev/null
@@ -1,147 +0,0 @@
-<?php
-
-namespace Friendica\Core\Console;
-
-use Asika\SimpleConsole\CommandArgsException;
-use Friendica\Core\StorageManager;
-
-/**
- * @brief tool to manage storage backend and stored data from CLI
- *
- */
-class Storage extends \Asika\SimpleConsole\Console
-{
-       protected $helpOptions = ['h', 'help', '?'];
-
-       protected function getHelp()
-       {
-               $help = <<<HELP
-console storage - manage storage backend and stored data
-Synopsis
-    bin/console storage [-h|--help|-?] [-v]
-        Show this help
-    
-    bin/console storage list
-        List available storage backends
-    
-    bin/console storage set <name>
-        Set current storage backend
-            name        storage backend to use. see "list".
-    
-    bin/console storage move [table] [-n 5000]
-        Move stored data to current storage backend.
-            table       one of "photo" or "attach". default to both
-            -n          limit of processed entry batch size
-HELP;
-               return $help;
-       }
-
-       protected function doExecute()
-       {
-               if ($this->getOption('v')) {
-                       $this->out('Executable: ' . $this->executable);
-                       $this->out('Class: ' . __CLASS__);
-                       $this->out('Arguments: ' . var_export($this->args, true));
-                       $this->out('Options: ' . var_export($this->options, true));
-               }
-
-               if (count($this->args) == 0) {
-                       $this->out($this->getHelp());
-                       return -1;
-               }
-
-               switch ($this->args[0]) {
-                       case 'list':
-                               return $this->doList();
-                               break;
-                       case 'set':
-                               return $this->doSet();
-                               break;
-                       case 'move':
-                               return $this->doMove();
-                               break;
-               }
-
-               $this->out(sprintf('Invalid action "%s"', $this->args[0]));
-               return -1;
-       }
-
-       protected function doList()
-       {
-               $rowfmt = ' %-3s | %-20s';
-               $current = StorageManager::getBackend();
-               $this->out(sprintf($rowfmt, 'Sel', 'Name'));
-               $this->out('-----------------------');
-               $isregisterd = false;
-               foreach (StorageManager::listBackends() as $name => $class) {
-                       $issel = ' ';
-                       if ($current === $class) {
-                               $issel = '*';
-                               $isregisterd = true;
-                       };
-                       $this->out(sprintf($rowfmt, $issel, $name));
-               }
-
-               if ($current === '') {
-                       $this->out();
-                       $this->out('This system is using legacy storage system');
-               }
-               if ($current !== '' && !$isregisterd) {
-                       $this->out();
-                       $this->out('The current storage class (' . $current . ') is not registered!');
-               }
-               return 0;
-       }
-
-       protected function doSet()
-       {
-               if (count($this->args) !== 2) {
-                       throw new CommandArgsException('Invalid arguments');
-               }
-
-               $name = $this->args[1];
-               $class = StorageManager::getByName($name);
-
-               if ($class === '') {
-                       $this->out($name . ' is not a registered backend.');
-                       return -1;
-               }
-
-               if (!StorageManager::setBackend($class)) {
-                       $this->out($class . ' is not a valid backend storage class.');
-                       return -1;
-               }
-
-               return 0;
-       }
-
-       protected function doMove()
-       {
-               $tables = null;
-               if (count($this->args) < 1 || count($this->args) > 2) {
-                       throw new CommandArgsException('Invalid arguments');
-               }
-
-               if (count($this->args) == 2) {
-                       $table = strtolower($this->args[1]);
-                       if (!in_array($table, ['photo', 'attach'])) {
-                               throw new CommandArgsException('Invalid table');
-                       }
-                       $tables = [$table];
-               }
-
-               $current = StorageManager::getBackend();
-               $total = 0;
-
-               do {
-                       $moved = StorageManager::move($current, $tables, $this->getOption('n', 5000));
-                       if ($moved) {
-                               $this->out(date('[Y-m-d H:i:s] ') . sprintf('Moved %d files', $moved));
-                       }
-
-                       $total += $moved;
-               } while ($moved);
-
-               $this->out(sprintf(date('[Y-m-d H:i:s] ') . 'Moved %d files total', $total));
-       }
-}
diff --git a/src/Core/Console/Typo.php b/src/Core/Console/Typo.php
deleted file mode 100644 (file)
index 8d07051..0000000
+++ /dev/null
@@ -1,117 +0,0 @@
-<?php
-
-namespace Friendica\Core\Console;
-
-use Friendica\BaseObject;
-
-/**
- * Tired of chasing typos and finding them after a commit.
- * Run this and quickly see if we've got any parse errors in our application files.
- *
- * @author Hypolite Petovan <hypolite@mrpetovan.com>
- */
-class Typo extends \Asika\SimpleConsole\Console
-{
-       protected $helpOptions = ['h', 'help', '?'];
-
-       protected function getHelp()
-       {
-               $help = <<<HELP
-console typo - Checks for parse errors in Friendica files
-Usage
-       bin/console typo [-h|--help|-?] [-v]
-
-Description
-       Checks all PHP files in the Friendica file tree for parse errors
-
-Options
-       -h|--help|-?  Show help information
-       -v            Show more debug information.
-HELP;
-               return $help;
-       }
-
-       protected function doExecute()
-       {
-               if ($this->getOption('v')) {
-                       $this->out('Class: ' . __CLASS__);
-                       $this->out('Arguments: ' . var_export($this->args, true));
-                       $this->out('Options: ' . var_export($this->options, true));
-               }
-
-               if (count($this->args) > 0) {
-                       throw new \Asika\SimpleConsole\CommandArgsException('Too many arguments');
-               }
-
-               $php_path = BaseObject::getApp()->getConfigCache()->get('config', 'php_path', 'php');
-
-               if ($this->getOption('v')) {
-                       $this->out('Directory: src');
-               }
-
-               $Iterator = new \RecursiveDirectoryIterator('src');
-
-               foreach (new \RecursiveIteratorIterator($Iterator) as $file) {
-                       if (substr($file, -4) === '.php') {
-                               $this->checkFile($php_path, $file);
-                       }
-               }
-
-               if ($this->getOption('v')) {
-                       $this->out('Directory: mod');
-               }
-
-               $files = glob('mod/*.php');
-               $this->checkFiles($php_path, $files);
-
-               if ($this->getOption('v')) {
-                       $this->out('Directory: include');
-               }
-
-               $files = glob('include/*.php');
-               $this->checkFiles($php_path, $files);
-
-               if ($this->getOption('v')) {
-                       $this->out('Directory: addon');
-               }
-
-               $dirs = glob('addon/*');
-               foreach ($dirs as $dir) {
-                       $addon = basename($dir);
-                       $files = glob($dir . '/' . $addon . '.php');
-                       $this->checkFiles($php_path, $files);
-               }
-
-               if ($this->getOption('v')) {
-                       $this->out('String files');
-               }
-
-               $files = glob('view/lang/*/strings.php');
-               $this->checkFiles($php_path, $files);
-
-               $this->out('No errors.');
-
-               return 0;
-       }
-
-       private function checkFiles($php_path, array $files)
-       {
-               foreach ($files as $file) {
-                       $this->checkFile($php_path, $file);
-               }
-       }
-
-       private function checkFile($php_path, $file)
-       {
-               if ($this->getOption('v')) {
-                       $this->out('Checking ' . $file);
-               }
-
-               $output = [];
-               $ret = 0;
-               exec("$php_path -l $file", $output, $ret);
-               if ($ret !== 0) {
-                       throw new \RuntimeException('Parse error found in ' . $file . ', scan stopped.');
-               }
-       }
-}
index 72073086ab33d5bfcbab1bdf0a5e9748dcc4c70f..fd5e73302512f0d8328690958941d2e356b8415c 100644 (file)
@@ -52,22 +52,20 @@ class Renderer extends BaseObject
        /**
         * @brief This is our template processor
         *
-        * @param string|FriendicaSmarty $s            The string requiring macro substitution or an instance of FriendicaSmarty
-        * @param array                  $vars         key value pairs (search => replace)
-        * @param bool                   $overwriteURL Overwrite the base url with the system wide set base url
+        * @param string|FriendicaSmarty $s    The string requiring macro substitution or an instance of FriendicaSmarty
+        * @param array                  $vars Key value pairs (search => replace)
         *
         * @return string substituted string
-        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @throws Exception
         */
-       public static function replaceMacros($s, $vars, $overwriteURL = true)
+       public static function replaceMacros($s, array $vars = [])
        {
                $stamp1 = microtime(true);
                $a = self::getApp();
 
-               // pass $baseurl to all templates
-               if ($overwriteURL) {
-                       $vars['$baseurl'] = System::baseUrl();
-               }
+               // pass $baseurl to all templates if it isn't set
+               $vars = array_merge(['$baseurl' => $a->getBaseURL()], $vars);
+
                $t = self::getTemplateEngine();
 
                try {
index 83c3dc908167fa6091f304c6e5203a7bd4f03962..31934af5a73e055474b035561690f067bd872201 100644 (file)
@@ -120,58 +120,17 @@ class System extends BaseObject
        /**
         * @brief Send HTTP status header and exit.
         *
-        * @param integer $val         HTTP status result value
-        * @param array   $description optional message
-        *                             'title' => header title
-        *                             'description' => optional message
-        * @throws InternalServerErrorException
+        * @param integer $val     HTTP status result value
+        * @param string  $message Error message. Optional.
+        * @param string  $content Response body. Optional.
+        * @throws \Exception
         */
-       public static function httpExit($val, $description = [])
+       public static function httpExit($val, $message = '', $content = '')
        {
-               $err = '';
-               if ($val >= 400) {
-                       if (!empty($description['title'])) {
-                               $err = $description['title'];
-                       } else {
-                               $title = [
-                                       '400' => L10n::t('Error 400 - Bad Request'),
-                                       '401' => L10n::t('Error 401 - Unauthorized'),
-                                       '403' => L10n::t('Error 403 - Forbidden'),
-                                       '404' => L10n::t('Error 404 - Not Found'),
-                                       '500' => L10n::t('Error 500 - Internal Server Error'),
-                                       '503' => L10n::t('Error 503 - Service Unavailable'),
-                                       ];
-                               $err = defaults($title, $val, 'Error ' . $val);
-                               $description['title'] = $err;
-                       }
-                       if (empty($description['description'])) {
-                               // Explanations are taken from https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
-                               $explanation = [
-                                       '400' => L10n::t('The server cannot or will not process the request due to an apparent client error.'),
-                                       '401' => L10n::t('Authentication is required and has failed or has not yet been provided.'),
-                                       '403' => L10n::t('The request was valid, but the server is refusing action. The user might not have the necessary permissions for a resource, or may need an account.'),
-                                       '404' => L10n::t('The requested resource could not be found but may be available in the future.'),
-                                       '500' => L10n::t('An unexpected condition was encountered and no more specific message is suitable.'),
-                                       '503' => L10n::t('The server is currently unavailable (because it is overloaded or down for maintenance). Please try again later.'),
-                                       ];
-                               if (!empty($explanation[$val])) {
-                                       $description['description'] = $explanation[$val];
-                               }
-                       }
-               }
-
-               if ($val >= 200 && $val < 300) {
-                       $err = 'OK';
-               }
-
                Logger::log('http_status_exit ' . $val);
-               header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
+               header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $message);
 
-               if (isset($description["title"])) {
-                       $tpl = Renderer::getMarkupTemplate('http_status.tpl');
-                       echo Renderer::replaceMacros($tpl, ['$title' => $description["title"],
-                               '$description' => defaults($description, 'description', '')]);
-               }
+               echo $content;
 
                exit();
        }
@@ -264,15 +223,27 @@ class System extends BaseObject
         * Redirects to an external URL (fully qualified URL)
         * If you want to route relative to the current Friendica base, use App->internalRedirect()
         *
-        * @param string $url The new Location to redirect
+        * @param string $url  The new Location to redirect
+        * @param int    $code The redirection code, which is used (Default is 302)
+        *
         * @throws InternalServerErrorException If the URL is not fully qualified
         */
-       public static function externalRedirect($url)
+       public static function externalRedirect($url, $code = 302)
        {
                if (empty(parse_url($url, PHP_URL_SCHEME))) {
                        throw new InternalServerErrorException("'$url' is not a fully qualified URL, please use App->internalRedirect() instead");
                }
 
+               switch ($code) {
+                       case 302:
+                               // this is the default code for a REDIRECT
+                               // We don't need a extra header here
+                               break;
+                       case 301:
+                               header('HTTP/1.1 301 Moved Permanently');
+                               break;
+               }
+
                header("Location: $url");
                exit();
        }
index c972e09fc71a659c085a7a0288c7b69f3391d19c..61798a3969d99e7345dc2f0559c9018db488bc96 100644 (file)
@@ -20,7 +20,7 @@ class Theme
        public static function getAllowedList()
        {
                $allowed_themes_str = Config::get('system', 'allowed_themes');
-               $allowed_themes_raw = explode(',', $allowed_themes_str);
+               $allowed_themes_raw = explode(',', str_replace(' ', '', $allowed_themes_str));
                $allowed_themes = [];
                if (count($allowed_themes_raw)) {
                        foreach ($allowed_themes_raw as $theme) {
@@ -34,6 +34,11 @@ class Theme
                return $allowed_themes;
        }
 
+       public static function setAllowedList(array $allowed_themes)
+       {
+               Config::set('system', 'allowed_themes', implode(',', $allowed_themes));
+       }
+
        /**
         * @brief Parse theme comment in search of theme infos.
         *
@@ -133,13 +138,20 @@ class Theme
 
                // silently fail if theme was removed or if $theme is funky
                if (file_exists("view/theme/$theme/theme.php")) {
-                       Logger::log("Addons: uninstalling theme " . $theme);
+                       include_once "view/theme/$theme/theme.php";
 
-                       if (function_exists("{$theme}_uninstall")) {
-                               $func = "{$theme}_uninstall";
+                       $func = "{$theme}_uninstall";
+                       if (function_exists($func)) {
                                $func();
                        }
                }
+
+               $allowed_themes = Theme::getAllowedList();
+               $key = array_search($theme, $allowed_themes);
+               if ($key !== false) {
+                       unset($allowed_themes[$key]);
+                       Theme::setAllowedList($allowed_themes);
+               }
        }
 
        public static function install($theme)
@@ -151,16 +163,21 @@ class Theme
                        return false;
                }
 
-               Logger::log("Addons: installing theme $theme");
-
-               include_once "view/theme/$theme/theme.php";
+               try {
+                       include_once "view/theme/$theme/theme.php";
 
-               if (function_exists("{$theme}_install")) {
                        $func = "{$theme}_install";
-                       $func();
+                       if (function_exists($func)) {
+                               $func();
+                       }
+
+                       $allowed_themes = Theme::getAllowedList();
+                       $allowed_themes[] = $theme;
+                       Theme::setAllowedList($allowed_themes);
+
                        return true;
-               } else {
-                       Logger::log("Addons: FAILED installing theme $theme");
+               } catch (\Exception $e) {
+                       Logger::error('Theme installation failed', ['theme' => $theme, 'error' => $e->getMessage()]);
                        return false;
                }
        }
index 3d0b9abfa19e946fca895c02057e507c545d0ca0..27ac3d33e1fec3669d71e66ef00177022879906a 100644 (file)
@@ -110,6 +110,20 @@ class Contact extends BaseObject
         * @}
         */
 
+       /**
+        * @param array $fields    Array of selected fields, empty for all
+        * @param array $condition Array of fields for condition
+        * @param array $params    Array of several parameters
+        * @return array
+        * @throws \Exception
+        */
+       public static function select(array $fields = [], array $condition = [], array $params = [])
+       {
+               $statement = DBA::select('contact', $fields, $condition, $params);
+
+               return DBA::toArray($statement);
+       }
+
        /**
         * @param  integer       $id
         * @return array|boolean Contact record if it exists, false otherwise
@@ -223,6 +237,28 @@ class Contact extends BaseObject
                return ['public' => $pcid, 'user' => $ucid];
        }
 
+       /**
+        * Returns contact details for a given contact id in combination with a user id
+        *
+        * @param int $cid A contact ID
+        * @param int $uid The User ID
+        * @param array $fields The selected fields for the contact
+        *
+        * @return array The contact details
+        *
+        * @throws \Exception
+        */
+       public static function getContactForUser($cid, $uid, array $fields = [])
+       {
+               $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
+
+               if (!DBA::isResult($contact)) {
+                       return [];
+               } else {
+                       return $contact;
+               }
+       }
+
        /**
         * @brief Block contact id for user id
         *
@@ -1133,7 +1169,7 @@ class Contact extends BaseObject
         *
         * @return array Contact array in the "probe" structure
        */
-       private static function getProbeDataFromDatabase($url, $cid)
+       private static function getProbeDataFromDatabase($url, $cid = null)
        {
                // The link could be provided as http although we stored it as https
                $ssl_url = str_replace('http://', 'https://', $url);
@@ -2300,12 +2336,12 @@ class Contact extends BaseObject
                        return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
                }
 
-               $cid = self::getIdForURL($contact_url, 0, true);
-               if (empty($cid)) {
+               $data = self::getProbeDataFromDatabase($contact_url);
+               if (empty($data)) {
                        return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
                }
 
-               return self::magicLinkbyId($cid, $url);
+               return self::magicLinkByContact($data, $contact_url);
        }
 
        /**
index c309da24ef1b289673be4eba6ccf04d1a2bcfe50..387014d4b93e55883b1c90e0a081d4bc961be060 100644 (file)
@@ -2508,62 +2508,6 @@ class Item extends BaseObject
                        }, $item["body"]);
        }
 
-       public static function getGuidById($id)
-       {
-               $item = self::selectFirst(['guid'], ['id' => $id]);
-               if (DBA::isResult($item)) {
-                       return $item['guid'];
-               } else {
-                       return '';
-               }
-       }
-
-       /**
-        * This function is only used for the old Friendica app on Android that doesn't like paths with guid
-        *
-        * @param string $guid item guid
-        * @param int    $uid  user id
-        * @return array with id and nick of the item with the given guid
-        * @throws \Exception
-        */
-       public static function getIdAndNickByGuid($guid, $uid = 0)
-       {
-               $nick = "";
-               $id = 0;
-
-               if ($uid == 0) {
-                       $uid = local_user();
-               }
-
-               // Does the given user have this item?
-               if ($uid) {
-                       $item = self::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
-                       if (DBA::isResult($item)) {
-                               $user = DBA::selectFirst('user', ['nickname'], ['uid' => $uid]);
-                               if (!DBA::isResult($user)) {
-                                       return;
-                               }
-                               $id = $item['id'];
-                               $nick = $user['nickname'];
-                       }
-               }
-
-               // Or is it anywhere on the server?
-               if ($nick == "") {
-                       $condition = ["`guid` = ? AND `uid` != 0", $guid];
-                       $item = self::selectFirst(['id', 'uid'], $condition);
-                       if (DBA::isResult($item)) {
-                               $user = DBA::selectFirst('user', ['nickname'], ['uid' => $item['uid']]);
-                               if (!DBA::isResult($user)) {
-                                       return;
-                               }
-                               $id = $item['id'];
-                               $nick = $user['nickname'];
-                       }
-               }
-               return ["nick" => $nick, "id" => $id];
-       }
-
        /**
         * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
         *
@@ -3466,9 +3410,7 @@ class Item extends BaseObject
                        if (strpos($mime, 'video') !== false) {
                                if (!$vhead) {
                                        $vhead = true;
-                                       $a->page['htmlhead'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate('videos_head.tpl'), [
-                                               '$baseurl' => System::baseUrl(),
-                                       ]);
+                                       $a->page['htmlhead'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate('videos_head.tpl'));
                                }
 
                                $url_parts = explode('/', $the_url);
index 79971cd9998e24045181d4249418220e00e11e68..9d2600b3daab16156c825ff4f458cd352ad1bf6a 100644 (file)
@@ -112,8 +112,6 @@ class Profile
 
                if (!DBA::isResult($user) && empty($profiledata)) {
                        Logger::log('profile error: ' . $a->query_string, Logger::DEBUG);
-                       notice(L10n::t('Requested account is not available.') . EOL);
-                       $a->error = 404;
                        return;
                }
 
@@ -130,8 +128,6 @@ class Profile
 
                if (empty($pdata) && empty($profiledata)) {
                        Logger::log('profile error: ' . $a->query_string, Logger::DEBUG);
-                       notice(L10n::t('Requested profile is not available.') . EOL);
-                       $a->error = 404;
                        return;
                }
 
@@ -641,7 +637,6 @@ class Profile
                }
                $tpl = Renderer::getMarkupTemplate('birthdays_reminder.tpl');
                return Renderer::replaceMacros($tpl, [
-                       '$baseurl' => System::baseUrl(),
                        '$classtoday' => $classtoday,
                        '$count' => $total,
                        '$event_reminders' => L10n::t('Birthday Reminders'),
@@ -730,7 +725,6 @@ class Profile
                }
                $tpl = Renderer::getMarkupTemplate('events_reminder.tpl');
                return Renderer::replaceMacros($tpl, [
-                       '$baseurl' => System::baseUrl(),
                        '$classtoday' => $classtoday,
                        '$count' => count($r),
                        '$event_reminders' => L10n::t('Event Reminders'),
@@ -1241,4 +1235,75 @@ class Profile
        {
                return preg_replace('/[\?&]' . $param . '=(.*?)(&|$)/ism', '$2', $s);
        }
+
+       /**
+        * search for Profiles
+        *
+        * @param int  $start
+        * @param int  $count
+        * @param null $search
+        *
+        * @return array [ 'total' => 123, 'entries' => [...] ];
+        *
+        * @throws \Exception
+        */
+       public static function searchProfiles($start = 0, $count = 100, $search = null)
+       {
+               if ($search) {
+                       $search = DBA::escape($search);
+
+                       $sql_extra = " AND ((`profile`.`name` LIKE '%$search%') OR
+                               (`user`.`nickname` LIKE '%$search%') OR
+                               (`profile`.`pdesc` LIKE '%$search%') OR
+                               (`profile`.`locality` LIKE '%$search%') OR
+                               (`profile`.`region` LIKE '%$search%') OR
+                               (`profile`.`country-name` LIKE '%$search%') OR
+                               (`profile`.`gender` LIKE '%$search%') OR
+                               (`profile`.`marital` LIKE '%$search%') OR
+                               (`profile`.`sexual` LIKE '%$search%') OR
+                               (`profile`.`about` LIKE '%$search%') OR
+                               (`profile`.`romance` LIKE '%$search%') OR
+                               (`profile`.`work` LIKE '%$search%') OR
+                               (`profile`.`education` LIKE '%$search%') OR
+                               (`profile`.`pub_keywords` LIKE '%$search%') OR
+                               (`profile`.`prv_keywords` LIKE '%$search%'))";
+               } else {
+                       $sql_extra = '';
+               }
+
+               $publish = (Config::get('system', 'publish_all') ? '' : " AND `publish` = 1 ");
+
+               $total = 0;
+               $cnt = DBA::fetchFirst("SELECT COUNT(*) AS `total` 
+                               FROM `profile`
+                               LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
+                               WHERE `is-default` $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed` $sql_extra");
+               if (DBA::isResult($cnt)) {
+                       $total = $cnt['total'];
+               }
+
+               $order = " ORDER BY `name` ASC ";
+               $limit = $start . ',' . $count;
+
+               $profiles = DBA::p("SELECT `profile`.*, `profile`.`uid` AS `profile_uid`, `user`.`nickname`, `user`.`timezone` , `user`.`page-flags`,
+                       `contact`.`addr`, `contact`.`url` AS `profile_url`
+                       FROM `profile`
+                       LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
+                       LEFT JOIN `contact` ON `contact`.`uid` = `user`.`uid`
+                       WHERE `is-default` $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed` AND `contact`.`self`
+                       $sql_extra $order LIMIT $limit"
+               );
+
+               if (DBA::isResult($profiles)) {
+                       return [
+                               'total'   => $total,
+                               'entries' => DBA::toArray($profiles),
+                       ];
+               } else {
+                       return [
+                               'total'   => $total,
+                               'entries' => [],
+                       ];
+               }
+       }
 }
diff --git a/src/Model/Search.php b/src/Model/Search.php
new file mode 100644 (file)
index 0000000..5829ff9
--- /dev/null
@@ -0,0 +1,32 @@
+<?php
+
+namespace Friendica\Model;
+
+use Friendica\BaseObject;
+use Friendica\Database\DBA;
+
+/**
+ * Model for DB specific logic for the search entity
+ */
+class Search extends BaseObject
+{
+       /**
+        * Returns the list of user defined tags (e.g. #Friendica)
+        *
+        * @return array
+        *
+        * @throws \Exception
+        */
+       public static function getUserTags()
+       {
+               $termsStmt = DBA::p("SELECT DISTINCT(`term`) FROM `search`");
+
+               $tags = [];
+
+               while ($term = DBA::fetch($termsStmt)) {
+                       $tags[] = trim($term['term'], '#');
+               }
+
+               return $tags;
+       }
+}
index 4b3823f040d0e1db8f1f7dca070274bee68667fa..c575b44d38ea222593a6b20896fec42ee6d2753d 100644 (file)
@@ -91,12 +91,24 @@ class User
 
        /**
         * @param  integer       $uid
+        * @param array          $fields
         * @return array|boolean User record if it exists, false otherwise
         * @throws Exception
         */
-       public static function getById($uid)
+       public static function getById($uid, array $fields = [])
        {
-               return DBA::selectFirst('user', [], ['uid' => $uid]);
+               return DBA::selectFirst('user', $fields, ['uid' => $uid]);
+       }
+
+       /**
+        * @param  string        $nickname
+        * @param array          $fields
+        * @return array|boolean User record if it exists, false otherwise
+        * @throws Exception
+        */
+       public static function getByNickname($nickname, array $fields = [])
+       {
+               return DBA::selectFirst('user', $fields, ['nickname' => $nickname]);
        }
 
        /**
diff --git a/src/Module/AccountManagementControlDocument.php b/src/Module/AccountManagementControlDocument.php
new file mode 100644 (file)
index 0000000..2e2a9e4
--- /dev/null
@@ -0,0 +1,65 @@
+<?php
+
+namespace Friendica\Module;
+
+use Friendica\BaseModule;
+
+/**
+ * Static definition for the Firefox Account Manager
+ *
+ * @see https://wiki.mozilla.org/Labs/Weave/Identity/Account_Manager/Spec/3#Contents_of_the_Account_Management_Control_Document
+ */
+class AccountManagementControlDocument extends BaseModule
+{
+       public static function rawContent()
+       {
+               $output = [
+                       'version' => 1,
+                       'sessionstatus' => [
+                               'method' => 'GET',
+                               'path' => '/session',
+                       ],
+                       'auth-methods' => [
+                               'username-password-form' => [
+                                       'connect' => [
+                                               'method' => 'POST',
+                                               'path' => '/login',
+                                               'params' => [
+                                                       'username' => 'login-name',
+                                                       'password' => 'password',
+                                               ],
+                                               'onsuccess' => [
+                                                       'action' => 'reload',
+                                               ],
+                                       ],
+                                       'disconnect' => [
+                                               'method' => 'GET',
+                                               'path' => '/logout',
+                                       ],
+                               ],
+                       ],
+                       'methods' => [
+                               'username-password-form' => [
+                                       'connect' => [
+                                               'method' => 'POST',
+                                               'path' => '/login',
+                                               'params' => [
+                                                       'username' => 'login-name',
+                                                       'password' => 'password',
+                                               ],
+                                               'onsuccess' => [
+                                                       'action' => 'reload',
+                                               ],
+                                       ],
+                                       'disconnect' => [
+                                               'method' => 'GET',
+                                               'path' => '/logout',
+                                       ],
+                               ],
+                       ],
+               ];
+
+               echo json_encode($output);
+               exit();
+       }
+}
diff --git a/src/Module/Admin/Addons/Details.php b/src/Module/Admin/Addons/Details.php
new file mode 100644 (file)
index 0000000..33e7c7a
--- /dev/null
@@ -0,0 +1,122 @@
+<?php
+
+namespace Friendica\Module\Admin\Addons;
+
+use Friendica\Content\Text\Markdown;
+use Friendica\Core\Addon;
+use Friendica\Core\L10n;
+use Friendica\Core\Renderer;
+use Friendica\Module\BaseAdminModule;
+use Friendica\Util\Strings;
+
+class Details extends BaseAdminModule
+{
+       public static function post()
+       {
+               parent::post();
+
+               $a = self::getApp();
+
+               if ($a->argc > 2) {
+                       // @TODO: Replace with parameter from router
+                       $addon = $a->argv[2];
+                       $addon = Strings::sanitizeFilePathItem($addon);
+                       if (is_file('addon/' . $addon . '/' . $addon . '.php')) {
+                               include_once 'addon/' . $addon . '/' . $addon . '.php';
+                               if (function_exists($addon . '_addon_admin_post')) {
+                                       $func = $addon . '_addon_admin_post';
+                                       $func($a);
+                               }
+
+                               $a->internalRedirect('admin/addons/' . $addon);
+                       }
+               }
+
+               $a->internalRedirect('admin/addons');
+       }
+
+       public static function content()
+       {
+               parent::content();
+
+               $a = self::getApp();
+
+               $addons_admin = Addon::getAdminList();
+
+               if ($a->argc > 2) {
+                       // @TODO: Replace with parameter from router
+                       $addon = $a->argv[2];
+                       $addon = Strings::sanitizeFilePathItem($addon);
+                       if (!is_file("addon/$addon/$addon.php")) {
+                               notice(L10n::t('Item not found.'));
+                               $a->internalRedirect('admin/addons');
+                       }
+
+                       if (defaults($_GET, 'action', '') == 'toggle') {
+                               parent::checkFormSecurityTokenRedirectOnError('/admin/addons', 'admin_themes', 't');
+
+                               // Toggle addon status
+                               if (Addon::isEnabled($addon)) {
+                                       Addon::uninstall($addon);
+                                       info(L10n::t('Addon %s disabled.', $addon));
+                               } else {
+                                       Addon::install($addon);
+                                       info(L10n::t('Addon %s enabled.', $addon));
+                               }
+
+                               Addon::saveEnabledList();
+
+                               $a->internalRedirect('admin/addons/' . $addon);
+                       }
+
+                       // display addon details
+                       if (Addon::isEnabled($addon)) {
+                               $status = 'on';
+                               $action = L10n::t('Disable');
+                       } else {
+                               $status = 'off';
+                               $action = L10n::t('Enable');
+                       }
+
+                       $readme = null;
+                       if (is_file("addon/$addon/README.md")) {
+                               $readme = Markdown::convert(file_get_contents("addon/$addon/README.md"), false);
+                       } elseif (is_file("addon/$addon/README")) {
+                               $readme = '<pre>' . file_get_contents("addon/$addon/README") . '</pre>';
+                       }
+
+                       $admin_form = '';
+                       if (array_key_exists($addon, $addons_admin)) {
+                               require_once "addon/$addon/$addon.php";
+                               $func = $addon . '_addon_admin';
+                               $func($a, $admin_form);
+                       }
+
+                       $t = Renderer::getMarkupTemplate('admin/addons/details.tpl');
+
+                       return Renderer::replaceMacros($t, [
+                               '$title' => L10n::t('Administration'),
+                               '$page' => L10n::t('Addons'),
+                               '$toggle' => L10n::t('Toggle'),
+                               '$settings' => L10n::t('Settings'),
+                               '$baseurl' => $a->getBaseURL(true),
+
+                               '$addon' => $addon,
+                               '$status' => $status,
+                               '$action' => $action,
+                               '$info' => Addon::getInfo($addon),
+                               '$str_author' => L10n::t('Author: '),
+                               '$str_maintainer' => L10n::t('Maintainer: '),
+
+                               '$admin_form' => $admin_form,
+                               '$function' => 'addons',
+                               '$screenshot' => '',
+                               '$readme' => $readme,
+
+                               '$form_security_token' => parent::getFormSecurityToken('admin_themes'),
+                       ]);
+               }
+
+               $a->internalRedirect('admin/addons');
+       }
+}
diff --git a/src/Module/Admin/Addons/Index.php b/src/Module/Admin/Addons/Index.php
new file mode 100644 (file)
index 0000000..2fa39d8
--- /dev/null
@@ -0,0 +1,62 @@
+<?php
+
+namespace Friendica\Module\Admin\Addons;
+
+use Friendica\Core\Addon;
+use Friendica\Core\L10n;
+use Friendica\Core\Renderer;
+use Friendica\Module\BaseAdminModule;
+
+class Index extends BaseAdminModule
+{
+       public static function content()
+       {
+               parent::content();
+
+               $a = self::getApp();
+
+               // reload active themes
+               if (!empty($_GET['action'])) {
+                       parent::checkFormSecurityTokenRedirectOnError('/admin/addons', 'admin_addons', 't');
+
+                       switch ($_GET['action']) {
+                               case 'reload':
+                                       Addon::reload();
+                                       info('Addons reloaded');
+                                       break;
+
+                               case 'toggle' :
+                                       $addon = defaults($_GET, 'addon', '');
+                                       if (Addon::isEnabled($addon)) {
+                                               Addon::uninstall($addon);
+                                               info(L10n::t('Addon %s disabled.', $addon));
+                                       } elseif (Addon::install($addon)) {
+                                               info(L10n::t('Addon %s enabled.', $addon));
+                                       } else {
+                                               info(L10n::t('Addon %s failed to install.', $addon));
+                                       }
+
+                                       break;
+
+                       }
+
+                       $a->internalRedirect('admin/addons');
+               }
+
+               $addons = Addon::getAvailableList();
+
+               $t = Renderer::getMarkupTemplate('admin/addons/index.tpl');
+               return Renderer::replaceMacros($t, [
+                       '$title' => L10n::t('Administration'),
+                       '$page' => L10n::t('Addons'),
+                       '$submit' => L10n::t('Save Settings'),
+                       '$reload' => L10n::t('Reload active addons'),
+                       '$baseurl' => $a->getBaseURL(true),
+                       '$function' => 'addons',
+                       '$addons' => $addons,
+                       '$pcount' => count($addons),
+                       '$noplugshint' => L10n::t('There are currently no addons available on your node. You can find the official addon repository at %1$s and might find other interesting addons in the open addon registry at %2$s', 'https://github.com/friendica/friendica-addons', 'http://addons.friendi.ca'),
+                       '$form_security_token' => parent::getFormSecurityToken('admin_addons'),
+               ]);
+       }
+}
diff --git a/src/Module/Admin/Blocklist/Contact.php b/src/Module/Admin/Blocklist/Contact.php
new file mode 100644 (file)
index 0000000..1ec6e00
--- /dev/null
@@ -0,0 +1,86 @@
+<?php
+
+namespace Friendica\Module\Admin\Blocklist;
+
+use Friendica\Content\Pager;
+use Friendica\Core\L10n;
+use Friendica\Core\Renderer;
+use Friendica\Database\DBA;
+use Friendica\Module\BaseAdminModule;
+use Friendica\Model;
+
+class Contact extends BaseAdminModule
+{
+       public static function post()
+       {
+               parent::post();
+
+               $contact_url = defaults($_POST, 'contact_url', '');
+               $contacts    = defaults($_POST, 'contacts', []);
+
+               parent::checkFormSecurityTokenRedirectOnError('/admin/blocklist/contact', 'admin_contactblock');
+
+               if (!empty($_POST['page_contactblock_block'])) {
+                       $contact_id = Model\Contact::getIdForURL($contact_url);
+                       if ($contact_id) {
+                               Model\Contact::block($contact_id);
+                               notice(L10n::t('The contact has been blocked from the node'));
+                       } else {
+                               notice(L10n::t("Could not find any contact entry for this URL \x28%s\x29", $contact_url));
+                       }
+               }
+
+               if (!empty($_POST['page_contactblock_unblock'])) {
+                       foreach ($contacts as $uid) {
+                               Model\Contact::unblock($uid);
+                       }
+                       notice(L10n::tt("%s contact unblocked", "%s contacts unblocked", count($contacts)));
+               }
+
+               self::getApp()->internalRedirect('admin/blocklist/contact');
+       }
+
+       public static function content()
+       {
+               parent::content();
+
+               $a = self::getApp();
+
+               $condition = ['uid' => 0, 'blocked' => true];
+
+               $total = DBA::count('contact', $condition);
+
+               $pager = new Pager($a->query_string, 30);
+
+               $contacts = Model\Contact::select([], $condition, ['limit' => [$pager->getStart(), $pager->getItemsPerPage()]]);
+
+               $t = Renderer::getMarkupTemplate('admin/blocklist/contact.tpl');
+               $o = Renderer::replaceMacros($t, [
+                       // strings //
+                       '$title'       => L10n::t('Administration'),
+                       '$page'        => L10n::t('Remote Contact Blocklist'),
+                       '$description' => L10n::t('This page allows you to prevent any message from a remote contact to reach your node.'),
+                       '$submit'      => L10n::t('Block Remote Contact'),
+                       '$select_all'  => L10n::t('select all'),
+                       '$select_none' => L10n::t('select none'),
+                       '$block'       => L10n::t('Block'),
+                       '$unblock'     => L10n::t('Unblock'),
+                       '$no_data'     => L10n::t('No remote contact is blocked from this node.'),
+
+                       '$h_contacts'  => L10n::t('Blocked Remote Contacts'),
+                       '$h_newblock'  => L10n::t('Block New Remote Contact'),
+                       '$th_contacts' => [L10n::t('Photo'), L10n::t('Name'), L10n::t('Address'), L10n::t('Profile URL')],
+
+                       '$form_security_token' => parent::getFormSecurityToken("admin_contactblock"),
+
+                       // values //
+                       '$baseurl'    => $a->getBaseURL(true),
+
+                       '$contacts'   => $contacts,
+                       '$total_contacts' => L10n::tt('%s total blocked contact', '%s total blocked contacts', $total),
+                       '$paginate'   => $pager->renderFull($total),
+                       '$contacturl' => ['contact_url', L10n::t("Profile URL"), '', L10n::t("URL of the remote contact to block.")],
+               ]);
+               return $o;
+       }
+}
diff --git a/src/Module/Admin/Blocklist/Server.php b/src/Module/Admin/Blocklist/Server.php
new file mode 100644 (file)
index 0000000..754d1aa
--- /dev/null
@@ -0,0 +1,92 @@
+<?php
+
+namespace Friendica\Module\Admin\Blocklist;
+
+use Friendica\Core\Config;
+use Friendica\Core\L10n;
+use Friendica\Core\Renderer;
+use Friendica\Module\BaseAdminModule;
+use Friendica\Util\Strings;
+
+class Server extends BaseAdminModule
+{
+       public static function post()
+       {
+               parent::post();
+
+               if (empty($_POST['page_blocklist_save']) && empty($_POST['page_blocklist_edit'])) {
+                       return;
+               }
+
+               parent::checkFormSecurityTokenRedirectOnError('/admin/blocklist/server', 'admin_blocklist');
+
+               if (!empty($_POST['page_blocklist_save'])) {
+                       //  Add new item to blocklist
+                       $blocklist = Config::get('system', 'blocklist');
+                       $blocklist[] = [
+                               'domain' => Strings::escapeTags(trim($_POST['newentry_domain'])),
+                               'reason' => Strings::escapeTags(trim($_POST['newentry_reason']))
+                       ];
+                       Config::set('system', 'blocklist', $blocklist);
+                       info(L10n::t('Server added to blocklist.') . EOL);
+               } else {
+                       // Edit the entries from blocklist
+                       $blocklist = [];
+                       foreach ($_POST['domain'] as $id => $domain) {
+                               // Trimming whitespaces as well as any lingering slashes
+                               $domain = Strings::escapeTags(trim($domain, "\x00..\x1F/"));
+                               $reason = Strings::escapeTags(trim($_POST['reason'][$id]));
+                               if (empty($_POST['delete'][$id])) {
+                                       $blocklist[] = [
+                                               'domain' => $domain,
+                                               'reason' => $reason
+                                       ];
+                               }
+                       }
+                       Config::set('system', 'blocklist', $blocklist);
+                       info(L10n::t('Site blocklist updated.') . EOL);
+               }
+
+               self::getApp()->internalRedirect('admin/blocklist/server');
+       }
+
+       public static function content()
+       {
+               parent::content();
+
+               $a = self::getApp();
+
+               $blocklist = Config::get('system', 'blocklist');
+               $blocklistform = [];
+               if (is_array($blocklist)) {
+                       foreach ($blocklist as $id => $b) {
+                               $blocklistform[] = [
+                                       'domain' => ["domain[$id]", L10n::t('Blocked domain'), $b['domain'], '', L10n::t('The blocked domain'), 'required', '', ''],
+                                       'reason' => ["reason[$id]", L10n::t("Reason for the block"), $b['reason'], L10n::t('The reason why you blocked this domain.') . '(' . $b['domain'] . ')', 'required', '', ''],
+                                       'delete' => ["delete[$id]", L10n::t("Delete domain") . ' (' . $b['domain'] . ')', false, L10n::t("Check to delete this entry from the blocklist")]
+                               ];
+                       }
+               }
+
+               $t = Renderer::getMarkupTemplate('admin/blocklist/server.tpl');
+               return Renderer::replaceMacros($t, [
+                       '$title' => L10n::t('Administration'),
+                       '$page' => L10n::t('Server Blocklist'),
+                       '$intro' => L10n::t('This page can be used to define a black list of servers from the federated network that are not allowed to interact with your node. For all entered domains you should also give a reason why you have blocked the remote server.'),
+                       '$public' => L10n::t('The list of blocked servers will be made publically available on the /friendica page so that your users and people investigating communication problems can find the reason easily.'),
+                       '$addtitle' => L10n::t('Add new entry to block list'),
+                       '$newdomain' => ['newentry_domain', L10n::t('Server Domain'), '', L10n::t('The domain of the new server to add to the block list. Do not include the protocol.'), 'required', '', ''],
+                       '$newreason' => ['newentry_reason', L10n::t('Block reason'), '', L10n::t('The reason why you blocked this domain.'), 'required', '', ''],
+                       '$submit' => L10n::t('Add Entry'),
+                       '$savechanges' => L10n::t('Save changes to the blocklist'),
+                       '$currenttitle' => L10n::t('Current Entries in the Blocklist'),
+                       '$thurl' => L10n::t('Blocked domain'),
+                       '$threason' => L10n::t('Reason for the block'),
+                       '$delentry' => L10n::t('Delete entry from blocklist'),
+                       '$entries' => $blocklistform,
+                       '$baseurl' => $a->getBaseURL(true),
+                       '$confirm_delete' => L10n::t('Delete entry from blocklist?'),
+                       '$form_security_token' => parent::getFormSecurityToken("admin_blocklist")
+               ]);
+       }
+}
diff --git a/src/Module/Admin/DBSync.php b/src/Module/Admin/DBSync.php
new file mode 100644 (file)
index 0000000..4c29eea
--- /dev/null
@@ -0,0 +1,107 @@
+<?php
+
+namespace Friendica\Module\Admin;
+
+use Friendica\Core\Config;
+use Friendica\Core\L10n;
+use Friendica\Core\Renderer;
+use Friendica\Core\Update;
+use Friendica\Database\DBA;
+use Friendica\Database\DBStructure;
+use Friendica\Module\BaseAdminModule;
+
+class DBSync extends BaseAdminModule
+{
+       public static function content()
+       {
+               parent::content();
+
+               $a = self::getApp();
+
+               $o = '';
+
+               if ($a->argc > 3 && $a->argv[2] === 'mark') {
+                       // @TODO: Replace with parameter from router
+                       $update = intval($a->argv[3]);
+                       if ($update) {
+                               Config::set('database', 'update_' . $update, 'success');
+                               $curr = Config::get('system', 'build');
+                               if (intval($curr) == $update) {
+                                       Config::set('system', 'build', intval($curr) + 1);
+                               }
+                               info(L10n::t('Update has been marked successful') . EOL);
+                       }
+                       $a->internalRedirect('admin/dbsync');
+               }
+
+               if ($a->argc > 2) {
+                       if ($a->argv[2] === 'check') {
+                               // @TODO Seems like a similar logic like Update::check()
+                               $retval = DBStructure::update($a->getBasePath(), false, true);
+                               if ($retval === '') {
+                                       $o .= L10n::t("Database structure update %s was successfully applied.", DB_UPDATE_VERSION) . "<br />";
+                                       Config::set('database', 'last_successful_update', DB_UPDATE_VERSION);
+                                       Config::set('database', 'last_successful_update_time', time());
+                               } else {
+                                       $o .= L10n::t("Executing of database structure update %s failed with error: %s", DB_UPDATE_VERSION, $retval) . "<br />";
+                               }
+                               if ($a->argv[2] === 'check') {
+                                       return $o;
+                               }
+                       } elseif (intval($a->argv[2])) {
+                               require_once 'update.php';
+
+                               // @TODO: Replace with parameter from router
+                               $update = intval($a->argv[2]);
+
+                               $func = 'update_' . $update;
+
+                               if (function_exists($func)) {
+                                       $retval = $func();
+
+                                       if ($retval === Update::FAILED) {
+                                               $o .= L10n::t("Executing %s failed with error: %s", $func, $retval);
+                                       } elseif ($retval === Update::SUCCESS) {
+                                               $o .= L10n::t('Update %s was successfully applied.', $func);
+                                               Config::set('database', $func, 'success');
+                                       } else {
+                                               $o .= L10n::t('Update %s did not return a status. Unknown if it succeeded.', $func);
+                                       }
+                               } else {
+                                       $o .= L10n::t('There was no additional update function %s that needed to be called.', $func) . "<br />";
+                                       Config::set('database', $func, 'success');
+                               }
+
+                               return $o;
+                       }
+               }
+
+               $failed = [];
+               $configStmt = DBA::select('config', ['k', 'v'], ['cat' => 'database']);
+               while ($config = DBA::fetch($configStmt)) {
+                       $upd = intval(substr($config['k'], 7));
+                       if ($upd >= 1139 && $config['v'] != 'success') {
+                               $failed[] = $upd;
+                       }
+               }
+
+               if (!count($failed)) {
+                       $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('admin/dbsync/structure_check.tpl'), [
+                               '$base' => $a->getBaseURL(true),
+                               '$banner' => L10n::t('No failed updates.'),
+                               '$check' => L10n::t('Check database structure'),
+                       ]);
+               } else {
+                       $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('admin/dbsync/failed_updates.tpl'), [
+                               '$base' => $a->getBaseURL(true),
+                               '$banner' => L10n::t('Failed Updates'),
+                               '$desc' => L10n::t('This does not include updates prior to 1139, which did not return a status.'),
+                               '$mark' => L10n::t("Mark success \x28if update was manually applied\x29"),
+                               '$apply' => L10n::t('Attempt to execute this update step automatically'),
+                               '$failed' => $failed
+                       ]);
+               }
+
+               return $o;
+       }
+}
diff --git a/src/Module/Admin/Features.php b/src/Module/Admin/Features.php
new file mode 100644 (file)
index 0000000..328e7e6
--- /dev/null
@@ -0,0 +1,74 @@
+<?php
+
+namespace Friendica\Module\Admin;
+
+use Friendica\Content\Feature;
+use Friendica\Core\Config;
+use Friendica\Core\L10n;
+use Friendica\Core\Renderer;
+use Friendica\Module\BaseAdminModule;
+
+class Features extends BaseAdminModule
+{
+       public static function post()
+       {
+               parent::post();
+
+               parent::checkFormSecurityTokenRedirectOnError('/admin/features', 'admin_manage_features');
+
+               $features = Feature::get(false);
+
+               foreach ($features as $fname => $fdata) {
+                       foreach (array_slice($fdata, 1) as $f) {
+                               $feature = $f[0];
+                               $feature_state = 'feature_' . $feature;
+                               $featurelock = 'featurelock_' . $feature;
+
+                               if (!empty($_POST[$feature_state])) {
+                                       $val = intval($_POST[$feature_state]);
+                               } else {
+                                       $val = 0;
+                               }
+                               Config::set('feature', $feature, $val);
+
+                               if (!empty($_POST[$featurelock])) {
+                                       Config::set('feature_lock', $feature, $val);
+                               } else {
+                                       Config::delete('feature_lock', $feature);
+                               }
+                       }
+               }
+
+               self::getApp()->internalRedirect('admin/features');
+       }
+
+       public static function content()
+       {
+               parent::content();
+
+               $arr = [];
+               $features = Feature::get(false);
+
+               foreach ($features as $fname => $fdata) {
+                       $arr[$fname] = [];
+                       $arr[$fname][0] = $fdata[0];
+                       foreach (array_slice($fdata, 1) as $f) {
+                               $set = Config::get('feature', $f[0], $f[3]);
+                               $arr[$fname][1][] = [
+                                       ['feature_' . $f[0], $f[1], $set, $f[2], [L10n::t('Off'), L10n::t('On')]],
+                                       ['featurelock_' . $f[0], L10n::t('Lock feature %s', $f[1]), (($f[4] !== false) ? "1" : ''), '', [L10n::t('Off'), L10n::t('On')]]
+                               ];
+                       }
+               }
+
+               $tpl = Renderer::getMarkupTemplate('admin/features.tpl');
+               $o = Renderer::replaceMacros($tpl, [
+                       '$form_security_token' => parent::getFormSecurityToken("admin_manage_features"),
+                       '$title' => L10n::t('Manage Additional Features'),
+                       '$features' => $arr,
+                       '$submit' => L10n::t('Save Settings'),
+               ]);
+
+               return $o;
+       }
+}
diff --git a/src/Module/Admin/Federation.php b/src/Module/Admin/Federation.php
new file mode 100644 (file)
index 0000000..f32f0e2
--- /dev/null
@@ -0,0 +1,195 @@
+<?php
+
+namespace Friendica\Module\Admin;
+
+use Friendica\Core\Config;
+use Friendica\Core\L10n;
+use Friendica\Core\Renderer;
+use Friendica\Database\DBA;
+use Friendica\Module\BaseAdminModule;
+
+class Federation extends BaseAdminModule
+{
+       public static function content()
+       {
+               parent::content();
+
+               // get counts on active friendica, diaspora, redmatrix, hubzilla, gnu
+               // social and statusnet nodes this node is knowing
+               //
+               // We are looking for the following platforms in the DB, "Red" should find
+               // all variants of that platform ID string as the q() function is stripping
+               // off one % two of them are needed in the query
+               // Add more platforms if you like, when one returns 0 known nodes it is not
+               // displayed on the stats page.
+               $platforms = ['Friendi%%a', 'Diaspora', '%%red%%', 'Hubzilla', 'BlaBlaNet', 'GNU Social', 'StatusNet', 'Mastodon', 'Pleroma', 'socialhome', 'ganggo'];
+               $colors = [
+                       'Friendi%%a' => '#ffc018', // orange from the logo
+                       'Diaspora'   => '#a1a1a1', // logo is black and white, makes a gray
+                       '%%red%%'    => '#c50001', // fire red from the logo
+                       'Hubzilla'   => '#43488a', // blue from the logo
+                       'BlaBlaNet'  => '#3B5998', // blue from the navbar at blablanet-dot-com
+                       'GNU Social' => '#a22430', // dark red from the logo
+                       'StatusNet'  => '#789240', // the green from the logo (red and blue have already others
+                       'Mastodon'   => '#1a9df9', // blue from the Mastodon logo
+                       'Pleroma'    => '#E46F0F', // Orange from the text that is used on Pleroma instances
+                       'socialhome' => '#52056b', // lilac from the Django Image used at the Socialhome homepage
+                       'ganggo'     => '#69d7e2', // from the favicon
+               ];
+               $counts = [];
+               $total = 0;
+               $users = 0;
+
+               foreach ($platforms as $platform) {
+                       // get a total count for the platform, the name and version of the
+                       // highest version and the protocol tpe
+                       $platformCount = DBA::fetchFirst('SELECT
+                               COUNT(*) AS `total`,
+                               SUM(`registered-users`) AS `users`,
+                               ANY_VALUE(`platform`) AS `platform`,
+                               ANY_VALUE(`network`) AS `network`,
+                               MAX(`version`) AS `version` FROM `gserver`
+                               WHERE `platform` LIKE ?
+                               AND `last_contact` >= `last_failure`
+                               ORDER BY `version` ASC', $platform);
+                       $total += $platformCount['total'];
+                       $users += $platformCount['users'];
+
+                       // what versions for that platform do we know at all?
+                       // again only the active nodes
+                       $versionCountsStmt = DBA::p('SELECT
+                               COUNT(*) AS `total`,
+                               `version` FROM `gserver`
+                               WHERE `last_contact` >= `last_failure`
+                               AND `platform` LIKE ?
+                               GROUP BY `version`
+                               ORDER BY `version`;', $platform);
+                       $versionCounts = DBA::toArray($versionCountsStmt);
+
+                       //
+                       // clean up version numbers
+                       //
+                       // some platforms do not provide version information, add a unkown there
+                       // to the version string for the displayed list.
+                       foreach ($versionCounts as $key => $value) {
+                               if ($versionCounts[$key]['version'] == '') {
+                                       $versionCounts[$key] = ['total' => $versionCounts[$key]['total'], 'version' => L10n::t('unknown')];
+                               }
+                       }
+
+                       // Reformat and compact version numbers
+                       if ($platform == 'Pleroma') {
+                               $compacted = [];
+                               foreach ($versionCounts as $key => $value) {
+                                       $version = $versionCounts[$key]['version'];
+                                       $parts = explode(' ', trim($version));
+                                       do {
+                                               $part = array_pop($parts);
+                                       } while (!empty($parts) && ((strlen($part) >= 40) || (strlen($part) <= 3)));
+                                       // only take the x.x.x part of the version, not the "release" after the dash
+                                       $part = array_shift(explode('-', $part));
+                                       if (!empty($part)) {
+                                               if (empty($compacted[$part])) {
+                                                       $compacted[$part] = $versionCounts[$key]['total'];
+                                               } else {
+                                                       $compacted[$part] += $versionCounts[$key]['total'];
+                                               }
+                                       }
+                               }
+
+                               $versionCounts = [];
+                               foreach ($compacted as $version => $pl_total) {
+                                       $versionCounts[] = ['version' => $version, 'total' => $pl_total];
+                               }
+                       }
+
+                       // in the DB the Diaspora versions have the format x.x.x.x-xx the last
+                       // part (-xx) should be removed to clean up the versions from the "head
+                       // commit" information and combined into a single entry for x.x.x.x
+                       if ($platform == 'Diaspora') {
+                               $newV = [];
+                               $newVv = [];
+                               foreach ($versionCounts as $vv) {
+                                       $newVC = $vv['total'];
+                                       $newVV = $vv['version'];
+                                       $posDash = strpos($newVV, '-');
+                                       if ($posDash) {
+                                               $newVV = substr($newVV, 0, $posDash);
+                                       }
+                                       if (isset($newV[$newVV])) {
+                                               $newV[$newVV] += $newVC;
+                                       } else {
+                                               $newV[$newVV] = $newVC;
+                                       }
+                               }
+                               foreach ($newV as $key => $value) {
+                                       array_push($newVv, ['total' => $value, 'version' => $key]);
+                               }
+                               $versionCounts = $newVv;
+                       }
+
+                       // early friendica versions have the format x.x.xxxx where xxxx is the
+                       // DB version stamp; those should be operated out and versions be
+                       // conbined
+                       if ($platform == 'Friendi%%a') {
+                               $newV = [];
+                               $newVv = [];
+                               foreach ($versionCounts as $vv) {
+                                       $newVC = $vv['total'];
+                                       $newVV = $vv['version'];
+                                       $lastDot = strrpos($newVV, '.');
+                                       $len = strlen($newVV) - 1;
+                                       if (($lastDot == $len - 4) && (!strrpos($newVV, '-rc') == $len - 3)) {
+                                               $newVV = substr($newVV, 0, $lastDot);
+                                       }
+                                       if (isset($newV[$newVV])) {
+                                               $newV[$newVV] += $newVC;
+                                       } else {
+                                               $newV[$newVV] = $newVC;
+                                       }
+                               }
+                               foreach ($newV as $key => $value) {
+                                       array_push($newVv, ['total' => $value, 'version' => $key]);
+                               }
+                               $versionCounts = $newVv;
+                       }
+
+                       // Assure that the versions are sorted correctly
+                       $v2 = [];
+                       $versions = [];
+                       foreach ($versionCounts as $vv) {
+                               $version = trim(strip_tags($vv["version"]));
+                               $v2[$version] = $vv;
+                               $versions[] = $version;
+                       }
+
+                       usort($versions, 'version_compare');
+
+                       $versionCounts = [];
+                       foreach ($versions as $version) {
+                               $versionCounts[] = $v2[$version];
+                       }
+
+                       // the 3rd array item is needed for the JavaScript graphs as JS does
+                       // not like some characters in the names of variables...
+                       $counts[$platform] = [$platformCount, $versionCounts, str_replace([' ', '%'], '', $platform), $colors[$platform]];
+               }
+
+               // some helpful text
+               $intro = L10n::t('This page offers you some numbers to the known part of the federated social network your Friendica node is part of. These numbers are not complete but only reflect the part of the network your node is aware of.');
+               $hint = L10n::t('The <em>Auto Discovered Contact Directory</em> feature is not enabled, it will improve the data displayed here.');
+
+               // load the template, replace the macros and return the page content
+               $t = Renderer::getMarkupTemplate('admin/federation.tpl');
+               return Renderer::replaceMacros($t, [
+                       '$title' => L10n::t('Administration'),
+                       '$page' => L10n::t('Federation Statistics'),
+                       '$intro' => $intro,
+                       '$hint' => $hint,
+                       '$autoactive' => Config::get('system', 'poco_completion'),
+                       '$counts' => $counts,
+                       '$version' => FRIENDICA_VERSION,
+                       '$legendtext' => L10n::t('Currently this node is aware of %d nodes with %d registered users from the following platforms:', $total, $users),
+               ]);
+       }
+}
diff --git a/src/Module/Admin/Item/Delete.php b/src/Module/Admin/Item/Delete.php
new file mode 100644 (file)
index 0000000..766e65c
--- /dev/null
@@ -0,0 +1,55 @@
+<?php
+
+namespace Friendica\Module\Admin\Item;
+
+use Friendica\Core\L10n;
+use Friendica\Core\Renderer;
+use Friendica\Model\Item;
+use Friendica\Module\BaseAdminModule;
+use Friendica\Util\Strings;
+
+class Delete extends BaseAdminModule
+{
+       public static function post()
+       {
+               parent::post();
+
+               if (empty($_POST['page_deleteitem_submit'])) {
+                       return;
+               }
+
+               parent::checkFormSecurityTokenRedirectOnError('/admin/item/delete', 'admin_deleteitem');
+
+               if (!empty($_POST['page_deleteitem_submit'])) {
+                       $guid = trim(Strings::escapeTags($_POST['deleteitemguid']));
+                       // The GUID should not include a "/", so if there is one, we got an URL
+                       // and the last part of it is most likely the GUID.
+                       if (strpos($guid, '/')) {
+                               $guid = substr($guid, strrpos($guid, '/') + 1);
+                       }
+                       // Now that we have the GUID, drop those items, which will also delete the
+                       // associated threads.
+                       Item::delete(['guid' => $guid]);
+               }
+
+               info(L10n::t('Item marked for deletion.') . EOL);
+               self::getApp()->internalRedirect('admin/item/delete');
+       }
+
+       public static function content()
+       {
+               parent::content();
+
+               $t = Renderer::getMarkupTemplate('admin/item/delete.tpl');
+
+               return Renderer::replaceMacros($t, [
+                       '$title' => L10n::t('Administration'),
+                       '$page' => L10n::t('Delete Item'),
+                       '$submit' => L10n::t('Delete this Item'),
+                       '$intro1' => L10n::t('On this page you can delete an item from your node. If the item is a top level posting, the entire thread will be deleted.'),
+                       '$intro2' => L10n::t('You need to know the GUID of the item. You can find it e.g. by looking at the display URL. The last part of http://example.com/display/123456 is the GUID, here 123456.'),
+                       '$deleteitemguid' => ['deleteitemguid', L10n::t("GUID"), '', L10n::t("The GUID of the item you want to delete."), 'required', 'autofocus'],
+                       '$form_security_token' => parent::getFormSecurityToken("admin_deleteitem")
+               ]);
+       }
+}
diff --git a/src/Module/Admin/Item/Source.php b/src/Module/Admin/Item/Source.php
new file mode 100644 (file)
index 0000000..1e85b7d
--- /dev/null
@@ -0,0 +1,55 @@
+<?php
+
+namespace Friendica\Module\Admin\Item;
+
+use Friendica\Core\L10n;
+use Friendica\Core\Renderer;
+use Friendica\Model;
+use Friendica\Module\BaseAdminModule;
+
+/**
+ * @author Hypolite Petovan <mrpetovan@gmail.com>
+ */
+class Source extends BaseAdminModule
+
+{
+       public static function content()
+       {
+               parent::content();
+
+               $a = self::getApp();
+
+               $guid = null;
+               if (!empty($a->argv[1])) {
+                       $guid = $a->argv[1];
+               }
+
+               $guid = defaults($_REQUEST['guid'], $guid);
+
+               $source = '';
+               $item_uri = '';
+               $item_id = '';
+               $terms = [];
+               if (!empty($guid)) {
+                       $item = Model\Item::selectFirst(['id', 'guid', 'uri'], ['guid' => $guid]);
+
+                       $conversation = Model\Conversation::getByItemUri($item['uri']);
+
+                       $item_id = $item['id'];
+                       $item_uri = $item['uri'];
+                       $source = $conversation['source'];
+                       $terms = Model\Term::tagArrayFromItemId($item['id'], [Model\Term::HASHTAG, Model\Term::MENTION, Model\Term::IMPLICIT_MENTION]);
+               }
+
+               $tpl = Renderer::getMarkupTemplate('admin/item/source.tpl');
+               $o = Renderer::replaceMacros($tpl, [
+                       '$guid'          => ['guid', L10n::t('Item Guid'), $guid, ''],
+                       '$source'        => $source,
+                       '$item_uri'      => $item_uri,
+                       '$item_id'       => $item_id,
+                       '$terms'         => $terms,
+               ]);
+
+               return $o;
+       }
+}
diff --git a/src/Module/Admin/Logs/Settings.php b/src/Module/Admin/Logs/Settings.php
new file mode 100644 (file)
index 0000000..d556184
--- /dev/null
@@ -0,0 +1,74 @@
+<?php
+
+namespace Friendica\Module\Admin\Logs;
+
+use Friendica\Core\Config;
+use Friendica\Core\L10n;
+use Friendica\Core\Renderer;
+use Friendica\Module\BaseAdminModule;
+use Friendica\Util\Strings;
+use Psr\Log\LogLevel;
+
+class Settings extends BaseAdminModule
+{
+       public static function post()
+       {
+               parent::post();
+
+               if (!empty($_POST['page_logs'])) {
+                       parent::checkFormSecurityTokenRedirectOnError('/admin/logs', 'admin_logs');
+
+                       $logfile   = (!empty($_POST['logfile']) ? Strings::escapeTags(trim($_POST['logfile'])) : '');
+                       $debugging = !empty($_POST['debugging']);
+                       $loglevel  = defaults($_POST, 'loglevel', LogLevel::ERROR);
+
+                       Config::set('system', 'logfile', $logfile);
+                       Config::set('system', 'debugging', $debugging);
+                       Config::set('system', 'loglevel', $loglevel);
+               }
+
+               info(L10n::t("Log settings updated."));
+               self::getApp()->internalRedirect('admin/logs');
+       }
+
+       public static function content()
+       {
+               parent::content();
+
+               $a = self::getApp();
+
+               $log_choices = [
+                       LogLevel::ERROR   => 'Error',
+                       LogLevel::WARNING => 'Warning',
+                       LogLevel::NOTICE  => 'Notice',
+                       LogLevel::INFO    => 'Info',
+                       LogLevel::DEBUG   => 'Debug',
+               ];
+
+               if (ini_get('log_errors')) {
+                       $phplogenabled = L10n::t('PHP log currently enabled.');
+               } else {
+                       $phplogenabled = L10n::t('PHP log currently disabled.');
+               }
+
+               $t = Renderer::getMarkupTemplate('admin/logs/settings.tpl');
+
+               return Renderer::replaceMacros($t, [
+                       '$title' => L10n::t('Administration'),
+                       '$page' => L10n::t('Logs'),
+                       '$submit' => L10n::t('Save Settings'),
+                       '$clear' => L10n::t('Clear'),
+                       '$baseurl' => $a->getBaseURL(true),
+                       '$logname' => Config::get('system', 'logfile'),
+                       // see /help/smarty3-templates#1_1 on any Friendica node
+                       '$debugging' => ['debugging', L10n::t("Enable Debugging"), Config::get('system', 'debugging'), ""],
+                       '$logfile' => ['logfile', L10n::t("Log file"), Config::get('system', 'logfile'), L10n::t("Must be writable by web server. Relative to your Friendica top-level directory.")],
+                       '$loglevel' => ['loglevel', L10n::t("Log level"), Config::get('system', 'loglevel'), "", $log_choices],
+                       '$form_security_token' => parent::getFormSecurityToken("admin_logs"),
+                       '$phpheader' => L10n::t("PHP logging"),
+                       '$phphint' => L10n::t("To temporarily enable logging of PHP errors and warnings you can prepend the following to the index.php file of your installation. The filename set in the 'error_log' line is relative to the friendica top-level directory and must be writeable by the web server. The option '1' for 'log_errors' and 'display_errors' is to enable these options, set to '0' to disable them."),
+                       '$phplogcode' => "error_reporting(E_ERROR | E_WARNING | E_PARSE);\nini_set('error_log','php.out');\nini_set('log_errors','1');\nini_set('display_errors', '1');",
+                       '$phplogenabled' => $phplogenabled,
+               ]);
+       }
+}
diff --git a/src/Module/Admin/Logs/View.php b/src/Module/Admin/Logs/View.php
new file mode 100644 (file)
index 0000000..b66a678
--- /dev/null
@@ -0,0 +1,52 @@
+<?php
+
+namespace Friendica\Module\Admin\Logs;
+
+use Friendica\Core\Config;
+use Friendica\Core\L10n;
+use Friendica\Core\Renderer;
+use Friendica\Module\BaseAdminModule;
+use Friendica\Util\Strings;
+
+class View extends BaseAdminModule
+{
+       public static function content()
+       {
+               parent::content();
+
+               $t = Renderer::getMarkupTemplate('admin/logs/view.tpl');
+               $f = Config::get('system', 'logfile');
+               $data = '';
+
+               if (!file_exists($f)) {
+                       $data = L10n::t('Error trying to open <strong>%1$s</strong> log file.\r\n<br/>Check to see if file %1$s exist and is readable.', $f);
+               } else {
+                       $fp = fopen($f, 'r');
+                       if (!$fp) {
+                               $data = L10n::t('Couldn\'t open <strong>%1$s</strong> log file.\r\n<br/>Check to see if file %1$s is readable.', $f);
+                       } else {
+                               $fstat = fstat($fp);
+                               $size = $fstat['size'];
+                               if ($size != 0) {
+                                       if ($size > 5000000 || $size < 0) {
+                                               $size = 5000000;
+                                       }
+                                       $seek = fseek($fp, 0 - $size, SEEK_END);
+                                       if ($seek === 0) {
+                                               $data = Strings::escapeHtml(fread($fp, $size));
+                                               while (!feof($fp)) {
+                                                       $data .= Strings::escapeHtml(fread($fp, 4096));
+                                               }
+                                       }
+                               }
+                               fclose($fp);
+                       }
+               }
+               return Renderer::replaceMacros($t, [
+                       '$title' => L10n::t('Administration'),
+                       '$page' => L10n::t('View Logs'),
+                       '$data' => $data,
+                       '$logname' => Config::get('system', 'logfile')
+               ]);
+       }
+}
diff --git a/src/Module/Admin/PhpInfo.php b/src/Module/Admin/PhpInfo.php
new file mode 100644 (file)
index 0000000..b912117
--- /dev/null
@@ -0,0 +1,16 @@
+<?php
+
+namespace Friendica\Module\Admin;
+
+use Friendica\Module\BaseAdminModule;
+
+class PhpInfo extends BaseAdminModule
+{
+       public static function rawContent()
+       {
+               parent::rawContent();
+
+               phpinfo();
+               exit();
+       }
+}
diff --git a/src/Module/Admin/Queue.php b/src/Module/Admin/Queue.php
new file mode 100644 (file)
index 0000000..e89aa53
--- /dev/null
@@ -0,0 +1,67 @@
+<?php
+
+namespace Friendica\Module\Admin;
+
+use Friendica\Core\L10n;
+use Friendica\Core\Renderer;
+use Friendica\Database\DBA;
+use Friendica\Module\BaseAdminModule;
+use Friendica\Util\Arrays;
+use Friendica\Util\DateTimeFormat;
+
+/**
+ * @brief Admin Inspect Queue Page
+ *
+ * Generates a page for the admin to have a look into the current queue of
+ * worker jobs. Shown are the parameters for the job and its priority.
+ *
+ * @return string
+ */
+class Queue extends BaseAdminModule
+{
+       public static function content()
+       {
+               parent::content();
+
+               $a = self::getApp();
+
+               // @TODO: Replace with parameter from router
+               $deferred = $a->argc > 2 && $a->argv[2] == 'deferred';
+
+               // get jobs from the workerqueue table
+               if ($deferred) {
+                       $condition = ["NOT `done` AND `next_try` > ?", DateTimeFormat::utcNow()];
+                       $sub_title = L10n::t('Inspect Deferred Worker Queue');
+                       $info = L10n::t("This page lists the deferred worker jobs. This are jobs that couldn't be executed at the first time.");
+               } else {
+                       $condition = ["NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
+                       $sub_title = L10n::t('Inspect Worker Queue');
+                       $info = L10n::t('This page lists the currently queued worker jobs. These jobs are handled by the worker cronjob you\'ve set up during install.');
+               }
+
+               // @TODO Move to Model\WorkerQueue::getEntries()
+               $entries = DBA::select('workerqueue', ['id', 'parameter', 'created', 'priority'], $condition, ['order' => ['priority']]);
+
+               $r = [];
+               while ($entry = DBA::fetch($entries)) {
+                       // fix GH-5469. ref: src/Core/Worker.php:217
+                       $entry['parameter'] = Arrays::recursiveImplode(json_decode($entry['parameter'], true), ': ');
+                       $entry['created'] = DateTimeFormat::local($entry['created']);
+                       $r[] = $entry;
+               }
+               DBA::close($entries);
+
+               $t = Renderer::getMarkupTemplate('admin/queue.tpl');
+               return Renderer::replaceMacros($t, [
+                       '$title' => L10n::t('Administration'),
+                       '$page' => $sub_title,
+                       '$count' => count($r),
+                       '$id_header' => L10n::t('ID'),
+                       '$param_header' => L10n::t('Job Parameters'),
+                       '$created_header' => L10n::t('Created'),
+                       '$prio_header' => L10n::t('Priority'),
+                       '$info' => $info,
+                       '$entries' => $r,
+               ]);
+       }
+}
diff --git a/src/Module/Admin/Site.php b/src/Module/Admin/Site.php
new file mode 100644 (file)
index 0000000..5d2004c
--- /dev/null
@@ -0,0 +1,686 @@
+<?php
+
+namespace Friendica\Module\Admin;
+
+use Friendica\App;
+use Friendica\Core\Config;
+use Friendica\Core\L10n;
+use Friendica\Core\Renderer;
+use Friendica\Core\StorageManager;
+use Friendica\Core\Theme;
+use Friendica\Core\Worker;
+use Friendica\Database\DBA;
+use Friendica\Module\BaseAdminModule;
+use Friendica\Module\Register;
+use Friendica\Protocol\PortableContact;
+use Friendica\Util\BasePath;
+use Friendica\Util\BaseURL;
+use Friendica\Util\Strings;
+
+require_once __DIR__ . '/../../../boot.php';
+
+class Site extends BaseAdminModule
+{
+       public static function post()
+       {
+               parent::post();
+
+               self::checkFormSecurityTokenRedirectOnError('/admin/site', 'admin_site');
+
+               $a = self::getApp();
+
+               if (!empty($_POST['republish_directory'])) {
+                       Worker::add(PRIORITY_LOW, 'Directory');
+                       return;
+               }
+
+               if (empty($_POST['page_site'])) {
+                       return;
+               }
+
+               // relocate
+               // @TODO This file could benefit from moving this feature away in a Module\Admin\Relocate class for example
+               if (!empty($_POST['relocate']) && !empty($_POST['relocate_url']) && $_POST['relocate_url'] != "") {
+                       $new_url = $_POST['relocate_url'];
+                       $new_url = rtrim($new_url, "/");
+
+                       $parsed = @parse_url($new_url);
+                       if (!is_array($parsed) || empty($parsed['host']) || empty($parsed['scheme'])) {
+                               notice(L10n::t("Can not parse base url. Must have at least <scheme>://<domain>"));
+                               $a->internalRedirect('admin/site');
+                       }
+
+                       /* steps:
+                        * replace all "baseurl" to "new_url" in config, profile, term, items and contacts
+                        * send relocate for every local user
+                        * */
+
+                       $old_url = $a->getBaseURL(true);
+
+                       // Generate host names for relocation the addresses in the format user@address.tld
+                       $new_host = str_replace("http://", "@", Strings::normaliseLink($new_url));
+                       $old_host = str_replace("http://", "@", Strings::normaliseLink($old_url));
+
+                       function update_table(App $a, $table_name, $fields, $old_url, $new_url)
+                       {
+                               $dbold = DBA::escape($old_url);
+                               $dbnew = DBA::escape($new_url);
+
+                               $upd = [];
+                               foreach ($fields as $f) {
+                                       $upd[] = "`$f` = REPLACE(`$f`, '$dbold', '$dbnew')";
+                               }
+
+                               $upds = implode(", ", $upd);
+
+                               $r = DBA::e(sprintf("UPDATE %s SET %s;", $table_name, $upds));
+                               if (!DBA::isResult($r)) {
+                                       notice("Failed updating '$table_name': " . DBA::errorMessage());
+                                       $a->internalRedirect('admin/site');
+                               }
+                       }
+
+                       // update tables
+                       // update profile links in the format "http://server.tld"
+                       update_table($a, "profile", ['photo', 'thumb'], $old_url, $new_url);
+                       update_table($a, "term", ['url'], $old_url, $new_url);
+                       update_table($a, "contact", ['photo', 'thumb', 'micro', 'url', 'nurl', 'alias', 'request', 'notify', 'poll', 'confirm', 'poco', 'avatar'], $old_url, $new_url);
+                       update_table($a, "gcontact", ['url', 'nurl', 'photo', 'server_url', 'notify', 'alias'], $old_url, $new_url);
+                       update_table($a, "item", ['owner-link', 'author-link', 'body', 'plink', 'tag'], $old_url, $new_url);
+
+                       // update profile addresses in the format "user@server.tld"
+                       update_table($a, "contact", ['addr'], $old_host, $new_host);
+                       update_table($a, "gcontact", ['connect', 'addr'], $old_host, $new_host);
+
+                       // update config
+                       Config::set('system', 'url', $new_url);
+                       $a->setBaseURL($new_url);
+
+                       // send relocate
+                       $usersStmt = DBA::select('user', ['uid'], ['account_removed' => false, 'account_expired' => false]);
+                       while ($user = DBA::fetch($usersStmt)) {
+                               Worker::add(PRIORITY_HIGH, 'Notifier', 'relocate', $user['uid']);
+                       }
+
+                       info("Relocation started. Could take a while to complete.");
+
+                       $a->internalRedirect('admin/site');
+               }
+               // end relocate
+
+               $sitename         = (!empty($_POST['sitename'])         ? Strings::escapeTags(trim($_POST['sitename']))      : '');
+               $sender_email     = (!empty($_POST['sender_email'])     ? Strings::escapeTags(trim($_POST['sender_email']))  : '');
+               $banner           = (!empty($_POST['banner'])           ? trim($_POST['banner'])                             : false);
+               $shortcut_icon    = (!empty($_POST['shortcut_icon'])    ? Strings::escapeTags(trim($_POST['shortcut_icon'])) : '');
+               $touch_icon       = (!empty($_POST['touch_icon'])       ? Strings::escapeTags(trim($_POST['touch_icon']))    : '');
+               $additional_info  = (!empty($_POST['additional_info'])  ? trim($_POST['additional_info'])                    : '');
+               $language         = (!empty($_POST['language'])         ? Strings::escapeTags(trim($_POST['language']))      : '');
+               $theme            = (!empty($_POST['theme'])            ? Strings::escapeTags(trim($_POST['theme']))         : '');
+               $theme_mobile     = (!empty($_POST['theme_mobile'])     ? Strings::escapeTags(trim($_POST['theme_mobile']))  : '');
+               $maximagesize     = (!empty($_POST['maximagesize'])     ? intval(trim($_POST['maximagesize']))               : 0);
+               $maximagelength   = (!empty($_POST['maximagelength'])   ? intval(trim($_POST['maximagelength']))             : MAX_IMAGE_LENGTH);
+               $jpegimagequality = (!empty($_POST['jpegimagequality']) ? intval(trim($_POST['jpegimagequality']))           : JPEG_QUALITY);
+
+               $register_policy        = (!empty($_POST['register_policy'])         ? intval(trim($_POST['register_policy']))             : 0);
+               $daily_registrations    = (!empty($_POST['max_daily_registrations']) ? intval(trim($_POST['max_daily_registrations']))     : 0);
+               $abandon_days           = (!empty($_POST['abandon_days'])            ? intval(trim($_POST['abandon_days']))                : 0);
+
+               $register_text          = (!empty($_POST['register_text'])           ? strip_tags(trim($_POST['register_text']))           : '');
+
+               $allowed_sites          = (!empty($_POST['allowed_sites'])           ? Strings::escapeTags(trim($_POST['allowed_sites']))  : '');
+               $allowed_email          = (!empty($_POST['allowed_email'])           ? Strings::escapeTags(trim($_POST['allowed_email']))  : '');
+               $forbidden_nicknames    = (!empty($_POST['forbidden_nicknames'])     ? strtolower(Strings::escapeTags(trim($_POST['forbidden_nicknames']))) : '');
+               $no_oembed_rich_content = !empty($_POST['no_oembed_rich_content']);
+               $allowed_oembed         = (!empty($_POST['allowed_oembed'])          ? Strings::escapeTags(trim($_POST['allowed_oembed'])) : '');
+               $block_public           = !empty($_POST['block_public']);
+               $force_publish          = !empty($_POST['publish_all']);
+               $global_directory       = (!empty($_POST['directory'])               ? Strings::escapeTags(trim($_POST['directory']))      : '');
+               $newuser_private        = !empty($_POST['newuser_private']);
+               $enotify_no_content     = !empty($_POST['enotify_no_content']);
+               $private_addons         = !empty($_POST['private_addons']);
+               $disable_embedded       = !empty($_POST['disable_embedded']);
+               $allow_users_remote_self = !empty($_POST['allow_users_remote_self']);
+               $explicit_content       = !empty($_POST['explicit_content']);
+
+               $no_multi_reg           = !empty($_POST['no_multi_reg']);
+               $no_openid              = !empty($_POST['no_openid']);
+               $no_regfullname         = !empty($_POST['no_regfullname']);
+               $community_page_style   = (!empty($_POST['community_page_style']) ? intval(trim($_POST['community_page_style'])) : 0);
+               $max_author_posts_community_page = (!empty($_POST['max_author_posts_community_page']) ? intval(trim($_POST['max_author_posts_community_page'])) : 0);
+
+               $verifyssl              = !empty($_POST['verifyssl']);
+               $proxyuser              = (!empty($_POST['proxyuser'])              ? Strings::escapeTags(trim($_POST['proxyuser'])) : '');
+               $proxy                  = (!empty($_POST['proxy'])                  ? Strings::escapeTags(trim($_POST['proxy']))     : '');
+               $timeout                = (!empty($_POST['timeout'])                ? intval(trim($_POST['timeout']))                : 60);
+               $maxloadavg             = (!empty($_POST['maxloadavg'])             ? intval(trim($_POST['maxloadavg']))             : 20);
+               $maxloadavg_frontend    = (!empty($_POST['maxloadavg_frontend'])    ? intval(trim($_POST['maxloadavg_frontend']))    : 50);
+               $min_memory             = (!empty($_POST['min_memory'])             ? intval(trim($_POST['min_memory']))             : 0);
+               $optimize_max_tablesize = (!empty($_POST['optimize_max_tablesize']) ? intval(trim($_POST['optimize_max_tablesize'])) : 100);
+               $optimize_fragmentation = (!empty($_POST['optimize_fragmentation']) ? intval(trim($_POST['optimize_fragmentation'])) : 30);
+               $poco_completion        = (!empty($_POST['poco_completion'])        ? intval(trim($_POST['poco_completion']))        : false);
+               $poco_requery_days      = (!empty($_POST['poco_requery_days'])      ? intval(trim($_POST['poco_requery_days']))      : 7);
+               $poco_discovery         = (!empty($_POST['poco_discovery'])         ? intval(trim($_POST['poco_discovery']))         : PortableContact::DISABLED);
+               $poco_discovery_since   = (!empty($_POST['poco_discovery_since'])   ? intval(trim($_POST['poco_discovery_since']))   : 30);
+               $poco_local_search      = !empty($_POST['poco_local_search']);
+               $nodeinfo               = !empty($_POST['nodeinfo']);
+               $dfrn_only              = !empty($_POST['dfrn_only']);
+               $ostatus_disabled       = !empty($_POST['ostatus_disabled']);
+               $ostatus_full_threads   = !empty($_POST['ostatus_full_threads']);
+               $diaspora_enabled       = !empty($_POST['diaspora_enabled']);
+               $ssl_policy             = (!empty($_POST['ssl_policy'])             ? intval($_POST['ssl_policy'])                    : 0);
+               $force_ssl              = !empty($_POST['force_ssl']);
+               $hide_help              = !empty($_POST['hide_help']);
+               $dbclean                = !empty($_POST['dbclean']);
+               $dbclean_expire_days    = (!empty($_POST['dbclean_expire_days'])    ? intval($_POST['dbclean_expire_days'])           : 0);
+               $dbclean_unclaimed      = (!empty($_POST['dbclean_unclaimed'])      ? intval($_POST['dbclean_unclaimed'])             : 0);
+               $dbclean_expire_conv    = (!empty($_POST['dbclean_expire_conv'])    ? intval($_POST['dbclean_expire_conv'])           : 0);
+               $suppress_tags          = !empty($_POST['suppress_tags']);
+               $itemcache              = (!empty($_POST['itemcache'])              ? Strings::escapeTags(trim($_POST['itemcache']))  : '');
+               $itemcache_duration     = (!empty($_POST['itemcache_duration'])     ? intval($_POST['itemcache_duration'])            : 0);
+               $max_comments           = (!empty($_POST['max_comments'])           ? intval($_POST['max_comments'])                  : 0);
+               $temppath               = (!empty($_POST['temppath'])               ? Strings::escapeTags(trim($_POST['temppath']))   : '');
+               $singleuser             = (!empty($_POST['singleuser'])             ? Strings::escapeTags(trim($_POST['singleuser'])) : '');
+               $proxy_disabled         = !empty($_POST['proxy_disabled']);
+               $only_tag_search        = !empty($_POST['only_tag_search']);
+               $rino                   = (!empty($_POST['rino'])                   ? intval($_POST['rino'])                          : 0);
+               $check_new_version_url  = (!empty($_POST['check_new_version_url'])  ? Strings::escapeTags(trim($_POST['check_new_version_url'])) : 'none');
+
+               $worker_queues    = (!empty($_POST['worker_queues'])                ? intval($_POST['worker_queues'])                 : 10);
+               $worker_dont_fork = !empty($_POST['worker_dont_fork']);
+               $worker_fastlane  = !empty($_POST['worker_fastlane']);
+               $worker_frontend  = !empty($_POST['worker_frontend']);
+
+               $relay_directly    = !empty($_POST['relay_directly']);
+               $relay_server      = (!empty($_POST['relay_server'])      ? Strings::escapeTags(trim($_POST['relay_server']))       : '');
+               $relay_subscribe   = !empty($_POST['relay_subscribe']);
+               $relay_scope       = (!empty($_POST['relay_scope'])       ? Strings::escapeTags(trim($_POST['relay_scope']))        : '');
+               $relay_server_tags = (!empty($_POST['relay_server_tags']) ? Strings::escapeTags(trim($_POST['relay_server_tags']))  : '');
+               $relay_user_tags   = !empty($_POST['relay_user_tags']);
+               $active_panel      = (!empty($_POST['active_panel'])      ? "#" . Strings::escapeTags(trim($_POST['active_panel'])) : '');
+
+               /**
+                * @var $storagebackend \Friendica\Model\Storage\IStorage
+                */
+               $storagebackend    = Strings::escapeTags(trim(defaults($_POST, 'storagebackend', '')));
+
+               // save storage backend form
+               if (!is_null($storagebackend) && $storagebackend != "") {
+                       if (StorageManager::setBackend($storagebackend)) {
+                               $storage_opts = $storagebackend::getOptions();
+                               $storage_form_prefix = preg_replace('|[^a-zA-Z0-9]|', '', $storagebackend);
+                               $storage_opts_data = [];
+                               foreach ($storage_opts as $name => $info) {
+                                       $fieldname = $storage_form_prefix . '_' . $name;
+                                       switch ($info[0]) { // type
+                                               case 'checkbox':
+                                               case 'yesno':
+                                                       $value = !empty($_POST[$fieldname]);
+                                                       break;
+                                               default:
+                                                       $value = defaults($_POST, $fieldname, '');
+                                       }
+                                       $storage_opts_data[$name] = $value;
+                               }
+                               unset($name);
+                               unset($info);
+
+                               $storage_form_errors = $storagebackend::saveOptions($storage_opts_data);
+                               if (count($storage_form_errors)) {
+                                       foreach ($storage_form_errors as $name => $err) {
+                                               notice('Storage backend, ' . $storage_opts[$name][1] . ': ' . $err);
+                                       }
+                                       $a->internalRedirect('admin/site' . $active_panel);
+                               }
+                       } else {
+                               info(L10n::t('Invalid storage backend setting value.'));
+                       }
+               }
+
+               // Has the directory url changed? If yes, then resubmit the existing profiles there
+               if ($global_directory != Config::get('system', 'directory') && ($global_directory != '')) {
+                       Config::set('system', 'directory', $global_directory);
+                       Worker::add(PRIORITY_LOW, 'Directory');
+               }
+
+               if ($a->getURLPath() != "") {
+                       $diaspora_enabled = false;
+               }
+               if ($ssl_policy != intval(Config::get('system', 'ssl_policy'))) {
+                       if ($ssl_policy == BaseURL::SSL_POLICY_FULL) {
+                               DBA::e("UPDATE `contact` SET
+                               `url`     = REPLACE(`url`    , 'http:' , 'https:'),
+                               `photo`   = REPLACE(`photo`  , 'http:' , 'https:'),
+                               `thumb`   = REPLACE(`thumb`  , 'http:' , 'https:'),
+                               `micro`   = REPLACE(`micro`  , 'http:' , 'https:'),
+                               `request` = REPLACE(`request`, 'http:' , 'https:'),
+                               `notify`  = REPLACE(`notify` , 'http:' , 'https:'),
+                               `poll`    = REPLACE(`poll`   , 'http:' , 'https:'),
+                               `confirm` = REPLACE(`confirm`, 'http:' , 'https:'),
+                               `poco`    = REPLACE(`poco`   , 'http:' , 'https:')
+                               WHERE `self` = 1"
+                               );
+                               DBA::e("UPDATE `profile` SET
+                               `photo`   = REPLACE(`photo`  , 'http:' , 'https:'),
+                               `thumb`   = REPLACE(`thumb`  , 'http:' , 'https:')
+                               WHERE 1 "
+                               );
+                       } elseif ($ssl_policy == BaseURL::SSL_POLICY_SELFSIGN) {
+                               DBA::e("UPDATE `contact` SET
+                               `url`     = REPLACE(`url`    , 'https:' , 'http:'),
+                               `photo`   = REPLACE(`photo`  , 'https:' , 'http:'),
+                               `thumb`   = REPLACE(`thumb`  , 'https:' , 'http:'),
+                               `micro`   = REPLACE(`micro`  , 'https:' , 'http:'),
+                               `request` = REPLACE(`request`, 'https:' , 'http:'),
+                               `notify`  = REPLACE(`notify` , 'https:' , 'http:'),
+                               `poll`    = REPLACE(`poll`   , 'https:' , 'http:'),
+                               `confirm` = REPLACE(`confirm`, 'https:' , 'http:'),
+                               `poco`    = REPLACE(`poco`   , 'https:' , 'http:')
+                               WHERE `self` = 1"
+                               );
+                               DBA::e("UPDATE `profile` SET
+                               `photo`   = REPLACE(`photo`  , 'https:' , 'http:'),
+                               `thumb`   = REPLACE(`thumb`  , 'https:' , 'http:')
+                               WHERE 1 "
+                               );
+                       }
+               }
+               Config::set('system', 'ssl_policy'            , $ssl_policy);
+               Config::set('system', 'maxloadavg'            , $maxloadavg);
+               Config::set('system', 'maxloadavg_frontend'   , $maxloadavg_frontend);
+               Config::set('system', 'min_memory'            , $min_memory);
+               Config::set('system', 'optimize_max_tablesize', $optimize_max_tablesize);
+               Config::set('system', 'optimize_fragmentation', $optimize_fragmentation);
+               Config::set('system', 'poco_completion'       , $poco_completion);
+               Config::set('system', 'poco_requery_days'     , $poco_requery_days);
+               Config::set('system', 'poco_discovery'        , $poco_discovery);
+               Config::set('system', 'poco_discovery_since'  , $poco_discovery_since);
+               Config::set('system', 'poco_local_search'     , $poco_local_search);
+               Config::set('system', 'nodeinfo'              , $nodeinfo);
+               Config::set('config', 'sitename'              , $sitename);
+               Config::set('config', 'sender_email'          , $sender_email);
+               Config::set('system', 'suppress_tags'         , $suppress_tags);
+               Config::set('system', 'shortcut_icon'         , $shortcut_icon);
+               Config::set('system', 'touch_icon'            , $touch_icon);
+
+               if ($banner == "") {
+                       Config::delete('system', 'banner');
+               } else {
+                       Config::set('system', 'banner', $banner);
+               }
+
+               if (empty($additional_info)) {
+                       Config::delete('config', 'info');
+               } else {
+                       Config::set('config', 'info', $additional_info);
+               }
+               Config::set('system', 'language', $language);
+               Config::set('system', 'theme', $theme);
+               Theme::install($theme);
+
+               if ($theme_mobile == '---') {
+                       Config::delete('system', 'mobile-theme');
+               } else {
+                       Config::set('system', 'mobile-theme', $theme_mobile);
+               }
+               if ($singleuser == '---') {
+                       Config::delete('system', 'singleuser');
+               } else {
+                       Config::set('system', 'singleuser', $singleuser);
+               }
+               Config::set('system', 'maximagesize'           , $maximagesize);
+               Config::set('system', 'max_image_length'       , $maximagelength);
+               Config::set('system', 'jpeg_quality'           , $jpegimagequality);
+
+               Config::set('config', 'register_policy'        , $register_policy);
+               Config::set('system', 'max_daily_registrations', $daily_registrations);
+               Config::set('system', 'account_abandon_days'   , $abandon_days);
+               Config::set('config', 'register_text'          , $register_text);
+               Config::set('system', 'allowed_sites'          , $allowed_sites);
+               Config::set('system', 'allowed_email'          , $allowed_email);
+               Config::set('system', 'forbidden_nicknames'    , $forbidden_nicknames);
+               Config::set('system', 'no_oembed_rich_content' , $no_oembed_rich_content);
+               Config::set('system', 'allowed_oembed'         , $allowed_oembed);
+               Config::set('system', 'block_public'           , $block_public);
+               Config::set('system', 'publish_all'            , $force_publish);
+               Config::set('system', 'newuser_private'        , $newuser_private);
+               Config::set('system', 'enotify_no_content'     , $enotify_no_content);
+               Config::set('system', 'disable_embedded'       , $disable_embedded);
+               Config::set('system', 'allow_users_remote_self', $allow_users_remote_self);
+               Config::set('system', 'explicit_content'       , $explicit_content);
+               Config::set('system', 'check_new_version_url'  , $check_new_version_url);
+
+               Config::set('system', 'block_extended_register', $no_multi_reg);
+               Config::set('system', 'no_openid'              , $no_openid);
+               Config::set('system', 'no_regfullname'         , $no_regfullname);
+               Config::set('system', 'community_page_style'   , $community_page_style);
+               Config::set('system', 'max_author_posts_community_page', $max_author_posts_community_page);
+               Config::set('system', 'verifyssl'              , $verifyssl);
+               Config::set('system', 'proxyuser'              , $proxyuser);
+               Config::set('system', 'proxy'                  , $proxy);
+               Config::set('system', 'curl_timeout'           , $timeout);
+               Config::set('system', 'dfrn_only'              , $dfrn_only);
+               Config::set('system', 'ostatus_disabled'       , $ostatus_disabled);
+               Config::set('system', 'ostatus_full_threads'   , $ostatus_full_threads);
+               Config::set('system', 'diaspora_enabled'       , $diaspora_enabled);
+
+               Config::set('config', 'private_addons'         , $private_addons);
+
+               Config::set('system', 'force_ssl'              , $force_ssl);
+               Config::set('system', 'hide_help'              , $hide_help);
+
+               Config::set('system', 'dbclean'                , $dbclean);
+               Config::set('system', 'dbclean-expire-days'    , $dbclean_expire_days);
+               Config::set('system', 'dbclean_expire_conversation', $dbclean_expire_conv);
+
+               if ($dbclean_unclaimed == 0) {
+                       $dbclean_unclaimed = $dbclean_expire_days;
+               }
+
+               Config::set('system', 'dbclean-expire-unclaimed', $dbclean_unclaimed);
+
+               if ($itemcache != '') {
+                       $itemcache = BasePath::getRealPath($itemcache);
+               }
+
+               Config::set('system', 'itemcache', $itemcache);
+               Config::set('system', 'itemcache_duration', $itemcache_duration);
+               Config::set('system', 'max_comments', $max_comments);
+
+               if ($temppath != '') {
+                       $temppath = BasePath::getRealPath($temppath);
+               }
+
+               Config::set('system', 'temppath', $temppath);
+
+               Config::set('system', 'proxy_disabled'   , $proxy_disabled);
+               Config::set('system', 'only_tag_search'  , $only_tag_search);
+
+               Config::set('system', 'worker_queues'    , $worker_queues);
+               Config::set('system', 'worker_dont_fork' , $worker_dont_fork);
+               Config::set('system', 'worker_fastlane'  , $worker_fastlane);
+               Config::set('system', 'frontend_worker'  , $worker_frontend);
+
+               Config::set('system', 'relay_directly'   , $relay_directly);
+               Config::set('system', 'relay_server'     , $relay_server);
+               Config::set('system', 'relay_subscribe'  , $relay_subscribe);
+               Config::set('system', 'relay_scope'      , $relay_scope);
+               Config::set('system', 'relay_server_tags', $relay_server_tags);
+               Config::set('system', 'relay_user_tags'  , $relay_user_tags);
+
+               Config::set('system', 'rino_encrypt'     , $rino);
+
+               info(L10n::t('Site settings updated.') . EOL);
+
+               $a->internalRedirect('admin/site' . $active_panel);
+       }
+
+       public static function content()
+       {
+               parent::content();
+
+               $a = self::getApp();
+
+               /* Installed langs */
+               $lang_choices = L10n::getAvailableLanguages();
+
+               if (strlen(Config::get('system', 'directory_submit_url')) &&
+                       !strlen(Config::get('system', 'directory'))) {
+                       Config::set('system', 'directory', dirname(Config::get('system', 'directory_submit_url')));
+                       Config::delete('system', 'directory_submit_url');
+               }
+
+               /* Installed themes */
+               $theme_choices = [];
+               $theme_choices_mobile = [];
+               $theme_choices_mobile['---'] = L10n::t('No special theme for mobile devices');
+               $files = glob('view/theme/*');
+               if (is_array($files)) {
+                       $allowed_theme_list = Config::get('system', 'allowed_themes');
+
+                       foreach ($files as $file) {
+                               if (intval(file_exists($file . '/unsupported'))) {
+                                       continue;
+                               }
+
+                               $f = basename($file);
+
+                               // Only show allowed themes here
+                               if (($allowed_theme_list != '') && !strstr($allowed_theme_list, $f)) {
+                                       continue;
+                               }
+
+                               $theme_name = ((file_exists($file . '/experimental')) ? L10n::t('%s - (Experimental)', $f) : $f);
+
+                               if (file_exists($file . '/mobile')) {
+                                       $theme_choices_mobile[$f] = $theme_name;
+                               } else {
+                                       $theme_choices[$f] = $theme_name;
+                               }
+                       }
+               }
+
+               /* Community page style */
+               $community_page_style_choices = [
+                       CP_NO_INTERNAL_COMMUNITY => L10n::t('No community page for local users'),
+                       CP_NO_COMMUNITY_PAGE => L10n::t('No community page'),
+                       CP_USERS_ON_SERVER => L10n::t('Public postings from users of this site'),
+                       CP_GLOBAL_COMMUNITY => L10n::t('Public postings from the federated network'),
+                       CP_USERS_AND_GLOBAL => L10n::t('Public postings from local users and the federated network')
+               ];
+
+               $poco_discovery_choices = [
+                       PortableContact::DISABLED => L10n::t('Disabled'),
+                       PortableContact::USERS => L10n::t('Users'),
+                       PortableContact::USERS_GCONTACTS => L10n::t('Users, Global Contacts'),
+                       PortableContact::USERS_GCONTACTS_FALLBACK => L10n::t('Users, Global Contacts/fallback'),
+               ];
+
+               $poco_discovery_since_choices = [
+                       '30' => L10n::t('One month'),
+                       '91' => L10n::t('Three months'),
+                       '182' => L10n::t('Half a year'),
+                       '365' => L10n::t('One year'),
+               ];
+
+               /* get user names to make the install a personal install of X */
+               // @TODO Move to Model\User::getNames()
+               $user_names = [];
+               $user_names['---'] = L10n::t('Multi user instance');
+
+               $usersStmt = DBA::select('user', ['username', 'nickname'], ['account_removed' => 0, 'account_expired' => 0]);
+               foreach (DBA::toArray($usersStmt) as $user) {
+                       $user_names[$user['nickname']] = $user['username'];
+               }
+
+               /* Banner */
+               $banner = Config::get('system', 'banner');
+
+               if ($banner == false) {
+                       $banner = '<a href="https://friendi.ca"><img id="logo-img" src="images/friendica-32.png" alt="logo" /></a><span id="logo-text"><a href="https://friendi.ca">Friendica</a></span>';
+               }
+
+               $additional_info = Config::get('config', 'info');
+
+               // Automatically create temporary paths
+               get_temppath();
+               get_itemcachepath();
+
+               /* Register policy */
+               $register_choices = [
+                       Register::CLOSED => L10n::t('Closed'),
+                       Register::APPROVE => L10n::t('Requires approval'),
+                       Register::OPEN => L10n::t('Open')
+               ];
+
+               $ssl_choices = [
+                       BaseURL::SSL_POLICY_NONE => L10n::t('No SSL policy, links will track page SSL state'),
+                       BaseURL::SSL_POLICY_FULL => L10n::t('Force all links to use SSL'),
+                       BaseURL::SSL_POLICY_SELFSIGN => L10n::t('Self-signed certificate, use SSL for local links only (discouraged)')
+               ];
+
+               $check_git_version_choices = [
+                       'none' => L10n::t('Don\'t check'),
+                       'master' => L10n::t('check the stable version'),
+                       'develop' => L10n::t('check the development version')
+               ];
+
+               $diaspora_able = ($a->getURLPath() == '');
+
+               $optimize_max_tablesize = Config::get('system', 'optimize_max_tablesize', -1);
+
+               if ($optimize_max_tablesize <= 0) {
+                       $optimize_max_tablesize = -1;
+               }
+
+               $storage_backends = StorageManager::listBackends();
+               /** @var $current_storage_backend \Friendica\Model\Storage\IStorage */
+               $current_storage_backend = StorageManager::getBackend();
+
+               $available_storage_backends = [];
+
+               // show legacy option only if it is the current backend:
+               // once changed can't be selected anymore
+               if ($current_storage_backend == '') {
+                       $available_storage_backends[''] = L10n::t('Database (legacy)');
+               }
+
+               foreach ($storage_backends as $name => $class) {
+                       $available_storage_backends[$class] = $name;
+               }
+               unset($storage_backends);
+
+               // build storage config form,
+               $storage_form_prefix = preg_replace('|[^a-zA-Z0-9]|' ,'', $current_storage_backend);
+
+               $storage_form = [];
+               if (!is_null($current_storage_backend) && $current_storage_backend != '') {
+                       foreach ($current_storage_backend::getOptions() as $name => $info) {
+                               $type = $info[0];
+                               $info[0] = $storage_form_prefix . '_' . $name;
+                               $info['type'] = $type;
+                               $info['field'] = 'field_' . $type . '.tpl';
+                               $storage_form[$name] = $info;
+                       }
+               }
+
+               $t = Renderer::getMarkupTemplate('admin/site.tpl');
+               return Renderer::replaceMacros($t, [
+                       '$title'             => L10n::t('Administration'),
+                       '$page'              => L10n::t('Site'),
+                       '$submit'            => L10n::t('Save Settings'),
+                       '$republish'         => L10n::t('Republish users to directory'),
+                       '$registration'      => L10n::t('Registration'),
+                       '$upload'            => L10n::t('File upload'),
+                       '$corporate'         => L10n::t('Policies'),
+                       '$advanced'          => L10n::t('Advanced'),
+                       '$portable_contacts' => L10n::t('Auto Discovered Contact Directory'),
+                       '$performance'       => L10n::t('Performance'),
+                       '$worker_title'      => L10n::t('Worker'),
+                       '$relay_title'       => L10n::t('Message Relay'),
+                       '$relocate'          => L10n::t('Relocate Instance'),
+                       '$relocate_warning'  => L10n::t('Warning! Advanced function. Could make this server unreachable.'),
+                       '$baseurl'           => $a->getBaseURL(true),
+
+                       // name, label, value, help string, extra data...
+                       '$sitename'         => ['sitename', L10n::t('Site name'), Config::get('config', 'sitename'), ''],
+                       '$sender_email'     => ['sender_email', L10n::t('Sender Email'), Config::get('config', 'sender_email'), L10n::t('The email address your server shall use to send notification emails from.'), '', '', 'email'],
+                       '$banner'           => ['banner', L10n::t('Banner/Logo'), $banner, ''],
+                       '$shortcut_icon'    => ['shortcut_icon', L10n::t('Shortcut icon'), Config::get('system', 'shortcut_icon'), L10n::t('Link to an icon that will be used for browsers.')],
+                       '$touch_icon'       => ['touch_icon', L10n::t('Touch icon'), Config::get('system', 'touch_icon'), L10n::t('Link to an icon that will be used for tablets and mobiles.')],
+                       '$additional_info'  => ['additional_info', L10n::t('Additional Info'), $additional_info, L10n::t('For public servers: you can add additional information here that will be listed at %s/servers.', get_server())],
+                       '$language'         => ['language', L10n::t('System language'), Config::get('system', 'language'), '', $lang_choices],
+                       '$theme'            => ['theme', L10n::t('System theme'), Config::get('system', 'theme'), L10n::t('Default system theme - may be over-ridden by user profiles - <a href="/admin/themes" id="cnftheme">Change default theme settings</a>'), $theme_choices],
+                       '$theme_mobile'     => ['theme_mobile', L10n::t('Mobile system theme'), Config::get('system', 'mobile-theme', '---'), L10n::t('Theme for mobile devices'), $theme_choices_mobile],
+                       '$ssl_policy'       => ['ssl_policy', L10n::t('SSL link policy'), (string)intval(Config::get('system', 'ssl_policy')), L10n::t('Determines whether generated links should be forced to use SSL'), $ssl_choices],
+                       '$force_ssl'        => ['force_ssl', L10n::t('Force SSL'), Config::get('system', 'force_ssl'), L10n::t('Force all Non-SSL requests to SSL - Attention: on some systems it could lead to endless loops.')],
+                       '$hide_help'        => ['hide_help', L10n::t('Hide help entry from navigation menu'), Config::get('system', 'hide_help'), L10n::t('Hides the menu entry for the Help pages from the navigation menu. You can still access it calling /help directly.')],
+                       '$singleuser'       => ['singleuser', L10n::t('Single user instance'), Config::get('system', 'singleuser', '---'), L10n::t('Make this instance multi-user or single-user for the named user'), $user_names],
+
+                       '$storagebackend'   => ['storagebackend', L10n::t('File storage backend'), $current_storage_backend, L10n::t('The backend used to store uploaded data. If you change the storage backend, you can manually move the existing files. If you do not do so, the files uploaded before the change will still be available at the old backend. Please see <a href="/help/Settings#1_2_3_1">the settings documentation</a> for more information about the choices and the moving procedure.'), $available_storage_backends],
+                       '$storageform'      => $storage_form,
+                       '$maximagesize'     => ['maximagesize', L10n::t('Maximum image size'), Config::get('system', 'maximagesize'), L10n::t('Maximum size in bytes of uploaded images. Default is 0, which means no limits.')],
+                       '$maximagelength'   => ['maximagelength', L10n::t('Maximum image length'), Config::get('system', 'max_image_length'), L10n::t('Maximum length in pixels of the longest side of uploaded images. Default is -1, which means no limits.')],
+                       '$jpegimagequality' => ['jpegimagequality', L10n::t('JPEG image quality'), Config::get('system', 'jpeg_quality'), L10n::t('Uploaded JPEGS will be saved at this quality setting [0-100]. Default is 100, which is full quality.')],
+
+                       '$register_policy'        => ['register_policy', L10n::t('Register policy'), Config::get('config', 'register_policy'), '', $register_choices],
+                       '$daily_registrations'    => ['max_daily_registrations', L10n::t('Maximum Daily Registrations'), Config::get('system', 'max_daily_registrations'), L10n::t('If registration is permitted above, this sets the maximum number of new user registrations to accept per day.  If register is set to closed, this setting has no effect.')],
+                       '$register_text'          => ['register_text', L10n::t('Register text'), Config::get('config', 'register_text'), L10n::t('Will be displayed prominently on the registration page. You can use BBCode here.')],
+                       '$forbidden_nicknames'    => ['forbidden_nicknames', L10n::t('Forbidden Nicknames'), Config::get('system', 'forbidden_nicknames'), L10n::t('Comma separated list of nicknames that are forbidden from registration. Preset is a list of role names according RFC 2142.')],
+                       '$abandon_days'           => ['abandon_days', L10n::t('Accounts abandoned after x days'), Config::get('system', 'account_abandon_days'), L10n::t('Will not waste system resources polling external sites for abandonded accounts. Enter 0 for no time limit.')],
+                       '$allowed_sites'          => ['allowed_sites', L10n::t('Allowed friend domains'), Config::get('system', 'allowed_sites'), L10n::t('Comma separated list of domains which are allowed to establish friendships with this site. Wildcards are accepted. Empty to allow any domains')],
+                       '$allowed_email'          => ['allowed_email', L10n::t('Allowed email domains'), Config::get('system', 'allowed_email'), L10n::t('Comma separated list of domains which are allowed in email addresses for registrations to this site. Wildcards are accepted. Empty to allow any domains')],
+                       '$no_oembed_rich_content' => ['no_oembed_rich_content', L10n::t('No OEmbed rich content'), Config::get('system', 'no_oembed_rich_content'), L10n::t('Don\'t show the rich content (e.g. embedded PDF), except from the domains listed below.')],
+                       '$allowed_oembed'         => ['allowed_oembed', L10n::t('Allowed OEmbed domains'), Config::get('system', 'allowed_oembed'), L10n::t('Comma separated list of domains which oembed content is allowed to be displayed. Wildcards are accepted.')],
+                       '$block_public'           => ['block_public', L10n::t('Block public'), Config::get('system', 'block_public'), L10n::t('Check to block public access to all otherwise public personal pages on this site unless you are currently logged in.')],
+                       '$force_publish'          => ['publish_all', L10n::t('Force publish'), Config::get('system', 'publish_all'), L10n::t('Check to force all profiles on this site to be listed in the site directory.') . '<strong>' . L10n::t('Enabling this may violate privacy laws like the GDPR') . '</strong>'],
+                       '$global_directory'       => ['directory', L10n::t('Global directory URL'), Config::get('system', 'directory', 'https://dir.friendica.social'), L10n::t('URL to the global directory. If this is not set, the global directory is completely unavailable to the application.')],
+                       '$newuser_private'        => ['newuser_private', L10n::t('Private posts by default for new users'), Config::get('system', 'newuser_private'), L10n::t('Set default post permissions for all new members to the default privacy group rather than public.')],
+                       '$enotify_no_content'     => ['enotify_no_content', L10n::t('Don\'t include post content in email notifications'), Config::get('system', 'enotify_no_content'), L10n::t('Don\'t include the content of a post/comment/private message/etc. in the email notifications that are sent out from this site, as a privacy measure.')],
+                       '$private_addons'         => ['private_addons', L10n::t('Disallow public access to addons listed in the apps menu.'), Config::get('config', 'private_addons'), L10n::t('Checking this box will restrict addons listed in the apps menu to members only.')],
+                       '$disable_embedded'       => ['disable_embedded', L10n::t('Don\'t embed private images in posts'), Config::get('system', 'disable_embedded'), L10n::t('Don\'t replace locally-hosted private photos in posts with an embedded copy of the image. This means that contacts who receive posts containing private photos will have to authenticate and load each image, which may take a while.')],
+                       '$explicit_content'       => ['explicit_content', L10n::t('Explicit Content'), Config::get('system', 'explicit_content', false), L10n::t('Set this to announce that your node is used mostly for explicit content that might not be suited for minors. This information will be published in the node information and might be used, e.g. by the global directory, to filter your node from listings of nodes to join. Additionally a note about this will be shown at the user registration page.')],
+                       '$allow_users_remote_self'=> ['allow_users_remote_self', L10n::t('Allow Users to set remote_self'), Config::get('system', 'allow_users_remote_self'), L10n::t('With checking this, every user is allowed to mark every contact as a remote_self in the repair contact dialog. Setting this flag on a contact causes mirroring every posting of that contact in the users stream.')],
+                       '$no_multi_reg'           => ['no_multi_reg', L10n::t('Block multiple registrations'), Config::get('system', 'block_extended_register'), L10n::t('Disallow users to register additional accounts for use as pages.')],
+                       '$no_openid'              => ['no_openid', L10n::t('Disable OpenID'), Config::get('system', 'no_openid'), L10n::t('Disable OpenID support for registration and logins.')],
+                       '$no_regfullname'         => ['no_regfullname', L10n::t('No Fullname check'), Config::get('system', 'no_regfullname'), L10n::t('Allow users to register without a space between the first name and the last name in their full name.')],
+                       '$community_page_style'   => ['community_page_style', L10n::t('Community pages for visitors'), Config::get('system', 'community_page_style'), L10n::t('Which community pages should be available for visitors. Local users always see both pages.'), $community_page_style_choices],
+                       '$max_author_posts_community_page' => ['max_author_posts_community_page', L10n::t('Posts per user on community page'), Config::get('system', 'max_author_posts_community_page'), L10n::t('The maximum number of posts per user on the community page. (Not valid for "Global Community")')],
+                       '$ostatus_disabled'       => ['ostatus_disabled', L10n::t('Disable OStatus support'), Config::get('system', 'ostatus_disabled'), L10n::t('Disable built-in OStatus (StatusNet, GNU Social etc.) compatibility. All communications in OStatus are public, so privacy warnings will be occasionally displayed.')],
+                       '$ostatus_full_threads'   => ['ostatus_full_threads', L10n::t('Only import OStatus/ActivityPub threads from our contacts'), Config::get('system', 'ostatus_full_threads'), L10n::t('Normally we import every content from our OStatus and ActivityPub contacts. With this option we only store threads that are started by a contact that is known on our system.')],
+                       '$ostatus_not_able'       => L10n::t('OStatus support can only be enabled if threading is enabled.'),
+                       '$diaspora_able'          => $diaspora_able,
+                       '$diaspora_not_able'      => L10n::t('Diaspora support can\'t be enabled because Friendica was installed into a sub directory.'),
+                       '$diaspora_enabled'       => ['diaspora_enabled', L10n::t('Enable Diaspora support'), Config::get('system', 'diaspora_enabled', $diaspora_able), L10n::t('Provide built-in Diaspora network compatibility.')],
+                       '$dfrn_only'              => ['dfrn_only', L10n::t('Only allow Friendica contacts'), Config::get('system', 'dfrn_only'), L10n::t('All contacts must use Friendica protocols. All other built-in communication protocols disabled.')],
+                       '$verifyssl'              => ['verifyssl', L10n::t('Verify SSL'), Config::get('system', 'verifyssl'), L10n::t('If you wish, you can turn on strict certificate checking. This will mean you cannot connect (at all) to self-signed SSL sites.')],
+                       '$proxyuser'              => ['proxyuser', L10n::t('Proxy user'), Config::get('system', 'proxyuser'), ''],
+                       '$proxy'                  => ['proxy', L10n::t('Proxy URL'), Config::get('system', 'proxy'), ''],
+                       '$timeout'                => ['timeout', L10n::t('Network timeout'), Config::get('system', 'curl_timeout', 60), L10n::t('Value is in seconds. Set to 0 for unlimited (not recommended).')],
+                       '$maxloadavg'             => ['maxloadavg', L10n::t('Maximum Load Average'), Config::get('system', 'maxloadavg', 20), L10n::t('Maximum system load before delivery and poll processes are deferred - default %d.', 20)],
+                       '$maxloadavg_frontend'    => ['maxloadavg_frontend', L10n::t('Maximum Load Average (Frontend)'), Config::get('system', 'maxloadavg_frontend', 50), L10n::t('Maximum system load before the frontend quits service - default 50.')],
+                       '$min_memory'             => ['min_memory', L10n::t('Minimal Memory'), Config::get('system', 'min_memory', 0), L10n::t('Minimal free memory in MB for the worker. Needs access to /proc/meminfo - default 0 (deactivated).')],
+                       '$optimize_max_tablesize' => ['optimize_max_tablesize', L10n::t('Maximum table size for optimization'), $optimize_max_tablesize, L10n::t('Maximum table size (in MB) for the automatic optimization. Enter -1 to disable it.')],
+                       '$optimize_fragmentation' => ['optimize_fragmentation', L10n::t('Minimum level of fragmentation'), Config::get('system', 'optimize_fragmentation', 30), L10n::t('Minimum fragmenation level to start the automatic optimization - default value is 30%.')],
+
+                       '$poco_completion'        => ['poco_completion', L10n::t('Periodical check of global contacts'), Config::get('system', 'poco_completion'), L10n::t('If enabled, the global contacts are checked periodically for missing or outdated data and the vitality of the contacts and servers.')],
+                       '$poco_requery_days'      => ['poco_requery_days', L10n::t('Days between requery'), Config::get('system', 'poco_requery_days'), L10n::t('Number of days after which a server is requeried for his contacts.')],
+                       '$poco_discovery'         => ['poco_discovery', L10n::t('Discover contacts from other servers'), (string)intval(Config::get('system', 'poco_discovery')), L10n::t('Periodically query other servers for contacts. You can choose between "Users": the users on the remote system, "Global Contacts": active contacts that are known on the system. The fallback is meant for Redmatrix servers and older friendica servers, where global contacts weren\'t available. The fallback increases the server load, so the recommended setting is "Users, Global Contacts".'), $poco_discovery_choices],
+                       '$poco_discovery_since'   => ['poco_discovery_since', L10n::t('Timeframe for fetching global contacts'), (string)intval(Config::get('system', 'poco_discovery_since')), L10n::t('When the discovery is activated, this value defines the timeframe for the activity of the global contacts that are fetched from other servers.'), $poco_discovery_since_choices],
+                       '$poco_local_search'      => ['poco_local_search', L10n::t('Search the local directory'), Config::get('system', 'poco_local_search'), L10n::t('Search the local directory instead of the global directory. When searching locally, every search will be executed on the global directory in the background. This improves the search results when the search is repeated.')],
+
+                       '$nodeinfo'               => ['nodeinfo', L10n::t('Publish server information'), Config::get('system', 'nodeinfo'), L10n::t('If enabled, general server and usage data will be published. The data contains the name and version of the server, number of users with public profiles, number of posts and the activated protocols and connectors. See <a href="http://the-federation.info/">the-federation.info</a> for details.')],
+
+                       '$check_new_version_url'  => ['check_new_version_url', L10n::t('Check upstream version'), Config::get('system', 'check_new_version_url'), L10n::t('Enables checking for new Friendica versions at github. If there is a new version, you will be informed in the admin panel overview.'), $check_git_version_choices],
+                       '$suppress_tags'          => ['suppress_tags', L10n::t('Suppress Tags'), Config::get('system', 'suppress_tags'), L10n::t('Suppress showing a list of hashtags at the end of the posting.')],
+                       '$dbclean'                => ['dbclean', L10n::t('Clean database'), Config::get('system', 'dbclean', false), L10n::t('Remove old remote items, orphaned database records and old content from some other helper tables.')],
+                       '$dbclean_expire_days'    => ['dbclean_expire_days', L10n::t('Lifespan of remote items'), Config::get('system', 'dbclean-expire-days', 0), L10n::t('When the database cleanup is enabled, this defines the days after which remote items will be deleted. Own items, and marked or filed items are always kept. 0 disables this behaviour.')],
+                       '$dbclean_unclaimed'      => ['dbclean_unclaimed', L10n::t('Lifespan of unclaimed items'), Config::get('system', 'dbclean-expire-unclaimed', 90), L10n::t('When the database cleanup is enabled, this defines the days after which unclaimed remote items (mostly content from the relay) will be deleted. Default value is 90 days. Defaults to the general lifespan value of remote items if set to 0.')],
+                       '$dbclean_expire_conv'    => ['dbclean_expire_conv', L10n::t('Lifespan of raw conversation data'), Config::get('system', 'dbclean_expire_conversation', 90), L10n::t('The conversation data is used for ActivityPub and OStatus, as well as for debug purposes. It should be safe to remove it after 14 days, default is 90 days.')],
+                       '$itemcache'              => ['itemcache', L10n::t('Path to item cache'), Config::get('system', 'itemcache'), L10n::t('The item caches buffers generated bbcode and external images.')],
+                       '$itemcache_duration'     => ['itemcache_duration', L10n::t('Cache duration in seconds'), Config::get('system', 'itemcache_duration'), L10n::t('How long should the cache files be hold? Default value is 86400 seconds (One day). To disable the item cache, set the value to -1.')],
+                       '$max_comments'           => ['max_comments', L10n::t('Maximum numbers of comments per post'), Config::get('system', 'max_comments'), L10n::t('How much comments should be shown for each post? Default value is 100.')],
+                       '$temppath'               => ['temppath', L10n::t('Temp path'), Config::get('system', 'temppath'), L10n::t('If you have a restricted system where the webserver can\'t access the system temp path, enter another path here.')],
+                       '$proxy_disabled'         => ['proxy_disabled', L10n::t('Disable picture proxy'), Config::get('system', 'proxy_disabled'), L10n::t('The picture proxy increases performance and privacy. It shouldn\'t be used on systems with very low bandwidth.')],
+                       '$only_tag_search'        => ['only_tag_search', L10n::t('Only search in tags'), Config::get('system', 'only_tag_search'), L10n::t('On large systems the text search can slow down the system extremely.')],
+
+                       '$relocate_url'           => ['relocate_url', L10n::t('New base url'), $a->getBaseURL(), L10n::t('Change base url for this server. Sends relocate message to all Friendica and Diaspora* contacts of all users.')],
+
+                       '$rino'                   => ['rino', L10n::t('RINO Encryption'), intval(Config::get('system', 'rino_encrypt')), L10n::t('Encryption layer between nodes.'), [0 => L10n::t('Disabled'), 1 => L10n::t('Enabled')]],
+
+                       '$worker_queues'          => ['worker_queues', L10n::t('Maximum number of parallel workers'), Config::get('system', 'worker_queues'), L10n::t('On shared hosters set this to %d. On larger systems, values of %d are great. Default value is %d.', 5, 20, 10)],
+                       '$worker_dont_fork'       => ['worker_dont_fork', L10n::t('Don\'t use "proc_open" with the worker'), Config::get('system', 'worker_dont_fork'), L10n::t('Enable this if your system doesn\'t allow the use of "proc_open". This can happen on shared hosters. If this is enabled you should increase the frequency of worker calls in your crontab.')],
+                       '$worker_fastlane'        => ['worker_fastlane', L10n::t('Enable fastlane'), Config::get('system', 'worker_fastlane'), L10n::t('When enabed, the fastlane mechanism starts an additional worker if processes with higher priority are blocked by processes of lower priority.')],
+                       '$worker_frontend'        => ['worker_frontend', L10n::t('Enable frontend worker'), Config::get('system', 'frontend_worker'), L10n::t('When enabled the Worker process is triggered when backend access is performed (e.g. messages being delivered). On smaller sites you might want to call %s/worker on a regular basis via an external cron job. You should only enable this option if you cannot utilize cron/scheduled jobs on your server.', $a->getBaseURL())],
+
+                       '$relay_subscribe'        => ['relay_subscribe', L10n::t('Subscribe to relay'), Config::get('system', 'relay_subscribe'), L10n::t('Enables the receiving of public posts from the relay. They will be included in the search, subscribed tags and on the global community page.')],
+                       '$relay_server'           => ['relay_server', L10n::t('Relay server'), Config::get('system', 'relay_server', 'https://relay.diasp.org'), L10n::t('Address of the relay server where public posts should be send to. For example https://relay.diasp.org')],
+                       '$relay_directly'         => ['relay_directly', L10n::t('Direct relay transfer'), Config::get('system', 'relay_directly'), L10n::t('Enables the direct transfer to other servers without using the relay servers')],
+                       '$relay_scope'            => ['relay_scope', L10n::t('Relay scope'), Config::get('system', 'relay_scope'), L10n::t('Can be "all" or "tags". "all" means that every public post should be received. "tags" means that only posts with selected tags should be received.'), ['' => L10n::t('Disabled'), 'all' => L10n::t('all'), 'tags' => L10n::t('tags')]],
+                       '$relay_server_tags'      => ['relay_server_tags', L10n::t('Server tags'), Config::get('system', 'relay_server_tags'), L10n::t('Comma separated list of tags for the "tags" subscription.')],
+                       '$relay_user_tags'        => ['relay_user_tags', L10n::t('Allow user tags'), Config::get('system', 'relay_user_tags', true), L10n::t('If enabled, the tags from the saved searches will used for the "tags" subscription in addition to the "relay_server_tags".')],
+
+                       '$form_security_token'    => parent::getFormSecurityToken('admin_site'),
+                       '$relocate_button'        => L10n::t('Start Relocation'),
+               ]);
+       }
+}
diff --git a/src/Module/Admin/Summary.php b/src/Module/Admin/Summary.php
new file mode 100644 (file)
index 0000000..a78a6b8
--- /dev/null
@@ -0,0 +1,147 @@
+<?php
+
+namespace Friendica\Module\Admin;
+
+use Friendica\Core\Addon;
+use Friendica\Core\Config;
+use Friendica\Core\L10n;
+use Friendica\Core\Logger;
+use Friendica\Core\Renderer;
+use Friendica\Core\Update;
+use Friendica\Database\DBA;
+use Friendica\Database\DBStructure;
+use Friendica\Model\Register;
+use Friendica\Module\BaseAdminModule;
+use Friendica\Util\DateTimeFormat;
+use Friendica\Util\Network;
+
+class Summary extends BaseAdminModule
+{
+       public static function content()
+       {
+               parent::content();
+
+               $a = self::getApp();
+
+               // are there MyISAM tables in the DB? If so, trigger a warning message
+               $warningtext = [];
+               if (DBA::count('`information_schema`.`tables`', ['engine' => 'myisam', 'table_schema' => DBA::databaseName()])) {
+                       $warningtext[] = L10n::t('Your DB still runs with MyISAM tables. You should change the engine type to InnoDB. As Friendica will use InnoDB only features in the future, you should change this! See <a href="%s">here</a> for a guide that may be helpful converting the table engines. You may also use the command <tt>php bin/console.php dbstructure toinnodb</tt> of your Friendica installation for an automatic conversion.<br />', 'https://dev.mysql.com/doc/refman/5.7/en/converting-tables-to-innodb.html');
+               }
+
+               // Check if github.com/friendica/master/VERSION is higher then
+               // the local version of Friendica. Check is opt-in, source may be master or devel branch
+               if (Config::get('system', 'check_new_version_url', 'none') != 'none') {
+                       $gitversion = Config::get('system', 'git_friendica_version');
+                       if (version_compare(FRIENDICA_VERSION, $gitversion) < 0) {
+                               $warningtext[] = L10n::t('There is a new version of Friendica available for download. Your current version is %1$s, upstream version is %2$s', FRIENDICA_VERSION, $gitversion);
+                       }
+               }
+
+               if (Config::get('system', 'dbupdate', DBStructure::UPDATE_NOT_CHECKED) == DBStructure::UPDATE_NOT_CHECKED) {
+                       DBStructure::update($a->getBasePath(), false, true);
+               }
+
+               if (Config::get('system', 'dbupdate') == DBStructure::UPDATE_FAILED) {
+                       $warningtext[] = L10n::t('The database update failed. Please run "php bin/console.php dbstructure update" from the command line and have a look at the errors that might appear.');
+               }
+
+               if (Config::get('system', 'update') == Update::FAILED) {
+                       $warningtext[] = L10n::t('The last update failed. Please run "php bin/console.php dbstructure update" from the command line and have a look at the errors that might appear. (Some of the errors are possibly inside the logfile.)');
+               }
+
+               $last_worker_call = Config::get('system', 'last_worker_execution', false);
+               if (!$last_worker_call) {
+                       $warningtext[] = L10n::t('The worker was never executed. Please check your database structure!');
+               } elseif ((strtotime(DateTimeFormat::utcNow()) - strtotime($last_worker_call)) > 60 * 60) {
+                       $warningtext[] = L10n::t('The last worker execution was on %s UTC. This is older than one hour. Please check your crontab settings.', $last_worker_call);
+               }
+
+               // Legacy config file warning
+               if (file_exists('.htconfig.php')) {
+                       $warningtext[] = L10n::t('Friendica\'s configuration now is stored in config/local.config.php, please copy config/local-sample.config.php and move your config from <code>.htconfig.php</code>. See <a href="%s">the Config help page</a> for help with the transition.', $a->getBaseURL() . '/help/Config');
+               }
+
+               if (file_exists('config/local.ini.php')) {
+                       $warningtext[] = L10n::t('Friendica\'s configuration now is stored in config/local.config.php, please copy config/local-sample.config.php and move your config from <code>config/local.ini.php</code>. See <a href="%s">the Config help page</a> for help with the transition.', $a->getBaseURL() . '/help/Config');
+               }
+
+               // Check server vitality
+               if (!self::checkSelfHostMeta()) {
+                       $well_known = $a->getBaseURL() . '/.well-known/host-meta';
+                       $warningtext[] = L10n::t('<a href="%s">%s</a> is not reachable on your system. This is a severe configuration issue that prevents server to server communication. See <a href="%s">the installation page</a> for help.',
+                               $well_known, $well_known, $a->getBaseURL() . '/help/Install');
+               }
+
+               $accounts = [
+                       [L10n::t('Normal Account'), 0],
+                       [L10n::t('Automatic Follower Account'), 0],
+                       [L10n::t('Public Forum Account'), 0],
+                       [L10n::t('Automatic Friend Account'), 0],
+                       [L10n::t('Blog Account'), 0],
+                       [L10n::t('Private Forum Account'), 0]
+               ];
+
+               $users = 0;
+               $pageFlagsCountStmt = DBA::p('SELECT `page-flags`, COUNT(`uid`) AS `count` FROM `user` GROUP BY `page-flags`');
+               while ($pageFlagsCount = DBA::fetch($pageFlagsCountStmt)) {
+                       $accounts[$pageFlagsCount['page-flags']][1] = $pageFlagsCount['count'];
+                       $users += $pageFlagsCount['count'];
+               }
+               DBA::close($pageFlagsCountStmt);
+
+               Logger::log('accounts: ' . print_r($accounts, true), Logger::DATA);
+
+               $pending = Register::getPendingCount();
+
+               $queue = DBA::count('queue', []);
+
+               $deferred = DBA::count('workerqueue', ['`executed` <= ? AND NOT `done` AND `next_try` > ?',
+                       DBA::NULL_DATETIME, DateTimeFormat::utcNow()]);
+
+               $workerqueue = DBA::count('workerqueue', ['`executed` <= ? AND NOT `done` AND `next_try` < ?',
+                       DBA::NULL_DATETIME, DateTimeFormat::utcNow()]);
+
+               // We can do better, but this is a quick queue status
+               $queues = ['label' => L10n::t('Message queues'), 'queue' => $queue, 'deferred' => $deferred, 'workerq' => $workerqueue];
+
+               $variables = DBA::toArray(DBA::p('SHOW variables LIKE "max_allowed_packet"'));
+               $max_allowed_packet = $variables ? $variables[0]['Value'] : 0;
+
+               $server_settings = [
+                       'label' => L10n::t('Server Settings'),
+                       'php' => [
+                               'upload_max_filesize' => ini_get('upload_max_filesize'),
+                               'post_max_size' => ini_get('post_max_size'),
+                               'memory_limit' => ini_get('memory_limit')
+                       ],
+                       'mysql' => [
+                               'max_allowed_packet' => $max_allowed_packet
+                       ]
+               ];
+
+               $t = Renderer::getMarkupTemplate('admin/summary.tpl');
+               return Renderer::replaceMacros($t, [
+                       '$title' => L10n::t('Administration'),
+                       '$page' => L10n::t('Summary'),
+                       '$queues' => $queues,
+                       '$users' => [L10n::t('Registered users'), $users],
+                       '$accounts' => $accounts,
+                       '$pending' => [L10n::t('Pending registrations'), $pending],
+                       '$version' => [L10n::t('Version'), FRIENDICA_VERSION],
+                       '$platform' => FRIENDICA_PLATFORM,
+                       '$codename' => FRIENDICA_CODENAME,
+                       '$build' => Config::get('system', 'build'),
+                       '$addons' => [L10n::t('Active addons'), Addon::getEnabledList()],
+                       '$serversettings' => $server_settings,
+                       '$warningtext' => $warningtext
+               ]);
+       }
+
+       private static function checkSelfHostMeta()
+       {
+               // Fetch the host-meta to check if this really is a vital server
+               return Network::curl(self::getApp()->getBaseURL() . '/.well-known/host-meta')->isSuccess();
+       }
+
+}
diff --git a/src/Module/Admin/Themes/Details.php b/src/Module/Admin/Themes/Details.php
new file mode 100644 (file)
index 0000000..3750e96
--- /dev/null
@@ -0,0 +1,126 @@
+<?php
+
+namespace Friendica\Module\Admin\Themes;
+
+use Friendica\Content\Text\Markdown;
+use Friendica\Core\L10n;
+use Friendica\Core\Renderer;
+use Friendica\Core\Theme;
+use Friendica\Module\BaseAdminModule;
+use Friendica\Util\Strings;
+
+class Details extends BaseAdminModule
+{
+       public static function post()
+       {
+               parent::post();
+
+               $a = self::getApp();
+
+               if ($a->argc > 2) {
+                       // @TODO: Replace with parameter from router
+                       $theme = $a->argv[2];
+                       $theme = Strings::sanitizeFilePathItem($theme);
+                       if (is_file("view/theme/$theme/config.php")) {
+                               require_once "view/theme/$theme/config.php";
+
+                               if (function_exists('theme_admin_post')) {
+                                       theme_admin_post($a);
+                               }
+                       }
+
+                       info(L10n::t('Theme settings updated.'));
+
+                       if ($a->isAjax()) {
+                               return;
+                       }
+
+                       $a->internalRedirect('admin/themes/' . $theme);
+               }
+       }
+
+       public static function content()
+       {
+               parent::content();
+
+               $a = self::getApp();
+
+               if ($a->argc > 2) {
+                       // @TODO: Replace with parameter from router
+                       $theme = $a->argv[2];
+                       $theme = Strings::sanitizeFilePathItem($theme);
+                       if (!is_dir("view/theme/$theme")) {
+                               notice(L10n::t("Item not found."));
+                               return '';
+                       }
+
+                       $isEnabled = in_array($theme, Theme::getAllowedList());
+                       if ($isEnabled) {
+                               $status = "on";
+                               $action = L10n::t("Disable");
+                       } else {
+                               $status = "off";
+                               $action = L10n::t("Enable");
+                       }
+
+                       if (!empty($_GET['action']) && $_GET['action'] == 'toggle') {
+                               parent::checkFormSecurityTokenRedirectOnError('/admin/themes', 'admin_themes', 't');
+
+                               if ($isEnabled) {
+                                       Theme::uninstall($theme);
+                                       info(L10n::t('Theme %s disabled.', $theme));
+                               } elseif (Theme::install($theme)) {
+                                       info(L10n::t('Theme %s successfully enabled.', $theme));
+                               } else {
+                                       info(L10n::t('Theme %s failed to install.', $theme));
+                               }
+
+                               $a->internalRedirect('admin/themes/' . $theme);
+                       }
+
+                       $readme = null;
+                       if (is_file("view/theme/$theme/README.md")) {
+                               $readme = Markdown::convert(file_get_contents("view/theme/$theme/README.md"), false);
+                       } elseif (is_file("view/theme/$theme/README")) {
+                               $readme = "<pre>" . file_get_contents("view/theme/$theme/README") . "</pre>";
+                       }
+
+                       $admin_form = '';
+                       if (is_file("view/theme/$theme/config.php")) {
+                               require_once "view/theme/$theme/config.php";
+
+                               if (function_exists('theme_admin')) {
+                                       $admin_form = '<iframe onload="resizeIframe(this);" src="/admin/themes/' . $theme . '/embed?mode=minimal" width="100%" height="600px" frameborder="no"></iframe>';
+                               }
+                       }
+
+                       $screenshot = [Theme::getScreenshot($theme), L10n::t('Screenshot')];
+                       if (!stristr($screenshot[0], $theme)) {
+                               $screenshot = null;
+                       }
+
+                       $t = Renderer::getMarkupTemplate('admin/addons/details.tpl');
+                       return Renderer::replaceMacros($t, [
+                               '$title' => L10n::t('Administration'),
+                               '$page' => L10n::t('Themes'),
+                               '$toggle' => L10n::t('Toggle'),
+                               '$settings' => L10n::t('Settings'),
+                               '$baseurl' => $a->getBaseURL(true),
+                               '$addon' => $theme,
+                               '$status' => $status,
+                               '$action' => $action,
+                               '$info' => Theme::getInfo($theme),
+                               '$function' => 'themes',
+                               '$admin_form' => $admin_form,
+                               '$str_author' => L10n::t('Author: '),
+                               '$str_maintainer' => L10n::t('Maintainer: '),
+                               '$screenshot' => $screenshot,
+                               '$readme' => $readme,
+
+                               '$form_security_token' => parent::getFormSecurityToken("admin_themes"),
+                       ]);
+               }
+
+               $a->internalRedirect('admin/themes');
+       }
+}
diff --git a/src/Module/Admin/Themes/Embed.php b/src/Module/Admin/Themes/Embed.php
new file mode 100644 (file)
index 0000000..dc41d11
--- /dev/null
@@ -0,0 +1,90 @@
+<?php
+
+namespace Friendica\Module\Admin\Themes;
+
+use Friendica\Core\L10n;
+use Friendica\Core\Renderer;
+use Friendica\Module\BaseAdminModule;
+use Friendica\Util\Strings;
+
+class Embed extends BaseAdminModule
+{
+       public static function init()
+       {
+               $a = self::getApp();
+
+               if ($a->argc > 2) {
+                       // @TODO: Replace with parameter from router
+                       $theme = $a->argv[2];
+                       $theme = Strings::sanitizeFilePathItem($theme);
+                       if (is_file("view/theme/$theme/config.php")) {
+                               $a->setCurrentTheme($theme);
+                       }
+               }
+       }
+
+       public static function post()
+       {
+               parent::post();
+
+               $a = self::getApp();
+
+               if ($a->argc > 2) {
+                       // @TODO: Replace with parameter from router
+                       $theme = $a->argv[2];
+                       $theme = Strings::sanitizeFilePathItem($theme);
+                       if (is_file("view/theme/$theme/config.php")) {
+                               self::checkFormSecurityTokenRedirectOnError('/admin/themes/' . $theme . '/embed?mode=minimal', 'admin_theme_settings');
+
+                               require_once "view/theme/$theme/config.php";
+
+                               if (function_exists('theme_admin_post')) {
+                                       theme_admin_post($a);
+                               }
+                       }
+
+                       info(L10n::t('Theme settings updated.'));
+
+                       if ($a->isAjax()) {
+                               return;
+                       }
+
+                       $a->internalRedirect('admin/themes/' . $theme . '/embed?mode=minimal');
+               }
+       }
+
+       public static function content()
+       {
+               parent::content();
+
+               $a = self::getApp();
+
+               if ($a->argc > 2) {
+                       // @TODO: Replace with parameter from router
+                       $theme = $a->argv[2];
+                       $theme = Strings::sanitizeFilePathItem($theme);
+                       if (!is_dir("view/theme/$theme")) {
+                               notice(L10n::t('Unknown theme.'));
+                               return '';
+                       }
+
+                       $admin_form = '';
+                       if (is_file("view/theme/$theme/config.php")) {
+                               require_once "view/theme/$theme/config.php";
+
+                               if (function_exists('theme_admin')) {
+                                       $admin_form = theme_admin($a);
+                               }
+                       }
+
+                       $t = Renderer::getMarkupTemplate('admin/addons/embed.tpl');
+                       return Renderer::replaceMacros($t, [
+                               '$action' => '/admin/themes/' . $theme . '/embed?mode=minimal',
+                               '$form' => $admin_form,
+                               '$form_security_token' => parent::getFormSecurityToken("admin_theme_settings"),
+                       ]);
+               }
+
+               return '';
+       }
+}
diff --git a/src/Module/Admin/Themes/Index.php b/src/Module/Admin/Themes/Index.php
new file mode 100644 (file)
index 0000000..71a9191
--- /dev/null
@@ -0,0 +1,107 @@
+<?php
+
+namespace Friendica\Module\Admin\Themes;
+
+use Friendica\Core\Config;
+use Friendica\Core\L10n;
+use Friendica\Core\Renderer;
+use Friendica\Core\Theme;
+use Friendica\Module\BaseAdminModule;
+use Friendica\Util\Strings;
+
+class Index extends BaseAdminModule
+{
+       public static function content()
+       {
+               parent::content();
+
+               $a = self::getApp();
+
+               $allowed_themes = Theme::getAllowedList();
+
+               // reload active themes
+               if (!empty($_GET['action'])) {
+                       parent::checkFormSecurityTokenRedirectOnError($a->getBaseURL() . '/admin/themes', 'admin_themes', 't');
+
+                       switch ($_GET['action']) {
+                               case 'reload':
+                                       foreach ($allowed_themes as $theme) {
+                                               Theme::uninstall($theme['name']);
+                                               Theme::install($theme['name']);
+                                       }
+
+                                       info('Themes reloaded');
+                                       break;
+
+                               case 'toggle' :
+                                       $theme = defaults($_GET, 'addon', '');
+                                       if ($theme) {
+                                               $theme = Strings::sanitizeFilePathItem($theme);
+                                               if (!is_dir("view/theme/$theme")) {
+                                                       notice(L10n::t('Item not found.'));
+                                                       return '';
+                                               }
+
+                                               if (in_array($theme, Theme::getAllowedList())) {
+                                                       Theme::uninstall($theme);
+                                                       info(L10n::t('Theme %s disabled.', $theme));
+                                               } elseif (Theme::install($theme)) {
+                                                       info(L10n::t('Theme %s successfully enabled.', $theme));
+                                               } else {
+                                                       info(L10n::t('Theme %s failed to install.', $theme));
+                                               }
+                                       }
+
+                                       break;
+
+                       }
+
+                       $a->internalRedirect('admin/themes');
+               }
+
+               $themes = [];
+               $files = glob('view/theme/*');
+               if (is_array($files)) {
+                       foreach ($files as $file) {
+                               $theme = basename($file);
+
+                               // Is there a style file?
+                               $theme_files = glob('view/theme/' . $theme . '/style.*');
+
+                               // If not then quit
+                               if (count($theme_files) == 0) {
+                                       continue;
+                               }
+
+                               $is_experimental = intval(file_exists($file . '/experimental'));
+                               $is_supported = 1 - (intval(file_exists($file . '/unsupported')));
+                               $is_allowed = intval(in_array($theme, $allowed_themes));
+
+                               if ($is_allowed || $is_supported || Config::get('system', 'show_unsupported_themes')) {
+                                       $themes[] = ['name' => $theme, 'experimental' => $is_experimental, 'supported' => $is_supported, 'allowed' => $is_allowed];
+                               }
+                       }
+               }
+
+               $addons = [];
+               foreach ($themes as $theme) {
+                       $addons[] = [$theme['name'], (($theme['allowed']) ? 'on' : 'off'), Theme::getInfo($theme['name'])];
+               }
+
+               $t = Renderer::getMarkupTemplate('admin/addons/index.tpl');
+               return Renderer::replaceMacros($t, [
+                       '$title'               => L10n::t('Administration'),
+                       '$page'                => L10n::t('Themes'),
+                       '$submit'              => L10n::t('Save Settings'),
+                       '$reload'              => L10n::t('Reload active themes'),
+                       '$baseurl'             => $a->getBaseURL(true),
+                       '$function'            => 'themes',
+                       '$addons'              => $addons,
+                       '$pcount'              => count($themes),
+                       '$noplugshint'         => L10n::t('No themes found on the system. They should be placed in %1$s', '<code>/view/themes</code>'),
+                       '$experimental'        => L10n::t('[Experimental]'),
+                       '$unsupported'         => L10n::t('[Unsupported]'),
+                       '$form_security_token' => parent::getFormSecurityToken('admin_themes'),
+               ]);
+       }
+}
diff --git a/src/Module/Admin/Tos.php b/src/Module/Admin/Tos.php
new file mode 100644 (file)
index 0000000..4eb6e34
--- /dev/null
@@ -0,0 +1,53 @@
+<?php
+
+namespace Friendica\Module\Admin;
+
+use Friendica\Core\Config;
+use Friendica\Core\L10n;
+use Friendica\Core\Renderer;
+use Friendica\Module\BaseAdminModule;
+
+class Tos extends BaseAdminModule
+{
+       public static function post()
+       {
+               parent::post();
+
+               parent::checkFormSecurityTokenRedirectOnError('/admin/tos', 'admin_tos');
+
+               if (empty($_POST['page_tos'])) {
+                       return;
+               }
+
+               $displaytos = !empty($_POST['displaytos']);
+               $displayprivstatement = !empty($_POST['displayprivstatement']);
+               $tostext = (!empty($_POST['tostext']) ? strip_tags(trim($_POST['tostext'])) : '');
+
+               Config::set('system', 'tosdisplay', $displaytos);
+               Config::set('system', 'tosprivstatement', $displayprivstatement);
+               Config::set('system', 'tostext', $tostext);
+
+               info(L10n::t('The Terms of Service settings have been updated.'));
+
+               self::getApp()->internalRedirect('admin/tos');
+       }
+
+       public static function content()
+       {
+               parent::content();
+
+               $tos = new \Friendica\Module\Tos();
+               $t = Renderer::getMarkupTemplate('admin/tos.tpl');
+               return Renderer::replaceMacros($t, [
+                       '$title' => L10n::t('Administration'),
+                       '$page' => L10n::t('Terms of Service'),
+                       '$displaytos' => ['displaytos', L10n::t('Display Terms of Service'), Config::get('system', 'tosdisplay'), L10n::t('Enable the Terms of Service page. If this is enabled a link to the terms will be added to the registration form and the general information page.')],
+                       '$displayprivstatement' => ['displayprivstatement', L10n::t('Display Privacy Statement'), Config::get('system', 'tosprivstatement'), L10n::t('Show some informations regarding the needed information to operate the node according e.g. to <a href="%s" target="_blank">EU-GDPR</a>.', 'https://en.wikipedia.org/wiki/General_Data_Protection_Regulation')],
+                       '$preview' => L10n::t('Privacy Statement Preview'),
+                       '$privtext' => $tos->privacy_complete,
+                       '$tostext' => ['tostext', L10n::t('The Terms of Service'), Config::get('system', 'tostext'), L10n::t('Enter the Terms of Service for your node here. You can use BBCode. Headers of sections should be [h2] and below.')],
+                       '$form_security_token' => parent::getFormSecurityToken('admin_tos'),
+                       '$submit' => L10n::t('Save Settings'),
+               ]);
+       }
+}
diff --git a/src/Module/Admin/Users.php b/src/Module/Admin/Users.php
new file mode 100644 (file)
index 0000000..92dddd9
--- /dev/null
@@ -0,0 +1,322 @@
+<?php
+
+namespace Friendica\Module\Admin;
+
+use Friendica\Content\Pager;
+use Friendica\Core\Config;
+use Friendica\Core\L10n;
+use Friendica\Core\Renderer;
+use Friendica\Database\DBA;
+use Friendica\Model\Register;
+use Friendica\Model\User;
+use Friendica\Module\BaseAdminModule;
+use Friendica\Util\Strings;
+use Friendica\Util\Temporal;
+
+class Users extends BaseAdminModule
+{
+       public static function post()
+       {
+               parent::post();
+
+               $a = self::getApp();
+
+               $pending     = defaults($_POST, 'pending'          , []);
+               $users       = defaults($_POST, 'user'             , []);
+               $nu_name     = defaults($_POST, 'new_user_name'    , '');
+               $nu_nickname = defaults($_POST, 'new_user_nickname', '');
+               $nu_email    = defaults($_POST, 'new_user_email'   , '');
+               $nu_language = Config::get('system', 'language');
+
+               parent::checkFormSecurityTokenRedirectOnError('/admin/users', 'admin_users');
+
+               if ($nu_name !== '' && $nu_email !== '' && $nu_nickname !== '') {
+                       try {
+                               $result = User::create([
+                                       'username' => $nu_name,
+                                       'email' => $nu_email,
+                                       'nickname' => $nu_nickname,
+                                       'verified' => 1,
+                                       'language' => $nu_language
+                               ]);
+                       } catch (\Exception $ex) {
+                               notice($ex->getMessage());
+                               return;
+                       }
+
+                       $user = $result['user'];
+                       $preamble = Strings::deindent(L10n::t('
+                       Dear %1$s,
+                               the administrator of %2$s has set up an account for you.'));
+                       $body = Strings::deindent(L10n::t('
+                       The login details are as follows:
+
+                       Site Location:  %1$s
+                       Login Name:             %2$s
+                       Password:               %3$s
+
+                       You may change your password from your account "Settings" page after logging
+                       in.
+
+                       Please take a few moments to review the other account settings on that page.
+
+                       You may also wish to add some basic information to your default profile
+                       (on the "Profiles" page) so that other people can easily find you.
+
+                       We recommend setting your full name, adding a profile photo,
+                       adding some profile "keywords" (very useful in making new friends) - and
+                       perhaps what country you live in; if you do not wish to be more specific
+                       than that.
+
+                       We fully respect your right to privacy, and none of these items are necessary.
+                       If you are new and do not know anybody here, they may help
+                       you to make some new and interesting friends.
+
+                       If you ever want to delete your account, you can do so at %1$s/removeme
+
+                       Thank you and welcome to %4$s.'));
+
+                       $preamble = sprintf($preamble, $user['username'], Config::get('config', 'sitename'));
+                       $body = sprintf($body, $a->getBaseURL(), $user['nickname'], $result['password'], Config::get('config', 'sitename'));
+
+                       notification([
+                               'type'     => SYSTEM_EMAIL,
+                               'language' => $user['language'],
+                               'to_name'  => $user['username'],
+                               'to_email' => $user['email'],
+                               'uid'      => $user['uid'],
+                               'subject'  => L10n::t('Registration details for %s', Config::get('config', 'sitename')),
+                               'preamble' => $preamble,
+                               'body'     => $body]);
+               }
+
+               if (!empty($_POST['page_users_block'])) {
+                       // @TODO Move this to Model\User:block($users);
+                       DBA::update('user', ['blocked' => 1], ['uid' => $users]);
+                       notice(L10n::tt('%s user blocked', '%s users blocked', count($users)));
+               }
+
+               if (!empty($_POST['page_users_unblock'])) {
+                       // @TODO Move this to Model\User:unblock($users);
+                       DBA::update('user', ['blocked' => 0], ['uid' => $users]);
+                       notice(L10n::tt('%s user unblocked', '%s users unblocked', count($users)));
+               }
+
+               if (!empty($_POST['page_users_delete'])) {
+                       foreach ($users as $uid) {
+                               if (local_user() != $uid) {
+                                       User::remove($uid);
+                               } else {
+                                       notice(L10n::t('You can\'t remove yourself'));
+                               }
+                       }
+
+                       notice(L10n::tt('%s user deleted', '%s users deleted', count($users)));
+               }
+
+               if (!empty($_POST['page_users_approve'])) {
+                       require_once 'mod/regmod.php';
+                       foreach ($pending as $hash) {
+                               user_allow($hash);
+                       }
+               }
+
+               if (!empty($_POST['page_users_deny'])) {
+                       require_once 'mod/regmod.php';
+                       foreach ($pending as $hash) {
+                               user_deny($hash);
+                       }
+               }
+
+               $a->internalRedirect('admin/users');
+       }
+
+       public static function content()
+       {
+               parent::content();
+
+               $a = self::getApp();
+
+               if ($a->argc > 3) {
+                       // @TODO: Replace with parameter from router
+                       $action = $a->argv[2];
+                       $uid = $a->argv[3];
+                       $user = User::getById($uid, ['username', 'blocked']);
+                       if (!DBA::isResult($user)) {
+                               notice('User not found' . EOL);
+                               $a->internalRedirect('admin/users');
+                               return ''; // NOTREACHED
+                       }
+
+                       switch ($action) {
+                               case 'delete':
+                                       if (local_user() != $uid) {
+                                               parent::checkFormSecurityTokenRedirectOnError('/admin/users', 'admin_users', 't');
+                                               // delete user
+                                               User::remove($uid);
+
+                                               notice(L10n::t('User "%s" deleted', $user['username']));
+                                       } else {
+                                               notice(L10n::t('You can\'t remove yourself'));
+                                       }
+                                       break;
+                               case 'block':
+                                       parent::checkFormSecurityTokenRedirectOnError('/admin/users', 'admin_users', 't');
+                                       // @TODO Move this to Model\User:block([$uid]);
+                                       DBA::update('user', ['blocked' => 1], ['uid' => $uid]);
+                                       notice(L10n::t('User "%s" blocked', $user['username']));
+                                       break;
+                               case 'unblock':
+                                       parent::checkFormSecurityTokenRedirectOnError('/admin/users', 'admin_users', 't');
+                                       // @TODO Move this to Model\User:unblock([$uid]);
+                                       DBA::update('user', ['blocked' => 0], ['uid' => $uid]);
+                                       notice(L10n::t('User "%s" unblocked', $user['username']));
+                                       break;
+                       }
+
+                       $a->internalRedirect('admin/users');
+               }
+
+               /* get pending */
+               $pending = Register::getPending();
+
+               $pager = new Pager($a->query_string, 100);
+
+               // @TODO Move below block to Model\User::getUsers($start, $count, $order = 'contact.name', $order_direction = '+')
+               $valid_orders = [
+                       'contact.name',
+                       'user.email',
+                       'user.register_date',
+                       'user.login_date',
+                       'lastitem_date',
+                       'user.page-flags'
+               ];
+
+               $order = 'contact.name';
+               $order_direction = '+';
+               if (!empty($_GET['o'])) {
+                       $new_order = $_GET['o'];
+                       if ($new_order[0] === '-') {
+                               $order_direction = '-';
+                               $new_order = substr($new_order, 1);
+                       }
+
+                       if (in_array($new_order, $valid_orders)) {
+                               $order = $new_order;
+                       }
+               }
+               $sql_order = '`' . str_replace('.', '`.`', $order) . '`';
+               $sql_order_direction = ($order_direction === '+') ? 'ASC' : 'DESC';
+
+               $usersStmt = DBA::p("SELECT `user`.*, `contact`.`name`, `contact`.`url`, `contact`.`micro`, `user`.`account_expired`, `contact`.`last-item` AS `lastitem_date`
+                               FROM `user`
+                               INNER JOIN `contact` ON `contact`.`uid` = `user`.`uid` AND `contact`.`self`
+                               WHERE `user`.`verified`
+                               ORDER BY $sql_order $sql_order_direction LIMIT ?, ?", $pager->getStart(), $pager->getItemsPerPage()
+               );
+               $users = DBA::toArray($usersStmt);
+
+               $adminlist = explode(',', str_replace(' ', '', Config::get('config', 'admin_email')));
+               $_setup_users = function ($e) use ($adminlist) {
+                       $page_types = [
+                               User::PAGE_FLAGS_NORMAL    => L10n::t('Normal Account Page'),
+                               User::PAGE_FLAGS_SOAPBOX   => L10n::t('Soapbox Page'),
+                               User::PAGE_FLAGS_COMMUNITY => L10n::t('Public Forum'),
+                               User::PAGE_FLAGS_FREELOVE  => L10n::t('Automatic Friend Page'),
+                               User::PAGE_FLAGS_PRVGROUP  => L10n::t('Private Forum')
+                       ];
+                       $account_types = [
+                               User::ACCOUNT_TYPE_PERSON       => L10n::t('Personal Page'),
+                               User::ACCOUNT_TYPE_ORGANISATION => L10n::t('Organisation Page'),
+                               User::ACCOUNT_TYPE_NEWS         => L10n::t('News Page'),
+                               User::ACCOUNT_TYPE_COMMUNITY    => L10n::t('Community Forum'),
+                               User::ACCOUNT_TYPE_RELAY        => L10n::t('Relay'),
+                       ];
+
+                       $e['page_flags_raw'] = $e['page-flags'];
+                       $e['page-flags'] = $page_types[$e['page-flags']];
+
+                       $e['account_type_raw'] = ($e['page_flags_raw'] == 0) ? $e['account-type'] : -1;
+                       $e['account-type'] = ($e['page_flags_raw'] == 0) ? $account_types[$e['account-type']] : '';
+
+                       $e['register_date'] = Temporal::getRelativeDate($e['register_date']);
+                       $e['login_date'] = Temporal::getRelativeDate($e['login_date']);
+                       $e['lastitem_date'] = Temporal::getRelativeDate($e['lastitem_date']);
+                       $e['is_admin'] = in_array($e['email'], $adminlist);
+                       $e['is_deletable'] = (intval($e['uid']) != local_user());
+                       $e['deleted'] = ($e['account_removed'] ? Temporal::getRelativeDate($e['account_expires_on']) : False);
+
+                       return $e;
+               };
+
+               $tmp_users = array_map($_setup_users, $users);
+
+               // Get rid of dashes in key names, Smarty3 can't handle them
+               // and extracting deleted users
+
+               $deleted = [];
+               $users = [];
+               foreach ($tmp_users as $user) {
+                       foreach ($user as $k => $v) {
+                               $newkey = str_replace('-', '_', $k);
+                               $user[$newkey] = $v;
+                       }
+
+                       if ($user['deleted']) {
+                               $deleted[] = $user;
+                       } else {
+                               $users[] = $user;
+                       }
+               }
+
+               $th_users = array_map(null, [L10n::t('Name'), L10n::t('Email'), L10n::t('Register date'), L10n::t('Last login'), L10n::t('Last item'), L10n::t('Type')], $valid_orders);
+
+               $t = Renderer::getMarkupTemplate('admin/users.tpl');
+               $o = Renderer::replaceMacros($t, [
+                       // strings //
+                       '$title' => L10n::t('Administration'),
+                       '$page' => L10n::t('Users'),
+                       '$submit' => L10n::t('Add User'),
+                       '$select_all' => L10n::t('select all'),
+                       '$h_pending' => L10n::t('User registrations waiting for confirm'),
+                       '$h_deleted' => L10n::t('User waiting for permanent deletion'),
+                       '$th_pending' => [L10n::t('Request date'), L10n::t('Name'), L10n::t('Email')],
+                       '$no_pending' => L10n::t('No registrations.'),
+                       '$pendingnotetext' => L10n::t('Note from the user'),
+                       '$approve' => L10n::t('Approve'),
+                       '$deny' => L10n::t('Deny'),
+                       '$delete' => L10n::t('Delete'),
+                       '$block' => L10n::t('Block'),
+                       '$blocked' => L10n::t('User blocked'),
+                       '$unblock' => L10n::t('Unblock'),
+                       '$siteadmin' => L10n::t('Site admin'),
+                       '$accountexpired' => L10n::t('Account expired'),
+
+                       '$h_users' => L10n::t('Users'),
+                       '$h_newuser' => L10n::t('New User'),
+                       '$th_deleted' => [L10n::t('Name'), L10n::t('Email'), L10n::t('Register date'), L10n::t('Last login'), L10n::t('Last item'), L10n::t('Permanent deletion')],
+                       '$th_users' => $th_users,
+                       '$order_users' => $order,
+                       '$order_direction_users' => $order_direction,
+
+                       '$confirm_delete_multi' => L10n::t('Selected users will be deleted!\n\nEverything these users had posted on this site will be permanently deleted!\n\nAre you sure?'),
+                       '$confirm_delete' => L10n::t('The user {0} will be deleted!\n\nEverything this user has posted on this site will be permanently deleted!\n\nAre you sure?'),
+
+                       '$form_security_token' => parent::getFormSecurityToken('admin_users'),
+
+                       // values //
+                       '$baseurl' => $a->getBaseURL(true),
+
+                       '$pending' => $pending,
+                       'deleted' => $deleted,
+                       '$users' => $users,
+                       '$newusername' => ['new_user_name', L10n::t('Name'), '', L10n::t('Name of the new user.')],
+                       '$newusernickname' => ['new_user_nickname', L10n::t('Nickname'), '', L10n::t('Nickname of the new user.')],
+                       '$newuseremail' => ['new_user_email', L10n::t('Email'), '', L10n::t('Email address of the new user.'), '', '', 'email'],
+               ]);
+
+               $o .= $pager->renderFull(DBA::count('user'));
+
+               return $o;
+       }
+}
diff --git a/src/Module/AllFriends.php b/src/Module/AllFriends.php
new file mode 100644 (file)
index 0000000..b0e6ea1
--- /dev/null
@@ -0,0 +1,107 @@
+<?php
+
+namespace Friendica\Module;
+
+use Friendica\BaseModule;
+use Friendica\Content\ContactSelector;
+use Friendica\Content\Pager;
+use Friendica\Core\L10n;
+use Friendica\Core\Renderer;
+use Friendica\Model;
+use Friendica\Network\HTTPException;
+use Friendica\Util\Proxy as ProxyUtils;
+
+/**
+ * This module shows all public friends of the selected contact
+ */
+class AllFriends extends BaseModule
+{
+       public static function content()
+       {
+               $app = self::getApp();
+
+               if (!local_user()) {
+                       throw new HTTPException\ForbiddenException();
+               }
+
+               $cid = 0;
+
+               // @TODO: Replace with parameter from router
+               if ($app->argc > 1) {
+                       $cid = intval($app->argv[1]);
+               }
+
+               if (!$cid) {
+                       throw new HTTPException\BadRequestException(L10n::t('Invalid contact.'));
+               }
+
+               $uid = $app->user['uid'];
+
+               $contact = Model\Contact::getContactForUser($cid, local_user(), ['name', 'url', 'photo', 'uid', 'id']);
+
+               if (empty($contact)) {
+                       throw new HTTPException\BadRequestException(L10n::t('Invalid contact.'));
+               }
+
+               $app->page['aside'] = "";
+               Model\Profile::load($app, "", 0, Model\Contact::getDetailsByURL($contact["url"]));
+
+               $total = Model\GContact::countAllFriends(local_user(), $cid);
+
+               $pager = new Pager($app->query_string);
+
+               $friends = Model\GContact::allFriends(local_user(), $cid, $pager->getStart(), $pager->getItemsPerPage());
+               if (empty($friends)) {
+                       return L10n::t('No friends to display.');
+               }
+
+               $id = 0;
+
+               $entries = [];
+               foreach ($friends as $friend) {
+                       //get further details of the contact
+                       $contactDetails = Model\Contact::getDetailsByURL($friend['url'], $uid, $friend);
+
+                       $connlnk = '';
+                       // $friend[cid] is only available for common contacts. So if the contact is a common one, use contact_photo_menu to generate the photoMenu
+                       // If the contact is not common to the user, Connect/Follow' will be added to the photo menu
+                       if ($friend['cid']) {
+                               $friend['id'] = $friend['cid'];
+                               $photoMenu = Model\Contact::photoMenu($friend);
+                       } else {
+                               $connlnk = $app->getBaseURL() . '/follow/?url=' . $friend['url'];
+                               $photoMenu = [
+                                       'profile' => [L10n::t('View Profile'), Model\Contact::magicLinkbyId($friend['id'], $friend['url'])],
+                                       'follow'  => [L10n::t('Connect/Follow'), $connlnk]
+                               ];
+                       }
+
+                       $entry = [
+                               'url'          => Model\Contact::magicLinkbyId($friend['id'], $friend['url']),
+                               'itemurl'      => defaults($contactDetails, 'addr', $friend['url']),
+                               'name'         => $contactDetails['name'],
+                               'thumb'        => ProxyUtils::proxifyUrl($contactDetails['thumb'], false, ProxyUtils::SIZE_THUMB),
+                               'img_hover'    => $contactDetails['name'],
+                               'details'      => $contactDetails['location'],
+                               'tags'         => $contactDetails['keywords'],
+                               'about'        => $contactDetails['about'],
+                               'account_type' => Model\Contact::getAccountType($contactDetails),
+                               'network'      => ContactSelector::networkToName($contactDetails['network'], $contactDetails['url']),
+                               'photoMenu'    => $photoMenu,
+                               'conntxt'      => L10n::t('Connect'),
+                               'connlnk'      => $connlnk,
+                               'id'           => ++$id,
+                       ];
+                       $entries[] = $entry;
+               }
+
+               $tab_str = Contact::getTabsHTML($app, $contact, 4);
+
+               $tpl = Renderer::getMarkupTemplate('viewcontact_template.tpl');
+               return Renderer::replaceMacros($tpl, [
+                       '$tab_str'  => $tab_str,
+                       '$contacts' => $entries,
+                       '$paginate' => $pager->renderFull($total),
+               ]);
+       }
+}
index dd4e368058b7c3583424dfed3122aef629f789d1..e9af90facc3fb1b0cc053acb93909e238c962e91 100644 (file)
@@ -8,8 +8,8 @@ namespace Friendica\Module;
 
 use Friendica\BaseModule;
 use Friendica\Core\L10n;
-use Friendica\Core\System;
 use Friendica\Core\Logger;
+use Friendica\Core\System;
 use Friendica\Model\Attach as MAttach;
 
 /**
@@ -24,28 +24,28 @@ class Attach extends BaseModule
        {
                $a = self::getApp();
                if ($a->argc != 2) {
-                       System::httpExit(400); // Bad Request.
+                       throw new \Friendica\Network\HTTPException\BadRequestException();
                }
-       
 
+               // @TODO: Replace with parameter from router
                $item_id = intval($a->argv[1]);
                
                // Check for existence
                $item = MAttach::exists(['id' => $item_id]);
                if ($item === false) {
-                       System::httpExit(404, ['description' => L10n::t('Item was not found.')]);
+                       throw new \Friendica\Network\HTTPException\NotFoundException(L10n::t('Item was not found.'));
                }
 
                // Now we'll fetch the item, if we have enough permisson
                $item = MAttach::getByIdWithPermission($item_id);
                if ($item === false) {
-                       System::httpExit(403, ['description' => L10n::t('Permission denied.')]);
+                       throw new \Friendica\Network\HTTPException\ForbiddenException(L10n::t('Permission denied.'));
                }
 
                $data = MAttach::getData($item);
                if (is_null($data)) {
                        Logger::log('NULL data for attachment with id ' . $item['id']);
-                       System::httpExit(404, ['description' => L10n::t('Item was not found.')]);
+                       throw new \Friendica\Network\HTTPException\NotFoundException(L10n::t('Item was not found.'));
                }
 
                // Use quotes around the filename to prevent a "multiple Content-Disposition"
diff --git a/src/Module/BaseAdminModule.php b/src/Module/BaseAdminModule.php
new file mode 100644 (file)
index 0000000..dd89bcb
--- /dev/null
@@ -0,0 +1,122 @@
+<?php
+
+namespace Friendica\Module;
+
+use Friendica\BaseModule;
+use Friendica\Core\Addon;
+use Friendica\Core\L10n;
+use Friendica\Core\Renderer;
+use Friendica\Core\System;
+
+/**
+ * This abstract module is meant to be extended by all modules that are reserved to administrator users.
+ *
+ * It performs a blanket permission check in all the module methods as long as the relevant `parent::method()` is
+ * called in the inheriting module.
+ *
+ * Additionally, it puts together the administration page aside with all the administration links.
+ *
+ * @package Friendica\Module
+ */
+abstract class BaseAdminModule extends BaseModule
+{
+       public static function post()
+       {
+               if (!is_site_admin()) {
+                       return;
+               }
+
+               // do not allow a page manager to access the admin panel at all.
+               if (!empty($_SESSION['submanage'])) {
+                       return;
+               }
+       }
+
+       public static function rawContent()
+       {
+               if (!is_site_admin()) {
+                       System::httpExit(403);
+               }
+
+               if (!empty($_SESSION['submanage'])) {
+                       System::httpExit(403);
+               }
+
+               return '';
+       }
+
+       public static function content()
+       {
+               if (!is_site_admin()) {
+                       return Login::form();
+               }
+
+               if (!empty($_SESSION['submanage'])) {
+                       return '';
+               }
+
+               $a = self::getApp();
+
+               // APC deactivated, since there are problems with PHP 5.5
+               //if (function_exists("apc_delete")) {
+               // $toDelete = new APCIterator('user', APC_ITER_VALUE);
+               // apc_delete($toDelete);
+               //}
+               // Header stuff
+               $a->page['htmlhead'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate('admin/settings_head.tpl'), []);
+
+               /*
+                * Side bar links
+                */
+
+               // array(url, name, extra css classes)
+               // not part of $aside to make the template more adjustable
+               $aside_sub = [
+                       'information' => [L10n::t('Information'), [
+                               'overview'     => ['admin'             , L10n::t('Overview')                , 'overview'],
+                               'federation'   => ['admin/federation'  , L10n::t('Federation Statistics')   , 'federation']
+                       ]],
+                       'configuration' => [L10n::t('Configuration'), [
+                               'site'         => ['admin/site'        , L10n::t('Site')                    , 'site'],
+                               'users'        => ['admin/users'       , L10n::t('Users')                   , 'users'],
+                               'addons'       => ['admin/addons'      , L10n::t('Addons')                  , 'addons'],
+                               'themes'       => ['admin/themes'      , L10n::t('Themes')                  , 'themes'],
+                               'features'     => ['admin/features'    , L10n::t('Additional features')     , 'features'],
+                               'tos'          => ['admin/tos'         , L10n::t('Terms of Service')        , 'tos'],
+                       ]],
+                       'database' => [L10n::t('Database'), [
+                               'dbsync'       => ['admin/dbsync'      , L10n::t('DB updates')              , 'dbsync'],
+                               'deferred'     => ['admin/queue/deferred', L10n::t('Inspect Deferred Workers'), 'deferred'],
+                               'workerqueue'  => ['admin/queue'       , L10n::t('Inspect worker Queue')    , 'workerqueue'],
+                       ]],
+                       'tools' => [L10n::t('Tools'), [
+                               'contactblock' => ['admin/blocklist/contact', L10n::t('Contact Blocklist')  , 'contactblock'],
+                               'blocklist'    => ['admin/blocklist/server' , L10n::t('Server Blocklist')   , 'blocklist'],
+                               'deleteitem'   => ['admin/item/delete' , L10n::t('Delete Item')             , 'deleteitem'],
+                       ]],
+                       'logs' => [L10n::t('Logs'), [
+                               'logsconfig'   => ['admin/logs/', L10n::t('Logs')                           , 'logs'],
+                               'logsview'     => ['admin/logs/view'    , L10n::t('View Logs')              , 'viewlogs'],
+                       ]],
+                       'diagnostics' => [L10n::t('Diagnostics'), [
+                               'phpinfo'      => ['admin/phpinfo'           , L10n::t('PHP Info')          , 'phpinfo'],
+                               'probe'        => ['probe'             , L10n::t('probe address')           , 'probe'],
+                               'webfinger'    => ['webfinger'         , L10n::t('check webfinger')         , 'webfinger'],
+                               'itemsource'   => ['admin/item/source' , L10n::t('Item Source')             , 'itemsource'],
+                               'babel'        => ['babel'             , L10n::t('Babel')                   , 'babel'],
+                       ]],
+               ];
+
+               $t = Renderer::getMarkupTemplate('admin/aside.tpl');
+               $a->page['aside'] .= Renderer::replaceMacros($t, [
+                       '$admin' => ['addons_admin' => Addon::getAdminList()],
+                       '$subpages' => $aside_sub,
+                       '$admtxt' => L10n::t('Admin'),
+                       '$plugadmtxt' => L10n::t('Addon Features'),
+                       '$h_pending' => L10n::t('User registrations waiting for confirmation'),
+                       '$admurl' => 'admin/'
+               ]);
+
+               return '';
+       }
+}
diff --git a/src/Module/BookMarklet.php b/src/Module/BookMarklet.php
new file mode 100644 (file)
index 0000000..51feb25
--- /dev/null
@@ -0,0 +1,63 @@
+<?php
+
+namespace Friendica\Module;
+
+use Friendica\BaseModule;
+use Friendica\Core\ACL;
+use Friendica\Core\L10n;
+use Friendica\Network\HTTPException;
+use Friendica\Util\Strings;
+
+/**
+ * Creates a bookmarklet
+ * Shows either a editor browser or adds the given bookmarklet to the current user
+ */
+class BookMarklet extends BaseModule
+{
+       public static function content()
+       {
+               $_GET['mode'] = 'minimal';
+
+               $app = self::getApp();
+               $config = $app->getConfig();
+
+               if (!local_user()) {
+                       $output = '<h2>' . L10n::t('Login') . '</h2>';
+                       $output .= Login::form($app->query_string, intval($config->get('config', 'register_policy')) === Register::CLOSED ? false : true);
+                       return $output;
+               }
+
+               $referer = Strings::normaliseLink(defaults($_SERVER, 'HTTP_REFERER', ''));
+               $page = Strings::normaliseLink($app->getBaseURL() . "/bookmarklet");
+
+               if (!strstr($referer, $page)) {
+                       if (empty($_REQUEST["url"])) {
+                               throw new HTTPException\BadRequestException(L10n::t('This page is missing a url parameter.'));
+                       }
+
+                       $content = add_page_info($_REQUEST["url"]);
+
+                       $x = [
+                               'is_owner'         => true,
+                               'allow_location'   => $app->user['allow_location'],
+                               'default_location' => $app->user['default-location'],
+                               'nickname'         => $app->user['nickname'],
+                               'lockstate'        => ((is_array($app->user) && ((strlen($app->user['allow_cid'])) || (strlen($a->user['allow_gid'])) || (strlen($app->user['deny_cid'])) || (strlen($app->user['deny_gid'])))) ? 'lock' : 'unlock'),
+                               'default_perms'    => ACL::getDefaultUserPermissions($app->user),
+                               'acl'              => ACL::getFullSelectorHTML($app->user, true),
+                               'bang'             => '',
+                               'visitor'          => 'block',
+                               'profile_uid'      => local_user(),
+                               'title'            => trim(defaults($_REQUEST, 'title', ''), '*'),
+                               'content'          => $content
+                       ];
+                       $output = status_editor($app, $x, 0, false);
+                       $output .= "<script>window.resizeTo(800,550);</script>";
+               } else {
+                       $output = '<h2>' . L10n::t('The post was created') . '</h2>';
+                       $output .= "<script>window.close()</script>";
+               }
+
+               return $output;
+       }
+}
index 230ad4b57bd008938c0a273846609c734424a4c8..ea3eecd4a278f675255e13b29a008b2c9260557d 100644 (file)
@@ -46,6 +46,7 @@ class Contact extends BaseModule
 
                $contact_id = null;
                $contact = null;
+               // @TODO: Replace with parameter from router
                if ($a->argc == 2 && intval($a->argv[1])
                        || $a->argc == 3 && intval($a->argv[1]) && in_array($a->argv[2], ['posts', 'conversations'])
                ) {
@@ -64,6 +65,7 @@ class Contact extends BaseModule
 
                if (DBA::isResult($contact)) {
                        if ($contact['self']) {
+                               // @TODO: Replace with parameter from router
                                if (($a->argc == 3) && intval($a->argv[1]) && in_array($a->argv[2], ['posts', 'conversations'])) {
                                        $a->internalRedirect('profile/' . $contact['nick']);
                                } else {
@@ -118,11 +120,9 @@ class Contact extends BaseModule
                        '$networks_widget'   => $networks_widget
                ]);
 
-               $base = $a->getBaseURL();
                $tpl = Renderer::getMarkupTemplate('contacts-head.tpl');
                $a->page['htmlhead'] .= Renderer::replaceMacros($tpl, [
-                       '$baseurl' => System::baseUrl(true),
-                       '$base' => $base
+                       '$baseurl' => $a->getBaseURL(true),
                ]);
        }
 
@@ -807,7 +807,6 @@ class Contact extends BaseModule
 
                $tpl = Renderer::getMarkupTemplate('contacts-template.tpl');
                $o .= Renderer::replaceMacros($tpl, [
-                       '$baseurl'    => System::baseUrl(),
                        '$header'     => L10n::t('Contacts') . (($nets) ? ' - ' . ContactSelector::networkToName($nets) : ''),
                        '$tabs'       => $t,
                        '$total'      => $total,
diff --git a/src/Module/Diaspora/Fetch.php b/src/Module/Diaspora/Fetch.php
new file mode 100644 (file)
index 0000000..bcb33e3
--- /dev/null
@@ -0,0 +1,70 @@
+<?php
+
+namespace Friendica\Module\Diaspora;
+
+use Friendica\BaseModule;
+use Friendica\Core\Protocol;
+use Friendica\Core\System;
+use Friendica\Model\Item;
+use Friendica\Model\User;
+use Friendica\Network\HTTPException;
+use Friendica\Protocol\Diaspora;
+use Friendica\Util\Strings;
+
+/**
+ * This module is part of the Diaspora protocol.
+ * It is used for fetching single public posts.
+ */
+class Fetch extends BaseModule
+{
+       public static function rawContent()
+       {
+               $app = self::getApp();
+
+               // @TODO: Replace with parameter from router
+               if (($app->argc != 3) || (!in_array($app->argv[1], ["post", "status_message", "reshare"]))) {
+                       throw new HTTPException\NotFoundException();
+               }
+
+               // @TODO: Replace with parameter from router
+               $guid = $app->argv[2];
+
+               // Fetch the item
+               $fields = [
+                       'uid', 'title', 'body', 'guid', 'contact-id', 'private', 'created', 'app', 'location', 'coord', 'network',
+                       'event-id', 'resource-id', 'author-link', 'author-avatar', 'author-name', 'plink', 'owner-link', 'attach'
+               ];
+               $condition = ['wall' => true, 'private' => false, 'guid' => $guid, 'network' => [Protocol::DFRN, Protocol::DIASPORA]];
+               $item = Item::selectFirst($fields, $condition);
+               if (empty($item)) {
+                       $condition = ['guid' => $guid, 'network' => [Protocol::DFRN, Protocol::DIASPORA]];
+                       $item = Item::selectFirst(['author-link'], $condition);
+                       if (empty($item)) {
+                               $parts = parse_url($item["author-link"]);
+                               $host = $parts["scheme"] . "://" . $parts["host"];
+
+                               if (Strings::normaliseLink($host) != Strings::normaliseLink($app->getBaseURL())) {
+                                       $location = $host . "/fetch/" . $app->argv[1] . "/" . urlencode($guid);
+                                       System::externalRedirect($location, 301);
+                               }
+                       }
+
+                       throw new HTTPException\NotFoundException();
+               }
+
+               // Fetch some data from the author (We could combine both queries - but I think this is more readable)
+               $user = User::getOwnerDataById($item["uid"]);
+               if (!$user) {
+                       throw new HTTPException\NotFoundException();
+               }
+
+               $status = Diaspora::buildStatus($item, $user);
+               $xml = Diaspora::buildPostXml($status["type"], $status["message"]);
+
+               // Send the envelope
+               header("Content-Type: application/magic-envelope+xml; charset=utf-8");
+               echo Diaspora::buildMagicEnvelope($xml, $user);
+
+               exit();
+       }
+}
diff --git a/src/Module/Directory.php b/src/Module/Directory.php
new file mode 100644 (file)
index 0000000..cdf43b8
--- /dev/null
@@ -0,0 +1,188 @@
+<?php
+
+namespace Friendica\Module;
+
+use Friendica\BaseModule;
+use Friendica\Content\Nav;
+use Friendica\Content\Pager;
+use Friendica\Content\Widget;
+use Friendica\Core\Hook;
+use Friendica\Core\L10n;
+use Friendica\Core\Renderer;
+use Friendica\Model\Contact;
+use Friendica\Model\Profile;
+use Friendica\Network\HTTPException;
+use Friendica\Util\Proxy as ProxyUtils;
+use Friendica\Util\Strings;
+
+/**
+ * Shows the local directory of this node
+ */
+class Directory extends BaseModule
+{
+       public static function init()
+       {
+               $app = self::getApp();
+
+               if (local_user()) {
+                       $app->page['aside'] .= Widget::findPeople();
+                       $app->page['aside'] .= Widget::follow();
+               } else {
+                       unset($_SESSION['theme']);
+                       unset($_SESSION['mobile-theme']);
+               }
+       }
+
+       public static function content()
+       {
+               $app = self::getApp();
+               $config = $app->getConfig();
+
+               if (($config->get('system', 'block_public') && !local_user() && !remote_user()) ||
+                       ($config->get('system', 'block_local_dir') && !local_user() && !remote_user())) {
+                       throw new HTTPException\ForbiddenException(L10n::t('Public access denied.'));
+               }
+
+               $output = '';
+               $entries = [];
+
+               Nav::setSelected('directory');
+
+               $search = (!empty($_REQUEST['search']) ?
+                       Strings::escapeTags(trim(rawurldecode($_REQUEST['search']))) :
+                       '');
+
+               $gDirPath = '';
+               $dirURL = $config->get('system', 'directory');
+               if (strlen($dirURL)) {
+                       $gDirPath = Profile::zrl($dirURL, true);
+               }
+
+               $pager = new Pager($app->query_string, 60);
+
+               $profiles = Profile::searchProfiles($pager->getStart(), $pager->getItemsPerPage(), $search);
+
+               if ($profiles['total'] === 0) {
+                       info(L10n::t('No entries (some entries may be hidden).') . EOL);
+               } else {
+                       if (in_array('small', $app->argv)) {
+                               $photo = 'thumb';
+                       } else {
+                               $photo = 'photo';
+                       }
+
+                       foreach ($profiles['entries'] as $entry) {
+                               $entries[] = self::formatEntry($entry, $photo);
+                       }
+               }
+
+               $tpl = Renderer::getMarkupTemplate('directory_header.tpl');
+
+               $output .= Renderer::replaceMacros($tpl, [
+                       '$search'     => $search,
+                       '$globaldir'  => L10n::t('Global Directory'),
+                       '$gDirPath'   => $gDirPath,
+                       '$desc'       => L10n::t('Find on this site'),
+                       '$contacts'   => $profiles['entries'],
+                       '$finding'    => L10n::t('Results for:'),
+                       '$findterm'   => (strlen($search) ? $search : ""),
+                       '$title'      => L10n::t('Site Directory'),
+                       '$search_mod' => 'directory',
+                       '$submit'     => L10n::t('Find'),
+                       '$paginate'   => $pager->renderFull($profiles['total']),
+               ]);
+
+               return $output;
+       }
+
+       /**
+        * Format contact/profile/user data from the database into an usable
+        * array for displaying directory entries.
+        *
+        * @param array  $contact    The directory entry from the database.
+        * @param string $photo_size Avatar size (thumb, photo or micro).
+        *
+        * @return array
+        *
+        * @throws \Exception
+        */
+       public static function formatEntry(array $contact, $photo_size = 'photo')
+       {
+               $itemurl = (($contact['addr'] != "") ? $contact['addr'] : $contact['profile_url']);
+
+               $profile_link = $contact['profile_url'];
+
+               $pdesc = (($contact['pdesc']) ? $contact['pdesc'] . '<br />' : '');
+
+               $details = '';
+               if (strlen($contact['locality'])) {
+                       $details .= $contact['locality'];
+               }
+               if (strlen($contact['region'])) {
+                       if (strlen($contact['locality'])) {
+                               $details .= ', ';
+                       }
+                       $details .= $contact['region'];
+               }
+               if (strlen($contact['country-name'])) {
+                       if (strlen($details)) {
+                               $details .= ', ';
+                       }
+                       $details .= $contact['country-name'];
+               }
+
+               $profile = $contact;
+
+               if (!empty($profile['address'])
+                       || !empty($profile['locality'])
+                       || !empty($profile['region'])
+                       || !empty($profile['postal-code'])
+                       || !empty($profile['country-name'])
+               ) {
+                       $location = L10n::t('Location:');
+               } else {
+                       $location = '';
+               }
+
+               $gender =   (!empty($profile['gender'])   ? L10n::t('Gender:')   : false);
+               $marital =  (!empty($profile['marital'])  ? L10n::t('Status:')   : false);
+               $homepage = (!empty($profile['homepage']) ? L10n::t('Homepage:') : false);
+               $about =    (!empty($profile['about'])    ? L10n::t('About:')    : false);
+
+               $location_e = $location;
+
+               $photo_menu = [
+                       'profile' => [L10n::t("View Profile"), Contact::magicLink($profile_link)]
+               ];
+
+               $entry = [
+                       'id'           => $contact['id'],
+                       'url'          => Contact::magicLInk($profile_link),
+                       'itemurl'      => $itemurl,
+                       'thumb'        => ProxyUtils::proxifyUrl($contact[$photo_size], false, ProxyUtils::SIZE_THUMB),
+                       'img_hover'    => $contact['name'],
+                       'name'         => $contact['name'],
+                       'details'      => $details,
+                       'account_type' => Contact::getAccountType($contact),
+                       'profile'      => $profile,
+                       'location'     => $location_e,
+                       'tags'         => $contact['pub_keywords'],
+                       'gender'       => $gender,
+                       'pdesc'        => $pdesc,
+                       'marital'      => $marital,
+                       'homepage'     => $homepage,
+                       'about'        => $about,
+                       'photo_menu'   => $photo_menu,
+
+               ];
+
+               $hook = ['contact' => $contact, 'entry' => $entry];
+
+               Hook::callAll('directory_item', $hook);
+
+               unset($profile);
+               unset($location);
+
+               return $hook['entry'];
+       }
+}
index e5ebe2a4d66239e4551232fb68c49b3fe639e05a..15b2026e2c246559668a4e30df495e8a811280d0 100644 (file)
@@ -3,7 +3,6 @@
 namespace Friendica\Module;
 
 use Friendica\BaseModule;
-use Friendica\Core\System;
 use Friendica\Protocol\OStatus;
 
 /**
@@ -31,11 +30,13 @@ class Feed extends BaseModule
                $last_update = defaults($_GET, 'last_update', '');
                $nocache     = !empty($_GET['nocache']) && local_user();
 
+               // @TODO: Replace with parameter from router
                if ($a->argc < 2) {
-                       System::httpExit(400);
+                       throw new \Friendica\Network\HTTPException\BadRequestException();
                }
 
                $type = null;
+               // @TODO: Replace with parameter from router
                if ($a->argc > 2) {
                        $type = $a->argv[2];
                }
@@ -53,6 +54,7 @@ class Feed extends BaseModule
                                $type = 'posts';
                }
 
+               // @TODO: Replace with parameter from router
                $nickname = $a->argv[1];
                header("Content-type: application/atom+xml; charset=utf-8");
                echo OStatus::feed($nickname, $last_update, 10, $type, $nocache, true);
index 08c656ed388151665aa17c30b42716c4e0c51e83..da59084da090c911ec1014e901cd43316a2b58b5 100644 (file)
@@ -28,6 +28,7 @@ class Filer extends BaseModule
                $logger = $a->getLogger();
 
                $term = XML::unescape(trim(defaults($_GET, 'term', '')));
+               // @TODO: Replace with parameter from router
                $item_id = (($a->argc > 1) ? intval($a->argv[1]) : 0);
 
                $logger->info('filer', ['tag' => $term, 'item' => $item_id]);
index 56160aecf81a10f8df4e857561ee99b1992302c5..79f34021b13243ebc883b01106cbf31b92d46a1c 100644 (file)
@@ -5,9 +5,9 @@
 namespace Friendica\Module;
 
 use Friendica\BaseModule;
-use Friendica\Protocol\ActivityPub;
 use Friendica\Core\System;
 use Friendica\Model\User;
+use Friendica\Protocol\ActivityPub;
 
 /**
  * ActivityPub Followers
@@ -18,13 +18,15 @@ class Followers extends BaseModule
        {
                $a = self::getApp();
 
+               // @TODO: Replace with parameter from router
                if (empty($a->argv[1])) {
-                       System::httpExit(404);
+                       throw new \Friendica\Network\HTTPException\NotFoundException();
                }
 
+               // @TODO: Replace with parameter from router
                $owner = User::getOwnerDataByNick($a->argv[1]);
                if (empty($owner)) {
-                       System::httpExit(404);
+                       throw new \Friendica\Network\HTTPException\NotFoundException();
                }
 
                $page = defaults($_REQUEST, 'page', null);
index 71e6613f0c19629810a7b7d0cd26ccb8f0da51b1..3a68e7e0afbd9bb21852e878e2decbd718e6e0ad 100644 (file)
@@ -5,9 +5,9 @@
 namespace Friendica\Module;
 
 use Friendica\BaseModule;
-use Friendica\Protocol\ActivityPub;
 use Friendica\Core\System;
 use Friendica\Model\User;
+use Friendica\Protocol\ActivityPub;
 
 /**
  * ActivityPub Following
@@ -18,13 +18,15 @@ class Following extends BaseModule
        {
                $a = self::getApp();
 
+               // @TODO: Replace with parameter from router
                if (empty($a->argv[1])) {
-                       System::httpExit(404);
+                       throw new \Friendica\Network\HTTPException\NotFoundException();
                }
 
+               // @TODO: Replace with parameter from router
                $owner = User::getOwnerDataByNick($a->argv[1]);
                if (empty($owner)) {
-                       System::httpExit(404);
+                       throw new \Friendica\Network\HTTPException\NotFoundException();
                }
 
                $page = defaults($_REQUEST, 'page', null);
index 747ec1e56d8224f8ae71e7930e38242fefba9773..d8d5fb1c592086e9e2574fb246fbdf8eb08a5992 100644 (file)
-<?php\r
-/**\r
- * @file src/Module/Group.php\r
- */\r
-\r
-namespace Friendica\Module;\r
-\r
-use Friendica\BaseModule;\r
-use Friendica\Core\Config;\r
-use Friendica\Core\L10n;\r
-use Friendica\Core\PConfig;\r
-use Friendica\Core\Renderer;\r
-use Friendica\Core\System;\r
-use Friendica\Database\DBA;\r
-use Friendica\Model;\r
-use Friendica\Util\Strings;\r
-\r
-require_once 'boot.php';\r
-\r
-class Group extends BaseModule\r
-{\r
-       public static function post()\r
-       {\r
-               $a = self::getApp();\r
-\r
-               if ($a->isAjax()) {\r
-                       self::ajaxPost();\r
-               }\r
-\r
-               if (!local_user()) {\r
-                       notice(L10n::t('Permission denied.'));\r
-                       $a->internalRedirect();\r
-               }\r
-\r
-               if (($a->argc == 2) && ($a->argv[1] === 'new')) {\r
-                       BaseModule::checkFormSecurityTokenRedirectOnError('/group/new', 'group_edit');\r
-\r
-                       $name = Strings::escapeTags(trim($_POST['groupname']));\r
-                       $r = Model\Group::create(local_user(), $name);\r
-                       if ($r) {\r
-                               info(L10n::t('Group created.'));\r
-                               $r = Model\Group::getIdByName(local_user(), $name);\r
-                               if ($r) {\r
-                                       $a->internalRedirect('group/' . $r);\r
-                               }\r
-                       } else {\r
-                               notice(L10n::t('Could not create group.'));\r
-                       }\r
-                       $a->internalRedirect('group');\r
-               }\r
-\r
-               if (($a->argc == 2) && intval($a->argv[1])) {\r
-                       BaseModule::checkFormSecurityTokenRedirectOnError('/group', 'group_edit');\r
-\r
-                       $group = DBA::selectFirst('group', ['id', 'name'], ['id' => $a->argv[1], 'uid' => local_user()]);\r
-                       if (!DBA::isResult($group)) {\r
-                               notice(L10n::t('Group not found.'));\r
-                               $a->internalRedirect('contact');\r
-                       }\r
-                       $groupname = Strings::escapeTags(trim($_POST['groupname']));\r
-                       if (strlen($groupname) && ($groupname != $group['name'])) {\r
-                               if (Model\Group::update($group['id'], $groupname)) {\r
-                                       info(L10n::t('Group name changed.'));\r
-                               }\r
-                       }\r
-               }\r
-       }\r
-\r
-       public static function ajaxPost()\r
-       {\r
-               try {\r
-                       $a = self::getApp();\r
-\r
-                       if (!local_user()) {\r
-                               throw new \Exception(L10n::t('Permission denied.'), 403);\r
-                       }\r
-\r
-                       // POST /group/123/add/123\r
-                       // POST /group/123/remove/123\r
-                       if ($a->argc == 4) {\r
-                               list($group_id, $command, $contact_id) = array_slice($a->argv, 1);\r
-\r
-                               if (!Model\Group::exists($group_id, local_user())) {\r
-                                       throw new \Exception(L10n::t('Unknown group.'), 404);\r
-                               }\r
-\r
-                               $contact = DBA::selectFirst('contact', ['pending', 'blocked', 'deleted'], ['id' => $contact_id, 'uid' => local_user()]);\r
-                               if (!DBA::isResult($contact)) {\r
-                                       throw new \Exception(L10n::t('Contact not found.'), 404);\r
-                               }\r
-\r
-                               if ($contact['pending']) {\r
-                                       throw new \Exception(L10n::t('Contact is unavailable.'), 400);\r
-                               }\r
-\r
-                               if ($contact['deleted']) {\r
-                                       throw new \Exception(L10n::t('Contact is deleted.'), 410);\r
-                               }\r
-\r
-                               switch($command) {\r
-                                       case 'add':\r
-                                               if ($contact['blocked']) {\r
-                                                       throw new \Exception(L10n::t('Contact is blocked, unable to add it to a group.'), 400);\r
-                                               }\r
-\r
-                                               if (!Model\Group::addMember($group_id, $contact_id)) {\r
-                                                       throw new \Exception(L10n::t('Unable to add the contact to the group.'), 500);\r
-                                               }\r
-                                               $message = L10n::t('Contact successfully added to group.');\r
-                                               break;\r
-                                       case 'remove':\r
-                                               if (!Model\Group::removeMember($group_id, $contact_id)) {\r
-                                                       throw new \Exception(L10n::t('Unable to remove the contact from the group.'), 500);\r
-                                               }\r
-                                               $message = L10n::t('Contact successfully removed from group.');\r
-                                               break;\r
-                                       default:\r
-                                               throw new \Exception(L10n::t('Unknown group command.'), 400);\r
-                               }\r
-                       } else {\r
-                               throw new \Exception(L10n::t('Bad request.'), 400);\r
-                       }\r
-\r
-                       notice($message);\r
-                       System::jsonExit(['status' => 'OK', 'message' => $message]);\r
-               } catch (\Exception $e) {\r
-                       notice($e->getMessage());\r
-                       System::jsonError($e->getCode(), ['status' => 'error', 'message' => $e->getMessage()]);\r
-               }\r
-       }\r
-\r
-       public static function content()\r
-       {\r
-               $change = false;\r
-\r
-               if (!local_user()) {\r
-                       System::httpExit(403);\r
-               }\r
-\r
-               $a = self::getApp();\r
-\r
-               $a->page['aside'] = Model\Group::sidebarWidget('contact', 'group', 'extended', (($a->argc > 1) ? $a->argv[1] : 'everyone'));\r
-\r
-               // With no group number provided we jump to the unassigned contacts as a starting point\r
-               if ($a->argc == 1) {\r
-                       $a->internalRedirect('group/none');\r
-               }\r
-\r
-               // Switch to text mode interface if we have more than 'n' contacts or group members\r
-               $switchtotext = PConfig::get(local_user(), 'system', 'groupedit_image_limit');\r
-               if (is_null($switchtotext)) {\r
-                       $switchtotext = Config::get('system', 'groupedit_image_limit', 200);\r
-               }\r
-\r
-               $tpl = Renderer::getMarkupTemplate('group_edit.tpl');\r
-\r
-\r
-               $context = [\r
-                       '$submit' => L10n::t('Save Group'),\r
-                       '$submit_filter' => L10n::t('Filter'),\r
-               ];\r
-\r
-               if (($a->argc == 2) && ($a->argv[1] === 'new')) {\r
-                       return Renderer::replaceMacros($tpl, $context + [\r
-                               '$title' => L10n::t('Create a group of contacts/friends.'),\r
-                               '$gname' => ['groupname', L10n::t('Group Name: '), '', ''],\r
-                               '$gid' => 'new',\r
-                               '$form_security_token' => BaseModule::getFormSecurityToken("group_edit"),\r
-                       ]);\r
-               }\r
-\r
-               $nogroup = false;\r
-\r
-               if (($a->argc == 2) && ($a->argv[1] === 'none')) {\r
-                       $id = -1;\r
-                       $nogroup = true;\r
-                       $group = [\r
-                               'id' => $id,\r
-                               'name' => L10n::t('Contacts not in any group'),\r
-                       ];\r
-\r
-                       $members = [];\r
-                       $preselected = [];\r
-\r
-                       $context = $context + [\r
-                               '$title' => $group['name'],\r
-                               '$gname' => ['groupname', L10n::t('Group Name: '), $group['name'], ''],\r
-                               '$gid' => $id,\r
-                               '$editable' => 0,\r
-                       ];\r
-               }\r
-\r
-               if (($a->argc == 3) && ($a->argv[1] === 'drop')) {\r
-                       BaseModule::checkFormSecurityTokenRedirectOnError('/group', 'group_drop', 't');\r
-\r
-                       if (intval($a->argv[2])) {\r
-                               if (!Model\Group::exists($a->argv[2], local_user())) {\r
-                                       notice(L10n::t('Group not found.'));\r
-                                       $a->internalRedirect('contact');\r
-                               }\r
-\r
-                               if (Model\Group::remove($a->argv[2])) {\r
-                                       info(L10n::t('Group removed.'));\r
-                               } else {\r
-                                       notice(L10n::t('Unable to remove group.'));\r
-                               }\r
-                       }\r
-                       $a->internalRedirect('group');\r
-               }\r
-\r
-               if (($a->argc > 2) && intval($a->argv[1]) && intval($a->argv[2])) {\r
-                       BaseModule::checkFormSecurityTokenForbiddenOnError('group_member_change', 't');\r
-\r
-                       if (DBA::exists('contact', ['id' => $a->argv[2], 'uid' => local_user(), 'self' => false, 'pending' => false, 'blocked' => false])) {\r
-                               $change = intval($a->argv[2]);\r
-                       }\r
-               }\r
-\r
-               if (($a->argc > 1) && intval($a->argv[1])) {\r
-                       $group = DBA::selectFirst('group', ['id', 'name'], ['id' => $a->argv[1], 'uid' => local_user(), 'deleted' => false]);\r
-                       if (!DBA::isResult($group)) {\r
-                               notice(L10n::t('Group not found.'));\r
-                               $a->internalRedirect('contact');\r
-                       }\r
-\r
-                       $members = Model\Contact::getByGroupId($group['id']);\r
-                       $preselected = [];\r
-\r
-                       if (count($members)) {\r
-                               foreach ($members as $member) {\r
-                                       $preselected[] = $member['id'];\r
-                               }\r
-                       }\r
-\r
-                       if ($change) {\r
-                               if (in_array($change, $preselected)) {\r
-                                       Model\Group::removeMember($group['id'], $change);\r
-                               } else {\r
-                                       Model\Group::addMember($group['id'], $change);\r
-                               }\r
-\r
-                               $members = Model\Contact::getByGroupId($group['id']);\r
-                               $preselected = [];\r
-                               if (count($members)) {\r
-                                       foreach ($members as $member) {\r
-                                               $preselected[] = $member['id'];\r
-                                       }\r
-                               }\r
-                       }\r
-\r
-                       $drop_tpl = Renderer::getMarkupTemplate('group_drop.tpl');\r
-                       $drop_txt = Renderer::replaceMacros($drop_tpl, [\r
-                               '$id' => $group['id'],\r
-                               '$delete' => L10n::t('Delete Group'),\r
-                               '$form_security_token' => BaseModule::getFormSecurityToken("group_drop"),\r
-                       ]);\r
-\r
-                       $context = $context + [\r
-                               '$title' => $group['name'],\r
-                               '$gname' => ['groupname', L10n::t('Group Name: '), $group['name'], ''],\r
-                               '$gid' => $group['id'],\r
-                               '$drop' => $drop_txt,\r
-                               '$form_security_token' => BaseModule::getFormSecurityToken('group_edit'),\r
-                               '$edit_name' => L10n::t('Edit Group Name'),\r
-                               '$editable' => 1,\r
-                       ];\r
-               }\r
-\r
-               if (!isset($group)) {\r
-                       System::httpExit(400);\r
-               }\r
-\r
-               $groupeditor = [\r
-                       'label_members' => L10n::t('Members'),\r
-                       'members' => [],\r
-                       'label_contacts' => L10n::t('All Contacts'),\r
-                       'group_is_empty' => L10n::t('Group is empty'),\r
-                       'contacts' => [],\r
-               ];\r
-\r
-               $sec_token = addslashes(BaseModule::getFormSecurityToken('group_member_change'));\r
-\r
-               // Format the data of the group members\r
-               foreach ($members as $member) {\r
-                       if ($member['url']) {\r
-                               $entry = Contact::getContactTemplateVars($member);\r
-                               $entry['label'] = 'members';\r
-                               $entry['photo_menu'] = '';\r
-                               $entry['change_member'] = [\r
-                                       'title'     => L10n::t("Remove contact from group"),\r
-                                       'gid'       => $group['id'],\r
-                                       'cid'       => $member['id'],\r
-                                       'sec_token' => $sec_token\r
-                               ];\r
-\r
-                               $groupeditor['members'][] = $entry;\r
-                       } else {\r
-                               Model\Group::removeMember($group['id'], $member['id']);\r
-                       }\r
-               }\r
-\r
-               if ($nogroup) {\r
-                       $contacts = Model\Contact::getUngroupedList(local_user());\r
-               } else {\r
-                       $contacts_stmt = DBA::select('contact', [],\r
-                               ['uid' => local_user(), 'pending' => false, 'blocked' => false, 'self' => false],\r
-                               ['order' => ['name']]\r
-                       );\r
-                       $contacts = DBA::toArray($contacts_stmt);\r
-                       $context['$desc'] = L10n::t('Click on a contact to add or remove.');\r
-               }\r
-\r
-               if (DBA::isResult($contacts)) {\r
-                       // Format the data of the contacts who aren't in the contact group\r
-                       foreach ($contacts as $member) {\r
-                               if (!in_array($member['id'], $preselected)) {\r
-                                       $entry = Contact::getContactTemplateVars($member);\r
-                                       $entry['label'] = 'contacts';\r
-                                       if (!$nogroup)\r
-                                               $entry['photo_menu'] = [];\r
-\r
-                                       if (!$nogroup) {\r
-                                               $entry['change_member'] = [\r
-                                                       'title'     => L10n::t("Add contact to group"),\r
-                                                       'gid'       => $group['id'],\r
-                                                       'cid'       => $member['id'],\r
-                                                       'sec_token' => $sec_token\r
-                                               ];\r
-                                       }\r
-\r
-                                       $groupeditor['contacts'][] = $entry;\r
-                               }\r
-                       }\r
-               }\r
-\r
-               $context['$groupeditor'] = $groupeditor;\r
-\r
-               // If there are to many contacts we could provide an alternative view mode\r
-               $total = count($groupeditor['members']) + count($groupeditor['contacts']);\r
-               $context['$shortmode'] = (($switchtotext && ($total > $switchtotext)) ? true : false);\r
-\r
-               if ($change) {\r
-                       $tpl = Renderer::getMarkupTemplate('groupeditor.tpl');\r
-                       echo Renderer::replaceMacros($tpl, $context);\r
-                       exit();\r
-               }\r
-\r
-               return Renderer::replaceMacros($tpl, $context);\r
-       }\r
+<?php
+/**
+ * @file src/Module/Group.php
+ */
+
+namespace Friendica\Module;
+
+use Friendica\BaseModule;
+use Friendica\Core\Config;
+use Friendica\Core\L10n;
+use Friendica\Core\PConfig;
+use Friendica\Core\Renderer;
+use Friendica\Core\System;
+use Friendica\Database\DBA;
+use Friendica\Model;
+use Friendica\Util\Strings;
+
+require_once 'boot.php';
+
+class Group extends BaseModule
+{
+       public static function post()
+       {
+               $a = self::getApp();
+
+               if ($a->isAjax()) {
+                       self::ajaxPost();
+               }
+
+               if (!local_user()) {
+                       notice(L10n::t('Permission denied.'));
+                       $a->internalRedirect();
+               }
+
+               // @TODO: Replace with parameter from router
+               if (($a->argc == 2) && ($a->argv[1] === 'new')) {
+                       BaseModule::checkFormSecurityTokenRedirectOnError('/group/new', 'group_edit');
+
+                       $name = Strings::escapeTags(trim($_POST['groupname']));
+                       $r = Model\Group::create(local_user(), $name);
+                       if ($r) {
+                               info(L10n::t('Group created.'));
+                               $r = Model\Group::getIdByName(local_user(), $name);
+                               if ($r) {
+                                       $a->internalRedirect('group/' . $r);
+                               }
+                       } else {
+                               notice(L10n::t('Could not create group.'));
+                       }
+                       $a->internalRedirect('group');
+               }
+
+               // @TODO: Replace with parameter from router
+               if (($a->argc == 2) && intval($a->argv[1])) {
+                       BaseModule::checkFormSecurityTokenRedirectOnError('/group', 'group_edit');
+
+                       $group = DBA::selectFirst('group', ['id', 'name'], ['id' => $a->argv[1], 'uid' => local_user()]);
+                       if (!DBA::isResult($group)) {
+                               notice(L10n::t('Group not found.'));
+                               $a->internalRedirect('contact');
+                       }
+                       $groupname = Strings::escapeTags(trim($_POST['groupname']));
+                       if (strlen($groupname) && ($groupname != $group['name'])) {
+                               if (Model\Group::update($group['id'], $groupname)) {
+                                       info(L10n::t('Group name changed.'));
+                               }
+                       }
+               }
+       }
+
+       public static function ajaxPost()
+       {
+               try {
+                       $a = self::getApp();
+
+                       if (!local_user()) {
+                               throw new \Exception(L10n::t('Permission denied.'), 403);
+                       }
+
+                       // POST /group/123/add/123
+                       // POST /group/123/remove/123
+                       // @TODO: Replace with parameter from router
+                       if ($a->argc == 4) {
+                               list($group_id, $command, $contact_id) = array_slice($a->argv, 1);
+
+                               if (!Model\Group::exists($group_id, local_user())) {
+                                       throw new \Exception(L10n::t('Unknown group.'), 404);
+                               }
+
+                               $contact = DBA::selectFirst('contact', ['pending', 'blocked', 'deleted'], ['id' => $contact_id, 'uid' => local_user()]);
+                               if (!DBA::isResult($contact)) {
+                                       throw new \Exception(L10n::t('Contact not found.'), 404);
+                               }
+
+                               if ($contact['pending']) {
+                                       throw new \Exception(L10n::t('Contact is unavailable.'), 400);
+                               }
+
+                               if ($contact['deleted']) {
+                                       throw new \Exception(L10n::t('Contact is deleted.'), 410);
+                               }
+
+                               switch($command) {
+                                       case 'add':
+                                               if ($contact['blocked']) {
+                                                       throw new \Exception(L10n::t('Contact is blocked, unable to add it to a group.'), 400);
+                                               }
+
+                                               if (!Model\Group::addMember($group_id, $contact_id)) {
+                                                       throw new \Exception(L10n::t('Unable to add the contact to the group.'), 500);
+                                               }
+                                               $message = L10n::t('Contact successfully added to group.');
+                                               break;
+                                       case 'remove':
+                                               if (!Model\Group::removeMember($group_id, $contact_id)) {
+                                                       throw new \Exception(L10n::t('Unable to remove the contact from the group.'), 500);
+                                               }
+                                               $message = L10n::t('Contact successfully removed from group.');
+                                               break;
+                                       default:
+                                               throw new \Exception(L10n::t('Unknown group command.'), 400);
+                               }
+                       } else {
+                               throw new \Exception(L10n::t('Bad request.'), 400);
+                       }
+
+                       notice($message);
+                       System::jsonExit(['status' => 'OK', 'message' => $message]);
+               } catch (\Exception $e) {
+                       notice($e->getMessage());
+                       System::jsonError($e->getCode(), ['status' => 'error', 'message' => $e->getMessage()]);
+               }
+       }
+
+       public static function content()
+       {
+               $change = false;
+
+               if (!local_user()) {
+                       throw new \Friendica\Network\HTTPException\ForbiddenException();
+               }
+
+               $a = self::getApp();
+
+               $a->page['aside'] = Model\Group::sidebarWidget('contact', 'group', 'extended', (($a->argc > 1) ? $a->argv[1] : 'everyone'));
+
+               // With no group number provided we jump to the unassigned contacts as a starting point
+               // @TODO: Replace with parameter from router
+               if ($a->argc == 1) {
+                       $a->internalRedirect('group/none');
+               }
+
+               // Switch to text mode interface if we have more than 'n' contacts or group members
+               $switchtotext = PConfig::get(local_user(), 'system', 'groupedit_image_limit');
+               if (is_null($switchtotext)) {
+                       $switchtotext = Config::get('system', 'groupedit_image_limit', 200);
+               }
+
+               $tpl = Renderer::getMarkupTemplate('group_edit.tpl');
+
+
+               $context = [
+                       '$submit' => L10n::t('Save Group'),
+                       '$submit_filter' => L10n::t('Filter'),
+               ];
+
+               // @TODO: Replace with parameter from router
+               if (($a->argc == 2) && ($a->argv[1] === 'new')) {
+                       return Renderer::replaceMacros($tpl, $context + [
+                               '$title' => L10n::t('Create a group of contacts/friends.'),
+                               '$gname' => ['groupname', L10n::t('Group Name: '), '', ''],
+                               '$gid' => 'new',
+                               '$form_security_token' => BaseModule::getFormSecurityToken("group_edit"),
+                       ]);
+               }
+
+               $nogroup = false;
+
+               // @TODO: Replace with parameter from router
+               if (($a->argc == 2) && ($a->argv[1] === 'none') ||
+                       ($a->argc == 1) && ($a->argv[0] === 'nogroup')) {
+                       $id = -1;
+                       $nogroup = true;
+                       $group = [
+                               'id' => $id,
+                               'name' => L10n::t('Contacts not in any group'),
+                       ];
+
+                       $members = [];
+                       $preselected = [];
+
+                       $context = $context + [
+                               '$title' => $group['name'],
+                               '$gname' => ['groupname', L10n::t('Group Name: '), $group['name'], ''],
+                               '$gid' => $id,
+                               '$editable' => 0,
+                       ];
+               }
+
+               // @TODO: Replace with parameter from router
+               if (($a->argc == 3) && ($a->argv[1] === 'drop')) {
+                       BaseModule::checkFormSecurityTokenRedirectOnError('/group', 'group_drop', 't');
+
+                       // @TODO: Replace with parameter from router
+                       if (intval($a->argv[2])) {
+                               if (!Model\Group::exists($a->argv[2], local_user())) {
+                                       notice(L10n::t('Group not found.'));
+                                       $a->internalRedirect('contact');
+                               }
+
+                               if (Model\Group::remove($a->argv[2])) {
+                                       info(L10n::t('Group removed.'));
+                               } else {
+                                       notice(L10n::t('Unable to remove group.'));
+                               }
+                       }
+                       $a->internalRedirect('group');
+               }
+
+               // @TODO: Replace with parameter from router
+               if (($a->argc > 2) && intval($a->argv[1]) && intval($a->argv[2])) {
+                       BaseModule::checkFormSecurityTokenForbiddenOnError('group_member_change', 't');
+
+                       if (DBA::exists('contact', ['id' => $a->argv[2], 'uid' => local_user(), 'self' => false, 'pending' => false, 'blocked' => false])) {
+                               $change = intval($a->argv[2]);
+                       }
+               }
+
+               // @TODO: Replace with parameter from router
+               if (($a->argc > 1) && intval($a->argv[1])) {
+                       $group = DBA::selectFirst('group', ['id', 'name'], ['id' => $a->argv[1], 'uid' => local_user(), 'deleted' => false]);
+                       if (!DBA::isResult($group)) {
+                               notice(L10n::t('Group not found.'));
+                               $a->internalRedirect('contact');
+                       }
+
+                       $members = Model\Contact::getByGroupId($group['id']);
+                       $preselected = [];
+
+                       if (count($members)) {
+                               foreach ($members as $member) {
+                                       $preselected[] = $member['id'];
+                               }
+                       }
+
+                       if ($change) {
+                               if (in_array($change, $preselected)) {
+                                       Model\Group::removeMember($group['id'], $change);
+                               } else {
+                                       Model\Group::addMember($group['id'], $change);
+                               }
+
+                               $members = Model\Contact::getByGroupId($group['id']);
+                               $preselected = [];
+                               if (count($members)) {
+                                       foreach ($members as $member) {
+                                               $preselected[] = $member['id'];
+                                       }
+                               }
+                       }
+
+                       $drop_tpl = Renderer::getMarkupTemplate('group_drop.tpl');
+                       $drop_txt = Renderer::replaceMacros($drop_tpl, [
+                               '$id' => $group['id'],
+                               '$delete' => L10n::t('Delete Group'),
+                               '$form_security_token' => BaseModule::getFormSecurityToken("group_drop"),
+                       ]);
+
+                       $context = $context + [
+                               '$title' => $group['name'],
+                               '$gname' => ['groupname', L10n::t('Group Name: '), $group['name'], ''],
+                               '$gid' => $group['id'],
+                               '$drop' => $drop_txt,
+                               '$form_security_token' => BaseModule::getFormSecurityToken('group_edit'),
+                               '$edit_name' => L10n::t('Edit Group Name'),
+                               '$editable' => 1,
+                       ];
+               }
+
+               if (!isset($group)) {
+                       throw new \Friendica\Network\HTTPException\BadRequestException();
+               }
+
+               $groupeditor = [
+                       'label_members' => L10n::t('Members'),
+                       'members' => [],
+                       'label_contacts' => L10n::t('All Contacts'),
+                       'group_is_empty' => L10n::t('Group is empty'),
+                       'contacts' => [],
+               ];
+
+               $sec_token = addslashes(BaseModule::getFormSecurityToken('group_member_change'));
+
+               // Format the data of the group members
+               foreach ($members as $member) {
+                       if ($member['url']) {
+                               $entry = Contact::getContactTemplateVars($member);
+                               $entry['label'] = 'members';
+                               $entry['photo_menu'] = '';
+                               $entry['change_member'] = [
+                                       'title'     => L10n::t("Remove contact from group"),
+                                       'gid'       => $group['id'],
+                                       'cid'       => $member['id'],
+                                       'sec_token' => $sec_token
+                               ];
+
+                               $groupeditor['members'][] = $entry;
+                       } else {
+                               Model\Group::removeMember($group['id'], $member['id']);
+                       }
+               }
+
+               if ($nogroup) {
+                       $contacts = Model\Contact::getUngroupedList(local_user());
+               } else {
+                       $contacts_stmt = DBA::select('contact', [],
+                               ['uid' => local_user(), 'pending' => false, 'blocked' => false, 'self' => false],
+                               ['order' => ['name']]
+                       );
+                       $contacts = DBA::toArray($contacts_stmt);
+                       $context['$desc'] = L10n::t('Click on a contact to add or remove.');
+               }
+
+               if (DBA::isResult($contacts)) {
+                       // Format the data of the contacts who aren't in the contact group
+                       foreach ($contacts as $member) {
+                               if (!in_array($member['id'], $preselected)) {
+                                       $entry = Contact::getContactTemplateVars($member);
+                                       $entry['label'] = 'contacts';
+                                       if (!$nogroup)
+                                               $entry['photo_menu'] = [];
+
+                                       if (!$nogroup) {
+                                               $entry['change_member'] = [
+                                                       'title'     => L10n::t("Add contact to group"),
+                                                       'gid'       => $group['id'],
+                                                       'cid'       => $member['id'],
+                                                       'sec_token' => $sec_token
+                                               ];
+                                       }
+
+                                       $groupeditor['contacts'][] = $entry;
+                               }
+                       }
+               }
+
+               $context['$groupeditor'] = $groupeditor;
+
+               // If there are to many contacts we could provide an alternative view mode
+               $total = count($groupeditor['members']) + count($groupeditor['contacts']);
+               $context['$shortmode'] = (($switchtotext && ($total > $switchtotext)) ? true : false);
+
+               if ($change) {
+                       $tpl = Renderer::getMarkupTemplate('groupeditor.tpl');
+                       echo Renderer::replaceMacros($tpl, $context);
+                       exit();
+               }
+
+               return Renderer::replaceMacros($tpl, $context);
+       }
 }
\ No newline at end of file
diff --git a/src/Module/Help.php b/src/Module/Help.php
new file mode 100644 (file)
index 0000000..04c4828
--- /dev/null
@@ -0,0 +1,122 @@
+<?php
+
+namespace Friendica\Module;
+
+use Friendica\BaseModule;
+use Friendica\Content\Nav;
+use Friendica\Content\Text\Markdown;
+use Friendica\Core\L10n;
+use Friendica\Network\HTTPException;
+use Friendica\Util\Strings;
+
+/**
+ * Shows the friendica help based on the /doc/ directory
+ */
+class Help extends BaseModule
+{
+       public static function content()
+       {
+               Nav::setSelected('help');
+
+               $text = '';
+               $filename = '';
+
+               $app = self::getApp();
+               $config = $app->getConfig();
+               $lang = $config->get('system', 'language');
+
+               // @TODO: Replace with parameter from router
+               if ($app->argc > 1) {
+                       $path = '';
+                       // looping through the argv keys bigger than 0 to build
+                       // a path relative to /help
+                       for ($x = 1; $x < $app->argc; $x ++) {
+                               if (strlen($path)) {
+                                       $path .= '/';
+                               }
+
+                               $path .= $app->getArgumentValue($x);
+                       }
+                       $title = basename($path);
+                       $filename = $path;
+                       $text = self::loadDocFile('doc/' . $path . '.md', $lang);
+                       $app->page['title'] = L10n::t('Help:') . ' ' . str_replace('-', ' ', Strings::escapeTags($title));
+               }
+
+               $home = self::loadDocFile('doc/Home.md', $lang);
+               if (!$text) {
+                       $text = $home;
+                       $filename = "Home";
+                       $app->page['title'] = L10n::t('Help');
+               } else {
+                       $app->page['aside'] = Markdown::convert($home, false);
+               }
+
+               if (!strlen($text)) {
+                       throw new HTTPException\NotFoundException();
+               }
+
+               $html = Markdown::convert($text, false);
+
+               if ($filename !== "Home") {
+                       // create TOC but not for home
+                       $lines = explode("\n", $html);
+                       $toc = "<h2>TOC</h2><ul id='toc'>";
+                       $lastLevel = 1;
+                       $idNum = [0, 0, 0, 0, 0, 0, 0];
+                       foreach ($lines as &$line) {
+                               if (substr($line, 0, 2) == "<h") {
+                                       $level = substr($line, 2, 1);
+                                       if ($level != "r") {
+                                               $level = intval($level);
+                                               if ($level < $lastLevel) {
+                                                       for ($k = $level; $k < $lastLevel; $k++) {
+                                                               $toc .= "</ul></li>";
+                                                       }
+
+                                                       for ($k = $level + 1; $k < count($idNum); $k++) {
+                                                               $idNum[$k] = 0;
+                                                       }
+                                               }
+
+                                               if ($level > $lastLevel) {
+                                                       $toc .= "<li><ul>";
+                                               }
+
+                                               $idNum[$level] ++;
+                                               $id = implode("_", array_slice($idNum, 1, $level));
+                                               $href = $app->getBaseURL() . "/help/{$filename}#{$id}";
+                                               $toc .= "<li><a href='{$href}'>" . strip_tags($line) . "</a></li>";
+                                               $line = "<a name='{$id}'></a>" . $line;
+                                               $lastLevel = $level;
+                                       }
+                               }
+                       }
+
+                       for ($k = 0; $k < $lastLevel; $k++) {
+                               $toc .= "</ul>";
+                       }
+
+                       $html = implode("\n", $lines);
+
+                       $a->page['aside'] = '<div class="help-aside-wrapper widget"><div id="toc-wrapper">' . $toc . '</div>' . $a->page['aside'] . '</div>';
+               }
+
+               return $html;
+       }
+
+       private static function loadDocFile($fileName, $lang = 'en')
+       {
+               $baseName = basename($fileName);
+               $dirName = dirname($fileName);
+               if (file_exists("$dirName/$lang/$baseName")) {
+                       return file_get_contents("$dirName/$lang/$baseName");
+               }
+
+               if (file_exists($fileName)) {
+                       return file_get_contents($fileName);
+               }
+
+               return '';
+       }
+}
diff --git a/src/Module/Home.php b/src/Module/Home.php
new file mode 100644 (file)
index 0000000..673701c
--- /dev/null
@@ -0,0 +1,68 @@
+<?php
+
+namespace Friendica\Module;
+
+use Friendica\BaseModule;
+use Friendica\Core\Hook;
+use Friendica\Core\L10n;
+use Friendica\Core\Renderer;
+
+/**
+ * Home module - Landing page of the current node
+ */
+class Home extends BaseModule
+{
+       public static function content()
+       {
+               if (!empty($_SESSION['theme'])) {
+                       unset($_SESSION['theme']);
+               }
+
+               if (!empty($_SESSION['mobile-theme'])) {
+                       unset($_SESSION['mobile-theme']);
+               }
+
+               $app = self::getApp();
+               $config = $app->getConfig();
+
+               // currently no returned data is used
+               $ret = [];
+
+               Hook::callAll('home_init', $ret);
+
+               if (local_user() && ($app->user['nickname'])) {
+                       $app->internalRedirect('network');
+               }
+
+               if (strlen($config->get('system', 'singleuser'))) {
+                       $app->internalRedirect('/profile/' . $config->get('system', 'singleuser'));
+               }
+
+               $customHome = '';
+               $defaultHeader = ($config->get('config', 'sitename') ? L10n::t('Welcome to %s', $config->get('config', 'sitename')) : '');
+
+               $homeFilePath = $app->getBasePath() . '/home.html';
+               $cssFilePath = $app->getBasePath() . '/home.css';
+
+               if (file_exists($homeFilePath)) {
+                       $customHome = $homeFilePath;
+
+                       if (file_exists($cssFilePath)) {
+                               $app->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $app->getBaseURL() . '/home.css' . '" media="all" />';
+                       }
+               }
+
+               $login = Login::form($app->query_string, $config->get('config', 'register_policy') === Register::CLOSED ? 0 : 1);
+
+               $content = '';
+               Hook::callAll('home_content', $content);
+
+               $tpl = Renderer::getMarkupTemplate('home.tpl');
+               return Renderer::replaceMacros($tpl, [
+                       '$defaultheader' => $defaultHeader,
+                       '$customhome'    => $customHome,
+                       '$login'         => $login,
+                       '$content'       => $content,
+               ]);
+       }
+}
index 1bc127b7c9a76c65c2188a402d3b5a80ef28271a..5367adb7e1c8f9e53f55920b7cecc72ec37ab31f 100644 (file)
@@ -6,12 +6,12 @@
 namespace Friendica\Module;
 
 use Friendica\BaseModule;
+use Friendica\Core\Config;
 use Friendica\Core\Logger;
-use Friendica\Protocol\ActivityPub;
 use Friendica\Core\System;
 use Friendica\Database\DBA;
+use Friendica\Protocol\ActivityPub;
 use Friendica\Util\HTTPSignature;
-use Friendica\Core\Config;
 
 /**
  * ActivityPub Inbox
@@ -25,7 +25,7 @@ class Inbox extends BaseModule
                $postdata = file_get_contents('php://input');
 
                if (empty($postdata)) {
-                       System::httpExit(400);
+                       throw new \Friendica\Network\HTTPException\BadRequestException();
                }
 
                if (Config::get('debug', 'ap_inbox_log')) {
@@ -39,10 +39,11 @@ class Inbox extends BaseModule
                        Logger::log('Incoming message stored under ' . $tempfile);
                }
 
+               // @TODO: Replace with parameter from router
                if (!empty($a->argv[1])) {
                        $user = DBA::selectFirst('user', ['uid'], ['nickname' => $a->argv[1]]);
                        if (!DBA::isResult($user)) {
-                               System::httpExit(404);
+                               throw new \Friendica\Network\HTTPException\NotFoundException();
                        }
                        $uid = $user['uid'];
                } else {
@@ -51,6 +52,6 @@ class Inbox extends BaseModule
 
                ActivityPub\Receiver::processInbox($postdata, $_SERVER, $uid);
 
-               System::httpExit(202);
+               throw new \Friendica\Network\HTTPException\AcceptedException();
        }
 }
index 65a30e894bed610c356318699910d7f1bc0b2f03..54c10534ddeafd27b976fa178d674b26a56edbbe 100644 (file)
@@ -51,14 +51,15 @@ class Install extends BaseModule
                $a = self::getApp();
 
                if (!$a->getMode()->isInstall()) {
-                       Core\System::httpExit(403);
+                       throw new \Friendica\Network\HTTPException\ForbiddenException();
                }
 
                // route: install/testrwrite
                // $baseurl/install/testrwrite to test if rewrite in .htaccess is working
+               // @TODO: Replace with parameter from router
                if ($a->getArgumentValue(1, '') == 'testrewrite') {
                        // Status Code 204 means that it worked without content
-                       Core\System::httpExit(204);
+                       throw new \Friendica\Network\HTTPException\NoContentException();
                }
 
                self::$installer = new Core\Installer();
@@ -172,15 +173,14 @@ class Install extends BaseModule
                                        '$next'        => L10n::t('Next'),
                                        '$reload'      => L10n::t('Check again'),
                                        '$php_path'    => $php_path,
-                                       '$baseurl'     => $a->getBaseURL()
                                ]);
                                break;
 
                        case self::BASE_CONFIG:
                                $ssl_choices = [
-                                       BaseUrl::SSL_POLICY_NONE     => L10n::t("No SSL policy, links will track page SSL state"),
-                                       BaseUrl::SSL_POLICY_FULL     => L10n::t("Force all links to use SSL"),
-                                       BaseUrl::SSL_POLICY_SELFSIGN => L10n::t("Self-signed certificate, use SSL for local links only \x28discouraged\x29")
+                                       BaseURL::SSL_POLICY_NONE     => L10n::t("No SSL policy, links will track page SSL state"),
+                                       BaseURL::SSL_POLICY_FULL     => L10n::t("Force all links to use SSL"),
+                                       BaseURL::SSL_POLICY_SELFSIGN => L10n::t("Self-signed certificate, use SSL for local links only \x28discouraged\x29")
                                ];
 
                                $tpl = Renderer::getMarkupTemplate('install_base.tpl');
@@ -207,7 +207,6 @@ class Install extends BaseModule
                                                $configCache->get('system', 'urlpath'),
                                                L10n::t('Overwrite this field in case the sub path determination isn\'t right, otherwise leave it as is. Leaving this field blank means the installation is at the base URL without sub path.'),
                                                ''],
-                                       '$baseurl'    => $a->getBaseURL(),
                                        '$php_path'   => $configCache->get('config', 'php_path'),
                                        '$submit'     => L10n::t('Submit'),
                                ]);
@@ -248,7 +247,6 @@ class Install extends BaseModule
                                                '',
                                                'required'],
                                        '$lbl_10'     => L10n::t('Please select a default timezone for your website'),
-                                       '$baseurl'    => $a->getBaseURL(),
                                        '$php_path'   => $configCache->get('config', 'php_path'),
                                        '$submit'     => L10n::t('Submit')
                                ]);
@@ -285,7 +283,6 @@ class Install extends BaseModule
                                                $configCache->get('system', 'language'),
                                                L10n::t('Set the default language for your Friendica installation interface and to send emails.'),
                                                $lang_choices],
-                                       '$baseurl'    => $a->getBaseURL(),
                                        '$php_path'   => $configCache->get('config', 'php_path'),
                                        '$submit'     => L10n::t('Submit')
                                ]);
diff --git a/src/Module/Invite.php b/src/Module/Invite.php
new file mode 100644 (file)
index 0000000..7860c70
--- /dev/null
@@ -0,0 +1,160 @@
+<?php
+
+namespace Friendica\Module;
+
+use Friendica\BaseModule;
+use Friendica\Core\L10n;
+use Friendica\Core\PConfig;
+use Friendica\Core\Renderer;
+use Friendica\Model;
+use Friendica\Network\HTTPException;
+use Friendica\Protocol\Email;
+use Friendica\Util\Strings;
+
+/**
+ * Invite people to friendica
+ */
+class Invite extends BaseModule
+{
+       public static function post()
+       {
+               if (!local_user()) {
+                       throw new HTTPException\ForbiddenException(L10n::t('Permission denied.'));
+               }
+
+               self::checkFormSecurityTokenRedirectOnError('/', 'send_invite');
+
+               $app = self::getApp();
+               $config = $app->getConfig();
+
+               $max_invites = intval($config->get('system', 'max_invites'));
+               if (!$max_invites) {
+                       $max_invites = 50;
+               }
+
+               $current_invites = intval(PConfig::get(local_user(), 'system', 'sent_invites'));
+               if ($current_invites > $max_invites) {
+                       throw new HTTPException\ForbiddenException(L10n::t('Total invitation limit exceeded.'));
+               }
+
+
+               $recipients = !empty($_POST['recipients']) ? explode("\n", $_POST['recipients']) : [];
+               $message = !empty($_POST['message']) ? Strings::escapeTags(trim($_POST['message'])) : '';
+
+               $total = 0;
+               $invitation_only = false;
+               $invites_remaining = null;
+
+               if ($config->get('system', 'invitation_only')) {
+                       $invitation_only = true;
+                       $invites_remaining = PConfig::get(local_user(), 'system', 'invites_remaining');
+                       if ((!$invites_remaining) && (!is_site_admin())) {
+                               throw new HTTPException\ForbiddenException();
+                       }
+               }
+
+               foreach ($recipients as $recipient) {
+                       $recipient = trim($recipient);
+
+                       if (!filter_var($recipient, FILTER_VALIDATE_EMAIL)) {
+                               notice(L10n::t('%s : Not a valid email address.', $recipient) . EOL);
+                               continue;
+                       }
+
+                       if ($invitation_only && ($invites_remaining || is_site_admin())) {
+                               $code = Model\Register::createForInvitation();
+                               $nmessage = str_replace('$invite_code', $code, $message);
+
+                               if (!is_site_admin()) {
+                                       $invites_remaining--;
+                                       if ($invites_remaining >= 0) {
+                                               PConfig::set(local_user(), 'system', 'invites_remaining', $invites_remaining);
+                                       } else {
+                                               return;
+                                       }
+                               }
+                       } else {
+                               $nmessage = $message;
+                       }
+
+                       $additional_headers = 'From: ' . $app->user['email'] . "\n"
+                               . 'Sender: ' . $app->getSenderEmailAddress() . "\n"
+                               . 'Content-type: text/plain; charset=UTF-8' . "\n"
+                               . 'Content-transfer-encoding: 8bit';
+
+                       $res = mail(
+                               $recipient,
+                               Email::encodeHeader(L10n::t('Please join us on Friendica'), 'UTF-8'),
+                               $nmessage,
+                               $additional_headers);
+
+                       if ($res) {
+                               $total++;
+                               $current_invites++;
+                               PConfig::set(local_user(), 'system', 'sent_invites', $current_invites);
+                               if ($current_invites > $max_invites) {
+                                       notice(L10n::t('Invitation limit exceeded. Please contact your site administrator.') . EOL);
+                                       return;
+                               }
+                       } else {
+                               notice(L10n::t('%s : Message delivery failed.', $recipient) . EOL);
+                       }
+
+               }
+               notice(L10n::tt('%d message sent.', '%d messages sent.', $total) . EOL);
+       }
+
+       public static function content()
+       {
+               if (!local_user()) {
+                       throw new HTTPException\ForbiddenException(L10n::t('Permission denied.'));
+               }
+
+               $app = self::getApp();
+               $config = $app->getConfig();
+
+               $inviteOnly = false;
+
+               if ($config->get('system', 'invitation_only')) {
+                       $inviteOnly = true;
+                       $x = PConfig::get(local_user(), 'system', 'invites_remaining');
+                       if ((!$x) && (!is_site_admin())) {
+                               throw new HTTPException\ForbiddenException(L10n::t('You have no more invitations available'));
+                       }
+               }
+
+               $dirLocation = $config->get('system', 'directory');
+               if (strlen($dirLocation)) {
+                       if ($config->get('config', 'register_policy') === Register::CLOSED) {
+                               $linkTxt = L10n::t('Visit %s for a list of public sites that you can join. Friendica members on other sites can all connect with each other, as well as with members of many other social networks.', $dirLocation . '/servers');
+                       } else {
+                               $linkTxt = L10n::t('To accept this invitation, please visit and register at %s or any other public Friendica website.', $app->getBaseURL())
+                                       . "\r\n" . "\r\n" . L10n::t('Friendica sites all inter-connect to create a huge privacy-enhanced social web that is owned and controlled by its members. They can also connect with many traditional social networks. See %s for a list of alternate Friendica sites you can join.', $dirLocation . '/servers');
+                       }
+               } else { // there is no global directory URL defined
+                       if ($config->get('config', 'register_policy') === Register::CLOSED) {
+                               return L10n::t('Our apologies. This system is not currently configured to connect with other public sites or invite members.');
+                       } else {
+                               $linkTxt = L10n::t('To accept this invitation, please visit and register at %s.', $app->getBaseURL()
+                                       . "\r\n" . "\r\n" . L10n::t('Friendica sites all inter-connect to create a huge privacy-enhanced social web that is owned and controlled by its members. They can also connect with many traditional social networks.'));
+                       }
+               }
+
+               $tpl = Renderer::getMarkupTemplate('invite.tpl');
+               return Renderer::replaceMacros($tpl, [
+                       '$form_security_token' => self::getFormSecurityToken('send_invite'),
+                       '$title'               => L10n::t('Send invitations'),
+                       '$recipients'          => ['recipients', L10n::t('Enter email addresses, one per line:')],
+                       '$message'             => [
+                               'message',
+                               L10n::t('Your message:'),
+                               L10n::t('You are cordially invited to join me and other close friends on Friendica - and help us to create a better social web.') . "\r\n" . "\r\n"
+                               . $linkTxt
+                               . "\r\n" . "\r\n" . (($inviteOnly) ? L10n::t('You will need to supply this invitation code: $invite_code') . "\r\n" . "\r\n" : '') . L10n::t('Once you have registered, please connect with me via my profile page at:')
+                               . "\r\n" . "\r\n" . $app->getBaseURL() . '/profile/' . $app->user['nickname']
+                               . "\r\n" . "\r\n" . L10n::t('For more information about the Friendica project and why we feel it is important, please visit http://friendi.ca') . "\r\n" . "\r\n",
+                       ],
+                       '$submit'              => L10n::t('Submit')
+               ]);
+       }
+}
index f92baa987c6d5de819402abf3a3c53c0d6f457a6..d781db3ac5d207b54bdfb4f3a7050e17587acdfa 100644 (file)
@@ -2,12 +2,9 @@
 
 namespace Friendica\Module;
 
-use Friendica\Content\Text\HTML;
 use Friendica\Core\L10n;
 use Friendica\Core\Renderer;
 use Friendica\Model;
-use Friendica\Protocol\ActivityPub\Processor;
-use Friendica\Protocol\Diaspora;
 
 /**
  * @author Hypolite Petovan <mrpetovan@gmail.com>
@@ -22,6 +19,7 @@ class Itemsource extends \Friendica\BaseModule
 
                $a = self::getApp();
 
+               // @TODO: Replace with parameter from router
                if (!empty($a->argv[1])) {
                        $guid = $a->argv[1];
                }
diff --git a/src/Module/Like.php b/src/Module/Like.php
new file mode 100644 (file)
index 0000000..f57cbad
--- /dev/null
@@ -0,0 +1,51 @@
+<?php
+
+namespace Friendica\Module;
+
+use Friendica\BaseModule;
+use Friendica\Model\Item;
+use Friendica\Network\HTTPException;
+use Friendica\Util\Strings;
+
+/**
+ * Performs a like and optionally redirects to a return path
+ */
+class Like extends BaseModule
+{
+       public static function rawContent()
+       {
+               if (!local_user() && !remote_user()) {
+                       throw new HTTPException\ForbiddenException();
+               }
+
+               $verb = Strings::escapeTags(trim($_GET['verb']));
+
+               if (!$verb) {
+                       $verb = 'like';
+               }
+
+               $app = self::getApp();
+
+               // @TODO: Replace with parameter from router
+               $itemId = (($app->argc > 1) ? Strings::escapeTags(trim($app->argv[1])) : 0);
+
+               if (!Item::performLike($itemId, $verb)) {
+                       throw new HTTPException\BadRequestException();
+               }
+
+               // Decide how to return. If we were called with a 'return' argument,
+               // then redirect back to the calling page. If not, just quietly end
+               $returnPath = defaults($_REQUEST, 'return', '');
+
+               if (!empty($returnPath)) {
+                       $rand = '_=' . time();
+                       if (strpos($returnPath, '?')) {
+                               $rand = "&$rand";
+                       } else {
+                               $rand = "?$rand";
+                       }
+
+                       $app->internalRedirect($returnPath . $rand);
+               }
+       }
+}
index 40ae53891e0bbde610c26f193ed439c2101c1c1e..9dadcf0f76206fa10dc3166939de27b3d92352d2 100644 (file)
@@ -22,7 +22,6 @@ class Manifest extends BaseModule
                }
 
                $output = Renderer::replaceMacros($tpl, [
-                       '$baseurl' => $app->getBaseURL(),
                        '$touch_icon' => $touch_icon,
                        '$title' => $config->get('config', 'sitename', 'Friendica'),
                ]);
diff --git a/src/Module/NodeInfo.php b/src/Module/NodeInfo.php
new file mode 100644 (file)
index 0000000..3261ef6
--- /dev/null
@@ -0,0 +1,184 @@
+<?php
+
+namespace Friendica\Module;
+
+use Friendica\App;
+use Friendica\BaseModule;
+use Friendica\Core\Addon;
+use Friendica\Core\System;
+
+/**
+ * Standardized way of exposing metadata about a server running one of the distributed social networks.
+ * @see https://github.com/jhass/nodeinfo/blob/master/PROTOCOL.md
+ */
+class NodeInfo extends BaseModule
+{
+       public static function init()
+       {
+               $config = self::getApp()->getConfig();
+
+               if (!$config->get('system', 'nodeinfo')) {
+                       throw new \Friendica\Network\HTTPException\NotFoundException();
+               }
+       }
+
+       public static function rawContent()
+       {
+               $app = self::getApp();
+
+               // @TODO: Replace with parameter from router
+               // if the first argument is ".well-known", print the well-known text
+               if (($app->argc > 1) && ($app->argv[0] == '.well-known')) {
+                       self::printWellKnown($app);
+               // otherwise print the nodeinfo
+               } else {
+                       self::printNodeInfo($app);
+               }
+       }
+
+       /**
+        * Prints the well-known nodeinfo redirect
+        *
+        * @param App $app
+        *
+        * @throws \Friendica\Network\HTTPException\NotFoundException
+        */
+       private static function printWellKnown(App $app)
+       {
+               $config = $app->getConfig();
+
+               if (!$config->get('system', 'nodeinfo')) {
+                       throw new \Friendica\Network\HTTPException\NotFoundException();
+               }
+
+               $nodeinfo = [
+                       'links' => [[
+                               'rel'  => 'http://nodeinfo.diaspora.software/ns/schema/1.0',
+                               'href' => $app->getBaseURL() . '/nodeinfo/1.0']]
+               ];
+
+               header('Content-type: application/json; charset=utf-8');
+               echo json_encode($nodeinfo, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
+               exit;
+       }
+
+       /**
+        * Print the nodeinfo
+        *
+        * @param App $app
+        */
+       private static function printNodeInfo(App $app)
+       {
+               $config = $app->getConfig();
+
+               $smtp = (function_exists('imap_open') && !$config->get('system', 'imap_disabled') && !$config->get('system', 'dfrn_only'));
+
+               $nodeinfo = [
+                       'version'           => 1.0,
+                       'software'          => [
+                               'name'    => 'friendica',
+                               'version' => FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION,
+                       ],
+                       'protocols'         => [
+                               'inbound'  => [
+                                       'friendica',
+                               ],
+                               'outbound' => [
+                                       'friendica',
+                               ],
+                       ],
+                       'services'          => [
+                               'inbound'  => [],
+                               'outbound' => [],
+                       ],
+                       'usage'             => [],
+                       'openRegistrations' => intval($config->get('config', 'register_policy')) !== Register::CLOSED,
+                       'metadata'          => [
+                               'nodeName' => $config->get('config', 'sitename'),
+                       ],
+               ];
+
+               if (!empty($config->get('system', 'diaspora_enabled'))) {
+                       $nodeinfo['protocols']['inbound'][] = 'diaspora';
+                       $nodeinfo['protocols']['outbound'][] = 'diaspora';
+               }
+
+               if (empty($config->get('system', 'ostatus_disabled'))) {
+                       $nodeinfo['protocols']['inbound'][] = 'gnusocial';
+                       $nodeinfo['protocols']['outbound'][] = 'gnusocial';
+               }
+
+               if (!empty($config->get('system', 'nodeinfo'))) {
+
+                       $nodeinfo['usage']['users'] = [
+                               'total'          => intval($config->get('nodeinfo', 'total_users')),
+                               'activeHalfyear' => intval($config->get('nodeinfo', 'active_users_halfyear')),
+                               'activeMonth'    => intval($config->get('nodeinfo', 'active_users_monthly'))
+                       ];
+                       $nodeinfo['usage']['localPosts'] = intval($config->get('nodeinfo', 'local_posts'));
+                       $nodeinfo['usage']['localComments'] = intval($config->get('nodeinfo', 'local_comments'));
+
+                       if (Addon::isEnabled('blogger')) {
+                               $nodeinfo['services']['outbound'][] = 'blogger';
+                       }
+                       if (Addon::isEnabled('dwpost')) {
+                               $nodeinfo['services']['outbound'][] = 'dreamwidth';
+                       }
+                       if (Addon::isEnabled('statusnet')) {
+                               $nodeinfo['services']['inbound'][] = 'gnusocial';
+                               $nodeinfo['services']['outbound'][] = 'gnusocial';
+                       }
+                       if (Addon::isEnabled('ijpost')) {
+                               $nodeinfo['services']['outbound'][] = 'insanejournal';
+                       }
+                       if (Addon::isEnabled('libertree')) {
+                               $nodeinfo['services']['outbound'][] = 'libertree';
+                       }
+                       if (Addon::isEnabled('buffer')) {
+                               $nodeinfo['services']['outbound'][] = 'linkedin';
+                       }
+                       if (Addon::isEnabled('ljpost')) {
+                               $nodeinfo['services']['outbound'][] = 'livejournal';
+                       }
+                       if (Addon::isEnabled('buffer')) {
+                               $nodeinfo['services']['outbound'][] = 'pinterest';
+                       }
+                       if (Addon::isEnabled('posterous')) {
+                               $nodeinfo['services']['outbound'][] = 'posterous';
+                       }
+                       if (Addon::isEnabled('pumpio')) {
+                               $nodeinfo['services']['inbound'][] = 'pumpio';
+                               $nodeinfo['services']['outbound'][] = 'pumpio';
+                       }
+
+                       if ($smtp) {
+                               $nodeinfo['services']['outbound'][] = 'smtp';
+                       }
+                       if (Addon::isEnabled('tumblr')) {
+                               $nodeinfo['services']['outbound'][] = 'tumblr';
+                       }
+                       if (Addon::isEnabled('twitter') || Addon::isEnabled('buffer')) {
+                               $nodeinfo['services']['outbound'][] = 'twitter';
+                       }
+                       if (Addon::isEnabled('wppost')) {
+                               $nodeinfo['services']['outbound'][] = 'wordpress';
+                       }
+                       $nodeinfo['metadata']['protocols'] = $nodeinfo['protocols'];
+                       $nodeinfo['metadata']['protocols']['outbound'][] = 'atom1.0';
+                       $nodeinfo['metadata']['protocols']['inbound'][] = 'atom1.0';
+                       $nodeinfo['metadata']['protocols']['inbound'][] = 'rss2.0';
+
+                       $nodeinfo['metadata']['services'] = $nodeinfo['services'];
+
+                       if (Addon::isEnabled('twitter')) {
+                               $nodeinfo['metadata']['services']['inbound'][] = 'twitter';
+                       }
+
+                       $nodeinfo['metadata']['explicitContent'] = $config->get('system', 'explicit_content', false) == true;
+               }
+
+               header('Content-type: application/json; charset=utf-8');
+               echo json_encode($nodeinfo, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
+               exit;
+       }
+}
diff --git a/src/Module/Nodeinfo.php b/src/Module/Nodeinfo.php
deleted file mode 100644 (file)
index 18f2c72..0000000
+++ /dev/null
@@ -1,169 +0,0 @@
-<?php
-
-namespace Friendica\Module;
-
-use Friendica\App;
-use Friendica\BaseModule;
-use Friendica\Core\Addon;
-use Friendica\Core\System;
-
-/**
- * Prints infos about the current node
- */
-class Nodeinfo extends BaseModule
-{
-       /**
-        * Prints the Nodeinfo for a well-known request
-        *
-        * @param App $app
-        *
-        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
-        */
-       public static function printWellKnown(App $app)
-       {
-               $config = $app->getConfig();
-
-               if (!$config->get('system', 'nodeinfo')) {
-                       System::httpExit(404);
-               }
-
-               $nodeinfo = [
-                       'links' => [[
-                               'rel'  => 'http://nodeinfo.diaspora.software/ns/schema/1.0',
-                               'href' => $app->getBaseURL() . '/nodeinfo/1.0']]
-               ];
-
-               header('Content-type: application/json; charset=utf-8');
-               echo json_encode($nodeinfo, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
-               exit;
-       }
-
-       public static function init()
-       {
-               $app = self::getApp();
-               $config = $app->getConfig();
-
-               if (!$config->get('system', 'nodeinfo')) {
-                       System::httpExit(404);
-               }
-
-               if (($app->argc != 2) || ($app->argv[1] != '1.0')) {
-                       System::httpExit(404);
-               }
-       }
-
-       public static function rawContent()
-       {
-               $config = self::getApp()->getConfig();
-
-               $smtp = (function_exists('imap_open') && !$config->get('system', 'imap_disabled') && !$config->get('system', 'dfrn_only'));
-
-               $nodeinfo = [
-                       'version'           => 1.0,
-                       'software'          => [
-                               'name'    => 'friendica',
-                               'version' => FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION,
-                       ],
-                       'protocols'         => [
-                               'inbound'  => [
-                                       'friendica',
-                               ],
-                               'outbound' => [
-                                       'friendica',
-                               ],
-                       ],
-                       'services'          => [
-                               'inbound'  => [],
-                               'outbound' => [],
-                       ],
-                       'usage'             => [],
-                       'openRegistrations' => intval($config->get('config', 'register_policy')) !== Register::CLOSED,
-                       'metadata'          => [
-                               'nodeName' => $config->get('config', 'sitename'),
-                       ],
-               ];
-
-               if (!empty($config->get('system', 'diaspora_enabled'))) {
-                       $nodeinfo['protocols']['inbound'][] = 'diaspora';
-                       $nodeinfo['protocols']['outbound'][] = 'diaspora';
-               }
-
-               if (empty($config->get('system', 'ostatus_disabled'))) {
-                       $nodeinfo['protocols']['inbound'][] = 'gnusocial';
-                       $nodeinfo['protocols']['outbound'][] = 'gnusocial';
-               }
-
-               if (!empty($config->get('system', 'nodeinfo'))) {
-
-                       $nodeinfo['usage']['users'] = [
-                               'total'          => intval($config->get('nodeinfo', 'total_users')),
-                               'activeHalfyear' => intval($config->get('nodeinfo', 'active_users_halfyear')),
-                               'activeMonth'    => intval($config->get('nodeinfo', 'active_users_monthly'))
-                       ];
-                       $nodeinfo['usage']['localPosts'] = intval($config->get('nodeinfo', 'local_posts'));
-                       $nodeinfo['usage']['localComments'] = intval($config->get('nodeinfo', 'local_comments'));
-
-                       if (Addon::isEnabled('blogger')) {
-                               $nodeinfo['services']['outbound'][] = 'blogger';
-                       }
-                       if (Addon::isEnabled('dwpost')) {
-                               $nodeinfo['services']['outbound'][] = 'dreamwidth';
-                       }
-                       if (Addon::isEnabled('statusnet')) {
-                               $nodeinfo['services']['inbound'][] = 'gnusocial';
-                               $nodeinfo['services']['outbound'][] = 'gnusocial';
-                       }
-                       if (Addon::isEnabled('ijpost')) {
-                               $nodeinfo['services']['outbound'][] = 'insanejournal';
-                       }
-                       if (Addon::isEnabled('libertree')) {
-                               $nodeinfo['services']['outbound'][] = 'libertree';
-                       }
-                       if (Addon::isEnabled('buffer')) {
-                               $nodeinfo['services']['outbound'][] = 'linkedin';
-                       }
-                       if (Addon::isEnabled('ljpost')) {
-                               $nodeinfo['services']['outbound'][] = 'livejournal';
-                       }
-                       if (Addon::isEnabled('buffer')) {
-                               $nodeinfo['services']['outbound'][] = 'pinterest';
-                       }
-                       if (Addon::isEnabled('posterous')) {
-                               $nodeinfo['services']['outbound'][] = 'posterous';
-                       }
-                       if (Addon::isEnabled('pumpio')) {
-                               $nodeinfo['services']['inbound'][] = 'pumpio';
-                               $nodeinfo['services']['outbound'][] = 'pumpio';
-                       }
-
-                       if ($smtp) {
-                               $nodeinfo['services']['outbound'][] = 'smtp';
-                       }
-                       if (Addon::isEnabled('tumblr')) {
-                               $nodeinfo['services']['outbound'][] = 'tumblr';
-                       }
-                       if (Addon::isEnabled('twitter') || Addon::isEnabled('buffer')) {
-                               $nodeinfo['services']['outbound'][] = 'twitter';
-                       }
-                       if (Addon::isEnabled('wppost')) {
-                               $nodeinfo['services']['outbound'][] = 'wordpress';
-                       }
-                       $nodeinfo['metadata']['protocols'] = $nodeinfo['protocols'];
-                       $nodeinfo['metadata']['protocols']['outbound'][] = 'atom1.0';
-                       $nodeinfo['metadata']['protocols']['inbound'][] = 'atom1.0';
-                       $nodeinfo['metadata']['protocols']['inbound'][] = 'rss2.0';
-
-                       $nodeinfo['metadata']['services'] = $nodeinfo['services'];
-
-                       if (Addon::isEnabled('twitter')) {
-                               $nodeinfo['metadata']['services']['inbound'][] = 'twitter';
-                       }
-
-                       $nodeinfo['metadata']['explicitContent'] = $config->get('system', 'explicit_content', false) == true;
-               }
-
-               header('Content-type: application/json; charset=utf-8');
-               echo json_encode($nodeinfo, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
-               exit;
-       }
-}
index 558b274919ce33bad609074dec5aac569ceca9e0..2104e8042fd98e3c2cc9f7bc57eb9782a7627826 100644 (file)
@@ -5,11 +5,10 @@
 namespace Friendica\Module;
 
 use Friendica\BaseModule;
-use Friendica\Protocol\ActivityPub;
 use Friendica\Core\System;
-use Friendica\Model\Item;
 use Friendica\Database\DBA;
-use Friendica\Util\HTTPSignature;
+use Friendica\Model\Item;
+use Friendica\Protocol\ActivityPub;
 
 /**
  * ActivityPub Objects
@@ -21,7 +20,7 @@ class Objects extends BaseModule
                $a = self::getApp();
 
                if (empty($a->argv[1])) {
-                       System::httpExit(404);
+                       throw new \Friendica\Network\HTTPException\NotFoundException();
                }
 
                if (!ActivityPub::isRequest()) {
@@ -32,12 +31,14 @@ class Objects extends BaseModule
                // $requester = HTTPSignature::getSigner('', $_SERVER);
 
                // At first we try the original post with that guid
+               // @TODO: Replace with parameter from router
                $item = Item::selectFirst(['id'], ['guid' => $a->argv[1], 'origin' => true, 'private' => false]);
                if (!DBA::isResult($item)) {
                        // If no original post could be found, it could possibly be a forum post, there we remove the "origin" field.
+                       // @TODO: Replace with parameter from router
                        $item = Item::selectFirst(['id', 'author-link'], ['guid' => $a->argv[1], 'private' => false]);
                        if (!DBA::isResult($item) || !strstr($item['author-link'], System::baseUrl())) {
-                               System::httpExit(404);
+                               throw new \Friendica\Network\HTTPException\NotFoundException();
                        }
                }
 
index d5ff62dac9c5a91aca8ef7e2d0cb5a4514e41a34..0107782122b5c0c877025d09805eca4a22794315 100644 (file)
@@ -35,6 +35,7 @@ class Oembed extends BaseModule
                        exit();
                }
 
+               // @TODO: Replace with parameter from router
                if ($a->argc == 2) {
                        echo '<html><body>';
                        $url = Strings::base64UrlDecode($a->argv[1]);
index 41e10757f1231ae90a10138fe49cc09cc4ef722b..14825677910919e92a50833d6866bbeb1b16f5c9 100644 (file)
@@ -5,10 +5,9 @@
 namespace Friendica\Module;
 
 use Friendica\BaseModule;
-use Friendica\Protocol\ActivityPub;
 use Friendica\Core\System;
 use Friendica\Model\User;
-use Friendica\Util\HTTPSignature;
+use Friendica\Protocol\ActivityPub;
 
 /**
  * ActivityPub Outbox
@@ -19,13 +18,14 @@ class Outbox extends BaseModule
        {
                $a = self::getApp();
 
+               // @TODO: Replace with parameter from router
                if (empty($a->argv[1])) {
-                       System::httpExit(404);
+                       throw new \Friendica\Network\HTTPException\NotFoundException();
                }
 
                $owner = User::getOwnerDataByNick($a->argv[1]);
                if (empty($owner)) {
-                       System::httpExit(404);
+                       throw new \Friendica\Network\HTTPException\NotFoundException();
                }
 
                $page = defaults($_REQUEST, 'page', null);
diff --git a/src/Module/PageNotFound.php b/src/Module/PageNotFound.php
new file mode 100644 (file)
index 0000000..764903c
--- /dev/null
@@ -0,0 +1,15 @@
+<?php
+
+namespace Friendica\Module;
+
+use Friendica\BaseModule;
+use Friendica\Core\L10n;
+use Friendica\Network\HTTPException;
+
+class PageNotFound extends BaseModule
+{
+       public static function content()
+       {
+               throw new HTTPException\NotFoundException(L10n::t('Page not found.'));
+       }
+}
index ed5609640c34eb4d9f9da17e15ffd0c2355fff8e..bcfe13f5372e4330a2650f15caa8225a3109ab66 100644 (file)
@@ -6,6 +6,7 @@
 namespace Friendica\Module;
 
 use Friendica\BaseModule;
+use Friendica\Core\L10n;
 use Friendica\Core\Logger;
 use Friendica\Core\System;
 use Friendica\Model\Photo as MPhoto;
@@ -25,8 +26,9 @@ class Photo extends BaseModule
        public static function init()
        {
                $a = self::getApp();
+               // @TODO: Replace with parameter from router
                if ($a->argc <= 1 || $a->argc > 4) {
-                       System::httpExit(400);
+                       throw new \Friendica\Network\HTTPException\BadRequestException();
                }
 
                if (isset($_SERVER["HTTP_IF_MODIFIED_SINCE"])) {
@@ -47,6 +49,7 @@ class Photo extends BaseModule
 
                $customsize = 0;
                $photo = false;
+               // @TODO: Replace with parameter from router
                switch($a->argc) {
                        case 4:
                                $customsize = intval($a->argv[2]);
@@ -72,9 +75,7 @@ class Photo extends BaseModule
                }
 
                if ($photo === false) {
-                       // not using System::httpExit() because we don't want html here.
-                       header($_SERVER["SERVER_PROTOCOL"] . " 404 Not Found" , true, 404);
-                       exit();
+                       System::httpExit('404', 'Not Found');
                }
 
                $cacheable = ($photo["allow_cid"] . $photo["allow_gid"] . $photo["deny_cid"] . $photo["deny_gid"] === "") && (isset($photo["cacheable"]) ? $photo["cacheable"] : true);
@@ -83,7 +84,7 @@ class Photo extends BaseModule
 
                if (is_null($img) || !$img->isValid()) {
                        Logger::log("Invalid photo with id {$photo["id"]}.");
-                       System::httpExit(500, ["description" => "Invalid photo with id {$photo["id"]}."]);
+                       throw new \Friendica\Network\HTTPException\InternalServerErrorException(L10n::t('Invalid photo with id %s.', $photo["id"]));
                }
 
                // if customsize is set and image is not a gif, resize it
index 55150a9649d8d1d741008945d041c95e419e5bfe..fceea726b4cfe863d203673dbf11095810c0595b 100644 (file)
-<?php\r
-\r
-namespace Friendica\Module;\r
-\r
-use Friendica\BaseModule;\r
-use Friendica\Content\Nav;\r
-use Friendica\Content\Pager;\r
-use Friendica\Content\Widget;\r
-use Friendica\Core\ACL;\r
-use Friendica\Core\Config;\r
-use Friendica\Core\Hook;\r
-use Friendica\Core\L10n;\r
-use Friendica\Core\PConfig;\r
-use Friendica\Core\System;\r
-use Friendica\Database\DBA;\r
-use Friendica\Model\Contact as ContactModel;\r
-use Friendica\Model\Group;\r
-use Friendica\Model\Item;\r
-use Friendica\Model\Profile AS ProfileModel;\r
-use Friendica\Model\User;\r
-use Friendica\Protocol\ActivityPub;\r
-use Friendica\Protocol\DFRN;\r
-use Friendica\Util\DateTimeFormat;\r
-use Friendica\Util\Security;\r
-use Friendica\Util\Strings;\r
-use Friendica\Util\XML;\r
-\r
-require_once 'boot.php';\r
-\r
-class Profile extends BaseModule\r
-{\r
-       public static $which = '';\r
-       public static $profile = 0;\r
-\r
-       public static function init()\r
-       {\r
-               $a = self::getApp();\r
-\r
-               if ($a->argc < 2) {\r
-                       System::httpExit(400);\r
-               }\r
-\r
-               self::$which = filter_var($a->argv[1], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH | FILTER_FLAG_STRIP_BACKTICK);\r
-\r
-               if (local_user() && $a->argc > 2 && $a->argv[2] === 'view') {\r
-                       self::$which = $a->user['nickname'];\r
-                       self::$profile = filter_var($a->argv[1], FILTER_SANITIZE_NUMBER_INT);\r
-               } else {\r
-                       DFRN::autoRedir($a, self::$which);\r
-               }\r
-       }\r
-\r
-       public static function rawContent()\r
-       {\r
-               if (ActivityPub::isRequest()) {\r
-                       $user = DBA::selectFirst('user', ['uid'], ['nickname' => self::$which]);\r
-                       $data = [];\r
-                       if (DBA::isResult($user)) {\r
-                               $data = ActivityPub\Transmitter::getProfile($user['uid']);\r
-                       }\r
-\r
-                       if (!empty($data)) {\r
-                               System::jsonExit($data, 'application/activity+json');\r
-                       } elseif (DBA::exists('userd', ['username' => self::$which])) {\r
-                               // Known deleted user\r
-                               $data = ActivityPub\Transmitter::getDeletedUser(self::$which);\r
-\r
-                               System::jsonError(410, $data);\r
-                       } else {\r
-                               // Any other case (unknown, blocked, unverified, expired, no profile, no self contact)\r
-                               System::jsonError(404, $data);\r
-                       }\r
-               }\r
-       }\r
-\r
-       public static function content($update = 0)\r
-       {\r
-               $a = self::getApp();\r
-\r
-               if (!$update) {\r
-                       ProfileModel::load($a, self::$which, self::$profile);\r
-\r
-                       $blocked   = !local_user() && !remote_user() && Config::get('system', 'block_public');\r
-                       $userblock = !local_user() && !remote_user() && $a->profile['hidewall'];\r
-\r
-                       if (!empty($a->profile['page-flags']) && $a->profile['page-flags'] == User::PAGE_FLAGS_COMMUNITY) {\r
-                               $a->page['htmlhead'] .= '<meta name="friendica.community" content="true" />';\r
-                       }\r
-\r
-                       if (!empty($a->profile['openidserver'])) {\r
-                               $a->page['htmlhead'] .= '<link rel="openid.server" href="' . $a->profile['openidserver'] . '" />' . "\n";\r
-                       }\r
-\r
-                       if (!empty($a->profile['openid'])) {\r
-                               $delegate = strstr($a->profile['openid'], '://') ? $a->profile['openid'] : 'https://' . $a->profile['openid'];\r
-                               $a->page['htmlhead'] .= '<link rel="openid.delegate" href="' . $delegate . '" />' . "\n";\r
-                       }\r
-\r
-                       // site block\r
-                       if (!$blocked && !$userblock) {\r
-                               $keywords = str_replace(['#', ',', ' ', ',,'], ['', ' ', ',', ','], defaults($a->profile, 'pub_keywords', ''));\r
-                               if (strlen($keywords)) {\r
-                                       $a->page['htmlhead'] .= '<meta name="keywords" content="' . $keywords . '" />' . "\n";\r
-                               }\r
-                       }\r
-\r
-                       $a->page['htmlhead'] .= '<meta name="dfrn-global-visibility" content="' . ($a->profile['net-publish'] ? 'true' : 'false') . '" />' . "\n";\r
-                       $a->page['htmlhead'] .= '<link rel="alternate" type="application/atom+xml" href="' . System::baseUrl() . '/dfrn_poll/' . self::$which . '" title="DFRN: ' . L10n::t('%s\'s timeline', $a->profile['username']) . '"/>' . "\n";\r
-                       $a->page['htmlhead'] .= '<link rel="alternate" type="application/atom+xml" href="' . System::baseUrl() . '/feed/' . self::$which . '/" title="' . L10n::t('%s\'s posts', $a->profile['username']) . '"/>' . "\n";\r
-                       $a->page['htmlhead'] .= '<link rel="alternate" type="application/atom+xml" href="' . System::baseUrl() . '/feed/' . self::$which . '/comments" title="' . L10n::t('%s\'s comments', $a->profile['username']) . '"/>' . "\n";\r
-                       $a->page['htmlhead'] .= '<link rel="alternate" type="application/atom+xml" href="' . System::baseUrl() . '/feed/' . self::$which . '/activity" title="' . L10n::t('%s\'s timeline', $a->profile['username']) . '"/>' . "\n";\r
-                       $uri = urlencode('acct:' . $a->profile['nickname'] . '@' . $a->getHostName() . ($a->getURLPath() ? '/' . $a->getURLPath() : ''));\r
-                       $a->page['htmlhead'] .= '<link rel="lrdd" type="application/xrd+xml" href="' . System::baseUrl() . '/xrd/?uri=' . $uri . '" />' . "\n";\r
-                       header('Link: <' . System::baseUrl() . '/xrd/?uri=' . $uri . '>; rel="lrdd"; type="application/xrd+xml"', false);\r
-\r
-                       $dfrn_pages = ['request', 'confirm', 'notify', 'poll'];\r
-                       foreach ($dfrn_pages as $dfrn) {\r
-                               $a->page['htmlhead'] .= '<link rel="dfrn-' . $dfrn . '" href="' . System::baseUrl() . '/dfrn_' . $dfrn . '/' . self::$which . '" />' . "\n";\r
-                       }\r
-                       $a->page['htmlhead'] .= '<link rel="dfrn-poco" href="' . System::baseUrl() . '/poco/' . self::$which . '" />' . "\n";\r
-               }\r
-\r
-               $category = $datequery = $datequery2 = '';\r
-\r
-               if ($a->argc > 2) {\r
-                       for ($x = 2; $x < $a->argc; $x ++) {\r
-                               if (is_a_date_arg($a->argv[$x])) {\r
-                                       if ($datequery) {\r
-                                               $datequery2 = Strings::escapeHtml($a->argv[$x]);\r
-                                       } else {\r
-                                               $datequery = Strings::escapeHtml($a->argv[$x]);\r
-                                       }\r
-                               } else {\r
-                                       $category = $a->argv[$x];\r
-                               }\r
-                       }\r
-               }\r
-\r
-               if (empty($category)) {\r
-                       $category = defaults($_GET, 'category', '');\r
-               }\r
-\r
-               $hashtags = defaults($_GET, 'tag', '');\r
-\r
-               if (Config::get('system', 'block_public') && !local_user() && !remote_user()) {\r
-                       return Login::form();\r
-               }\r
-\r
-               $groups = [];\r
-               $remote_cid = null;\r
-\r
-               $o = '';\r
-\r
-               if ($update) {\r
-                       // Ensure we've got a profile owner if updating.\r
-                       $a->profile['profile_uid'] = $update;\r
-               } elseif ($a->profile['profile_uid'] == local_user()) {\r
-                       Nav::setSelected('home');\r
-               }\r
-\r
-               $remote_contact = ContactModel::isFollower(remote_user(), $a->profile['profile_uid']);\r
-               $is_owner = local_user() == $a->profile['profile_uid'];\r
-               $last_updated_key = "profile:" . $a->profile['profile_uid'] . ":" . local_user() . ":" . remote_user();\r
-\r
-               if ($remote_contact) {\r
-                       $cdata = ContactModel::getPublicAndUserContacID(remote_user(), $a->profile['profile_uid']);\r
-                       if (!empty($cdata['user'])) {\r
-                               $groups = Group::getIdsByContactId($cdata['user']);\r
-                               $remote_cid = $cdata['user'];\r
-                       }\r
-               }\r
-\r
-               if (!empty($a->profile['hidewall']) && !$is_owner && !$remote_contact) {\r
-                       notice(L10n::t('Access to this profile has been restricted.') . EOL);\r
-                       return '';\r
-               }\r
-\r
-               if (!$update) {\r
-                       $tab = false;\r
-                       if (!empty($_GET['tab'])) {\r
-                               $tab = Strings::escapeTags(trim($_GET['tab']));\r
-                       }\r
-\r
-                       $o .= ProfileModel::getTabs($a, $is_owner, $a->profile['nickname']);\r
-\r
-                       if ($tab === 'profile') {\r
-                               $o .= ProfileModel::getAdvanced($a);\r
-                               Hook::callAll('profile_advanced', $o);\r
-                               return $o;\r
-                       }\r
-\r
-                       $o .= Widget::commonFriendsVisitor($a->profile['profile_uid']);\r
-\r
-                       $commpage = $a->profile['page-flags'] == User::PAGE_FLAGS_COMMUNITY;\r
-                       $commvisitor = $commpage && $remote_contact;\r
-\r
-                       $a->page['aside'] .= posted_date_widget(System::baseUrl(true) . '/profile/' . $a->profile['nickname'], $a->profile['profile_uid'], true);\r
-                       $a->page['aside'] .= Widget::categories(System::baseUrl(true) . '/profile/' . $a->profile['nickname'], (!empty($category) ? XML::escape($category) : ''));\r
-                       $a->page['aside'] .= Widget::tagCloud();\r
-\r
-                       if (Security::canWriteToUserWall($a->profile['profile_uid'])) {\r
-                               $x = [\r
-                                       'is_owner' => $is_owner,\r
-                                       'allow_location' => ($is_owner || $commvisitor) && $a->profile['allow_location'],\r
-                                       'default_location' => $is_owner ? $a->user['default-location'] : '',\r
-                                       'nickname' => $a->profile['nickname'],\r
-                                       'lockstate' => is_array($a->user)\r
-                                       && (strlen($a->user['allow_cid'])\r
-                                               || strlen($a->user['allow_gid'])\r
-                                               || strlen($a->user['deny_cid'])\r
-                                               || strlen($a->user['deny_gid'])\r
-                                       ) ? 'lock' : 'unlock',\r
-                                       'acl' => $is_owner ? ACL::getFullSelectorHTML($a->user, true) : '',\r
-                                       'bang' => '',\r
-                                       'visitor' => $is_owner || $commvisitor ? 'block' : 'none',\r
-                                       'profile_uid' => $a->profile['profile_uid'],\r
-                               ];\r
-\r
-                               $o .= status_editor($a, $x);\r
-                       }\r
-               }\r
-\r
-               // Get permissions SQL - if $remote_contact is true, our remote user has been pre-verified and we already have fetched his/her groups\r
-               $sql_extra = Item::getPermissionsSQLByUserId($a->profile['profile_uid'], $remote_contact, $groups, $remote_cid);\r
-               $sql_extra2 = '';\r
-\r
-               if ($update) {\r
-                       $last_updated = (defaults($_SESSION['last_updated'], $last_updated_key, 0));\r
-\r
-                       // If the page user is the owner of the page we should query for unseen\r
-                       // items. Otherwise use a timestamp of the last succesful update request.\r
-                       if ($is_owner || !$last_updated) {\r
-                               $sql_extra4 = " AND `item`.`unseen`";\r
-                       } else {\r
-                               $gmupdate = gmdate(DateTimeFormat::MYSQL, $last_updated);\r
-                               $sql_extra4 = " AND `item`.`received` > '" . $gmupdate . "'";\r
-                       }\r
-\r
-                       $items_stmt = DBA::p(\r
-                               "SELECT DISTINCT(`parent-uri`) AS `uri`, `item`.`created`\r
-                               FROM `item`\r
-                               INNER JOIN `contact`\r
-                               ON `contact`.`id` = `item`.`contact-id`\r
-                                       AND NOT `contact`.`blocked`\r
-                                       AND NOT `contact`.`pending`\r
-                               WHERE `item`.`uid` = ?\r
-                                       AND `item`.`visible`\r
-                                       AND     (NOT `item`.`deleted` OR `item`.`gravity` = ?)\r
-                                       AND NOT `item`.`moderated`\r
-                                       AND `item`.`wall`\r
-                                       $sql_extra4\r
-                                       $sql_extra\r
-                               ORDER BY `item`.`created` DESC",\r
-                               $a->profile['profile_uid'],\r
-                               GRAVITY_ACTIVITY\r
-                       );\r
-\r
-                       if (!DBA::isResult($items_stmt)) {\r
-                               return '';\r
-                       }\r
-\r
-                       $pager = new Pager($a->query_string);\r
-               } else {\r
-                       $sql_post_table = "";\r
-\r
-                       if (!empty($category)) {\r
-                               $sql_post_table = sprintf("INNER JOIN (SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d ORDER BY `tid` DESC) AS `term` ON `item`.`id` = `term`.`oid` ",\r
-                                       DBA::escape(Strings::protectSprintf($category)), intval(TERM_OBJ_POST), intval(TERM_CATEGORY), intval($a->profile['profile_uid']));\r
-                       }\r
-\r
-                       if (!empty($hashtags)) {\r
-                               $sql_post_table .= sprintf("INNER JOIN (SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d ORDER BY `tid` DESC) AS `term` ON `item`.`id` = `term`.`oid` ",\r
-                                       DBA::escape(Strings::protectSprintf($hashtags)), intval(TERM_OBJ_POST), intval(TERM_HASHTAG), intval($a->profile['profile_uid']));\r
-                       }\r
-\r
-                       if (!empty($datequery)) {\r
-                               $sql_extra2 .= Strings::protectSprintf(sprintf(" AND `thread`.`created` <= '%s' ", DBA::escape(DateTimeFormat::convert($datequery, 'UTC', date_default_timezone_get()))));\r
-                       }\r
-                       if (!empty($datequery2)) {\r
-                               $sql_extra2 .= Strings::protectSprintf(sprintf(" AND `thread`.`created` >= '%s' ", DBA::escape(DateTimeFormat::convert($datequery2, 'UTC', date_default_timezone_get()))));\r
-                       }\r
-\r
-                       // Does the profile page belong to a forum?\r
-                       // If not then we can improve the performance with an additional condition\r
-                       $condition = ['uid' => $a->profile['profile_uid'], 'page-flags' => [User::PAGE_FLAGS_COMMUNITY, User::PAGE_FLAGS_PRVGROUP]];\r
-                       if (!DBA::exists('user', $condition)) {\r
-                               $sql_extra3 = sprintf(" AND `thread`.`contact-id` = %d ", intval(intval($a->profile['contact_id'])));\r
-                       } else {\r
-                               $sql_extra3 = "";\r
-                       }\r
-\r
-                       //  check if we serve a mobile device and get the user settings\r
-                       //  accordingly\r
-                       if ($a->is_mobile) {\r
-                               $itemspage_network = PConfig::get(local_user(), 'system', 'itemspage_mobile_network', 10);\r
-                       } else {\r
-                               $itemspage_network = PConfig::get(local_user(), 'system', 'itemspage_network', 20);\r
-                       }\r
-\r
-                       //  now that we have the user settings, see if the theme forces\r
-                       //  a maximum item number which is lower then the user choice\r
-                       if (($a->force_max_items > 0) && ($a->force_max_items < $itemspage_network)) {\r
-                               $itemspage_network = $a->force_max_items;\r
-                       }\r
-\r
-                       $pager = new Pager($a->query_string, $itemspage_network);\r
-\r
-                       $pager_sql = sprintf(" LIMIT %d, %d ", $pager->getStart(), $pager->getItemsPerPage());\r
-\r
-                       $items_stmt = DBA::p(\r
-                               "SELECT `item`.`uri`\r
-                               FROM `thread`\r
-                               STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`\r
-                               $sql_post_table\r
-                               STRAIGHT_JOIN `contact`\r
-                               ON `contact`.`id` = `thread`.`contact-id`\r
-                                       AND NOT `contact`.`blocked`\r
-                                       AND NOT `contact`.`pending`\r
-                               WHERE `thread`.`uid` = ?\r
-                                       AND `thread`.`visible`\r
-                                       AND NOT `thread`.`deleted`\r
-                                       AND NOT `thread`.`moderated`\r
-                                       AND `thread`.`wall`\r
-                                       $sql_extra3\r
-                                       $sql_extra\r
-                                       $sql_extra2\r
-                               ORDER BY `thread`.`created` DESC\r
-                               $pager_sql",\r
-                               $a->profile['profile_uid']\r
-                       );\r
-               }\r
-\r
-               // Set a time stamp for this page. We will make use of it when we\r
-               // search for new items (update routine)\r
-               $_SESSION['last_updated'][$last_updated_key] = time();\r
-\r
-               if ($is_owner && !$update && !Config::get('theme', 'hide_eventlist')) {\r
-                       $o .= ProfileModel::getBirthdays();\r
-                       $o .= ProfileModel::getEventsReminderHTML();\r
-               }\r
-\r
-               if ($is_owner) {\r
-                       $unseen = Item::exists(['wall' => true, 'unseen' => true, 'uid' => local_user()]);\r
-                       if ($unseen) {\r
-                               Item::update(['unseen' => false], ['wall' => true, 'unseen' => true, 'uid' => local_user()]);\r
-                       }\r
-               }\r
-\r
-               $items = DBA::toArray($items_stmt);\r
-\r
-               $o .= conversation($a, $items, $pager, 'profile', $update, false, 'created', $a->profile['profile_uid']);\r
-\r
-               if (!$update) {\r
-                       $o .= $pager->renderMinimal(count($items));\r
-               }\r
-\r
-               return $o;\r
-       }\r
-}\r
+<?php
+
+namespace Friendica\Module;
+
+use Friendica\BaseModule;
+use Friendica\Content\Nav;
+use Friendica\Content\Pager;
+use Friendica\Content\Widget;
+use Friendica\Core\ACL;
+use Friendica\Core\Config;
+use Friendica\Core\Hook;
+use Friendica\Core\L10n;
+use Friendica\Core\PConfig;
+use Friendica\Core\System;
+use Friendica\Database\DBA;
+use Friendica\Model\Contact as ContactModel;
+use Friendica\Model\Group;
+use Friendica\Model\Item;
+use Friendica\Model\Profile as ProfileModel;
+use Friendica\Model\User;
+use Friendica\Protocol\ActivityPub;
+use Friendica\Protocol\DFRN;
+use Friendica\Util\DateTimeFormat;
+use Friendica\Util\Security;
+use Friendica\Util\Strings;
+use Friendica\Util\XML;
+
+require_once 'boot.php';
+
+class Profile extends BaseModule
+{
+       public static $which = '';
+       public static $profile = 0;
+
+       public static function init()
+       {
+               $a = self::getApp();
+
+               // @TODO: Replace with parameter from router
+               if ($a->argc < 2) {
+                       throw new \Friendica\Network\HTTPException\BadRequestException();
+               }
+
+               self::$which = filter_var($a->argv[1], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH | FILTER_FLAG_STRIP_BACKTICK);
+
+               // @TODO: Replace with parameter from router
+               if (local_user() && $a->argc > 2 && $a->argv[2] === 'view') {
+                       self::$which = $a->user['nickname'];
+                       self::$profile = filter_var($a->argv[1], FILTER_SANITIZE_NUMBER_INT);
+               } else {
+                       DFRN::autoRedir($a, self::$which);
+               }
+       }
+
+       public static function rawContent()
+       {
+               if (ActivityPub::isRequest()) {
+                       $user = DBA::selectFirst('user', ['uid'], ['nickname' => self::$which]);
+                       $data = [];
+                       if (DBA::isResult($user)) {
+                               $data = ActivityPub\Transmitter::getProfile($user['uid']);
+                       }
+
+                       if (!empty($data)) {
+                               System::jsonExit($data, 'application/activity+json');
+                       } elseif (DBA::exists('userd', ['username' => self::$which])) {
+                               // Known deleted user
+                               $data = ActivityPub\Transmitter::getDeletedUser(self::$which);
+
+                               System::jsonError(410, $data);
+                       } else {
+                               // Any other case (unknown, blocked, unverified, expired, no profile, no self contact)
+                               System::jsonError(404, $data);
+                       }
+               }
+       }
+
+       public static function content($update = 0)
+       {
+               $a = self::getApp();
+
+               if (!$update) {
+                       ProfileModel::load($a, self::$which, self::$profile);
+
+                       $blocked   = !local_user() && !remote_user() && Config::get('system', 'block_public');
+                       $userblock = !local_user() && !remote_user() && $a->profile['hidewall'];
+
+                       if (!empty($a->profile['page-flags']) && $a->profile['page-flags'] == User::PAGE_FLAGS_COMMUNITY) {
+                               $a->page['htmlhead'] .= '<meta name="friendica.community" content="true" />';
+                       }
+
+                       if (!empty($a->profile['openidserver'])) {
+                               $a->page['htmlhead'] .= '<link rel="openid.server" href="' . $a->profile['openidserver'] . '" />' . "\n";
+                       }
+
+                       if (!empty($a->profile['openid'])) {
+                               $delegate = strstr($a->profile['openid'], '://') ? $a->profile['openid'] : 'https://' . $a->profile['openid'];
+                               $a->page['htmlhead'] .= '<link rel="openid.delegate" href="' . $delegate . '" />' . "\n";
+                       }
+
+                       // site block
+                       if (!$blocked && !$userblock) {
+                               $keywords = str_replace(['#', ',', ' ', ',,'], ['', ' ', ',', ','], defaults($a->profile, 'pub_keywords', ''));
+                               if (strlen($keywords)) {
+                                       $a->page['htmlhead'] .= '<meta name="keywords" content="' . $keywords . '" />' . "\n";
+                               }
+                       }
+
+                       $a->page['htmlhead'] .= '<meta name="dfrn-global-visibility" content="' . ($a->profile['net-publish'] ? 'true' : 'false') . '" />' . "\n";
+                       $a->page['htmlhead'] .= '<link rel="alternate" type="application/atom+xml" href="' . System::baseUrl() . '/dfrn_poll/' . self::$which . '" title="DFRN: ' . L10n::t('%s\'s timeline', $a->profile['username']) . '"/>' . "\n";
+                       $a->page['htmlhead'] .= '<link rel="alternate" type="application/atom+xml" href="' . System::baseUrl() . '/feed/' . self::$which . '/" title="' . L10n::t('%s\'s posts', $a->profile['username']) . '"/>' . "\n";
+                       $a->page['htmlhead'] .= '<link rel="alternate" type="application/atom+xml" href="' . System::baseUrl() . '/feed/' . self::$which . '/comments" title="' . L10n::t('%s\'s comments', $a->profile['username']) . '"/>' . "\n";
+                       $a->page['htmlhead'] .= '<link rel="alternate" type="application/atom+xml" href="' . System::baseUrl() . '/feed/' . self::$which . '/activity" title="' . L10n::t('%s\'s timeline', $a->profile['username']) . '"/>' . "\n";
+                       $uri = urlencode('acct:' . $a->profile['nickname'] . '@' . $a->getHostName() . ($a->getURLPath() ? '/' . $a->getURLPath() : ''));
+                       $a->page['htmlhead'] .= '<link rel="lrdd" type="application/xrd+xml" href="' . System::baseUrl() . '/xrd/?uri=' . $uri . '" />' . "\n";
+                       header('Link: <' . System::baseUrl() . '/xrd/?uri=' . $uri . '>; rel="lrdd"; type="application/xrd+xml"', false);
+
+                       $dfrn_pages = ['request', 'confirm', 'notify', 'poll'];
+                       foreach ($dfrn_pages as $dfrn) {
+                               $a->page['htmlhead'] .= '<link rel="dfrn-' . $dfrn . '" href="' . System::baseUrl() . '/dfrn_' . $dfrn . '/' . self::$which . '" />' . "\n";
+                       }
+                       $a->page['htmlhead'] .= '<link rel="dfrn-poco" href="' . System::baseUrl() . '/poco/' . self::$which . '" />' . "\n";
+               }
+
+               $category = $datequery = $datequery2 = '';
+
+               if ($a->argc > 2) {
+                       for ($x = 2; $x < $a->argc; $x ++) {
+                               if (is_a_date_arg($a->argv[$x])) {
+                                       if ($datequery) {
+                                               $datequery2 = Strings::escapeHtml($a->argv[$x]);
+                                       } else {
+                                               $datequery = Strings::escapeHtml($a->argv[$x]);
+                                       }
+                               } else {
+                                       $category = $a->argv[$x];
+                               }
+                       }
+               }
+
+               if (empty($category)) {
+                       $category = defaults($_GET, 'category', '');
+               }
+
+               $hashtags = defaults($_GET, 'tag', '');
+
+               if (Config::get('system', 'block_public') && !local_user() && !remote_user()) {
+                       return Login::form();
+               }
+
+               $groups = [];
+               $remote_cid = null;
+
+               $o = '';
+
+               if ($update) {
+                       // Ensure we've got a profile owner if updating.
+                       $a->profile['profile_uid'] = $update;
+               } elseif ($a->profile['profile_uid'] == local_user()) {
+                       Nav::setSelected('home');
+               }
+
+               $remote_contact = ContactModel::isFollower(remote_user(), $a->profile['profile_uid']);
+               $is_owner = local_user() == $a->profile['profile_uid'];
+               $last_updated_key = "profile:" . $a->profile['profile_uid'] . ":" . local_user() . ":" . remote_user();
+
+               if ($remote_contact) {
+                       $cdata = ContactModel::getPublicAndUserContacID(remote_user(), $a->profile['profile_uid']);
+                       if (!empty($cdata['user'])) {
+                               $groups = Group::getIdsByContactId($cdata['user']);
+                               $remote_cid = $cdata['user'];
+                       }
+               }
+
+               if (!empty($a->profile['hidewall']) && !$is_owner && !$remote_contact) {
+                       notice(L10n::t('Access to this profile has been restricted.') . EOL);
+                       return '';
+               }
+
+               if (!$update) {
+                       $tab = false;
+                       if (!empty($_GET['tab'])) {
+                               $tab = Strings::escapeTags(trim($_GET['tab']));
+                       }
+
+                       $o .= ProfileModel::getTabs($a, $is_owner, $a->profile['nickname']);
+
+                       if ($tab === 'profile') {
+                               $o .= ProfileModel::getAdvanced($a);
+                               Hook::callAll('profile_advanced', $o);
+                               return $o;
+                       }
+
+                       $o .= Widget::commonFriendsVisitor($a->profile['profile_uid']);
+
+                       $commpage = $a->profile['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
+                       $commvisitor = $commpage && $remote_contact;
+
+                       $a->page['aside'] .= posted_date_widget(System::baseUrl(true) . '/profile/' . $a->profile['nickname'], $a->profile['profile_uid'], true);
+                       $a->page['aside'] .= Widget::categories(System::baseUrl(true) . '/profile/' . $a->profile['nickname'], (!empty($category) ? XML::escape($category) : ''));
+                       $a->page['aside'] .= Widget::tagCloud();
+
+                       if (Security::canWriteToUserWall($a->profile['profile_uid'])) {
+                               $x = [
+                                       'is_owner' => $is_owner,
+                                       'allow_location' => ($is_owner || $commvisitor) && $a->profile['allow_location'],
+                                       'default_location' => $is_owner ? $a->user['default-location'] : '',
+                                       'nickname' => $a->profile['nickname'],
+                                       'lockstate' => is_array($a->user)
+                                       && (strlen($a->user['allow_cid'])
+                                               || strlen($a->user['allow_gid'])
+                                               || strlen($a->user['deny_cid'])
+                                               || strlen($a->user['deny_gid'])
+                                       ) ? 'lock' : 'unlock',
+                                       'acl' => $is_owner ? ACL::getFullSelectorHTML($a->user, true) : '',
+                                       'bang' => '',
+                                       'visitor' => $is_owner || $commvisitor ? 'block' : 'none',
+                                       'profile_uid' => $a->profile['profile_uid'],
+                               ];
+
+                               $o .= status_editor($a, $x);
+                       }
+               }
+
+               // Get permissions SQL - if $remote_contact is true, our remote user has been pre-verified and we already have fetched his/her groups
+               $sql_extra = Item::getPermissionsSQLByUserId($a->profile['profile_uid'], $remote_contact, $groups, $remote_cid);
+               $sql_extra2 = '';
+
+               if ($update) {
+                       $last_updated = (defaults($_SESSION['last_updated'], $last_updated_key, 0));
+
+                       // If the page user is the owner of the page we should query for unseen
+                       // items. Otherwise use a timestamp of the last succesful update request.
+                       if ($is_owner || !$last_updated) {
+                               $sql_extra4 = " AND `item`.`unseen`";
+                       } else {
+                               $gmupdate = gmdate(DateTimeFormat::MYSQL, $last_updated);
+                               $sql_extra4 = " AND `item`.`received` > '" . $gmupdate . "'";
+                       }
+
+                       $items_stmt = DBA::p(
+                               "SELECT DISTINCT(`parent-uri`) AS `uri`, `item`.`created`
+                               FROM `item`
+                               INNER JOIN `contact`
+                               ON `contact`.`id` = `item`.`contact-id`
+                                       AND NOT `contact`.`blocked`
+                                       AND NOT `contact`.`pending`
+                               WHERE `item`.`uid` = ?
+                                       AND `item`.`visible`
+                                       AND     (NOT `item`.`deleted` OR `item`.`gravity` = ?)
+                                       AND NOT `item`.`moderated`
+                                       AND `item`.`wall`
+                                       $sql_extra4
+                                       $sql_extra
+                               ORDER BY `item`.`created` DESC",
+                               $a->profile['profile_uid'],
+                               GRAVITY_ACTIVITY
+                       );
+
+                       if (!DBA::isResult($items_stmt)) {
+                               return '';
+                       }
+
+                       $pager = new Pager($a->query_string);
+               } else {
+                       $sql_post_table = "";
+
+                       if (!empty($category)) {
+                               $sql_post_table = sprintf("INNER JOIN (SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d ORDER BY `tid` DESC) AS `term` ON `item`.`id` = `term`.`oid` ",
+                                       DBA::escape(Strings::protectSprintf($category)), intval(TERM_OBJ_POST), intval(TERM_CATEGORY), intval($a->profile['profile_uid']));
+                       }
+
+                       if (!empty($hashtags)) {
+                               $sql_post_table .= sprintf("INNER JOIN (SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d ORDER BY `tid` DESC) AS `term` ON `item`.`id` = `term`.`oid` ",
+                                       DBA::escape(Strings::protectSprintf($hashtags)), intval(TERM_OBJ_POST), intval(TERM_HASHTAG), intval($a->profile['profile_uid']));
+                       }
+
+                       if (!empty($datequery)) {
+                               $sql_extra2 .= Strings::protectSprintf(sprintf(" AND `thread`.`created` <= '%s' ", DBA::escape(DateTimeFormat::convert($datequery, 'UTC', date_default_timezone_get()))));
+                       }
+                       if (!empty($datequery2)) {
+                               $sql_extra2 .= Strings::protectSprintf(sprintf(" AND `thread`.`created` >= '%s' ", DBA::escape(DateTimeFormat::convert($datequery2, 'UTC', date_default_timezone_get()))));
+                       }
+
+                       // Does the profile page belong to a forum?
+                       // If not then we can improve the performance with an additional condition
+                       $condition = ['uid' => $a->profile['profile_uid'], 'page-flags' => [User::PAGE_FLAGS_COMMUNITY, User::PAGE_FLAGS_PRVGROUP]];
+                       if (!DBA::exists('user', $condition)) {
+                               $sql_extra3 = sprintf(" AND `thread`.`contact-id` = %d ", intval(intval($a->profile['contact_id'])));
+                       } else {
+                               $sql_extra3 = "";
+                       }
+
+                       //  check if we serve a mobile device and get the user settings
+                       //  accordingly
+                       if ($a->is_mobile) {
+                               $itemspage_network = PConfig::get(local_user(), 'system', 'itemspage_mobile_network', 10);
+                       } else {
+                               $itemspage_network = PConfig::get(local_user(), 'system', 'itemspage_network', 20);
+                       }
+
+                       //  now that we have the user settings, see if the theme forces
+                       //  a maximum item number which is lower then the user choice
+                       if (($a->force_max_items > 0) && ($a->force_max_items < $itemspage_network)) {
+                               $itemspage_network = $a->force_max_items;
+                       }
+
+                       $pager = new Pager($a->query_string, $itemspage_network);
+
+                       $pager_sql = sprintf(" LIMIT %d, %d ", $pager->getStart(), $pager->getItemsPerPage());
+
+                       $items_stmt = DBA::p(
+                               "SELECT `item`.`uri`
+                               FROM `thread`
+                               STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
+                               $sql_post_table
+                               STRAIGHT_JOIN `contact`
+                               ON `contact`.`id` = `thread`.`contact-id`
+                                       AND NOT `contact`.`blocked`
+                                       AND NOT `contact`.`pending`
+                               WHERE `thread`.`uid` = ?
+                                       AND `thread`.`visible`
+                                       AND NOT `thread`.`deleted`
+                                       AND NOT `thread`.`moderated`
+                                       AND `thread`.`wall`
+                                       $sql_extra3
+                                       $sql_extra
+                                       $sql_extra2
+                               ORDER BY `thread`.`created` DESC
+                               $pager_sql",
+                               $a->profile['profile_uid']
+                       );
+               }
+
+               // Set a time stamp for this page. We will make use of it when we
+               // search for new items (update routine)
+               $_SESSION['last_updated'][$last_updated_key] = time();
+
+               if ($is_owner && !$update && !Config::get('theme', 'hide_eventlist')) {
+                       $o .= ProfileModel::getBirthdays();
+                       $o .= ProfileModel::getEventsReminderHTML();
+               }
+
+               if ($is_owner) {
+                       $unseen = Item::exists(['wall' => true, 'unseen' => true, 'uid' => local_user()]);
+                       if ($unseen) {
+                               Item::update(['unseen' => false], ['wall' => true, 'unseen' => true, 'uid' => local_user()]);
+                       }
+               }
+
+               $items = DBA::toArray($items_stmt);
+
+               $o .= conversation($a, $items, $pager, 'profile', $update, false, 'created', $a->profile['profile_uid']);
+
+               if (!$update) {
+                       $o .= $pager->renderMinimal(count($items));
+               }
+
+               return $o;
+       }
+}
index 54870abe055469e20e715b269281644d539b5de3..75a1142af6221331ce4715d3a87c7f8988a7c44f 100644 (file)
@@ -12,7 +12,6 @@ use Friendica\Model\Photo;
 use Friendica\Object\Image;
 use Friendica\Util\HTTPSignature;
 use Friendica\Util\Proxy as ProxyUtils;
-use Friendica\Core\Logger;
 
 /**
  * @brief Module Proxy
@@ -71,7 +70,7 @@ class Proxy extends BaseModule
                $request = self::getRequestInfo();
 
                if (empty($request['url'])) {
-                       System::httpExit(400, ['title' => L10n::t('Bad Request.')]);
+                       throw new \Friendica\Network\HTTPException\BadRequestException();
                }
 
                // Webserver already tried direct cache...
@@ -159,6 +158,7 @@ class Proxy extends BaseModule
                $sizetype = '';
 
                // Look for filename in the arguments
+               // @TODO: Replace with parameter from router
                if (($a->argc > 1) && !isset($_REQUEST['url'])) {
                        if (isset($a->argv[3])) {
                                $url = $a->argv[3];
@@ -169,6 +169,7 @@ class Proxy extends BaseModule
                        }
 
                        /// @TODO: Why? And what about $url in this case?
+                       /// @TODO: Replace with parameter from router
                        if (isset($a->argv[3]) && ($a->argv[3] == 'thumb')) {
                                $size = 200;
                        }
index f888f263266dbdd65f8f527f835fe50b112c3c2b..a723f6a290756ddcf9ad1b40fae71a050e13cfb9 100644 (file)
@@ -3,8 +3,29 @@
 The Module namespace contains the different modules of Friendica.
 Each module is loaded through the [`App`](https://github.com/friendica/friendica/blob/develop/src/App.php).
 
-Rules for Modules:
--      Named like the call (i.e. https://friendica.test/contact => `Contact`)
--      Start with capitals and are **not** camelCased.
--      Directly interacting with a given request (POST or GET)
--      Extending [`BaseModule`](https://github.com/friendica/friendica/blob/develop/src/BaseModule.php).
\ No newline at end of file
+There are mainly two types of modules:
+-      frontend modules to interact with users
+-      backend modules to interact with machine requests
+
+### Frontend modules
+
+This type of modules mainly needs a template, which are generally located at
+[view/templates/](https://github.com/friendica/friendica/tree/develop/view/templates).
+
+A frontend module should extend the [`BaseModule`](https://github.com/friendica/friendica/blob/develop/src/BaseModule.php), especially the `content()` method. 
+
+### Backend modules
+
+This type of modules mainly responds either with encoded `XML` or with `JSON` output.
+It isn't intended to respond with human readable text.
+
+A frontend module should extend the [`BaseModule`](https://github.com/friendica/friendica/blob/develop/src/BaseModule.php), especially the `rawContent()` method.
+### Routing
+
+Every module needs to be accessed within a route.
+The routes are defined inside [`Router->collectRoutes()`](https://github.com/friendica/friendica/blob/develop/src/App/Router.php).
+
+Use the given routes as a pattern for further routes.
+
+The routing library and further documentation can be found [here](https://github.com/nikic/FastRoute).
\ No newline at end of file
diff --git a/src/Module/ReallySimpleDiscovery.php b/src/Module/ReallySimpleDiscovery.php
new file mode 100644 (file)
index 0000000..4c14d3c
--- /dev/null
@@ -0,0 +1,21 @@
+<?php
+
+namespace Friendica\Module;
+
+use Friendica\BaseModule;
+use Friendica\Core\Renderer;
+
+/**
+ * Prints the rsd.xml
+ * @see http://danielberlinger.github.io/rsd/
+ */
+class ReallySimpleDiscovery extends BaseModule
+{
+       public static function rawContent()
+       {
+               header ('Content-Type: text/xml');
+               $tpl = Renderer::getMarkupTemplate('rsd.tpl');
+               echo Renderer::replaceMacros($tpl);
+               exit();
+       }
+}
index 6744a0a5f34040ca1a2e02b7968dfdc4353d701f..06b62783f6eb8a4a9929b90879eb5562d74591ef 100644 (file)
@@ -19,7 +19,7 @@ use Friendica\Util\Strings;
 /**
  * @author Hypolite Petovan <hypolite@mrpetovan.com>
  */
-abstract class Register extends BaseModule
+class Register extends BaseModule
 {
        const CLOSED  = 0;
        const APPROVE = 1;
@@ -144,7 +144,6 @@ abstract class Register extends BaseModule
                        '$tostext'      => L10n::t('Terms of Service'),
                        '$showprivstatement' => Config::get('system', 'tosprivstatement'),
                        '$privstatement'=> $tos->privacy_complete,
-                       '$baseurl'      => System::baseurl(),
                        '$form_security_token' => BaseModule::getFormSecurityToken('register'),
                        '$explicit_content' => Config::get('system', 'explicit_content', false),
                        '$explicit_content_note' => L10n::t('Note: This node explicitly contains adult content')
diff --git a/src/Module/Special/HTTPException.php b/src/Module/Special/HTTPException.php
new file mode 100644 (file)
index 0000000..5c6ff79
--- /dev/null
@@ -0,0 +1,91 @@
+<?php
+
+
+namespace Friendica\Module\Special;
+
+use Friendica\Core\L10n;
+use Friendica\Core\Logger;
+use Friendica\Core\Renderer;
+use Friendica\Core\System;
+
+/**
+ * This special module displays HTTPException when they are thrown in modules.
+ *
+ * @package Friendica\Module\Special
+ */
+class HTTPException
+{
+       /**
+        * Generates the necessary template variables from the caught HTTPException.
+        *
+        * Fills in the blanks if title or descriptions aren't provided by the exception.
+        *
+        * @param \Friendica\Network\HTTPException $e
+        * @return array ['$title' => ..., '$description' => ...]
+        */
+       private static function getVars(\Friendica\Network\HTTPException $e)
+       {
+               $message = $e->getMessage();
+
+               $titles = [
+                       200 => 'OK',
+                       400 => L10n::t('Bad Request'),
+                       401 => L10n::t('Unauthorized'),
+                       403 => L10n::t('Forbidden'),
+                       404 => L10n::t('Not Found'),
+                       500 => L10n::t('Internal Server Error'),
+                       503 => L10n::t('Service Unavailable'),
+               ];
+               $title = defaults($titles, $e->getCode(), 'Error ' . $e->getCode());
+
+               if (empty($message)) {
+                       // Explanations are taken from https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
+                       $explanation = [
+                               400 => L10n::t('The server cannot or will not process the request due to an apparent client error.'),
+                               401 => L10n::t('Authentication is required and has failed or has not yet been provided.'),
+                               403 => L10n::t('The request was valid, but the server is refusing action. The user might not have the necessary permissions for a resource, or may need an account.'),
+                               404 => L10n::t('The requested resource could not be found but may be available in the future.'),
+                               500 => L10n::t('An unexpected condition was encountered and no more specific message is suitable.'),
+                               503 => L10n::t('The server is currently unavailable (because it is overloaded or down for maintenance). Please try again later.'),
+                       ];
+
+                       $message = defaults($explanation, $e->getCode(), '');
+               }
+
+               return ['$title' => $title, '$description' => $message];
+       }
+
+       /**
+        * Displays a bare message page with no theming at all.
+        *
+        * @param \Friendica\Network\HTTPException $e
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        */
+       public static function rawContent(\Friendica\Network\HTTPException $e)
+       {
+               $content = '';
+
+               if ($e->getCode() >= 400) {
+                       $tpl = Renderer::getMarkupTemplate('http_status.tpl');
+                       $content = Renderer::replaceMacros($tpl, self::getVars($e));
+               }
+
+               System::httpExit($e->getCode(), $e->httpdesc, $content);
+       }
+
+       /**
+        * Returns a content string that can be integrated in the current theme.
+        *
+        * @param \Friendica\Network\HTTPException $e
+        * @return string
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        */
+       public static function content(\Friendica\Network\HTTPException $e)
+       {
+               header($_SERVER["SERVER_PROTOCOL"] . ' ' . $e->getCode() . ' ' . $e->httpdesc);
+
+               $tpl = Renderer::getMarkupTemplate('exception.tpl');
+
+               return Renderer::replaceMacros($tpl, self::getVars($e));
+       }
+}
diff --git a/src/Module/Statistics.php b/src/Module/Statistics.php
new file mode 100644 (file)
index 0000000..3e64828
--- /dev/null
@@ -0,0 +1,60 @@
+<?php
+
+namespace Friendica\Module;
+
+use Friendica\BaseModule;
+use Friendica\Core\Addon;
+use Friendica\Core\System;
+
+class Statistics extends BaseModule
+{
+       public static function init()
+       {
+               $config = self::getApp()->getConfig();
+
+               if (!$config->get("system", "nodeinfo")) {
+                       throw new \Friendica\Network\HTTPException\NotFoundException();
+               }
+       }
+
+       public static function rawContent()
+       {
+               $config = self::getApp()->getConfig();
+               $logger = self::getApp()->getLogger();
+
+               $registration_open =
+                       intval($config->get('config', 'register_policy')) !== Register::CLOSED
+                       && !$config->get('config', 'invitation_only');
+
+               /// @todo mark the "service" addons and load them dynamically here
+               $services = [
+                       'appnet'      => Addon::isEnabled('appnet'),
+                       'buffer'      => Addon::isEnabled('buffer'),
+                       'dreamwidth'  => Addon::isEnabled('dreamwidth'),
+                       'gnusocial'   => Addon::isEnabled('gnusocial'),
+                       'libertree'   => Addon::isEnabled('libertree'),
+                       'livejournal' => Addon::isEnabled('livejournal'),
+                       'pumpio'      => Addon::isEnabled('pumpio'),
+                       'twitter'     => Addon::isEnabled('twitter'),
+                       'tumblr'      => Addon::isEnabled('tumblr'),
+                       'wordpress'   => Addon::isEnabled('wordpress'),
+               ];
+
+               $statistics = array_merge([
+                       'name'                  => $config->get('config', 'sitename'),
+                       'network'               => FRIENDICA_PLATFORM,
+                       'version'               => FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION,
+                       'registrations_open'    => $registration_open,
+                       'total_users'           => $config->get('nodeinfo', 'total_users'),
+                       'active_users_halfyear' => $config->get('nodeinfo', 'active_users_halfyear'),
+                       'active_users_monthly'  => $config->get('nodeinfo', 'active_users_monthly'),
+                       'local_posts'           => $config->get('nodeinfo', 'local_posts'),
+                       'services'              => $services,
+               ], $services);
+
+               header("Content-Type: application/json");
+               echo json_encode($statistics, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
+               $logger->debug("statistics.", ['statistics' => $statistics]);
+               exit();
+       }
+}
diff --git a/src/Module/Statistics_json.php b/src/Module/Statistics_json.php
deleted file mode 100644 (file)
index aca204b..0000000
+++ /dev/null
@@ -1,60 +0,0 @@
-<?php
-
-namespace Friendica\Module;
-
-use Friendica\BaseModule;
-use Friendica\Core\Addon;
-use Friendica\Core\System;
-
-class Statistics_json extends BaseModule
-{
-       public static function init()
-       {
-               $config = self::getApp()->getConfig();
-
-               if (!$config->get("system", "nodeinfo")) {
-                       System::httpExit(404);
-               }
-       }
-
-       public static function rawContent()
-       {
-               $config = self::getApp()->getConfig();
-               $logger = self::getApp()->getLogger();
-
-               $registration_open =
-                       intval($config->get('config', 'register_policy')) !== Register::CLOSED
-                       && !$config->get('config', 'invitation_only');
-
-               /// @todo mark the "service" addons and load them dynamically here
-               $services = [
-                       'appnet'      => Addon::isEnabled('appnet'),
-                       'buffer'      => Addon::isEnabled('buffer'),
-                       'dreamwidth'  => Addon::isEnabled('dreamwidth'),
-                       'gnusocial'   => Addon::isEnabled('gnusocial'),
-                       'libertree'   => Addon::isEnabled('libertree'),
-                       'livejournal' => Addon::isEnabled('livejournal'),
-                       'pumpio'      => Addon::isEnabled('pumpio'),
-                       'twitter'     => Addon::isEnabled('twitter'),
-                       'tumblr'      => Addon::isEnabled('tumblr'),
-                       'wordpress'   => Addon::isEnabled('wordpress'),
-               ];
-
-               $statistics = array_merge([
-                       'name'                  => $config->get('config', 'sitename'),
-                       'network'               => FRIENDICA_PLATFORM,
-                       'version'               => FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION,
-                       'registrations_open'    => $registration_open,
-                       'total_users'           => $config->get('nodeinfo', 'total_users'),
-                       'active_users_halfyear' => $config->get('nodeinfo', 'active_users_halfyear'),
-                       'active_users_monthly'  => $config->get('nodeinfo', 'active_users_monthly'),
-                       'local_posts'           => $config->get('nodeinfo', 'local_posts'),
-                       'services'              => $services,
-               ], $services);
-
-               header("Content-Type: application/json");
-               echo json_encode($statistics, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
-               $logger->debug("statistics.", ['statistics' => $statistics]);
-               exit();
-       }
-}
diff --git a/src/Module/WebFinger.php b/src/Module/WebFinger.php
new file mode 100644 (file)
index 0000000..0c1a692
--- /dev/null
@@ -0,0 +1,39 @@
+<?php
+
+namespace Friendica\Module;
+
+use Friendica\BaseModule;
+use Friendica\Core\L10n;
+use Friendica\Core\Renderer;
+use Friendica\Network\Probe;
+
+/**
+ * Web based module to perform webfinger probing
+ */
+class WebFinger extends BaseModule
+{
+       public static function content()
+       {
+               if (!local_user()) {
+                       $e = new \Friendica\Network\HTTPException\ForbiddenException(L10n::t("Only logged in users are permitted to perform a probing."));
+                       $e->httpdesc = L10n::t("Public access denied.");
+                       throw $e;
+               }
+
+               $app = self::getApp();
+
+               $addr = defaults($_GET, 'addr', '');
+               $res = '';
+
+               if (!empty($addr)) {
+                       $res = Probe::lrdd($addr);
+                       $res = print_r($res, true);
+               }
+
+               $tpl = Renderer::getMarkupTemplate('webfinger.tpl');
+               return Renderer::replaceMacros($tpl, [
+                       '$addr' => $addr,
+                       '$res'  => $res,
+               ]);
+       }
+}
diff --git a/src/Module/WellKnown/HostMeta.php b/src/Module/WellKnown/HostMeta.php
new file mode 100644 (file)
index 0000000..fd04467
--- /dev/null
@@ -0,0 +1,40 @@
+<?php
+
+namespace Friendica\Module\WellKnown;
+
+use Friendica\BaseModule;
+use Friendica\Core\Renderer;
+use Friendica\Protocol\Salmon;
+use Friendica\Util\Crypto;
+
+/**
+ * Prints the metadata for describing this host
+ * @see https://tools.ietf.org/html/rfc6415
+ */
+class HostMeta extends BaseModule
+{
+       public static function rawContent()
+       {
+               $app = self::getApp();
+               $config = $app->getConfig();
+
+               header('Content-type: text/xml');
+
+               if (!$config->get('system', 'site_pubkey', false)) {
+                       $res = Crypto::newKeypair(1024);
+
+                       $config->set('system', 'site_prvkey', $res['prvkey']);
+                       $config->set('system', 'site_pubkey', $res['pubkey']);
+               }
+
+               $tpl = Renderer::getMarkupTemplate('xrd_host.tpl');
+               echo Renderer::replaceMacros($tpl, [
+                       '$zhost'  => $app->getHostName(),
+                       '$zroot'  => $app->getBaseURL(),
+                       '$domain' => $app->getBaseURL(),
+                       '$bigkey' => Salmon::salmonKey($config->get('system', 'site_pubkey'))
+               ]);
+
+               exit();
+       }
+}
diff --git a/src/Module/WellKnown/XSocialRelay.php b/src/Module/WellKnown/XSocialRelay.php
new file mode 100644 (file)
index 0000000..a1bbeb7
--- /dev/null
@@ -0,0 +1,64 @@
+<?php
+
+namespace Friendica\Module\WellKnown;
+
+use Friendica\BaseModule;
+use Friendica\Model\Search;
+
+/**
+ * Node subscription preferences for social realy systems
+ * @see https://git.feneas.org/jaywink/social-relay/blob/master/docs/relays.md
+ */
+class XSocialRelay extends BaseModule
+{
+       public static function rawContent()
+       {
+               $app = self::getApp();
+               $config = $app->getConfig();
+
+               $subscribe = $config->get('system', 'relay_subscribe', false);
+
+               if ($subscribe) {
+                       $scope = $config->get('system', 'relay_scope', SR_SCOPE_ALL);
+               } else {
+                       $scope = SR_SCOPE_NONE;
+               }
+
+               $systemTags = [];
+               $userTags = [];
+
+               if ($scope == SR_SCOPE_TAGS) {
+                       $server_tags = $config->get('system', 'relay_server_tags');
+                       $tagitems = explode(',', $server_tags);
+
+                       /// @todo Check if it was better to use "strtolower" on the tags
+                       foreach ($tagitems AS $tag) {
+                               $systemTags[] = trim($tag, '# ');
+                       }
+
+                       if ($config->get('system', 'relay_user_tags')) {
+                               $userTags = Search::getUserTags();
+                       }
+               }
+
+               $tagList = array_unique(array_merge($systemTags, $userTags));
+
+               $relay = [
+                       'subscribe' => $subscribe,
+                       'scope'     => $scope,
+                       'tags'      => $tagList,
+                       'protocols' => [
+                               'diaspora' => [
+                                       'receive' => $app->getBaseURL() . '/receive/public'
+                               ],
+                               'dfrn'     => [
+                                       'receive' => $app->getBaseURL() . '/dfrn_notify'
+                               ]
+                       ]
+               ];
+
+               header('Content-type: application/json; charset=utf-8');
+               echo json_encode($relay, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
+               exit;
+       }
+}
diff --git a/src/Module/Xrd.php b/src/Module/Xrd.php
new file mode 100644 (file)
index 0000000..b6bd875
--- /dev/null
@@ -0,0 +1,194 @@
+<?php
+
+namespace Friendica\Module;
+
+use Friendica\BaseModule;
+use Friendica\Core\Hook;
+use Friendica\Core\Renderer;
+use Friendica\Core\System;
+use Friendica\Model\User;
+use Friendica\Protocol\Salmon;
+use Friendica\Util\Strings;
+
+/**
+ * Prints responses to /.well-known/webfinger  or /xrd requests
+ */
+class Xrd extends BaseModule
+{
+       public static function rawContent()
+       {
+               $app = self::getApp();
+
+               // @TODO: Replace with parameter from router
+               if ($app->argv[0] == 'xrd') {
+                       if (empty($_GET['uri'])) {
+                               return;
+                       }
+
+                       $uri = urldecode(Strings::escapeTags(trim($_GET['uri'])));
+                       if (defaults($_SERVER, 'HTTP_ACCEPT', '') == 'application/jrd+json') {
+                               $mode = 'json';
+                       } else {
+                               $mode = 'xml';
+                       }
+               } else {
+                       if (empty($_GET['resource'])) {
+                               return;
+                       }
+
+                       $uri = urldecode(Strings::escapeTags(trim($_GET['resource'])));
+                       if (defaults($_SERVER, 'HTTP_ACCEPT', '') == 'application/xrd+xml') {
+                               $mode = 'xml';
+                       } else {
+                               $mode = 'json';
+                       }
+               }
+
+               if (substr($uri, 0, 4) === 'http') {
+                       $name = ltrim(basename($uri), '~');
+               } else {
+                       $local = str_replace('acct:', '', $uri);
+                       if (substr($local, 0, 2) == '//') {
+                               $local = substr($local, 2);
+                       }
+
+                       $name = substr($local, 0, strpos($local, '@'));
+               }
+
+               $user = User::getByNickname($name);
+
+               if (empty($user)) {
+                       throw new \Friendica\Network\HTTPException\NotFoundException();
+               }
+
+               $profileURL = $app->getBaseURL() . '/profile/' . $user['nickname'];
+               $alias = str_replace('/profile/', '/~', $profileURL);
+
+               $addr = 'acct:' . $user['nickname'] . '@' . $app->getHostName();
+               if ($app->getURLPath()) {
+                       $addr .= '/' . $app->getURLPath();
+               }
+
+               if ($mode == 'xml') {
+                       self::printXML($addr, $alias, $profileURL, $app->getBaseURL(), $user);
+               } else {
+                       self::printJSON($addr, $alias, $profileURL, $app->getBaseURL(), $user);
+               }
+       }
+
+       private static function printJSON($uri, $alias, $orofileURL, $baseURL, $user)
+       {
+               $salmon_key = Salmon::salmonKey($user['spubkey']);
+
+               header('Access-Control-Allow-Origin: *');
+               header('Content-type: application/json; charset=utf-8');
+
+               $json = [
+                       'subject' => $uri,
+                       'aliases' => [
+                               $alias,
+                               $orofileURL,
+                       ],
+                       'links'   => [
+                               [
+                                       'rel'  => NAMESPACE_DFRN,
+                                       'href' => $orofileURL,
+                               ],
+                               [
+                                       'rel'  => NAMESPACE_FEED,
+                                       'type' => 'application/atom+xml',
+                                       'href' => $baseURL . '/dfrn_poll/' . $user['nickname'],
+                               ],
+                               [
+                                       'rel'  => 'http://webfinger.net/rel/profile-page',
+                                       'type' => 'text/html',
+                                       'href' => $orofileURL,
+                               ],
+                               [
+                                       'rel'  => 'self',
+                                       'type' => 'application/activity+json',
+                                       'href' => $orofileURL,
+                               ],
+                               [
+                                       'rel'  => 'http://microformats.org/profile/hcard',
+                                       'type' => 'text/html',
+                                       'href' => $baseURL . '/hcard/' . $user['nickname'],
+                               ],
+                               [
+                                       'rel'  => NAMESPACE_POCO,
+                                       'href' => $baseURL . '/poco/' . $user['nickname'],
+                               ],
+                               [
+                                       'rel'  => 'http://webfinger.net/rel/avatar',
+                                       'type' => 'image/jpeg',
+                                       'href' => $baseURL . '/photo/profile/' . $user['uid'] . '.jpg',
+                               ],
+                               [
+                                       'rel'  => 'http://joindiaspora.com/seed_location',
+                                       'type' => 'text/html',
+                                       'href' => $baseURL,
+                               ],
+                               [
+                                       'rel'  => 'salmon',
+                                       'href' => $baseURL . '/salmon/' . $user['nickname'],
+                               ],
+                               [
+                                       'rel'  => 'http://salmon-protocol.org/ns/salmon-replies',
+                                       'href' => $baseURL . '/salmon/' . $user['nickname'],
+                               ],
+                               [
+                                       'rel'  => 'http://salmon-protocol.org/ns/salmon-mention',
+                                       'href' => $baseURL . '/salmon/' . $user['nickname'] . '/mention',
+                               ],
+                               [
+                                       'rel'      => 'http://ostatus.org/schema/1.0/subscribe',
+                                       'template' => $baseURL . '/follow?url={uri}',
+                               ],
+                               [
+                                       'rel'  => 'magic-public-key',
+                                       'href' => 'data:application/magic-public-key,' . $salmon_key,
+                               ],
+                               [
+                                       'rel'  => 'http://purl.org/openwebauth/v1',
+                                       'type' => 'application/x-zot+json',
+                                       'href' => $baseURL . '/owa',
+                               ],
+                       ],
+               ];
+
+               echo json_encode($json);
+               exit();
+       }
+
+       private static function printXML($uri, $alias, $profileURL, $baseURL, $user)
+       {
+               $salmon_key = Salmon::salmonKey($user['spubkey']);
+
+               header('Access-Control-Allow-Origin: *');
+               header('Content-type: text/xml');
+
+               $tpl = Renderer::getMarkupTemplate('xrd_person.tpl');
+
+               $o = Renderer::replaceMacros($tpl, [
+                       '$nick'        => $user['nickname'],
+                       '$accturi'     => $uri,
+                       '$alias'       => $alias,
+                       '$profile_url' => $profileURL,
+                       '$hcard_url'   => $baseURL . '/hcard/' . $user['nickname'],
+                       '$atom'        => $baseURL . '/dfrn_poll/' . $user['nickname'],
+                       '$poco_url'    => $baseURL . '/poco/' . $user['nickname'],
+                       '$photo'       => $baseURL . '/photo/profile/' . $user['uid'] . '.jpg',
+                       '$salmon'      => $baseURL . '/salmon/' . $user['nickname'],
+                       '$salmen'      => $baseURL . '/salmon/' . $user['nickname'] . '/mention',
+                       '$subscribe'   => $baseURL . '/follow?url={uri}',
+                       '$openwebauth' => $baseURL . '/owa',
+                       '$modexp'      => 'data:application/magic-public-key,' . $salmon_key
+               ]);
+
+               $arr = ['user' => $user, 'xml' => $o];
+               Hook::callAll('personal_xrd', $arr);
+
+               echo $arr['xml'];
+               exit();
+       }
+}
index b9bad457da13b0dbd17b45b7145abc1c12597197..89c447b71470ecd302b86ae8f2f105c42c4969b2 100644 (file)
@@ -3,7 +3,7 @@
 /**
  * Throwable exceptions to return HTTP status code
  *
- * This list of Exception has be extracted from
+ * This list of Exception has been extracted from
  * here http://racksburg.com/choosing-an-http-status-code/
  */
 
@@ -11,17 +11,17 @@ namespace Friendica\Network;
 
 use Exception;
 
-class HTTPException extends Exception
+abstract class HTTPException extends Exception
 {
-       var $httpcode = 200;
-       var $httpdesc = "";
+       public $httpdesc = '';
 
-       public function __construct($message = '', $code = 0, Exception $previous = null)
+       public function __construct($message = '', Exception $previous = null)
        {
-               if ($this->httpdesc == '') {
+               parent::__construct($message, $this->code, $previous);
+
+               if (empty($this->httpdesc)) {
                        $classname = str_replace('Exception', '', str_replace('Friendica\Network\HTTPException\\', '', get_class($this)));
                        $this->httpdesc = preg_replace("|([a-z])([A-Z])|",'$1 $2', $classname);
                }
-               parent::__construct($message, $code, $previous);
        }
 }
diff --git a/src/Network/HTTPException/AcceptedException.php b/src/Network/HTTPException/AcceptedException.php
new file mode 100644 (file)
index 0000000..b8c843e
--- /dev/null
@@ -0,0 +1,10 @@
+<?php
+
+namespace Friendica\Network\HTTPException;
+
+use Friendica\Network\HTTPException;
+
+class AcceptedException extends HTTPException
+{
+       protected $code = 202;
+}
index 6fc80c909115ba09e19c09e6406c6fbdebff6239..c23d7e5a34d290ac6390b0b72cdf35a21de5a390 100644 (file)
@@ -6,5 +6,5 @@ use Friendica\Network\HTTPException;
 
 class BadGatewayException extends HTTPException
 {
-       var $httpcode = 502;
+       protected $code = 502;
 }
index dd1dc191b81f99d0bd3a770d0b55d9fd34085051..9f25c61a8f3b5e92ab52df62c95c7cab9154aae3 100644 (file)
@@ -6,5 +6,5 @@ use Friendica\Network\HTTPException;
 
 class BadRequestException extends HTTPException
 {
-       var $httpcode = 400;
+       protected $code = 400;
 }
index 1d5053c4b7e9dbcb2ebf5373de19fa016ae3aca4..5d63922c9b60836aacb5d2c9908fa0d91006d944 100644 (file)
@@ -6,5 +6,5 @@ use Friendica\Network\HTTPException;
 
 class ConflictException extends HTTPException
 {
-       var $httpcode = 409;
+       protected $code = 409;
 }
index fe932a9f0a4861fe467c34c3456227c17df44f28..7c928f34fa282f2c7c27f17cbe1a571dc0cbc984 100644 (file)
@@ -6,5 +6,5 @@ use Friendica\Network\HTTPException;
 
 class ExpectationFailedException extends HTTPException
 {
-       var $httpcode = 417;
+       protected $code = 417;
 }
index 66a063e137a47778099abdd1bd98e9e6b99300ce..f83fe524baf3bf9a32d56e3b29a1d48ecc03d3af 100644 (file)
@@ -6,5 +6,5 @@ use Friendica\Network\HTTPException;
 
 class ForbiddenException extends HTTPException
 {
-       var $httpcode = 403;
-}
\ No newline at end of file
+       protected $code = 403;
+}
index bcd98080eda8e82113e007058f0a45985c38de87..2e516485064454917c05f30b501373a85c8fc58c 100644 (file)
@@ -6,5 +6,5 @@ use Friendica\Network\HTTPException;
 
 class GatewayTimeoutException extends HTTPException
 {
-       var $httpcode = 504;
+       protected $code = 504;
 }
index 42e19e89da6e50933f2ce8832e8b50c603047a52..0f665206f9bd52fb6698c9a0e4e90cf9531bb9ec 100644 (file)
@@ -6,5 +6,5 @@ use Friendica\Network\HTTPException;
 
 class GoneException extends HTTPException
 {
-       var $httpcode = 410;
+       protected $code = 410;
 }
index f4eea4077c7b710fa9e34f3e46c0d945bd417d85..89a28bebd89f4c9dbf841a644e34f192a99eaf8a 100644 (file)
@@ -6,6 +6,6 @@ use Friendica\Network\HTTPException;
 
 class ImATeapotException extends HTTPException
 {
-       var $httpcode = 418;
+       protected $code = 418;
        var $httpdesc = "I'm A Teapot";
 }
index c049ef25bacbfbf40b484acd946bdc35ed051e2d..dca1894fb4121263cc78a8408020dbd7febadaa6 100644 (file)
@@ -6,5 +6,5 @@ use Friendica\Network\HTTPException;
 
 class InternalServerErrorException extends HTTPException
 {
-       var $httpcode = 500;
+       protected $code = 500;
 }
index 1f2f0f16bcb748eaef98f33a096d6bfca7fbd206..071cac73d08bc7c5f9d3e654c2a374d6f61735c6 100644 (file)
@@ -6,5 +6,5 @@ use Friendica\Network\HTTPException;
 
 class LenghtRequiredException extends HTTPException
 {
-       var $httpcode = 411;
+       protected $code = 411;
 }
index 82fd3e786bd1f1695efa561c33de823be3355a92..128b9dc062cc1980bac994640552e99da6e072e1 100644 (file)
@@ -6,5 +6,5 @@ use Friendica\Network\HTTPException;
 
 class MethodNotAllowedException extends HTTPException
 {
-       var $httpcode = 405;
+       protected $code = 405;
 }
diff --git a/src/Network/HTTPException/NoContentException.php b/src/Network/HTTPException/NoContentException.php
new file mode 100644 (file)
index 0000000..7bd60fb
--- /dev/null
@@ -0,0 +1,10 @@
+<?php
+
+namespace Friendica\Network\HTTPException;
+
+use Friendica\Network\HTTPException;
+
+class NoContentException extends HTTPException
+{
+       protected $code = 204;
+}
index 356bc0c545a157ab50d36ca624c9d02d31f1c335..9ef40d60b6b21bad9d387f80a62ea5b1535ff4f5 100644 (file)
@@ -6,5 +6,5 @@ use Friendica\Network\HTTPException;
 
 class NonAcceptableException extends HTTPException
 {
-       var $httpcode = 406;
+       protected $code = 406;
 }
index 2d24ccef044736e724c4f158555674dcf6c03bec..f581794796fe46f6f2ed855b36a537b488e37958 100644 (file)
@@ -4,6 +4,7 @@ namespace Friendica\Network\HTTPException;
 
 use Friendica\Network\HTTPException;
 
-class NotFoundException extends HTTPException {
-       var $httpcode = 404;
+class NotFoundException extends HTTPException
+{
+       protected $code = 404;
 }
index c0dc21c15860404a02e9cbdfbd724cbf6578b122..76cb5d42065defb003b515d320471121db1db183 100644 (file)
@@ -6,5 +6,5 @@ use Friendica\Network\HTTPException;
 
 class NotImplementedException extends HTTPException
 {
-       var $httpcode = 501;
+       protected $code = 501;
 }
diff --git a/src/Network/HTTPException/OKException.php b/src/Network/HTTPException/OKException.php
new file mode 100644 (file)
index 0000000..d506ddf
--- /dev/null
@@ -0,0 +1,10 @@
+<?php
+
+namespace Friendica\Network\HTTPException;
+
+use Friendica\Network\HTTPException;
+
+class OKException extends HTTPException
+{
+       protected $code = 200;
+}
index fd5fdbc995a072aeecd841a0f9b4095f40eed29b..325c88aa4706b402b98dc2bbde07c7b3e1e082b0 100644 (file)
@@ -6,5 +6,5 @@ use Friendica\Network\HTTPException;
 
 class PreconditionFailedException extends HTTPException
 {
-       var $httpcode = 412;
+       protected $code = 412;
 }
index 9270bc4505b6dbee4d7ec08e291107b974465772..6c0e6595d849f6aba5ab55490867289dcd41e1ab 100644 (file)
@@ -6,5 +6,5 @@ use Friendica\Network\HTTPException;
 
 class ServiceUnavaiableException extends HTTPException
 {
-       var $httpcode = 503;
+       protected $code = 503;
 }
index 093911f932917aefe9dfd9923ac5850c149ad1f3..e06d9d9cbf00a581779287f2af032d7392f10ec3 100644 (file)
@@ -6,5 +6,5 @@ use Friendica\Network\HTTPException;
 
 class TooManyRequestsException extends HTTPException
 {
-       var $httpcode = 429;
+       protected $code = 429;
 }
index a3015d412da0648e32dccdcf5bd905288582914d..eda1f071bc5d4f4677dd7e88eeb2d474c70b0b8f 100644 (file)
@@ -6,5 +6,5 @@ use Friendica\Network\HTTPException;
 
 class UnauthorizedException extends HTTPException
 {
-       var $httpcode = 401;
+       protected $code = 401;
 }
index 02852e2f929e4e821a8a5a769c74c59a7b12be6d..b33a75f7932051a2ca7ca0fb193484d7789a22c0 100644 (file)
@@ -6,5 +6,5 @@ use Friendica\Network\HTTPException;
 
 class UnprocessableEntityException extends HTTPException
 {
-       var $httpcode = 422;
+       protected $code = 422;
 }
index b0399017392cf00e1d43bc7e3392d1e726eea64e..02962dfc29a72bd04ee03d756d125f7a44fcc270 100644 (file)
@@ -6,5 +6,5 @@ use Friendica\Network\HTTPException;
 
 class UnsupportedMediaTypeException extends HTTPException
 {
-       var $httpcode = 415;
+       protected $code = 415;
 }
index b6252655acf651560314ae32dbbe0b57bc3aff07..1ceab79f65c37aa5074b03987c81982a35bb08c9 100644 (file)
@@ -359,7 +359,7 @@ class DFRN
                $ret = Item::select(Item::DELIVER_FIELDLIST, $condition);
                $items = Item::inArray($ret);
                if (!DBA::isResult($items)) {
-                       exit();
+                       return '';
                }
 
                $item = $items[0];
@@ -367,7 +367,7 @@ class DFRN
                if ($item['uid'] != 0) {
                        $owner = User::getOwnerDataById($item['uid']);
                        if (!$owner) {
-                               exit();
+                               return '';
                        }
                } else {
                        $owner = ['uid' => 0, 'nick' => 'feed-item'];
@@ -400,7 +400,7 @@ class DFRN
                                }
                        }
                } else {
-                       $root = self::entry($doc, $type, $item, $owner, true, 0, true);
+                       self::entry($doc, $type, $item, $owner, true, 0, true);
                }
 
                $atom = trim($doc->saveXML());
@@ -987,7 +987,7 @@ class DFRN
                }
 
                // Add conversation data. This is used for OStatus
-               $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
+               $conversation_href = System::baseUrl()."/display/".$item["parent-guid"];
                $conversation_uri = $conversation_href;
 
                if (isset($parent_item)) {
@@ -2212,14 +2212,13 @@ class DFRN
        /**
         * @brief Send a "poke"
         *
-        * @param array $item      the new item record
+        * @param array $item      The new item record
         * @param array $importer  Record of the importer user mixed with contact of the content
-        * @param int   $posted_id The record number of item record that was just posted
         * @return void
         * @throws \Friendica\Network\HTTPException\InternalServerErrorException
         * @todo  set proper type-hints (array?)
         */
-       private static function doPoke($item, $importer, $posted_id)
+       private static function doPoke(array $item, array $importer)
        {
                $verb = urldecode(substr($item["verb"], strpos($item["verb"], "#")+1));
                if (!$verb) {
@@ -2244,8 +2243,6 @@ class DFRN
                        if ($Blink && Strings::compareLink($Blink, System::baseUrl() . "/profile/" . $importer["nickname"])) {
                                $author = DBA::selectFirst('contact', ['name', 'thumb', 'url'], ['id' => $item['author-id']]);
 
-                               $item['id'] = $posted_id;
-
                                $parent = Item::selectFirst(['id'], ['uri' => $item['parent-uri'], 'uid' => $importer["importer_uid"]]);
                                $item["parent"] = $parent['id'];
 
@@ -2259,7 +2256,7 @@ class DFRN
                                        "to_email"     => $importer["email"],
                                        "uid"          => $importer["importer_uid"],
                                        "item"         => $item,
-                                       "link"         => System::baseUrl()."/display/".urlencode(Item::getGuidById($posted_id)),
+                                       "link"         => System::baseUrl()."/display/".urlencode($item['guid']),
                                        "source_name"  => $author["name"],
                                        "source_link"  => $author["url"],
                                        "source_photo" => $author["thumb"],
@@ -2754,7 +2751,8 @@ class DFRN
                        }
 
                        if (stristr($item["verb"], ACTIVITY_POKE)) {
-                               self::doPoke($item, $importer, $posted_id);
+                               $item['id'] = $posted_id;
+                               self::doPoke($item, $importer);
                        }
                }
        }
index 33cbb2659d8aabeec6e9d246ae4a39089f467bf6..3a7e73cee56b56bf49d841e0e1e34a0183632331 100644 (file)
@@ -400,7 +400,7 @@ class Diaspora
                                if ($no_exit) {
                                        return false;
                                } else {
-                                       System::httpExit(400);
+                                       throw new \Friendica\Network\HTTPException\BadRequestException();
                                }
                        }
 
@@ -419,7 +419,7 @@ class Diaspora
                        if ($no_exit) {
                                return false;
                        } else {
-                               System::httpExit(400);
+                               throw new \Friendica\Network\HTTPException\BadRequestException();
                        }
                }
 
@@ -445,7 +445,7 @@ class Diaspora
                        if ($no_exit) {
                                return false;
                        } else {
-                               System::httpExit(400);
+                               throw new \Friendica\Network\HTTPException\BadRequestException();
                        }
                }
 
@@ -455,7 +455,7 @@ class Diaspora
                        if ($no_exit) {
                                return false;
                        } else {
-                               System::httpExit(400);
+                               throw new \Friendica\Network\HTTPException\BadRequestException();
                        }
                }
 
@@ -465,7 +465,7 @@ class Diaspora
                        if ($no_exit) {
                                return false;
                        } else {
-                               System::httpExit(400);
+                               throw new \Friendica\Network\HTTPException\BadRequestException();
                        }
                }
 
@@ -550,7 +550,7 @@ class Diaspora
 
                if (!$base) {
                        Logger::log('unable to locate salmon data in xml');
-                       System::httpExit(400);
+                       throw new \Friendica\Network\HTTPException\BadRequestException();
                }
 
 
@@ -588,7 +588,7 @@ class Diaspora
 
                if (!$author_link) {
                        Logger::log('Could not retrieve author URI.');
-                       System::httpExit(400);
+                       throw new \Friendica\Network\HTTPException\BadRequestException();
                }
                // Once we have the author URI, go to the web and try to find their public key
                // (first this will look it up locally if it is in the fcontact cache)
@@ -599,14 +599,14 @@ class Diaspora
 
                if (!$key) {
                        Logger::log('Could not retrieve author key.');
-                       System::httpExit(400);
+                       throw new \Friendica\Network\HTTPException\BadRequestException();
                }
 
                $verify = Crypto::rsaVerify($signed_data, $signature, $key);
 
                if (!$verify) {
                        Logger::log('Message did not verify. Discarding.');
-                       System::httpExit(400);
+                       throw new \Friendica\Network\HTTPException\BadRequestException();
                }
 
                Logger::log('Message verified.');
index 8dc3304f2bd7341451bcce63aab382393404a68f..6f1172666ac69613081fb7be7f76880c6a7f57b1 100644 (file)
@@ -610,8 +610,8 @@ class ApiTest extends DatabaseTest
        public function testApiErrorWithJson()
        {
                $this->assertEquals(
-                       '{"status":{"error":"error_message","code":"200 Friendica\\\\Network\\\\HTTP","request":""}}',
-                       api_error('json', new HTTPException('error_message'))
+                       '{"status":{"error":"error_message","code":"200 OK","request":""}}',
+                       api_error('json', new HTTPException\OKException('error_message'))
                );
        }
 
@@ -628,10 +628,10 @@ class ApiTest extends DatabaseTest
                                'xmlns:friendica="http://friendi.ca/schema/api/1/" '.
                                'xmlns:georss="http://www.georss.org/georss">'."\n".
                        '  <error>error_message</error>'."\n".
-                       '  <code>200 Friendica\Network\HTTP</code>'."\n".
+                       '  <code>200 OK</code>'."\n".
                        '  <request/>'."\n".
                        '</status>'."\n",
-                       api_error('xml', new HTTPException('error_message'))
+                       api_error('xml', new HTTPException\OKException('error_message'))
                );
        }
 
@@ -648,10 +648,10 @@ class ApiTest extends DatabaseTest
                                'xmlns:friendica="http://friendi.ca/schema/api/1/" '.
                                'xmlns:georss="http://www.georss.org/georss">'."\n".
                        '  <error>error_message</error>'."\n".
-                       '  <code>200 Friendica\Network\HTTP</code>'."\n".
+                       '  <code>200 OK</code>'."\n".
                        '  <request/>'."\n".
                        '</status>'."\n",
-                       api_error('rss', new HTTPException('error_message'))
+                       api_error('rss', new HTTPException\OKException('error_message'))
                );
        }
 
@@ -668,10 +668,10 @@ class ApiTest extends DatabaseTest
                                'xmlns:friendica="http://friendi.ca/schema/api/1/" '.
                                'xmlns:georss="http://www.georss.org/georss">'."\n".
                        '  <error>error_message</error>'."\n".
-                       '  <code>200 Friendica\Network\HTTP</code>'."\n".
+                       '  <code>200 OK</code>'."\n".
                        '  <request/>'."\n".
                        '</status>'."\n",
-                       api_error('atom', new HTTPException('error_message'))
+                       api_error('atom', new HTTPException\OKException('error_message'))
                );
        }
 
index 749ae77c2a2554416600e24a485c3c7b73ef50ec..cb980b47e90698639f71a1381ba7c19b046e2db5 100644 (file)
@@ -33,7 +33,7 @@ class BaseObjectTest extends TestCase
                $this->setUpVfsDir();
                $this->mockApp($this->root);
 
-               $this->assertNull($baseObject->setApp($this->app));
+               $baseObject->setApp($this->app);
                $this->assertEquals($this->app, $baseObject->getApp());
        }
 
@@ -45,7 +45,6 @@ class BaseObjectTest extends TestCase
         */
        public function testGetAppFailed()
        {
-               $baseObject = new BaseObject();
-               $baseObject->getApp();
+               BaseObject::getApp();
        }
 }
diff --git a/tests/src/Console/AutomaticInstallationConsoleTest.php b/tests/src/Console/AutomaticInstallationConsoleTest.php
new file mode 100644 (file)
index 0000000..5ea349f
--- /dev/null
@@ -0,0 +1,646 @@
+<?php
+
+namespace Friendica\Test\src\Console;
+
+use Friendica\Console\AutomaticInstallation;
+use Friendica\Core\Config\Cache\ConfigCache;
+use Friendica\Core\Installer;
+use Friendica\Core\Logger;
+use Friendica\Test\Util\DBAMockTrait;
+use Friendica\Test\Util\DBStructureMockTrait;
+use Friendica\Test\Util\L10nMockTrait;
+use Friendica\Test\Util\RendererMockTrait;
+use Friendica\Util\BaseURL;
+use Friendica\Util\Logger\VoidLogger;
+use org\bovigo\vfs\vfsStream;
+use org\bovigo\vfs\vfsStreamFile;
+
+/**
+ * @runTestsInSeparateProcesses
+ * @preserveGlobalState disabled
+ * @requires PHP 7.0
+ */
+class AutomaticInstallationConsoleTest extends ConsoleTest
+{
+       use L10nMockTrait;
+       use DBAMockTrait;
+       use DBStructureMockTrait;
+       use RendererMockTrait;
+
+       /**
+        * @var vfsStreamFile Assert file without DB credentials
+        */
+       private $assertFile;
+       /**
+        * @var vfsStreamFile Assert file with DB credentials
+        */
+       private $assertFileDb;
+
+       /**
+        * @var ConfigCache The configuration cache to check after each test
+        */
+       private $configCache;
+
+       public function setUp()
+       {
+               parent::setUp();
+
+               if ($this->root->hasChild('config' . DIRECTORY_SEPARATOR . 'local.config.php')) {
+                       $this->root->getChild('config')
+                               ->removeChild('local.config.php');
+               }
+
+               $this->mockL10nT();
+
+               $this->configCache = new ConfigCache();
+               $this->configCache->set('system', 'basepath', $this->root->url());
+               $this->configCache->set('config', 'php_path', trim(shell_exec('which php')));
+               $this->configCache->set('system', 'theme', 'smarty3');
+
+               $this->mockApp($this->root, true);
+
+               $this->configMock->shouldReceive('set')->andReturnUsing(function ($cat, $key, $value) {
+                       if ($key !== 'basepath') {
+                               return $this->configCache->set($cat, $key, $value);
+                       } else {
+                               return true;
+                       }
+               });
+
+               $this->configMock->shouldReceive('has')->andReturn(true);
+               $this->configMock->shouldReceive('get')->andReturnUsing(function ($cat, $key) {
+                       return $this->configCache->get($cat, $key);
+               });
+               $this->configMock->shouldReceive('load')->andReturnUsing(function ($config, $overwrite = false) {
+                       return $this->configCache->load($config, $overwrite);
+               });
+
+               $this->mode->shouldReceive('isInstall')->andReturn(true);
+               Logger::init(new VoidLogger());
+       }
+
+       /**
+        * Returns the dataset for each automatic installation test
+        *
+        * @return array the dataset
+        */
+       public function dataInstaller()
+       {
+               return [
+                       'empty' => [
+                               'data' => [
+                                       'database' => [
+                                               'hostname'    => '',
+                                               'username'    => '',
+                                               'password'    => '',
+                                               'database'    => '',
+                                               'port'        => '',
+                                       ],
+                                       'config' => [
+                                               'php_path'    => '',
+                                               'hostname'    => 'friendica.local',
+                                               'admin_email' => '',
+                                       ],
+                                       'system' => [
+                                               'basepath'    => '',
+                                               'urlpath'     => '',
+                                               'url'         => 'http://friendica.local',
+                                               'ssl_policy'  => 0,
+                                               'default_timezone' => '',
+                                               'language'    => '',
+                                       ],
+                               ],
+                       ],
+                       'normal' => [
+                               'data' => [
+                                       'database' => [
+                                               'hostname'    => 'testhost',
+                                               'port'        => 3306,
+                                               'username'    => 'friendica',
+                                               'password'    => 'a password',
+                                               'database'    => 'database',
+                                       ],
+                                       'config' => [
+                                               'php_path'    => '',
+                                               'hostname'    => 'friendica.local',
+                                               'admin_email' => 'admin@philipp.info',
+                                       ],
+                                       'system' => [
+                                               'urlpath'     => 'test/it',
+                                               'url'         => 'http://friendica.local/test/it',
+                                               'basepath'    => '',
+                                               'ssl_policy'  => '2',
+                                               'default_timezone' => 'en',
+                                               'language'    => 'Europe/Berlin',
+                                       ],
+                               ],
+                       ],
+                       'special' => [
+                               'data' => [
+                                       'database' => [
+                                               'hostname'    => 'testhost.new.domain',
+                                               'port'        => 3341,
+                                               'username'    => 'fr"§%ica',
+                                               'password'    => '$%\"gse',
+                                               'database'    => 'db',
+                                       ],
+                                       'config' => [
+                                               'php_path'    => '',
+                                               'hostname'    => 'friendica.local',
+                                               'admin_email' => 'admin@philipp.info',
+                                       ],
+                                       'system' => [
+                                               'urlpath'     => 'test/it',
+                                               'url'         => 'https://friendica.local/test/it',
+                                               'basepath'    => '',
+                                               'ssl_policy'  => '1',
+                                               'default_timezone' => 'en',
+                                               'language'    => 'Europe/Berlin',
+                                       ],
+                               ],
+                       ],
+               ];
+       }
+
+       private function assertFinished($txt, $withconfig = false, $copyfile = false)
+       {
+               $cfg = '';
+
+               if ($withconfig) {
+                       $cfg = <<<CFG
+
+
+Creating config file...
+
+ Complete!
+CFG;
+               }
+
+               if ($copyfile) {
+                       $cfg = <<<CFG
+
+
+Copying config file...
+
+ Complete!
+CFG;
+               }
+
+               $finished = <<<FIN
+Initializing setup...
+
+ Complete!
+
+
+Checking environment...
+
+ NOTICE: Not checking .htaccess/URL-Rewrite during CLI installation.
+
+ Complete!
+{$cfg}
+
+
+Checking database...
+
+ Complete!
+
+
+Inserting data into database...
+
+ Complete!
+
+
+Installing theme
+
+ Complete
+
+
+
+Installation is finished
+
+
+FIN;
+               $this->assertEquals($finished, $txt);
+       }
+
+       private function assertStuckDB($txt)
+       {
+               $finished = <<<FIN
+Initializing setup...
+
+ Complete!
+
+
+Checking environment...
+
+ NOTICE: Not checking .htaccess/URL-Rewrite during CLI installation.
+
+ Complete!
+
+
+Creating config file...
+
+ Complete!
+
+
+Checking database...
+
+[Error] --------
+Could not connect to database.: 
+
+
+FIN;
+
+               $this->assertEquals($finished, $txt);
+       }
+
+       private function assertStuckURL($txt)
+       {
+               $finished = <<<FIN
+Initializing setup...
+
+ Complete!
+
+
+Checking environment...
+
+ NOTICE: Not checking .htaccess/URL-Rewrite during CLI installation.
+
+ Complete!
+
+
+Creating config file...
+
+The Friendica URL has to be set during CLI installation.
+
+FIN;
+
+               $this->assertEquals($finished, $txt);
+       }
+
+       /**
+        * Asserts one config entry
+        *
+        * @param string     $cat           The category to test
+        * @param string     $key           The key to test
+        * @param null|array $assertion     The asserted value (null = empty, or array/string)
+        * @param string     $default_value The default value
+        */
+       public function assertConfigEntry($cat, $key, $assertion = null, $default_value = null)
+       {
+               if (!empty($assertion[$cat][$key])) {
+                       $this->assertEquals($assertion[$cat][$key], $this->configCache->get($cat, $key));
+               } elseif (!empty($assertion) && !is_array($assertion)) {
+                       $this->assertEquals($assertion, $this->configCache->get($cat, $key));
+               } elseif (!empty($default_value)) {
+                       $this->assertEquals($default_value, $this->configCache->get($cat, $key));
+               } else {
+                       $this->assertEmpty($this->configCache->get($cat, $key), $this->configCache->get($cat, $key));
+               }
+       }
+
+       /**
+        * Asserts all config entries
+        *
+        * @param null|array $assertion    The optional assertion array
+        * @param boolean    $saveDb       True, if the db credentials should get saved to the file
+        * @param boolean    $default      True, if we use the default values
+        * @param boolean    $defaultDb    True, if we use the default value for the DB
+        * @param boolean    $realBasepath True, if we use the real basepath of the installation, not the mocked one
+        */
+       public function assertConfig($assertion = null, $saveDb = false, $default = true, $defaultDb = true, $realBasepath = false)
+       {
+               if (!empty($assertion['database']['hostname'])) {
+                       $assertion['database']['hostname'] .= (!empty($assertion['database']['port']) ? ':' . $assertion['database']['port'] : '');
+               }
+
+               $this->assertConfigEntry('database', 'hostname', ($saveDb) ? $assertion : null, (!$saveDb || $defaultDb) ? Installer::DEFAULT_HOST : null);
+               $this->assertConfigEntry('database', 'username', ($saveDb) ? $assertion : null);
+               $this->assertConfigEntry('database', 'password', ($saveDb) ? $assertion : null);
+               $this->assertConfigEntry('database', 'database', ($saveDb) ? $assertion : null);
+
+               $this->assertConfigEntry('config', 'admin_email', $assertion);
+               $this->assertConfigEntry('config', 'php_path', trim(shell_exec('which php')));
+               $this->assertConfigEntry('config', 'hostname', $assertion);
+
+               $this->assertConfigEntry('system', 'default_timezone', $assertion, ($default) ? Installer::DEFAULT_TZ : null);
+               $this->assertConfigEntry('system', 'language', $assertion, ($default) ? Installer::DEFAULT_LANG : null);
+               $this->assertConfigEntry('system', 'url', $assertion);
+               $this->assertConfigEntry('system', 'urlpath', $assertion);
+               $this->assertConfigEntry('system', 'ssl_policy', $assertion, ($default) ? BaseURL::DEFAULT_SSL_SCHEME : null);
+               $this->assertConfigEntry('system', 'basepath', ($realBasepath) ? $this->root->url() : $assertion);
+       }
+
+       /**
+        * Test the automatic installation without any parameter/setting
+        * Should stuck because of missing hostname
+        */
+       public function testEmpty()
+       {
+               $console = new AutomaticInstallation($this->consoleArgv);
+
+               $txt = $this->dumpExecute($console);
+
+               $this->assertStuckURL($txt);
+       }
+
+       /**
+        * Test the automatic installation without any parameter/setting
+        * except URL
+        */
+       public function testEmptyWithURL()
+       {
+               $this->mockConnect(true, 1);
+               $this->mockConnected(true, 1);
+               $this->mockExistsTable('user', false, 1);
+               $this->mockUpdate([$this->root->url(), false, true, true], null, 1);
+
+               $this->mockGetMarkupTemplate('local.config.tpl', 'testTemplate', 1);
+               $this->mockReplaceMacros('testTemplate', \Mockery::any(), false, '', 1);
+
+               $console = new AutomaticInstallation($this->consoleArgv);
+               $console->setOption('url', 'http://friendica.local');
+
+               $txt = $this->dumpExecute($console);
+
+               $this->assertFinished($txt, true, false);
+               $this->assertTrue($this->root->hasChild('config' . DIRECTORY_SEPARATOR . 'local.config.php'));
+
+               $this->assertConfig(['config' => ['hostname' => 'friendica.local'], 'system' => ['url' => 'http://friendica.local', 'ssl_policy' => 0, 'urlPath' => '']], false, true, true, true);
+       }
+
+       /**
+        * Test the automatic installation with a prepared config file
+        * @dataProvider dataInstaller
+        */
+       public function testWithConfig(array $data)
+       {
+               $this->mockConnect(true, 1);
+               $this->mockConnected(true, 1);
+               $this->mockExistsTable('user', false, 1);
+               $this->mockUpdate([$this->root->url(), false, true, true], null, 1);
+
+               $conf = function ($cat, $key) use ($data) {
+                       if ($cat == 'database' && $key == 'hostname' && !empty($data['database']['port'])) {
+                               return $data[$cat][$key] . ':' . $data['database']['port'];
+                       }
+                       return $data[$cat][$key];
+               };
+
+               $config = <<<CONF
+<?php
+
+// Local configuration
+
+// If you're unsure about what any of the config keys below do, please check the config/defaults.config.php for detailed
+// documentation of their data type and behavior.
+
+return [
+       'database' => [
+               'hostname' => '{$conf('database', 'hostname')}',
+               'username' => '{$conf('database', 'username')}',
+               'password' => '{$conf('database', 'password')}',
+               'database' => '{$conf('database', 'database')}',
+               'charset' => 'utf8mb4',
+       ],
+
+       // ****************************************************************
+       // The configuration below will be overruled by the admin panel.
+       // Changes made below will only have an effect if the database does
+       // not contain any configuration for the friendica system.
+       // ****************************************************************
+
+       'config' => [
+               'admin_email' => '{$conf('config', 'admin_email')}',
+               'hostname' => '{$conf('config', 'hostname')}',
+               'sitename' => 'Friendica Social Network',
+               'register_policy' => \Friendica\Module\Register::OPEN,
+               'register_text' => '',
+       ],
+       'system' => [
+               'basepath' => '{$conf('system', 'basepath')}',
+               'urlpath' => '{$conf('system', 'urlpath')}',
+               'url' => '{$conf('system', 'url')}',
+               'ssl_policy' => '{$conf('system', 'ssl_policy')}',
+               'default_timezone' => '{$conf('system', 'default_timezone')}',
+               'language' => '{$conf('system', 'language')}',
+       ],
+];
+CONF;
+
+               vfsStream::newFile('prepared.config.php')
+                       ->at($this->root)
+                       ->setContent($config);
+
+               $console = new AutomaticInstallation($this->consoleArgv);
+               $console->setOption('f', 'prepared.config.php');
+
+               $txt = $this->dumpExecute($console);
+
+               $this->assertFinished($txt, false, true);
+
+               $this->assertTrue($this->root->hasChild('config' . DIRECTORY_SEPARATOR . 'local.config.php'));
+               $this->assertEquals($config, file_get_contents($this->root->getChild('config' . DIRECTORY_SEPARATOR . 'local.config.php')->url()));
+
+               $this->assertConfig($data, true, false, false);
+       }
+
+       /**
+        * Test the automatic installation with environment variables
+        * Includes saving the DB credentials to the file
+        * @dataProvider dataInstaller
+        */
+       public function testWithEnvironmentAndSave(array $data)
+       {
+               $this->mockConnect(true, 1);
+               $this->mockConnected(true, 1);
+               $this->mockExistsTable('user', false, 1);
+               $this->mockUpdate([$this->root->url(), false, true, true], null, 1);
+
+               $this->mockGetMarkupTemplate('local.config.tpl', 'testTemplate', 1);
+               $this->mockReplaceMacros('testTemplate', \Mockery::any(), false, '', 1);
+
+               $this->assertTrue(putenv('MYSQL_HOST='     . $data['database']['hostname']));
+               $this->assertTrue(putenv('MYSQL_PORT='     . $data['database']['port']));
+               $this->assertTrue(putenv('MYSQL_DATABASE=' . $data['database']['database']));
+               $this->assertTrue(putenv('MYSQL_USERNAME=' . $data['database']['username']));
+               $this->assertTrue(putenv('MYSQL_PASSWORD=' . $data['database']['password']));
+
+               $this->assertTrue(putenv('FRIENDICA_HOSTNAME='   . $data['config']['hostname']));
+               $this->assertTrue(putenv('FRIENDICA_BASE_PATH='  . $data['system']['basepath']));
+               $this->assertTrue(putenv('FRIENDICA_URL='        . $data['system']['url']));
+               $this->assertTrue(putenv('FRIENDICA_PHP_PATH='   . $data['config']['php_path']));
+               $this->assertTrue(putenv('FRIENDICA_ADMIN_MAIL=' . $data['config']['admin_email']));
+               $this->assertTrue(putenv('FRIENDICA_TZ='         . $data['system']['default_timezone']));
+               $this->assertTrue(putenv('FRIENDICA_LANG='       . $data['system']['language']));
+
+               $console = new AutomaticInstallation($this->consoleArgv);
+               $console->setOption('savedb', true);
+
+               $txt = $this->dumpExecute($console);
+
+               $this->assertFinished($txt, true);
+               $this->assertConfig($data, true, true, false, true);
+       }
+
+       /**
+        * Test the automatic installation with environment variables
+        * Don't save the db credentials to the file
+        * @dataProvider dataInstaller
+        */
+       public function testWithEnvironmentWithoutSave(array $data)
+       {
+               $this->mockConnect(true, 1);
+               $this->mockConnected(true, 1);
+               $this->mockExistsTable('user', false, 1);
+               $this->mockUpdate([$this->root->url(), false, true, true], null, 1);
+
+               $this->mockGetMarkupTemplate('local.config.tpl', 'testTemplate', 1);
+               $this->mockReplaceMacros('testTemplate', \Mockery::any(), false, '', 1);
+
+               $this->assertTrue(putenv('MYSQL_HOST=' . $data['database']['hostname']));
+               $this->assertTrue(putenv('MYSQL_PORT=' . $data['database']['port']));
+               $this->assertTrue(putenv('MYSQL_DATABASE=' . $data['database']['database']));
+               $this->assertTrue(putenv('MYSQL_USERNAME=' . $data['database']['username']));
+               $this->assertTrue(putenv('MYSQL_PASSWORD=' . $data['database']['password']));
+
+               $this->assertTrue(putenv('FRIENDICA_HOSTNAME='   . $data['config']['hostname']));
+               $this->assertTrue(putenv('FRIENDICA_BASE_PATH='  . $data['system']['basepath']));
+               $this->assertTrue(putenv('FRIENDICA_URL='        . $data['system']['url']));
+               $this->assertTrue(putenv('FRIENDICA_PHP_PATH='   . $data['config']['php_path']));
+               $this->assertTrue(putenv('FRIENDICA_ADMIN_MAIL=' . $data['config']['admin_email']));
+               $this->assertTrue(putenv('FRIENDICA_TZ='         . $data['system']['default_timezone']));
+               $this->assertTrue(putenv('FRIENDICA_LANG='       . $data['system']['language']));
+
+               $console = new AutomaticInstallation($this->consoleArgv);
+
+               $txt = $this->dumpExecute($console);
+
+               $this->assertFinished($txt, true);
+               $this->assertConfig($data, false, true, false, true);
+       }
+
+       /**
+        * Test the automatic installation with arguments
+        * @dataProvider dataInstaller
+        */
+       public function testWithArguments(array $data)
+       {
+               $this->mockConnect(true, 1);
+               $this->mockConnected(true, 1);
+               $this->mockExistsTable('user', false, 1);
+               $this->mockUpdate([$this->root->url(), false, true, true], null, 1);
+
+               $this->mockGetMarkupTemplate('local.config.tpl', 'testTemplate', 1);
+               $this->mockReplaceMacros('testTemplate', \Mockery::any(), false, '', 1);
+
+               $console = new AutomaticInstallation($this->consoleArgv);
+
+               $option = function($var, $cat, $key) use ($data, $console) {
+                       if (!empty($data[$cat][$key])) {
+                               $console->setOption($var, $data[$cat][$key]);
+                       }
+               };
+               $option('dbhost'    , 'database', 'hostname');
+               $option('dbport'    , 'database', 'port');
+               $option('dbuser'    , 'database', 'username');
+               $option('dbpass'    , 'database', 'password');
+               $option('dbdata'    , 'database', 'database');
+               $option('url'       , 'system'  , 'url');
+               $option('phppath'   , 'config'  , 'php_path');
+               $option('admin'     , 'config'  , 'admin_email');
+               $option('tz'        , 'system'  , 'default_timezone');
+               $option('lang'      , 'system'  , 'language');
+               $option('basepath'  , 'system'  , 'basepath');
+
+               $txt = $this->dumpExecute($console);
+
+               $this->assertFinished($txt, true);
+               $this->assertConfig($data, true, true, true, true);
+       }
+
+       /**
+        * Test the automatic installation with a wrong database connection
+        */
+       public function testNoDatabaseConnection()
+       {
+               $this->mockConnect(false, 1);
+
+               $this->mockGetMarkupTemplate('local.config.tpl', 'testTemplate', 1);
+               $this->mockReplaceMacros('testTemplate', \Mockery::any(), false, '', 1);
+
+               $console = new AutomaticInstallation($this->consoleArgv);
+               $console->setOption('url', 'http://friendica.local');
+
+               $txt = $this->dumpExecute($console);
+
+               $this->assertStuckDB($txt);
+               $this->assertTrue($this->root->hasChild('config' . DIRECTORY_SEPARATOR . 'local.config.php'));
+
+               $this->assertConfig(['config' => ['hostname' => 'friendica.local'], 'system' => ['url' => 'http://friendica.local', 'ssl_policy' => 0, 'urlpath' => '']], false, true, false, true);
+       }
+
+       public function testGetHelp()
+       {
+               // Usable to purposely fail if new commands are added without taking tests into account
+               $theHelp = <<<HELP
+Installation - Install Friendica automatically
+Synopsis
+       bin/console autoinstall [-h|--help|-?] [-v] [-a] [-f]
+
+Description
+    Installs Friendica with data based on the local.config.php file or environment variables
+
+Notes
+    Not checking .htaccess/URL-Rewrite during CLI installation.
+
+Options
+    -h|--help|-?            Show help information
+    -v                      Show more debug information.
+    -a                      All setup checks are required (except .htaccess)
+    -f|--file <config>      prepared config file (e.g. "config/local.config.php" itself) which will override every other config option - except the environment variables)
+    -s|--savedb               Save the DB credentials to the file (if environment variables is used)
+    -H|--dbhost <host>        The host of the mysql/mariadb database (env MYSQL_HOST)
+    -p|--dbport <port>        The port of the mysql/mariadb database (env MYSQL_PORT)
+    -d|--dbdata <database>    The name of the mysql/mariadb database (env MYSQL_DATABASE)
+    -U|--dbuser <username>    The username of the mysql/mariadb database login (env MYSQL_USER or MYSQL_USERNAME)
+    -P|--dbpass <password>    The password of the mysql/mariadb database login (env MYSQL_PASSWORD)
+    -U|--url <url>            The full base URL of Friendica - f.e. 'https://friendica.local/sub' (env FRIENDICA_URL) 
+    -B|--phppath <php_path>   The path of the PHP binary (env FRIENDICA_PHP_PATH)
+    -b|--basepath <base_path> The basepath of Friendica (env FRIENDICA_BASE_PATH)
+    -t|--tz <timezone>        The timezone of Friendica (env FRIENDICA_TZ)
+    -L|--lang <language>      The language of Friendica (env FRIENDICA_LANG)
+Environment variables
+   MYSQL_HOST                  The host of the mysql/mariadb database (mandatory if mysql and environment is used)
+   MYSQL_PORT                  The port of the mysql/mariadb database
+   MYSQL_USERNAME|MYSQL_USER   The username of the mysql/mariadb database login (MYSQL_USERNAME is for mysql, MYSQL_USER for mariadb)
+   MYSQL_PASSWORD              The password of the mysql/mariadb database login
+   MYSQL_DATABASE              The name of the mysql/mariadb database
+   FRIENDICA_URL               The full base URL of Friendica - f.e. 'https://friendica.local/sub'
+   FRIENDICA_PHP_PATH          The path of the PHP binary - leave empty for auto detection
+   FRIENDICA_BASE_PATH         The basepath of Friendica - leave empty for auto detection
+   FRIENDICA_ADMIN_MAIL        The admin email address of Friendica (this email will be used for admin access)
+   FRIENDICA_TZ                The timezone of Friendica
+   FRIENDICA_LANG              The langauge of Friendica
+   
+Examples
+       bin/console autoinstall -f 'input.config.php
+               Installs Friendica with the prepared 'input.config.php' file
+
+       bin/console autoinstall --savedb
+               Installs Friendica with environment variables and saves them to the 'config/local.config.php' file
+
+       bin/console autoinstall -h localhost -p 3365 -U user -P passwort1234 -d friendica
+               Installs Friendica with a local mysql database with credentials
+
+HELP;
+
+               $console = new AutomaticInstallation($this->consoleArgv);
+               $console->setOption('help', true);
+
+               $txt = $this->dumpExecute($console);
+
+               $this->assertEquals($theHelp, $txt);
+       }
+}
diff --git a/tests/src/Console/ConfigConsoleTest.php b/tests/src/Console/ConfigConsoleTest.php
new file mode 100644 (file)
index 0000000..8658097
--- /dev/null
@@ -0,0 +1,193 @@
+<?php
+
+namespace Friendica\Test\src\Console;
+
+use Friendica\App\Mode;
+use Friendica\Console\Config;
+
+/**
+ * @runTestsInSeparateProcesses
+ * @preserveGlobalState disabled
+ * @requires PHP 7.0
+ */
+class ConfigConsoleTest extends ConsoleTest
+{
+       protected function setUp()
+       {
+               parent::setUp();
+
+               $this->mockApp($this->root);
+
+               \Mockery::getConfiguration()->setConstantsMap([
+                       Mode::class => [
+                               'DBCONFIGAVAILABLE' => 0
+                       ]
+               ]);
+
+               $this->mode
+                       ->shouldReceive('has')
+                       ->andReturn(true);
+
+       }
+
+       function testSetGetKeyValue() {
+               $this->configMock
+                       ->shouldReceive('set')
+                       ->with('config', 'test', 'now')
+                       ->andReturn(true)
+                       ->once();
+               $this->configMock
+                       ->shouldReceive('get')
+                       ->with('config', 'test')
+                       ->andReturn('now')
+                       ->twice();
+
+               $console = new Config($this->consoleArgv);
+               $console->setArgument(0, 'config');
+               $console->setArgument(1, 'test');
+               $console->setArgument(2, 'now');
+               $txt = $this->dumpExecute($console);
+               $this->assertEquals("config.test <= now\n", $txt);
+
+               $this->configMock
+                       ->shouldReceive('get')
+                       ->with('config', 'test')
+                       ->andReturn('now')
+                       ->once();
+
+               $console = new Config($this->consoleArgv);
+               $console->setArgument(0, 'config');
+               $console->setArgument(1, 'test');
+               $txt = $this->dumpExecute($console);
+               $this->assertEquals("config.test => now\n", $txt);
+
+               $this->configMock
+                       ->shouldReceive('get')
+                       ->with('config', 'test')
+                       ->andReturn(null)
+                       ->once();
+
+               $console = new Config($this->consoleArgv);
+               $console->setArgument(0, 'config');
+               $console->setArgument(1, 'test');
+               $txt = $this->dumpExecute($console);
+               $this->assertEquals("config.test => \n", $txt);
+       }
+
+       function testSetArrayValue() {
+               $testArray = [1, 2, 3];
+               $this->configMock
+                       ->shouldReceive('get')
+                       ->with('config', 'test')
+                       ->andReturn($testArray)
+                       ->once();
+
+               $console = new Config($this->consoleArgv);
+               $console->setArgument(0, 'config');
+               $console->setArgument(1, 'test');
+               $console->setArgument(2, 'now');
+               $txt = $this->dumpExecute($console);
+
+               $this->assertEquals("[Error] config.test is an array and can't be set using this command.\n", $txt);
+       }
+
+       function testTooManyArguments() {
+               $console = new Config($this->consoleArgv);
+               $console->setArgument(0, 'config');
+               $console->setArgument(1, 'test');
+               $console->setArgument(2, 'it');
+               $console->setArgument(3, 'now');
+               $txt = $this->dumpExecute($console);
+               $assertion = '[Warning] Too many arguments';
+               $firstline = substr($txt, 0, strlen($assertion));
+               $this->assertEquals($assertion, $firstline);
+       }
+
+       function testVerbose() {
+               $this->configMock
+                       ->shouldReceive('get')
+                       ->with('test', 'it')
+                       ->andReturn('now')
+                       ->once();
+               $console = new Config($this->consoleArgv);
+               $console->setArgument(0, 'test');
+               $console->setArgument(1, 'it');
+               $console->setOption('v', 1);
+               $executable = $this->consoleArgv[0];
+               $assertion = <<<CONF
+Executable: {$executable}
+Class: Friendica\Console\Config
+Arguments: array (
+  0 => 'test',
+  1 => 'it',
+)
+Options: array (
+  'v' => 1,
+)
+test.it => now
+
+CONF;
+               $txt = $this->dumpExecute($console);
+               $this->assertEquals($assertion, $txt);
+       }
+
+       function testUnableToSet() {
+               $this->configMock
+                       ->shouldReceive('set')
+                       ->with('test', 'it', 'now')
+                       ->andReturn(false)
+                       ->once();
+               $this->configMock
+                       ->shouldReceive('get')
+                       ->with('test', 'it')
+                       ->andReturn(NULL)
+                       ->once();
+               $console = new Config();
+               $console->setArgument(0, 'test');
+               $console->setArgument(1, 'it');
+               $console->setArgument(2, 'now');
+               $txt = $this->dumpExecute($console);
+               $this->assertSame("Unable to set test.it\n", $txt);
+       }
+
+       public function testGetHelp()
+       {
+               // Usable to purposely fail if new commands are added without taking tests into account
+               $theHelp = <<<HELP
+console config - Manage site configuration
+Synopsis
+       bin/console config [-h|--help|-?] [-v]
+       bin/console config <category> [-h|--help|-?] [-v]
+       bin/console config <category> <key> [-h|--help|-?] [-v]
+       bin/console config <category> <key> <value> [-h|--help|-?] [-v]
+
+Description
+       bin/console config
+               Lists all config values
+
+       bin/console config <category>
+               Lists all config values in the provided category
+
+       bin/console config <category> <key>
+               Shows the value of the provided key in the category
+
+       bin/console config <category> <key> <value>
+               Sets the value of the provided key in the category
+
+Notes:
+       Setting config entries which are manually set in config/local.config.php may result in
+       conflict between database settings and the manual startup settings.
+
+Options
+    -h|--help|-? Show help information
+    -v           Show more debug information.
+
+HELP;
+               $console = new Config($this->consoleArgv);
+               $console->setOption('help', true);
+
+               $txt = $this->dumpExecute($console);
+
+               $this->assertEquals($txt, $theHelp);
+       }
+}
diff --git a/tests/src/Console/ConsoleTest.php b/tests/src/Console/ConsoleTest.php
new file mode 100644 (file)
index 0000000..21979e7
--- /dev/null
@@ -0,0 +1,46 @@
+<?php
+
+namespace Friendica\Test\src\Console;
+
+use Asika\SimpleConsole\Console;
+use Friendica\Test\MockedTest;
+use Friendica\Test\Util\AppMockTrait;
+use Friendica\Test\Util\Intercept;
+use Friendica\Test\Util\VFSTrait;
+
+abstract class ConsoleTest extends MockedTest
+{
+       use VFSTrait;
+       use AppMockTrait;
+
+       /**
+        * @var array The default argv for a Console Instance
+        */
+       protected $consoleArgv = [ 'consoleTest.php' ];
+
+       protected function setUp()
+       {
+               parent::setUp();
+
+               Intercept::setUp();
+
+               $this->setUpVfsDir();
+       }
+
+       /**
+        * Dumps the execution of an console output to a string and returns it
+        *
+        * @param Console $console The current console instance
+        *
+        * @return string the output of the execution
+        */
+       protected function dumpExecute($console)
+       {
+               Intercept::reset();
+               $console->execute();
+               $returnStr = Intercept::$cache;
+               Intercept::reset();
+
+               return $returnStr;
+       }
+}
diff --git a/tests/src/Console/ServerBlockConsoleTest.php b/tests/src/Console/ServerBlockConsoleTest.php
new file mode 100644 (file)
index 0000000..11856ea
--- /dev/null
@@ -0,0 +1,337 @@
+<?php
+
+namespace Friendica\Test\src\Console;
+
+use Friendica\Console\ServerBlock;
+
+/**
+ * @runTestsInSeparateProcesses
+ * @preserveGlobalState disabled
+ */
+class ServerBlockConsoleTest extends ConsoleTest
+{
+       protected $defaultBlockList = [
+               [
+                       'domain' => 'social.nobodyhasthe.biz',
+                       'reason' => 'Illegal content',
+               ],
+               [
+                       'domain' => 'pod.ordoevangelistarum.com',
+                       'reason' => 'Illegal content',
+               ]
+       ];
+
+       protected function setUp()
+       {
+               parent::setUp();
+
+               $this->mockApp($this->root);
+       }
+
+       /**
+        * Test to list the default blocked servers
+        */
+       public function testBlockedServersList()
+       {
+               $this->configMock
+                       ->shouldReceive('get')
+                       ->with('system', 'blocklist')
+                       ->andReturn($this->defaultBlockList)
+                       ->once();
+
+               $console = new ServerBlock($this->consoleArgv);
+               $txt = $this->dumpExecute($console);
+
+               $output = <<<CONS
++----------------------------+-----------------+
+| Domain                     | Reason          |
++----------------------------+-----------------+
+| social.nobodyhasthe.biz    | Illegal content |
+| pod.ordoevangelistarum.com | Illegal content |
++----------------------------+-----------------+
+
+
+CONS;
+
+               $this->assertEquals($output, $txt);
+       }
+
+       /**
+        * Test blockedservers add command
+        */
+       public function testAddBlockedServer()
+       {
+               $this->configMock
+                       ->shouldReceive('get')
+                       ->with('system', 'blocklist')
+                       ->andReturn($this->defaultBlockList)
+                       ->once();
+
+               $newBlockList = $this->defaultBlockList;
+               $newBlockList[] = [
+                       'domain' => 'testme.now',
+                       'reason' => 'I like it!',
+               ];
+
+               $this->configMock
+                       ->shouldReceive('set')
+                       ->with('system', 'blocklist', $newBlockList)
+                       ->andReturn(true)
+                       ->once();
+
+               $console = new ServerBlock($this->consoleArgv);
+               $console->setArgument(0, 'add');
+               $console->setArgument(1, 'testme.now');
+               $console->setArgument(2, 'I like it!');
+               $txt = $this->dumpExecute($console);
+
+               $this->assertEquals('The domain \'testme.now\' is now blocked. (Reason: \'I like it!\')' . PHP_EOL, $txt);
+       }
+
+       /**
+        * Test blockedservers add command with the default reason
+        */
+       public function testAddBlockedServerWithDefaultReason()
+       {
+               $this->configMock
+                       ->shouldReceive('get')
+                       ->with('system', 'blocklist')
+                       ->andReturn($this->defaultBlockList)
+                       ->once();
+
+               $newBlockList = $this->defaultBlockList;
+               $newBlockList[] = [
+                       'domain' => 'testme.now',
+                       'reason' => ServerBlock::DEFAULT_REASON,
+               ];
+
+               $this->configMock
+                       ->shouldReceive('set')
+                       ->with('system', 'blocklist', $newBlockList)
+                       ->andReturn(true)
+                       ->once();
+
+               $console = new ServerBlock($this->consoleArgv);
+               $console->setArgument(0, 'add');
+               $console->setArgument(1, 'testme.now');
+               $txt = $this->dumpExecute($console);
+
+               $this->assertEquals('The domain \'testme.now\' is now blocked. (Reason: \'' . ServerBlock::DEFAULT_REASON . '\')' . PHP_EOL, $txt);
+       }
+
+       /**
+        * Test blockedservers add command on existed domain
+        */
+       public function testUpdateBlockedServer()
+       {
+               $this->configMock
+                       ->shouldReceive('get')
+                       ->with('system', 'blocklist')
+                       ->andReturn($this->defaultBlockList)
+                       ->once();
+
+               $newBlockList = [
+                       [
+                               'domain' => 'social.nobodyhasthe.biz',
+                               'reason' => 'Illegal content',
+                       ],
+                       [
+                               'domain' => 'pod.ordoevangelistarum.com',
+                               'reason' => 'Other reason',
+                       ]
+               ];
+
+               $this->configMock
+                       ->shouldReceive('set')
+                       ->with('system', 'blocklist', $newBlockList)
+                       ->andReturn(true)
+                       ->once();
+
+               $console = new ServerBlock($this->consoleArgv);
+               $console->setArgument(0, 'add');
+               $console->setArgument(1, 'pod.ordoevangelistarum.com');
+               $console->setArgument(2, 'Other reason');
+               $txt = $this->dumpExecute($console);
+
+               $this->assertEquals('The domain \'pod.ordoevangelistarum.com\' is now updated. (Reason: \'Other reason\')' . PHP_EOL, $txt);
+       }
+
+       /**
+        * Test blockedservers remove command
+        */
+       public function testRemoveBlockedServer()
+       {
+               $this->configMock
+                       ->shouldReceive('get')
+                       ->with('system', 'blocklist')
+                       ->andReturn($this->defaultBlockList)
+                       ->once();
+
+               $newBlockList = [
+                       [
+                               'domain' => 'social.nobodyhasthe.biz',
+                               'reason' => 'Illegal content',
+                       ],
+               ];
+
+               $this->configMock
+                       ->shouldReceive('set')
+                       ->with('system', 'blocklist', $newBlockList)
+                       ->andReturn(true)
+                       ->once();
+
+               $console = new ServerBlock($this->consoleArgv);
+               $console->setArgument(0, 'remove');
+               $console->setArgument(1, 'pod.ordoevangelistarum.com');
+               $txt = $this->dumpExecute($console);
+
+               $this->assertEquals('The domain \'pod.ordoevangelistarum.com\' is not more blocked' . PHP_EOL, $txt);
+       }
+
+       /**
+        * Test blockedservers with a wrong command
+        */
+       public function testBlockedServersWrongCommand()
+       {
+               $console = new ServerBlock($this->consoleArgv);
+               $console->setArgument(0, 'wrongcommand');
+               $txt = $this->dumpExecute($console);
+
+               $this->assertStringStartsWith('[Warning] Unknown command', $txt);
+       }
+
+       /**
+        * Test blockedservers remove with not existing domain
+        */
+       public function testRemoveBlockedServerNotExist()
+       {
+               $this->configMock
+                       ->shouldReceive('get')
+                       ->with('system', 'blocklist')
+                       ->andReturn($this->defaultBlockList)
+                       ->once();
+
+               $console = new ServerBlock($this->consoleArgv);
+               $console->setArgument(0, 'remove');
+               $console->setArgument(1, 'not.exiting');
+               $txt = $this->dumpExecute($console);
+
+               $this->assertEquals('The domain \'not.exiting\' is not blocked.' . PHP_EOL, $txt);
+       }
+
+       /**
+        * Test blockedservers add command without argument
+        */
+       public function testAddBlockedServerMissingArgument()
+       {
+               $console = new ServerBlock($this->consoleArgv);
+               $console->setArgument(0, 'add');
+               $txt = $this->dumpExecute($console);
+
+               $this->assertStringStartsWith('[Warning] Add needs a domain and optional a reason.', $txt);
+       }
+
+       /**
+        * Test blockedservers add command without save
+        */
+       public function testAddBlockedServerNoSave()
+       {
+               $this->configMock
+                       ->shouldReceive('get')
+                       ->with('system', 'blocklist')
+                       ->andReturn($this->defaultBlockList)
+                       ->once();
+
+               $newBlockList = $this->defaultBlockList;
+               $newBlockList[] = [
+                       'domain' => 'testme.now',
+                       'reason' => ServerBlock::DEFAULT_REASON,
+               ];
+
+               $this->configMock
+                       ->shouldReceive('set')
+                       ->with('system', 'blocklist', $newBlockList)
+                       ->andReturn(false)
+                       ->once();
+
+               $console = new ServerBlock($this->consoleArgv);
+               $console->setArgument(0, 'add');
+               $console->setArgument(1, 'testme.now');
+               $txt = $this->dumpExecute($console);
+
+               $this->assertEquals('Couldn\'t save \'testme.now\' as blocked server' . PHP_EOL, $txt);
+       }
+
+       /**
+        * Test blockedservers remove command without save
+        */
+       public function testRemoveBlockedServerNoSave()
+       {
+               $this->configMock
+                       ->shouldReceive('get')
+                       ->with('system', 'blocklist')
+                       ->andReturn($this->defaultBlockList)
+                       ->once();
+
+               $newBlockList = [
+                       [
+                               'domain' => 'social.nobodyhasthe.biz',
+                               'reason' => 'Illegal content',
+                       ],
+               ];
+
+               $this->configMock
+                       ->shouldReceive('set')
+                       ->with('system', 'blocklist', $newBlockList)
+                       ->andReturn(false)
+                       ->once();
+
+               $console = new ServerBlock($this->consoleArgv);
+               $console->setArgument(0, 'remove');
+               $console->setArgument(1, 'pod.ordoevangelistarum.com');
+               $txt = $this->dumpExecute($console);
+
+               $this->assertEquals('Couldn\'t remove \'pod.ordoevangelistarum.com\' from blocked servers' . PHP_EOL, $txt);
+       }
+
+       /**
+        * Test blockedservers remove command without argument
+        */
+       public function testRemoveBlockedServerMissingArgument()
+       {
+               $console = new ServerBlock($this->consoleArgv);
+               $console->setArgument(0, 'remove');
+               $txt = $this->dumpExecute($console);
+
+               $this->assertStringStartsWith('[Warning] Remove needs a second parameter.', $txt);
+       }
+
+       /**
+        * Test the blockedservers help
+        */
+       public function testBlockedServersHelp()
+       {
+               $console = new ServerBlock($this->consoleArgv);
+               $console->setOption('help', true);
+               $txt = $this->dumpExecute($console);
+
+               $help = <<<HELP
+console serverblock - Manage blocked servers
+Usage
+       bin/console serverblock [-h|--help|-?] [-v]
+       bin/console serverblock add <server> <reason> [-h|--help|-?] [-v]
+       bin/console serverblock remove <server> [-h|--help|-?] [-v]
+
+Description
+       With this tool, you can list the current blocked servers
+    or you can add / remove a blocked server from the list
+
+Options
+    -h|--help|-? Show help information
+    -v           Show more debug information.
+
+HELP;
+
+               $this->assertEquals($help, $txt);
+       }
+}
diff --git a/tests/src/Core/Console/AutomaticInstallationConsoleTest.php b/tests/src/Core/Console/AutomaticInstallationConsoleTest.php
deleted file mode 100644 (file)
index 9ed3d40..0000000
+++ /dev/null
@@ -1,646 +0,0 @@
-<?php
-
-namespace Friendica\Test\src\Core\Console;
-
-use Friendica\Core\Config\Cache\ConfigCache;
-use Friendica\Core\Console\AutomaticInstallation;
-use Friendica\Core\Installer;
-use Friendica\Core\Logger;
-use Friendica\Test\Util\DBAMockTrait;
-use Friendica\Test\Util\DBStructureMockTrait;
-use Friendica\Test\Util\L10nMockTrait;
-use Friendica\Test\Util\RendererMockTrait;
-use Friendica\Util\BaseURL;
-use Friendica\Util\Logger\VoidLogger;
-use org\bovigo\vfs\vfsStream;
-use org\bovigo\vfs\vfsStreamFile;
-
-/**
- * @runTestsInSeparateProcesses
- * @preserveGlobalState disabled
- * @requires PHP 7.0
- */
-class AutomaticInstallationConsoleTest extends ConsoleTest
-{
-       use L10nMockTrait;
-       use DBAMockTrait;
-       use DBStructureMockTrait;
-       use RendererMockTrait;
-
-       /**
-        * @var vfsStreamFile Assert file without DB credentials
-        */
-       private $assertFile;
-       /**
-        * @var vfsStreamFile Assert file with DB credentials
-        */
-       private $assertFileDb;
-
-       /**
-        * @var ConfigCache The configuration cache to check after each test
-        */
-       private $configCache;
-
-       public function setUp()
-       {
-               parent::setUp();
-
-               if ($this->root->hasChild('config' . DIRECTORY_SEPARATOR . 'local.config.php')) {
-                       $this->root->getChild('config')
-                               ->removeChild('local.config.php');
-               }
-
-               $this->mockL10nT();
-
-               $this->configCache = new ConfigCache();
-               $this->configCache->set('system', 'basepath', $this->root->url());
-               $this->configCache->set('config', 'php_path', trim(shell_exec('which php')));
-               $this->configCache->set('system', 'theme', 'smarty3');
-
-               $this->mockApp($this->root, true);
-
-               $this->configMock->shouldReceive('set')->andReturnUsing(function ($cat, $key, $value) {
-                       if ($key !== 'basepath') {
-                               return $this->configCache->set($cat, $key, $value);
-                       } else {
-                               return true;
-                       }
-               });
-
-               $this->configMock->shouldReceive('has')->andReturn(true);
-               $this->configMock->shouldReceive('get')->andReturnUsing(function ($cat, $key) {
-                       return $this->configCache->get($cat, $key);
-               });
-               $this->configMock->shouldReceive('load')->andReturnUsing(function ($config, $overwrite = false) {
-                       return $this->configCache->load($config, $overwrite);
-               });
-
-               $this->mode->shouldReceive('isInstall')->andReturn(true);
-               Logger::init(new VoidLogger());
-       }
-
-       /**
-        * Returns the dataset for each automatic installation test
-        *
-        * @return array the dataset
-        */
-       public function dataInstaller()
-       {
-               return [
-                       'empty' => [
-                               'data' => [
-                                       'database' => [
-                                               'hostname'    => '',
-                                               'username'    => '',
-                                               'password'    => '',
-                                               'database'    => '',
-                                               'port'        => '',
-                                       ],
-                                       'config' => [
-                                               'php_path'    => '',
-                                               'hostname'    => 'friendica.local',
-                                               'admin_email' => '',
-                                       ],
-                                       'system' => [
-                                               'basepath'    => '',
-                                               'urlpath'     => '',
-                                               'url'         => 'http://friendica.local',
-                                               'ssl_policy'  => 0,
-                                               'default_timezone' => '',
-                                               'language'    => '',
-                                       ],
-                               ],
-                       ],
-                       'normal' => [
-                               'data' => [
-                                       'database' => [
-                                               'hostname'    => 'testhost',
-                                               'port'        => 3306,
-                                               'username'    => 'friendica',
-                                               'password'    => 'a password',
-                                               'database'    => 'database',
-                                       ],
-                                       'config' => [
-                                               'php_path'    => '',
-                                               'hostname'    => 'friendica.local',
-                                               'admin_email' => 'admin@philipp.info',
-                                       ],
-                                       'system' => [
-                                               'urlpath'     => 'test/it',
-                                               'url'         => 'http://friendica.local/test/it',
-                                               'basepath'    => '',
-                                               'ssl_policy'  => '2',
-                                               'default_timezone' => 'en',
-                                               'language'    => 'Europe/Berlin',
-                                       ],
-                               ],
-                       ],
-                       'special' => [
-                               'data' => [
-                                       'database' => [
-                                               'hostname'    => 'testhost.new.domain',
-                                               'port'        => 3341,
-                                               'username'    => 'fr"§%ica',
-                                               'password'    => '$%\"gse',
-                                               'database'    => 'db',
-                                       ],
-                                       'config' => [
-                                               'php_path'    => '',
-                                               'hostname'    => 'friendica.local',
-                                               'admin_email' => 'admin@philipp.info',
-                                       ],
-                                       'system' => [
-                                               'urlpath'     => 'test/it',
-                                               'url'         => 'https://friendica.local/test/it',
-                                               'basepath'    => '',
-                                               'ssl_policy'  => '1',
-                                               'default_timezone' => 'en',
-                                               'language'    => 'Europe/Berlin',
-                                       ],
-                               ],
-                       ],
-               ];
-       }
-
-       private function assertFinished($txt, $withconfig = false, $copyfile = false)
-       {
-               $cfg = '';
-
-               if ($withconfig) {
-                       $cfg = <<<CFG
-
-
-Creating config file...
-
- Complete!
-CFG;
-               }
-
-               if ($copyfile) {
-                       $cfg = <<<CFG
-
-
-Copying config file...
-
- Complete!
-CFG;
-               }
-
-               $finished = <<<FIN
-Initializing setup...
-
- Complete!
-
-
-Checking environment...
-
- NOTICE: Not checking .htaccess/URL-Rewrite during CLI installation.
-
- Complete!
-{$cfg}
-
-
-Checking database...
-
- Complete!
-
-
-Inserting data into database...
-
- Complete!
-
-
-Installing theme
-
- Complete
-
-
-
-Installation is finished
-
-
-FIN;
-               $this->assertEquals($finished, $txt);
-       }
-
-       private function assertStuckDB($txt)
-       {
-               $finished = <<<FIN
-Initializing setup...
-
- Complete!
-
-
-Checking environment...
-
- NOTICE: Not checking .htaccess/URL-Rewrite during CLI installation.
-
- Complete!
-
-
-Creating config file...
-
- Complete!
-
-
-Checking database...
-
-[Error] --------
-Could not connect to database.: 
-
-
-FIN;
-
-               $this->assertEquals($finished, $txt);
-       }
-
-       private function assertStuckURL($txt)
-       {
-               $finished = <<<FIN
-Initializing setup...
-
- Complete!
-
-
-Checking environment...
-
- NOTICE: Not checking .htaccess/URL-Rewrite during CLI installation.
-
- Complete!
-
-
-Creating config file...
-
-The Friendica URL has to be set during CLI installation.
-
-FIN;
-
-               $this->assertEquals($finished, $txt);
-       }
-
-       /**
-        * Asserts one config entry
-        *
-        * @param string     $cat           The category to test
-        * @param string     $key           The key to test
-        * @param null|array $assertion     The asserted value (null = empty, or array/string)
-        * @param string     $default_value The default value
-        */
-       public function assertConfigEntry($cat, $key, $assertion = null, $default_value = null)
-       {
-               if (!empty($assertion[$cat][$key])) {
-                       $this->assertEquals($assertion[$cat][$key], $this->configCache->get($cat, $key));
-               } elseif (!empty($assertion) && !is_array($assertion)) {
-                       $this->assertEquals($assertion, $this->configCache->get($cat, $key));
-               } elseif (!empty($default_value)) {
-                       $this->assertEquals($default_value, $this->configCache->get($cat, $key));
-               } else {
-                       $this->assertEmpty($this->configCache->get($cat, $key), $this->configCache->get($cat, $key));
-               }
-       }
-
-       /**
-        * Asserts all config entries
-        *
-        * @param null|array $assertion    The optional assertion array
-        * @param boolean    $saveDb       True, if the db credentials should get saved to the file
-        * @param boolean    $default      True, if we use the default values
-        * @param boolean    $defaultDb    True, if we use the default value for the DB
-        * @param boolean    $realBasepath True, if we use the real basepath of the installation, not the mocked one
-        */
-       public function assertConfig($assertion = null, $saveDb = false, $default = true, $defaultDb = true, $realBasepath = false)
-       {
-               if (!empty($assertion['database']['hostname'])) {
-                       $assertion['database']['hostname'] .= (!empty($assertion['database']['port']) ? ':' . $assertion['database']['port'] : '');
-               }
-
-               $this->assertConfigEntry('database', 'hostname', ($saveDb) ? $assertion : null, (!$saveDb || $defaultDb) ? Installer::DEFAULT_HOST : null);
-               $this->assertConfigEntry('database', 'username', ($saveDb) ? $assertion : null);
-               $this->assertConfigEntry('database', 'password', ($saveDb) ? $assertion : null);
-               $this->assertConfigEntry('database', 'database', ($saveDb) ? $assertion : null);
-
-               $this->assertConfigEntry('config', 'admin_email', $assertion);
-               $this->assertConfigEntry('config', 'php_path', trim(shell_exec('which php')));
-               $this->assertConfigEntry('config', 'hostname', $assertion);
-
-               $this->assertConfigEntry('system', 'default_timezone', $assertion, ($default) ? Installer::DEFAULT_TZ : null);
-               $this->assertConfigEntry('system', 'language', $assertion, ($default) ? Installer::DEFAULT_LANG : null);
-               $this->assertConfigEntry('system', 'url', $assertion);
-               $this->assertConfigEntry('system', 'urlpath', $assertion);
-               $this->assertConfigEntry('system', 'ssl_policy', $assertion, ($default) ? BaseURL::DEFAULT_SSL_SCHEME : null);
-               $this->assertConfigEntry('system', 'basepath', ($realBasepath) ? $this->root->url() : $assertion);
-       }
-
-       /**
-        * Test the automatic installation without any parameter/setting
-        * Should stuck because of missing hostname
-        */
-       public function testEmpty()
-       {
-               $console = new AutomaticInstallation($this->consoleArgv);
-
-               $txt = $this->dumpExecute($console);
-
-               $this->assertStuckURL($txt);
-       }
-
-       /**
-        * Test the automatic installation without any parameter/setting
-        * except URL
-        */
-       public function testEmptyWithURL()
-       {
-               $this->mockConnect(true, 1);
-               $this->mockConnected(true, 1);
-               $this->mockExistsTable('user', false, 1);
-               $this->mockUpdate([$this->root->url(), false, true, true], null, 1);
-
-               $this->mockGetMarkupTemplate('local.config.tpl', 'testTemplate', 1);
-               $this->mockReplaceMacros('testTemplate', \Mockery::any(), false, '', 1);
-
-               $console = new AutomaticInstallation($this->consoleArgv);
-               $console->setOption('url', 'http://friendica.local');
-
-               $txt = $this->dumpExecute($console);
-
-               $this->assertFinished($txt, true, false);
-               $this->assertTrue($this->root->hasChild('config' . DIRECTORY_SEPARATOR . 'local.config.php'));
-
-               $this->assertConfig(['config' => ['hostname' => 'friendica.local'], 'system' => ['url' => 'http://friendica.local', 'ssl_policy' => 0, 'urlPath' => '']], false, true, true, true);
-       }
-
-       /**
-        * Test the automatic installation with a prepared config file
-        * @dataProvider dataInstaller
-        */
-       public function testWithConfig(array $data)
-       {
-               $this->mockConnect(true, 1);
-               $this->mockConnected(true, 1);
-               $this->mockExistsTable('user', false, 1);
-               $this->mockUpdate([$this->root->url(), false, true, true], null, 1);
-
-               $conf = function ($cat, $key) use ($data) {
-                       if ($cat == 'database' && $key == 'hostname' && !empty($data['database']['port'])) {
-                               return $data[$cat][$key] . ':' . $data['database']['port'];
-                       }
-                       return $data[$cat][$key];
-               };
-
-               $config = <<<CONF
-<?php
-
-// Local configuration
-
-// If you're unsure about what any of the config keys below do, please check the config/defaults.config.php for detailed
-// documentation of their data type and behavior.
-
-return [
-       'database' => [
-               'hostname' => '{$conf('database', 'hostname')}',
-               'username' => '{$conf('database', 'username')}',
-               'password' => '{$conf('database', 'password')}',
-               'database' => '{$conf('database', 'database')}',
-               'charset' => 'utf8mb4',
-       ],
-
-       // ****************************************************************
-       // The configuration below will be overruled by the admin panel.
-       // Changes made below will only have an effect if the database does
-       // not contain any configuration for the friendica system.
-       // ****************************************************************
-
-       'config' => [
-               'admin_email' => '{$conf('config', 'admin_email')}',
-               'hostname' => '{$conf('config', 'hostname')}',
-               'sitename' => 'Friendica Social Network',
-               'register_policy' => \Friendica\Module\Register::OPEN,
-               'register_text' => '',
-       ],
-       'system' => [
-               'basepath' => '{$conf('system', 'basepath')}',
-               'urlpath' => '{$conf('system', 'urlpath')}',
-               'url' => '{$conf('system', 'url')}',
-               'ssl_policy' => '{$conf('system', 'ssl_policy')}',
-               'default_timezone' => '{$conf('system', 'default_timezone')}',
-               'language' => '{$conf('system', 'language')}',
-       ],
-];
-CONF;
-
-               vfsStream::newFile('prepared.config.php')
-                       ->at($this->root)
-                       ->setContent($config);
-
-               $console = new AutomaticInstallation($this->consoleArgv);
-               $console->setOption('f', 'prepared.config.php');
-
-               $txt = $this->dumpExecute($console);
-
-               $this->assertFinished($txt, false, true);
-
-               $this->assertTrue($this->root->hasChild('config' . DIRECTORY_SEPARATOR . 'local.config.php'));
-               $this->assertEquals($config, file_get_contents($this->root->getChild('config' . DIRECTORY_SEPARATOR . 'local.config.php')->url()));
-
-               $this->assertConfig($data, true, false, false);
-       }
-
-       /**
-        * Test the automatic installation with environment variables
-        * Includes saving the DB credentials to the file
-        * @dataProvider dataInstaller
-        */
-       public function testWithEnvironmentAndSave(array $data)
-       {
-               $this->mockConnect(true, 1);
-               $this->mockConnected(true, 1);
-               $this->mockExistsTable('user', false, 1);
-               $this->mockUpdate([$this->root->url(), false, true, true], null, 1);
-
-               $this->mockGetMarkupTemplate('local.config.tpl', 'testTemplate', 1);
-               $this->mockReplaceMacros('testTemplate', \Mockery::any(), false, '', 1);
-
-               $this->assertTrue(putenv('MYSQL_HOST='     . $data['database']['hostname']));
-               $this->assertTrue(putenv('MYSQL_PORT='     . $data['database']['port']));
-               $this->assertTrue(putenv('MYSQL_DATABASE=' . $data['database']['database']));
-               $this->assertTrue(putenv('MYSQL_USERNAME=' . $data['database']['username']));
-               $this->assertTrue(putenv('MYSQL_PASSWORD=' . $data['database']['password']));
-
-               $this->assertTrue(putenv('FRIENDICA_HOSTNAME='   . $data['config']['hostname']));
-               $this->assertTrue(putenv('FRIENDICA_BASE_PATH='  . $data['system']['basepath']));
-               $this->assertTrue(putenv('FRIENDICA_URL='        . $data['system']['url']));
-               $this->assertTrue(putenv('FRIENDICA_PHP_PATH='   . $data['config']['php_path']));
-               $this->assertTrue(putenv('FRIENDICA_ADMIN_MAIL=' . $data['config']['admin_email']));
-               $this->assertTrue(putenv('FRIENDICA_TZ='         . $data['system']['default_timezone']));
-               $this->assertTrue(putenv('FRIENDICA_LANG='       . $data['system']['language']));
-
-               $console = new AutomaticInstallation($this->consoleArgv);
-               $console->setOption('savedb', true);
-
-               $txt = $this->dumpExecute($console);
-
-               $this->assertFinished($txt, true);
-               $this->assertConfig($data, true, true, false, true);
-       }
-
-       /**
-        * Test the automatic installation with environment variables
-        * Don't save the db credentials to the file
-        * @dataProvider dataInstaller
-        */
-       public function testWithEnvironmentWithoutSave(array $data)
-       {
-               $this->mockConnect(true, 1);
-               $this->mockConnected(true, 1);
-               $this->mockExistsTable('user', false, 1);
-               $this->mockUpdate([$this->root->url(), false, true, true], null, 1);
-
-               $this->mockGetMarkupTemplate('local.config.tpl', 'testTemplate', 1);
-               $this->mockReplaceMacros('testTemplate', \Mockery::any(), false, '', 1);
-
-               $this->assertTrue(putenv('MYSQL_HOST=' . $data['database']['hostname']));
-               $this->assertTrue(putenv('MYSQL_PORT=' . $data['database']['port']));
-               $this->assertTrue(putenv('MYSQL_DATABASE=' . $data['database']['database']));
-               $this->assertTrue(putenv('MYSQL_USERNAME=' . $data['database']['username']));
-               $this->assertTrue(putenv('MYSQL_PASSWORD=' . $data['database']['password']));
-
-               $this->assertTrue(putenv('FRIENDICA_HOSTNAME='   . $data['config']['hostname']));
-               $this->assertTrue(putenv('FRIENDICA_BASE_PATH='  . $data['system']['basepath']));
-               $this->assertTrue(putenv('FRIENDICA_URL='        . $data['system']['url']));
-               $this->assertTrue(putenv('FRIENDICA_PHP_PATH='   . $data['config']['php_path']));
-               $this->assertTrue(putenv('FRIENDICA_ADMIN_MAIL=' . $data['config']['admin_email']));
-               $this->assertTrue(putenv('FRIENDICA_TZ='         . $data['system']['default_timezone']));
-               $this->assertTrue(putenv('FRIENDICA_LANG='       . $data['system']['language']));
-
-               $console = new AutomaticInstallation($this->consoleArgv);
-
-               $txt = $this->dumpExecute($console);
-
-               $this->assertFinished($txt, true);
-               $this->assertConfig($data, false, true, false, true);
-       }
-
-       /**
-        * Test the automatic installation with arguments
-        * @dataProvider dataInstaller
-        */
-       public function testWithArguments(array $data)
-       {
-               $this->mockConnect(true, 1);
-               $this->mockConnected(true, 1);
-               $this->mockExistsTable('user', false, 1);
-               $this->mockUpdate([$this->root->url(), false, true, true], null, 1);
-
-               $this->mockGetMarkupTemplate('local.config.tpl', 'testTemplate', 1);
-               $this->mockReplaceMacros('testTemplate', \Mockery::any(), false, '', 1);
-
-               $console = new AutomaticInstallation($this->consoleArgv);
-
-               $option = function($var, $cat, $key) use ($data, $console) {
-                       if (!empty($data[$cat][$key])) {
-                               $console->setOption($var, $data[$cat][$key]);
-                       }
-               };
-               $option('dbhost'    , 'database', 'hostname');
-               $option('dbport'    , 'database', 'port');
-               $option('dbuser'    , 'database', 'username');
-               $option('dbpass'    , 'database', 'password');
-               $option('dbdata'    , 'database', 'database');
-               $option('url'       , 'system'  , 'url');
-               $option('phppath'   , 'config'  , 'php_path');
-               $option('admin'     , 'config'  , 'admin_email');
-               $option('tz'        , 'system'  , 'default_timezone');
-               $option('lang'      , 'system'  , 'language');
-               $option('basepath'  , 'system'  , 'basepath');
-
-               $txt = $this->dumpExecute($console);
-
-               $this->assertFinished($txt, true);
-               $this->assertConfig($data, true, true, true, true);
-       }
-
-       /**
-        * Test the automatic installation with a wrong database connection
-        */
-       public function testNoDatabaseConnection()
-       {
-               $this->mockConnect(false, 1);
-
-               $this->mockGetMarkupTemplate('local.config.tpl', 'testTemplate', 1);
-               $this->mockReplaceMacros('testTemplate', \Mockery::any(), false, '', 1);
-
-               $console = new AutomaticInstallation($this->consoleArgv);
-               $console->setOption('url', 'http://friendica.local');
-
-               $txt = $this->dumpExecute($console);
-
-               $this->assertStuckDB($txt);
-               $this->assertTrue($this->root->hasChild('config' . DIRECTORY_SEPARATOR . 'local.config.php'));
-
-               $this->assertConfig(['config' => ['hostname' => 'friendica.local'], 'system' => ['url' => 'http://friendica.local', 'ssl_policy' => 0, 'urlpath' => '']], false, true, false, true);
-       }
-
-       public function testGetHelp()
-       {
-               // Usable to purposely fail if new commands are added without taking tests into account
-               $theHelp = <<<HELP
-Installation - Install Friendica automatically
-Synopsis
-       bin/console autoinstall [-h|--help|-?] [-v] [-a] [-f]
-
-Description
-    Installs Friendica with data based on the local.config.php file or environment variables
-
-Notes
-    Not checking .htaccess/URL-Rewrite during CLI installation.
-
-Options
-    -h|--help|-?            Show help information
-    -v                      Show more debug information.
-    -a                      All setup checks are required (except .htaccess)
-    -f|--file <config>      prepared config file (e.g. "config/local.config.php" itself) which will override every other config option - except the environment variables)
-    -s|--savedb               Save the DB credentials to the file (if environment variables is used)
-    -H|--dbhost <host>        The host of the mysql/mariadb database (env MYSQL_HOST)
-    -p|--dbport <port>        The port of the mysql/mariadb database (env MYSQL_PORT)
-    -d|--dbdata <database>    The name of the mysql/mariadb database (env MYSQL_DATABASE)
-    -U|--dbuser <username>    The username of the mysql/mariadb database login (env MYSQL_USER or MYSQL_USERNAME)
-    -P|--dbpass <password>    The password of the mysql/mariadb database login (env MYSQL_PASSWORD)
-    -U|--url <url>            The full base URL of Friendica - f.e. 'https://friendica.local/sub' (env FRIENDICA_URL) 
-    -B|--phppath <php_path>   The path of the PHP binary (env FRIENDICA_PHP_PATH)
-    -b|--basepath <base_path> The basepath of Friendica (env FRIENDICA_BASE_PATH)
-    -t|--tz <timezone>        The timezone of Friendica (env FRIENDICA_TZ)
-    -L|--lang <language>      The language of Friendica (env FRIENDICA_LANG)
-Environment variables
-   MYSQL_HOST                  The host of the mysql/mariadb database (mandatory if mysql and environment is used)
-   MYSQL_PORT                  The port of the mysql/mariadb database
-   MYSQL_USERNAME|MYSQL_USER   The username of the mysql/mariadb database login (MYSQL_USERNAME is for mysql, MYSQL_USER for mariadb)
-   MYSQL_PASSWORD              The password of the mysql/mariadb database login
-   MYSQL_DATABASE              The name of the mysql/mariadb database
-   FRIENDICA_URL               The full base URL of Friendica - f.e. 'https://friendica.local/sub'
-   FRIENDICA_PHP_PATH          The path of the PHP binary - leave empty for auto detection
-   FRIENDICA_BASE_PATH         The basepath of Friendica - leave empty for auto detection
-   FRIENDICA_ADMIN_MAIL        The admin email address of Friendica (this email will be used for admin access)
-   FRIENDICA_TZ                The timezone of Friendica
-   FRIENDICA_LANG              The langauge of Friendica
-   
-Examples
-       bin/console autoinstall -f 'input.config.php
-               Installs Friendica with the prepared 'input.config.php' file
-
-       bin/console autoinstall --savedb
-               Installs Friendica with environment variables and saves them to the 'config/local.config.php' file
-
-       bin/console autoinstall -h localhost -p 3365 -U user -P passwort1234 -d friendica
-               Installs Friendica with a local mysql database with credentials
-
-HELP;
-
-               $console = new AutomaticInstallation($this->consoleArgv);
-               $console->setOption('help', true);
-
-               $txt = $this->dumpExecute($console);
-
-               $this->assertEquals($theHelp, $txt);
-       }
-}
diff --git a/tests/src/Core/Console/ConfigConsoleTest.php b/tests/src/Core/Console/ConfigConsoleTest.php
deleted file mode 100644 (file)
index c58b05e..0000000
+++ /dev/null
@@ -1,193 +0,0 @@
-<?php
-
-namespace Friendica\Test\src\Core\Console;
-
-use Friendica\App\Mode;
-use Friendica\Core\Console\Config;
-
-/**
- * @runTestsInSeparateProcesses
- * @preserveGlobalState disabled
- * @requires PHP 7.0
- */
-class ConfigConsoleTest extends ConsoleTest
-{
-       protected function setUp()
-       {
-               parent::setUp();
-
-               $this->mockApp($this->root);
-
-               \Mockery::getConfiguration()->setConstantsMap([
-                       Mode::class => [
-                               'DBCONFIGAVAILABLE' => 0
-                       ]
-               ]);
-
-               $this->mode
-                       ->shouldReceive('has')
-                       ->andReturn(true);
-
-       }
-
-       function testSetGetKeyValue() {
-               $this->configMock
-                       ->shouldReceive('set')
-                       ->with('config', 'test', 'now')
-                       ->andReturn(true)
-                       ->once();
-               $this->configMock
-                       ->shouldReceive('get')
-                       ->with('config', 'test')
-                       ->andReturn('now')
-                       ->twice();
-
-               $console = new Config($this->consoleArgv);
-               $console->setArgument(0, 'config');
-               $console->setArgument(1, 'test');
-               $console->setArgument(2, 'now');
-               $txt = $this->dumpExecute($console);
-               $this->assertEquals("config.test <= now\n", $txt);
-
-               $this->configMock
-                       ->shouldReceive('get')
-                       ->with('config', 'test')
-                       ->andReturn('now')
-                       ->once();
-
-               $console = new Config($this->consoleArgv);
-               $console->setArgument(0, 'config');
-               $console->setArgument(1, 'test');
-               $txt = $this->dumpExecute($console);
-               $this->assertEquals("config.test => now\n", $txt);
-
-               $this->configMock
-                       ->shouldReceive('get')
-                       ->with('config', 'test')
-                       ->andReturn(null)
-                       ->once();
-
-               $console = new Config($this->consoleArgv);
-               $console->setArgument(0, 'config');
-               $console->setArgument(1, 'test');
-               $txt = $this->dumpExecute($console);
-               $this->assertEquals("config.test => \n", $txt);
-       }
-
-       function testSetArrayValue() {
-               $testArray = [1, 2, 3];
-               $this->configMock
-                       ->shouldReceive('get')
-                       ->with('config', 'test')
-                       ->andReturn($testArray)
-                       ->once();
-
-               $console = new Config($this->consoleArgv);
-               $console->setArgument(0, 'config');
-               $console->setArgument(1, 'test');
-               $console->setArgument(2, 'now');
-               $txt = $this->dumpExecute($console);
-
-               $this->assertEquals("[Error] config.test is an array and can't be set using this command.\n", $txt);
-       }
-
-       function testTooManyArguments() {
-               $console = new Config($this->consoleArgv);
-               $console->setArgument(0, 'config');
-               $console->setArgument(1, 'test');
-               $console->setArgument(2, 'it');
-               $console->setArgument(3, 'now');
-               $txt = $this->dumpExecute($console);
-               $assertion = '[Warning] Too many arguments';
-               $firstline = substr($txt, 0, strlen($assertion));
-               $this->assertEquals($assertion, $firstline);
-       }
-
-       function testVerbose() {
-               $this->configMock
-                       ->shouldReceive('get')
-                       ->with('test', 'it')
-                       ->andReturn('now')
-                       ->once();
-               $console = new Config($this->consoleArgv);
-               $console->setArgument(0, 'test');
-               $console->setArgument(1, 'it');
-               $console->setOption('v', 1);
-               $executable = $this->consoleArgv[0];
-               $assertion = <<<CONF
-Executable: {$executable}
-Class: Friendica\Core\Console\Config
-Arguments: array (
-  0 => 'test',
-  1 => 'it',
-)
-Options: array (
-  'v' => 1,
-)
-test.it => now
-
-CONF;
-               $txt = $this->dumpExecute($console);
-               $this->assertEquals($assertion, $txt);
-       }
-
-       function testUnableToSet() {
-               $this->configMock
-                       ->shouldReceive('set')
-                       ->with('test', 'it', 'now')
-                       ->andReturn(false)
-                       ->once();
-               $this->configMock
-                       ->shouldReceive('get')
-                       ->with('test', 'it')
-                       ->andReturn(NULL)
-                       ->once();
-               $console = new Config();
-               $console->setArgument(0, 'test');
-               $console->setArgument(1, 'it');
-               $console->setArgument(2, 'now');
-               $txt = $this->dumpExecute($console);
-               $this->assertSame("Unable to set test.it\n", $txt);
-       }
-
-       public function testGetHelp()
-       {
-               // Usable to purposely fail if new commands are added without taking tests into account
-               $theHelp = <<<HELP
-console config - Manage site configuration
-Synopsis
-       bin/console config [-h|--help|-?] [-v]
-       bin/console config <category> [-h|--help|-?] [-v]
-       bin/console config <category> <key> [-h|--help|-?] [-v]
-       bin/console config <category> <key> <value> [-h|--help|-?] [-v]
-
-Description
-       bin/console config
-               Lists all config values
-
-       bin/console config <category>
-               Lists all config values in the provided category
-
-       bin/console config <category> <key>
-               Shows the value of the provided key in the category
-
-       bin/console config <category> <key> <value>
-               Sets the value of the provided key in the category
-
-Notes:
-       Setting config entries which are manually set in config/local.config.php may result in
-       conflict between database settings and the manual startup settings.
-
-Options
-    -h|--help|-? Show help information
-    -v           Show more debug information.
-
-HELP;
-               $console = new Config($this->consoleArgv);
-               $console->setOption('help', true);
-
-               $txt = $this->dumpExecute($console);
-
-               $this->assertEquals($txt, $theHelp);
-       }
-}
diff --git a/tests/src/Core/Console/ConsoleTest.php b/tests/src/Core/Console/ConsoleTest.php
deleted file mode 100644 (file)
index e142e60..0000000
+++ /dev/null
@@ -1,46 +0,0 @@
-<?php
-
-namespace Friendica\Test\src\Core\Console;
-
-use Asika\SimpleConsole\Console;
-use Friendica\Test\MockedTest;
-use Friendica\Test\Util\AppMockTrait;
-use Friendica\Test\Util\Intercept;
-use Friendica\Test\Util\VFSTrait;
-
-abstract class ConsoleTest extends MockedTest
-{
-       use VFSTrait;
-       use AppMockTrait;
-
-       /**
-        * @var array The default argv for a Console Instance
-        */
-       protected $consoleArgv = [ 'consoleTest.php' ];
-
-       protected function setUp()
-       {
-               parent::setUp();
-
-               Intercept::setUp();
-
-               $this->setUpVfsDir();
-       }
-
-       /**
-        * Dumps the execution of an console output to a string and returns it
-        *
-        * @param Console $console The current console instance
-        *
-        * @return string the output of the execution
-        */
-       protected function dumpExecute($console)
-       {
-               Intercept::reset();
-               $console->execute();
-               $returnStr = Intercept::$cache;
-               Intercept::reset();
-
-               return $returnStr;
-       }
-}
diff --git a/tests/src/Core/Console/ServerBlockConsoleTest.php b/tests/src/Core/Console/ServerBlockConsoleTest.php
deleted file mode 100644 (file)
index 512a416..0000000
+++ /dev/null
@@ -1,337 +0,0 @@
-<?php
-
-namespace Friendica\Test\src\Core\Console;
-
-use Friendica\Core\Console\ServerBlock;
-
-/**
- * @runTestsInSeparateProcesses
- * @preserveGlobalState disabled
- */
-class ServerBlockConsoleTest extends ConsoleTest
-{
-       protected $defaultBlockList = [
-               [
-                       'domain' => 'social.nobodyhasthe.biz',
-                       'reason' => 'Illegal content',
-               ],
-               [
-                       'domain' => 'pod.ordoevangelistarum.com',
-                       'reason' => 'Illegal content',
-               ]
-       ];
-
-       protected function setUp()
-       {
-               parent::setUp();
-
-               $this->mockApp($this->root);
-       }
-
-       /**
-        * Test to list the default blocked servers
-        */
-       public function testBlockedServersList()
-       {
-               $this->configMock
-                       ->shouldReceive('get')
-                       ->with('system', 'blocklist')
-                       ->andReturn($this->defaultBlockList)
-                       ->once();
-
-               $console = new ServerBlock($this->consoleArgv);
-               $txt = $this->dumpExecute($console);
-
-               $output = <<<CONS
-+----------------------------+-----------------+
-| Domain                     | Reason          |
-+----------------------------+-----------------+
-| social.nobodyhasthe.biz    | Illegal content |
-| pod.ordoevangelistarum.com | Illegal content |
-+----------------------------+-----------------+
-
-
-CONS;
-
-               $this->assertEquals($output, $txt);
-       }
-
-       /**
-        * Test blockedservers add command
-        */
-       public function testAddBlockedServer()
-       {
-               $this->configMock
-                       ->shouldReceive('get')
-                       ->with('system', 'blocklist')
-                       ->andReturn($this->defaultBlockList)
-                       ->once();
-
-               $newBlockList = $this->defaultBlockList;
-               $newBlockList[] = [
-                       'domain' => 'testme.now',
-                       'reason' => 'I like it!',
-               ];
-
-               $this->configMock
-                       ->shouldReceive('set')
-                       ->with('system', 'blocklist', $newBlockList)
-                       ->andReturn(true)
-                       ->once();
-
-               $console = new ServerBlock($this->consoleArgv);
-               $console->setArgument(0, 'add');
-               $console->setArgument(1, 'testme.now');
-               $console->setArgument(2, 'I like it!');
-               $txt = $this->dumpExecute($console);
-
-               $this->assertEquals('The domain \'testme.now\' is now blocked. (Reason: \'I like it!\')' . PHP_EOL, $txt);
-       }
-
-       /**
-        * Test blockedservers add command with the default reason
-        */
-       public function testAddBlockedServerWithDefaultReason()
-       {
-               $this->configMock
-                       ->shouldReceive('get')
-                       ->with('system', 'blocklist')
-                       ->andReturn($this->defaultBlockList)
-                       ->once();
-
-               $newBlockList = $this->defaultBlockList;
-               $newBlockList[] = [
-                       'domain' => 'testme.now',
-                       'reason' => ServerBlock::DEFAULT_REASON,
-               ];
-
-               $this->configMock
-                       ->shouldReceive('set')
-                       ->with('system', 'blocklist', $newBlockList)
-                       ->andReturn(true)
-                       ->once();
-
-               $console = new ServerBlock($this->consoleArgv);
-               $console->setArgument(0, 'add');
-               $console->setArgument(1, 'testme.now');
-               $txt = $this->dumpExecute($console);
-
-               $this->assertEquals('The domain \'testme.now\' is now blocked. (Reason: \'' . ServerBlock::DEFAULT_REASON . '\')' . PHP_EOL, $txt);
-       }
-
-       /**
-        * Test blockedservers add command on existed domain
-        */
-       public function testUpdateBlockedServer()
-       {
-               $this->configMock
-                       ->shouldReceive('get')
-                       ->with('system', 'blocklist')
-                       ->andReturn($this->defaultBlockList)
-                       ->once();
-
-               $newBlockList = [
-                       [
-                               'domain' => 'social.nobodyhasthe.biz',
-                               'reason' => 'Illegal content',
-                       ],
-                       [
-                               'domain' => 'pod.ordoevangelistarum.com',
-                               'reason' => 'Other reason',
-                       ]
-               ];
-
-               $this->configMock
-                       ->shouldReceive('set')
-                       ->with('system', 'blocklist', $newBlockList)
-                       ->andReturn(true)
-                       ->once();
-
-               $console = new ServerBlock($this->consoleArgv);
-               $console->setArgument(0, 'add');
-               $console->setArgument(1, 'pod.ordoevangelistarum.com');
-               $console->setArgument(2, 'Other reason');
-               $txt = $this->dumpExecute($console);
-
-               $this->assertEquals('The domain \'pod.ordoevangelistarum.com\' is now updated. (Reason: \'Other reason\')' . PHP_EOL, $txt);
-       }
-
-       /**
-        * Test blockedservers remove command
-        */
-       public function testRemoveBlockedServer()
-       {
-               $this->configMock
-                       ->shouldReceive('get')
-                       ->with('system', 'blocklist')
-                       ->andReturn($this->defaultBlockList)
-                       ->once();
-
-               $newBlockList = [
-                       [
-                               'domain' => 'social.nobodyhasthe.biz',
-                               'reason' => 'Illegal content',
-                       ],
-               ];
-
-               $this->configMock
-                       ->shouldReceive('set')
-                       ->with('system', 'blocklist', $newBlockList)
-                       ->andReturn(true)
-                       ->once();
-
-               $console = new ServerBlock($this->consoleArgv);
-               $console->setArgument(0, 'remove');
-               $console->setArgument(1, 'pod.ordoevangelistarum.com');
-               $txt = $this->dumpExecute($console);
-
-               $this->assertEquals('The domain \'pod.ordoevangelistarum.com\' is not more blocked' . PHP_EOL, $txt);
-       }
-
-       /**
-        * Test blockedservers with a wrong command
-        */
-       public function testBlockedServersWrongCommand()
-       {
-               $console = new ServerBlock($this->consoleArgv);
-               $console->setArgument(0, 'wrongcommand');
-               $txt = $this->dumpExecute($console);
-
-               $this->assertStringStartsWith('[Warning] Unknown command', $txt);
-       }
-
-       /**
-        * Test blockedservers remove with not existing domain
-        */
-       public function testRemoveBlockedServerNotExist()
-       {
-               $this->configMock
-                       ->shouldReceive('get')
-                       ->with('system', 'blocklist')
-                       ->andReturn($this->defaultBlockList)
-                       ->once();
-
-               $console = new ServerBlock($this->consoleArgv);
-               $console->setArgument(0, 'remove');
-               $console->setArgument(1, 'not.exiting');
-               $txt = $this->dumpExecute($console);
-
-               $this->assertEquals('The domain \'not.exiting\' is not blocked.' . PHP_EOL, $txt);
-       }
-
-       /**
-        * Test blockedservers add command without argument
-        */
-       public function testAddBlockedServerMissingArgument()
-       {
-               $console = new ServerBlock($this->consoleArgv);
-               $console->setArgument(0, 'add');
-               $txt = $this->dumpExecute($console);
-
-               $this->assertStringStartsWith('[Warning] Add needs a domain and optional a reason.', $txt);
-       }
-
-       /**
-        * Test blockedservers add command without save
-        */
-       public function testAddBlockedServerNoSave()
-       {
-               $this->configMock
-                       ->shouldReceive('get')
-                       ->with('system', 'blocklist')
-                       ->andReturn($this->defaultBlockList)
-                       ->once();
-
-               $newBlockList = $this->defaultBlockList;
-               $newBlockList[] = [
-                       'domain' => 'testme.now',
-                       'reason' => ServerBlock::DEFAULT_REASON,
-               ];
-
-               $this->configMock
-                       ->shouldReceive('set')
-                       ->with('system', 'blocklist', $newBlockList)
-                       ->andReturn(false)
-                       ->once();
-
-               $console = new ServerBlock($this->consoleArgv);
-               $console->setArgument(0, 'add');
-               $console->setArgument(1, 'testme.now');
-               $txt = $this->dumpExecute($console);
-
-               $this->assertEquals('Couldn\'t save \'testme.now\' as blocked server' . PHP_EOL, $txt);
-       }
-
-       /**
-        * Test blockedservers remove command without save
-        */
-       public function testRemoveBlockedServerNoSave()
-       {
-               $this->configMock
-                       ->shouldReceive('get')
-                       ->with('system', 'blocklist')
-                       ->andReturn($this->defaultBlockList)
-                       ->once();
-
-               $newBlockList = [
-                       [
-                               'domain' => 'social.nobodyhasthe.biz',
-                               'reason' => 'Illegal content',
-                       ],
-               ];
-
-               $this->configMock
-                       ->shouldReceive('set')
-                       ->with('system', 'blocklist', $newBlockList)
-                       ->andReturn(false)
-                       ->once();
-
-               $console = new ServerBlock($this->consoleArgv);
-               $console->setArgument(0, 'remove');
-               $console->setArgument(1, 'pod.ordoevangelistarum.com');
-               $txt = $this->dumpExecute($console);
-
-               $this->assertEquals('Couldn\'t remove \'pod.ordoevangelistarum.com\' from blocked servers' . PHP_EOL, $txt);
-       }
-
-       /**
-        * Test blockedservers remove command without argument
-        */
-       public function testRemoveBlockedServerMissingArgument()
-       {
-               $console = new ServerBlock($this->consoleArgv);
-               $console->setArgument(0, 'remove');
-               $txt = $this->dumpExecute($console);
-
-               $this->assertStringStartsWith('[Warning] Remove needs a second parameter.', $txt);
-       }
-
-       /**
-        * Test the blockedservers help
-        */
-       public function testBlockedServersHelp()
-       {
-               $console = new ServerBlock($this->consoleArgv);
-               $console->setOption('help', true);
-               $txt = $this->dumpExecute($console);
-
-               $help = <<<HELP
-console serverblock - Manage blocked servers
-Usage
-       bin/console serverblock [-h|--help|-?] [-v]
-       bin/console serverblock add <server> <reason> [-h|--help|-?] [-v]
-       bin/console serverblock remove <server> [-h|--help|-?] [-v]
-
-Description
-       With this tool, you can list the current blocked servers
-    or you can add / remove a blocked server from the list
-
-Options
-    -h|--help|-? Show help information
-    -v           Show more debug information.
-
-HELP;
-
-               $this->assertEquals($help, $txt);
-       }
-}
index dabd422dbb4538a81c7b6554483791023f8d8ce3..caa6c64d964416b97faa5edab4c79fd2f6f65a27 100644 (file)
@@ -5,8 +5,8 @@
   <script>var baseurl="<?php echo Friendica\Core\System::baseUrl() ?>";</script>
   <?php if(!empty($page['htmlhead'])) echo $page['htmlhead'] ?>
 </head>
-<body>
-       <section class="minimal" style="margin:0px!important; padding:0px!important; float:none!important;display:block!important;"><?php if(!empty($page['content'])) echo $page['content']; ?>
+<body class="minimal">
+       <section><?php if(!empty($page['content'])) echo $page['content']; ?>
                <div id="page-footer"></div>
        </section>
 </body>
diff --git a/view/templates/admin/addon_details.tpl b/view/templates/admin/addon_details.tpl
deleted file mode 100644 (file)
index 7479b13..0000000
+++ /dev/null
@@ -1,37 +0,0 @@
-
-<div id='adminpage'>
-       <h1>{{$title}} - {{$page}}</h1>
-
-       <p><span class='toggleaddon icon {{$status}}'></span> {{$info.name}} - {{$info.version}} : <a href="{{$baseurl}}/admin/{{$function}}/{{$addon}}/?a=t&amp;t={{$form_security_token}}">{{$action}}</a></p>
-       <p>{{$info.description nofilter}}</p>
-
-       <p class="author">{{$str_author}}
-       {{foreach $info.author as $a name=authors}}
-               {{if $a.link}}<a href="{{$a.link}}">{{$a.name}}</a>{{else}}{{$a.name}}{{/if}}{{if $smarty.foreach.authors.last}}{{else}}, {{/if}}
-       {{/foreach}}
-       </p>
-
-       <p class="maintainer">{{$str_maintainer}}
-       {{foreach $info.maintainer as $a name=maintainers}}
-               {{if $a.link}}<a href="{{$a.link}}">{{$a.name}}</a>{{else}}{{$a.name}}{{/if}}{{if $smarty.foreach.maintainers.last}}{{else}}, {{/if}}
-       {{/foreach}}
-       </p>
-
-       {{if $screenshot}}
-       <a href="{{$screenshot.0}}" class='screenshot'><img src="{{$screenshot.0}}" alt="{{$screenshot.1}}" /></a>
-       {{/if}}
-
-       {{if $admin_form}}
-       <h3>{{$settings}}</h3>
-       <form method="post" action="{{$baseurl}}/admin/{{$function}}/{{$addon}}">
-               {{$admin_form nofilter}}
-       </form>
-       {{/if}}
-
-       {{if $readme}}
-       <h3>Readme</h3>
-       <div id="addon_readme">
-               {{$readme nofilter}}
-       </div>
-       {{/if}}
-</div>
diff --git a/view/templates/admin/addons.tpl b/view/templates/admin/addons.tpl
deleted file mode 100644 (file)
index c144a5e..0000000
+++ /dev/null
@@ -1,22 +0,0 @@
-
-<div id='adminpage'>
-       <h1>{{$title}} - {{$page}}</h1>
-               {{if $pcount eq 0}}
-                   <div class="error-message">
-                   {{$noplugshint}}
-                   </div>
-               {{else}}
-               <a class="btn" href="{{$baseurl}}/admin/{{$function}}?a=r&amp;t={{$form_security_token}}">{{$reload}}</a>
-               <ul id='addonslist'>
-               {{foreach $addons as $p}}
-                       <li class='addon {{$p.1}}'>
-                               <a class='toggleaddon' href='{{$baseurl}}/admin/{{$function}}/{{$p.0}}?a=t&amp;t={{$form_security_token}}' title="{{if $p.1==on}}Disable{{else}}Enable{{/if}}" ><span class='icon {{$p.1}}'></span></a>
-                               <a href='{{$baseurl}}/admin/{{$function}}/{{$p.0}}'><span class='name'>{{$p.2.name}}</span></a> - <span class="version">{{$p.2.version}}</span>
-                               {{if $p.2.experimental}} {{$experimental}} {{/if}}{{if $p.2.unsupported}} {{$unsupported}} {{/if}}
-
-                               <div class='desc'>{{$p.2.description nofilter}}</div>
-                       </li>
-               {{/foreach}}
-               </ul>
-               {{/if}}
-</div>
diff --git a/view/templates/admin/addons/details.tpl b/view/templates/admin/addons/details.tpl
new file mode 100644 (file)
index 0000000..f5bb165
--- /dev/null
@@ -0,0 +1,37 @@
+
+<div id="adminpage">
+       <h1>{{$title}} - {{$page}}</h1>
+
+       <p><span class="toggleaddon icon {{$status}}"></span> {{$info.name}} - {{$info.version}} : <a href="{{$baseurl}}/admin/{{$function}}/{{$addon}}/?action=toggle&amp;t={{$form_security_token}}">{{$action}}</a></p>
+       <p>{{$info.description nofilter}}</p>
+
+       <p class="author">{{$str_author}}
+       {{foreach $info.author as $a name=authors}}
+               {{if $a.link}}<a href="{{$a.link}}">{{$a.name}}</a>{{else}}{{$a.name}}{{/if}}{{if $smarty.foreach.authors.last}}{{else}}, {{/if}}
+       {{/foreach}}
+       </p>
+
+       <p class="maintainer">{{$str_maintainer}}
+       {{foreach $info.maintainer as $a name=maintainers}}
+               {{if $a.link}}<a href="{{$a.link}}">{{$a.name}}</a>{{else}}{{$a.name}}{{/if}}{{if $smarty.foreach.maintainers.last}}{{else}}, {{/if}}
+       {{/foreach}}
+       </p>
+
+       {{if $screenshot}}
+       <a href="{{$screenshot.0}}" class="screenshot"><img src="{{$screenshot.0}}" alt="{{$screenshot.1}}" /></a>
+       {{/if}}
+
+       {{if $admin_form}}
+       <h3>{{$settings}}</h3>
+       <form method="post" action="{{$baseurl}}/admin/{{$function}}/{{$addon}}">
+               {{$admin_form nofilter}}
+       </form>
+       {{/if}}
+
+       {{if $readme}}
+       <h3>Readme</h3>
+       <div id="addon_readme">
+               {{$readme nofilter}}
+       </div>
+       {{/if}}
+</div>
diff --git a/view/templates/admin/addons/embed.tpl b/view/templates/admin/addons/embed.tpl
new file mode 100644 (file)
index 0000000..71fb12d
--- /dev/null
@@ -0,0 +1,5 @@
+
+<form method="post" action="{{$action}}">
+    <input type="hidden" name="form_security_token" value="{{$form_security_token}}">
+       {{$form nofilter}}
+</form>
diff --git a/view/templates/admin/addons/index.tpl b/view/templates/admin/addons/index.tpl
new file mode 100644 (file)
index 0000000..4a2b057
--- /dev/null
@@ -0,0 +1,24 @@
+
+<div id="adminpage">
+       <h1>{{$title}} - {{$page}}</h1>
+{{if $pcount eq 0}}
+       <div class="error-message">
+       {{$noplugshint}}
+       </div>
+{{else}}
+       <a class="btn" href="{{$baseurl}}/admin/{{$function}}?action=reload&amp;t={{$form_security_token}}">{{$reload}}</a>
+       <ul id="addonslist">
+       {{foreach $addons as $p}}
+               <li class="addon {{$p.1}}">
+                       <span class="offset-anchor" id="{{$p.0}}"></span>
+                       <a class="toggleaddon" href="{{$baseurl}}/admin/{{$function}}?action=toggle&amp;addon={{$p.0}}&amp;t={{$form_security_token}}#{{$p.0}}" title="{{if $p.1==on}}Disable{{else}}Enable{{/if}}">
+                               <span class="icon {{$p.1}}"></span>
+                       </a>
+                       <a href="{{$baseurl}}/admin/{{$function}}/{{$p.0}}"><span class="name">{{$p.2.name}}</span></a> - <span class="version">{{$p.2.version}}</span>
+                       {{if $p.2.experimental}} {{$experimental}} {{/if}}{{if $p.2.unsupported}} {{$unsupported}} {{/if}}
+                       <div class="desc">{{$p.2.description nofilter}}</div>
+               </li>
+       {{/foreach}}
+       </ul>
+{{/if}}
+</div>
diff --git a/view/templates/admin/blocklist.tpl b/view/templates/admin/blocklist.tpl
deleted file mode 100644 (file)
index 1484c98..0000000
+++ /dev/null
@@ -1,33 +0,0 @@
-<script>
-       function confirm_delete(uname){
-               return confirm("{{$confirm_delete}}".format(uname));
-       }
-</script>
-<div id="adminpage">
-       <h1>{{$title}} - {{$page}}</h1>
-       <p>{{$intro}}</p>
-       <p>{{$public}}</p>
-
-       <h2>{{$addtitle}}</h2>
-       <form action="{{$baseurl}}/admin/blocklist" method="post">
-               <input type="hidden" name="form_security_token" value="{{$form_security_token}}">
-               {{include file="field_input.tpl" field=$newdomain}}
-               {{include file="field_input.tpl" field=$newreason}}
-               <div class="submit"><input type="submit" name="page_blocklist_save" value="{{$submit}}" /></div>
-       </form>
-
-       {{if $entries}}
-       <h2>{{$currenttitle}}</h2>
-       <p>{{$currentintro}}</p>
-       <form action="{{$baseurl}}/admin/blocklist" method="post">
-               <input type="hidden" name="form_security_token" value="{{$form_security_token}}">
-               {{foreach $entries as $e}}
-                       {{include file="field_input.tpl" field=$e.domain}}
-                       {{include file="field_input.tpl" field=$e.reason}}
-                       {{include file="field_checkbox.tpl" field=$e.delete}}
-               {{/foreach}}
-               <div class="submit"><input type="submit" name="page_blocklist_edit" value="{{$savechanges}}" /></div>
-               {{/if}}
-       </form>
-
-</div>
diff --git a/view/templates/admin/blocklist/contact.tpl b/view/templates/admin/blocklist/contact.tpl
new file mode 100644 (file)
index 0000000..228ad69
--- /dev/null
@@ -0,0 +1,63 @@
+<script>
+       function selectall(cls) {
+               $('.' + cls).prop('checked', true);
+               return false;
+       }
+       function selectnone(cls) {
+               $('.' + cls).prop('checked', false);
+               return false;
+       }
+</script>
+<div id="adminpage">
+       <h1>{{$title}} - {{$page}}</h1>
+       <p>{{$description nofilter}}</p>
+       <form action="{{$baseurl}}/admin/blocklist/contact" method="post">
+        <input type="hidden" name="form_security_token" value="{{$form_security_token}}">
+
+               <h3>{{$h_contacts}}</h3>
+       {{if $contacts}}
+               <table id="contactblock">
+                       <thead>
+                               <tr>
+                                       <th></th>
+                                               {{foreach $th_contacts as $th}}
+                                       <th>
+                                               {{$th}}
+                                       </th>
+                                       {{/foreach}}
+                                       <th></th>
+                               </tr>
+                       </thead>
+                       <tbody>
+                               {{foreach $contacts as $contact}}
+                               <tr>
+                                       <td class="checkbox"><input type="checkbox" class="contacts_ckbx" id="id_contact_{{$contact.id}}" name="contacts[]" value="{{$contact.id}}"/></td>
+                                       <td><img class="icon" src="{{$contact.micro}}" alt="{{$contact.nickname}}" title="{{$contact.nickname}}"></td>
+                                       <td class="name">{{$contact.name}}</td>
+                                       <td class="addr">{{$contact.addr}}</td>
+                                       <td class="addr"><a href="{{$contact.url}}" title="{{$contact.nickname}}" >{{$contact.url}}</a></td>
+                               </tr>
+                               {{/foreach}}
+                       </tbody>
+               </table>
+               <p><a href="#" onclick="return selectall('contacts_ckbx');">{{$select_all}}</a> | <a href="#" onclick="return selectnone('contacts_ckbx');">{{$select_none}}</a></p>
+               {{$paginate nofilter}}
+               <div class="submit"><input type="submit" name="page_contactblock_unblock" value="{{$unblock}}" /></div>
+       {{else}}
+               <p>{{$no_data}}</p>
+       {{/if}}
+       </form>
+
+       <h3>{{$h_newblock}}</h3>
+       <form action="{{$baseurl}}/admin/blocklist/contact" method="post">
+               <input type="hidden" name="form_security_token" value="{{$form_security_token}}">
+               <table id="contactblock">
+                       <tbody>
+                               <tr>
+                                       <td>{{include file="field_input.tpl" field=$contacturl}}</td>
+                               </tr>
+                       </tbody>
+               </table>
+               <div class="submit"><input type="submit" name="page_contactblock_block" value="{{$submit}}" /></div>
+       </form>
+</div>
diff --git a/view/templates/admin/blocklist/server.tpl b/view/templates/admin/blocklist/server.tpl
new file mode 100644 (file)
index 0000000..beea96f
--- /dev/null
@@ -0,0 +1,33 @@
+<script>
+       function confirm_delete(uname){
+               return confirm("{{$confirm_delete}}".format(uname));
+       }
+</script>
+<div id="adminpage">
+       <h1>{{$title}} - {{$page}}</h1>
+       <p>{{$intro}}</p>
+       <p>{{$public}}</p>
+
+       <h2>{{$addtitle}}</h2>
+       <form action="{{$baseurl}}/admin/blocklist/server" method="post">
+               <input type="hidden" name="form_security_token" value="{{$form_security_token}}">
+               {{include file="field_input.tpl" field=$newdomain}}
+               {{include file="field_input.tpl" field=$newreason}}
+               <div class="submit"><input type="submit" name="page_blocklist_save" value="{{$submit}}" /></div>
+       </form>
+
+       {{if $entries}}
+       <h2>{{$currenttitle}}</h2>
+       <p>{{$currentintro}}</p>
+       <form action="{{$baseurl}}/admin/blocklist/server" method="post">
+               <input type="hidden" name="form_security_token" value="{{$form_security_token}}">
+               {{foreach $entries as $e}}
+                       {{include file="field_input.tpl" field=$e.domain}}
+                       {{include file="field_input.tpl" field=$e.reason}}
+                       {{include file="field_checkbox.tpl" field=$e.delete}}
+               {{/foreach}}
+               <div class="submit"><input type="submit" name="page_blocklist_edit" value="{{$savechanges}}" /></div>
+               {{/if}}
+       </form>
+
+</div>
diff --git a/view/templates/admin/contactblock.tpl b/view/templates/admin/contactblock.tpl
deleted file mode 100644 (file)
index f454938..0000000
+++ /dev/null
@@ -1,63 +0,0 @@
-<script>
-       function selectall(cls) {
-               $('.' + cls).prop('checked', true);
-               return false;
-       }
-       function selectnone(cls) {
-               $('.' + cls).prop('checked', false);
-               return false;
-       }
-</script>
-<div id="adminpage">
-       <h1>{{$title}} - {{$page}}</h1>
-       <p>{{$description nofilter}}</p>
-       <form action="{{$baseurl}}/admin/contactblock" method="post">
-        <input type="hidden" name="form_security_token" value="{{$form_security_token}}">
-
-               <h3>{{$h_contacts}}</h3>
-       {{if $contacts}}
-               <table id="contactblock">
-                       <thead>
-                               <tr>
-                                       <th></th>
-                                               {{foreach $th_contacts as $th}}
-                                       <th>
-                                               {{$th}}
-                                       </th>
-                                       {{/foreach}}
-                                       <th></th>
-                               </tr>
-                       </thead>
-                       <tbody>
-                               {{foreach $contacts as $contact}}
-                               <tr>
-                                       <td class="checkbox"><input type="checkbox" class="contacts_ckbx" id="id_contact_{{$contact.id}}" name="contacts[]" value="{{$contact.id}}"/></td>
-                                       <td><img class="icon" src="{{$contact.micro}}" alt="{{$contact.nickname}}" title="{{$contact.nickname}}"></td>
-                                       <td class="name">{{$contact.name}}</td>
-                                       <td class="addr">{{$contact.addr}}</td>
-                                       <td class="addr"><a href="{{$contact.url}}" title="{{$contact.nickname}}" >{{$contact.url}}</a></td>
-                               </tr>
-                               {{/foreach}}
-                       </tbody>
-               </table>
-               <p><a href="#" onclick="return selectall('contacts_ckbx');">{{$select_all}}</a> | <a href="#" onclick="return selectnone('contacts_ckbx');">{{$select_none}}</a></p>
-               {{$paginate nofilter}}
-               <div class="submit"><input type="submit" name="page_contactblock_unblock" value="{{$unblock}}" /></div>
-       {{else}}
-               <p>{{$no_data}}</p>
-       {{/if}}
-       </form>
-
-       <h3>{{$h_newblock}}</h3>
-       <form action="{{$baseurl}}/admin/contactblock" method="post">
-               <input type="hidden" name="form_security_token" value="{{$form_security_token}}">
-               <table id="contactblock">
-                       <tbody>
-                               <tr>
-                                       <td>{{include file="field_input.tpl" field=$contacturl}}</td>
-                               </tr>
-                       </tbody>
-               </table>
-               <div class="submit"><input type="submit" name="page_contactblock_block" value="{{$submit}}" /></div>
-       </form>
-</div>
diff --git a/view/templates/admin/dbsync/failed_updates.tpl b/view/templates/admin/dbsync/failed_updates.tpl
new file mode 100644 (file)
index 0000000..f75f266
--- /dev/null
@@ -0,0 +1,19 @@
+
+<div id="adminpage">
+       <h2>{{$banner}}</h2>
+
+       <div id="failed_updates_desc">{{$desc nofilter}}</div>
+
+       {{if $failed}}
+       {{foreach $failed as $f}}
+               <h4>{{$f}}</h4>
+
+               <ul>
+                       <li><a href="{{$baseurl}}/admin/dbsync/mark/{{$f}}">{{$mark}}</a></li>
+                       <li><a href="{{$baseurl}}/admin/dbsync/{{$f}}">{{$apply}}</a></li>
+               </ul>
+
+               <hr />
+       {{/foreach}}
+       {{/if}}
+</div>
diff --git a/view/templates/admin/dbsync/structure_check.tpl b/view/templates/admin/dbsync/structure_check.tpl
new file mode 100644 (file)
index 0000000..06d61a0
--- /dev/null
@@ -0,0 +1,8 @@
+
+<div id="adminpage">
+       <h2>{{$banner}}</h2>
+
+       <p><a href="{{$baseurl}}/admin/dbsync/check">{{$check}}</a></p>
+
+       <hr />
+</div>
diff --git a/view/templates/admin/deleteitem.tpl b/view/templates/admin/deleteitem.tpl
deleted file mode 100644 (file)
index f5abc96..0000000
+++ /dev/null
@@ -1,12 +0,0 @@
-<div id="adminpage">
-       <h1>{{$title}} - {{$page}}</h1>
-       <p>{{$intro1}}</p>
-       <p>{{$intro2}}</p>
-
-       <form action="{{$baseurl}}/admin/deleteitem" method="post">
-               <input type="hidden" name="form_security_token" value="{{$form_security_token}}">
-               {{include file="field_input.tpl" field=$deleteitemguid}}
-               <div class="submit"><input type="submit" name="page_deleteitem_submit" value="{{$submit}}" /></div>
-       </form>
-
-</div>
diff --git a/view/templates/admin/features.tpl b/view/templates/admin/features.tpl
new file mode 100644 (file)
index 0000000..f0b696f
--- /dev/null
@@ -0,0 +1,26 @@
+
+<div id="adminpage">
+       <h1>{{$title}}</h1>
+
+       <form action="admin/features" method="post" autocomplete="off">
+       <input type='hidden' name='form_security_token' value='{{$form_security_token}}'>
+
+       {{foreach $features as $g => $f}}
+       <h3 class="settings-heading"><a href="javascript:;">{{$f.0}}</a></h3>
+
+       <div class="settings-content-block">
+               {{foreach $f.1 as $fcat}}
+                       <div class="settings-block">
+                       {{include file="field_yesno.tpl" field=$fcat.0}}
+                       {{include file="field_yesno.tpl" field=$fcat.1}}
+                       </div>
+               {{/foreach}}
+
+               <div class="settings-submit-wrapper" >
+                       <input type="submit" name="submit" class="settings-features-submit" value="{{$submit}}" />
+               </div>
+       </div>
+       {{/foreach}}
+
+       </form>
+</div>
diff --git a/view/templates/admin/item/delete.tpl b/view/templates/admin/item/delete.tpl
new file mode 100644 (file)
index 0000000..497b776
--- /dev/null
@@ -0,0 +1,12 @@
+<div id="adminpage">
+       <h1>{{$title}} - {{$page}}</h1>
+       <p>{{$intro1}}</p>
+       <p>{{$intro2}}</p>
+
+       <form action="{{$baseurl}}/admin/item/delete" method="post">
+               <input type="hidden" name="form_security_token" value="{{$form_security_token}}">
+               {{include file="field_input.tpl" field=$deleteitemguid}}
+               <div class="submit"><input type="submit" name="page_deleteitem_submit" value="{{$submit}}" /></div>
+       </form>
+
+</div>
diff --git a/view/templates/admin/item/source.tpl b/view/templates/admin/item/source.tpl
new file mode 100644 (file)
index 0000000..4f985cb
--- /dev/null
@@ -0,0 +1,65 @@
+<h2>Item Source</h2>
+<form action="admin/item/source" method="get" class="panel panel-default">
+       <div class="panel-body">
+               <div class="form-group">
+                       {{include file="field_input.tpl" field=$guid}}
+               </div>
+               <p><button type="submit" class="btn btn-primary">Submit</button></p>
+       </div>
+</form>
+
+{{if $source}}
+<div class="itemsource-results">
+       <div class="panel panel-default">
+               <div class="panel-heading">
+                       <h3 class="panel-title">Item Id</h3>
+               </div>
+               <div class="panel-body">
+                       {{$item_id}}
+               </div>
+       </div>
+       <div class="panel panel-default">
+               <div class="panel-heading">
+                       <h3 class="panel-title">Item URI</h3>
+               </div>
+               <div class="panel-body">
+                       {{$item_uri}}
+               </div>
+       </div>
+       <div class="panel panel-default">
+               <div class="panel-heading">
+                       <h3 class="panel-title">Terms</h3>
+               </div>
+               <div class="panel-body">
+                       <table class="table table-condensed table-striped">
+                               <tr>
+                                       <th>Type</th>
+                                       <th>Term</th>
+                                       <th>URL</th>
+                               </tr>
+               {{foreach $terms as $term}}
+                               <tr>
+                                       <td>
+                       {{if $term.type == 1}}Tag{{/if}}
+                       {{if $term.type == 2}}Mention{{/if}}
+                       {{if $term.type == 8}}Implicit Mention{{/if}}
+                                       </td>
+                                       <td>
+                                               {{$term.term}}
+                                       </td>
+                                       <td>
+                                               {{$term.url}}
+                                       </td>
+                               </tr>
+               {{/foreach}}
+                       </table>
+               </div>
+       </div>
+       <div class="panel panel-default">
+               <div class="panel-heading">
+                       <h3 class="panel-title">Source</h3>
+               </div>
+               <pre><code class="language-php">{{$source}}</code></pre>
+       </div>
+</div>
+{{/if}}
diff --git a/view/templates/admin/logs.tpl b/view/templates/admin/logs.tpl
deleted file mode 100644 (file)
index a218a38..0000000
+++ /dev/null
@@ -1,22 +0,0 @@
-<div id='adminpage'>
-    <h1>{{$title}} - {{$page}}</h1>
-       
-       <form action="{{$baseurl}}/admin/logs" method="post">
-           <input type='hidden' name='form_security_token' value="{{$form_security_token}}">
-
-           {{include file="field_checkbox.tpl" field=$debugging}}
-           {{include file="field_input.tpl" field=$logfile}}
-           {{include file="field_select.tpl" field=$loglevel}}
-       
-           <div class="submit"><input type="submit" name="page_logs" value="{{$submit}}" /></div>
-       
-       </form>
-
-       <h2>{{$phpheader}}</h2>
-       <div>
-               <p>{{$phplogenabled}}<p>
-               <p>{{$phphint}}</p>
-               <pre>{{$phplogcode}}</pre>
-       </div>
-       
-</div>
diff --git a/view/templates/admin/logs/settings.tpl b/view/templates/admin/logs/settings.tpl
new file mode 100644 (file)
index 0000000..b584605
--- /dev/null
@@ -0,0 +1,22 @@
+<div id='adminpage'>
+    <h1>{{$title}} - {{$page}}</h1>
+       
+       <form action="{{$baseurl}}/admin/logs/settings" method="post">
+           <input type='hidden' name='form_security_token' value="{{$form_security_token}}">
+
+           {{include file="field_checkbox.tpl" field=$debugging}}
+           {{include file="field_input.tpl" field=$logfile}}
+           {{include file="field_select.tpl" field=$loglevel}}
+       
+           <div class="submit"><input type="submit" name="page_logs" value="{{$submit}}" /></div>
+       
+       </form>
+
+       <h2>{{$phpheader}}</h2>
+       <div>
+               <p>{{$phplogenabled}}<p>
+               <p>{{$phphint}}</p>
+               <pre>{{$phplogcode}}</pre>
+       </div>
+       
+</div>
diff --git a/view/templates/admin/logs/view.tpl b/view/templates/admin/logs/view.tpl
new file mode 100644 (file)
index 0000000..9ac5acd
--- /dev/null
@@ -0,0 +1,6 @@
+<div id="adminpage">
+       <h1>{{$title}} - {{$page}}</h1>
+       
+       <h3>{{$logname}}</h3>
+       <div style="width:100%; height:400px; overflow: auto; "><pre>{{$data}}</pre></div>
+</div>
index aaca9b014877d37db584bf1e501da73277eef076..5bab58a5e91937b044dcdfc90747f20b9d3cbfab 100644 (file)
@@ -5,20 +5,16 @@
        <table>
                <tr>
                        <th>{{$id_header}}</th>
-                       <th>{{$to_header}}</th>
-                       <th>{{$url_header}}</th>
-                       <th>{{$network_header}}</th>
+                       <th>{{$param_header}}</th>
                        <th>{{$created_header}}</th>
-                       <th>{{$last_header}}</th>
+                       <th>{{$prio_header}}</th>
                </tr>
                {{foreach $entries as $e}}
                <tr>
                        <td>{{$e.id}}</td>
-                       <td>{{$e.name}}</td>
-                       <td><a href="{{$e.nurl}}">{{$e.nurl}}</a></td>
-                       <td>{{$e.network}}</td>
+                       <td>{{$e.parameter}}</td>
                        <td>{{$e.created}}</td>
-                       <td>{{$e.last}}</td>
+                       <td>{{$e.priority}}</td>
                </tr>
                {{/foreach}}
        </table>
diff --git a/view/templates/admin/settings_features.tpl b/view/templates/admin/settings_features.tpl
deleted file mode 100644 (file)
index f0b696f..0000000
+++ /dev/null
@@ -1,26 +0,0 @@
-
-<div id="adminpage">
-       <h1>{{$title}}</h1>
-
-       <form action="admin/features" method="post" autocomplete="off">
-       <input type='hidden' name='form_security_token' value='{{$form_security_token}}'>
-
-       {{foreach $features as $g => $f}}
-       <h3 class="settings-heading"><a href="javascript:;">{{$f.0}}</a></h3>
-
-       <div class="settings-content-block">
-               {{foreach $f.1 as $fcat}}
-                       <div class="settings-block">
-                       {{include file="field_yesno.tpl" field=$fcat.0}}
-                       {{include file="field_yesno.tpl" field=$fcat.1}}
-                       </div>
-               {{/foreach}}
-
-               <div class="settings-submit-wrapper" >
-                       <input type="submit" name="submit" class="settings-features-submit" value="{{$submit}}" />
-               </div>
-       </div>
-       {{/foreach}}
-
-       </form>
-</div>
index 6da3e35f56869c917b596e66f73c7bf5dfc0c861..823753768eba3291c96ae961dc004259ba644175 100644 (file)
@@ -1,45 +1,12 @@
 <script>
        $(function(){
-
                $("#cnftheme").click(function(){
-                       $.colorbox({
-                               width: 800,
-                               height: '90%',
-                               /*onOpen: function(){
-                                       var theme = $("#id_theme :selected").val();
-                                       $("#cnftheme").attr('href',"{{$baseurl}}/admin/themes/"+theme);
-                               },*/
-                               iframe: true,
-                               href: "{{$baseurl}}/admin/themes/" + $("#id_theme :selected").val() + "?mode=minimal",
-                               onComplete: function(){
-                                       $("div#fancybox-content form").submit(function(e){
-                                               var url = $(this).attr('action');
-                                               // can't get .serialize() to work...
-                                               var data={};
-                                               $(this).find("input").each(function(){
-                                                       data[$(this).attr('name')] = $(this).val();
-                                               });
-                                               $(this).find("select").each(function(){
-                                                       data[$(this).attr('name')] = $(this).children(":selected").val();
-                                               });
-                                               console.log(":)", url, data);
-
-                                               $.post(url, data, function(data) {
-                                                       if(timer) clearTimeout(timer);
-                                                       NavUpdate();
-                                                       $.colorbox.close();
-                                               })
-
-                                               return false;
-                                       });
-
-                               }
-                       });
+                       document.location.assign("{{$baseurl}}/admin/themes/" + $("#id_theme :selected").val());
                        return false;
                });
        });
 </script>
-<div id='adminpage'>
+<div id="adminpage">
        <h1>{{$title}} - {{$page}}</h1>
 
        <form action="{{$baseurl}}/admin/site" method="post">
index 09419929d2168984a804cff287993a6c8dcc89a8..121eb833b9ae1284add8cd50d0cfc6eed9caf1d3 100644 (file)
@@ -1,7 +1,7 @@
 
 <div id='adminpage'>
        <h1>{{$title}} - {{$page}}</h1>
-{{if $showwarning}}
+{{if $warningtext|count}}
        <div id="admin-warning-message-wrapper">
                {{foreach $warningtext as $wt}}
                <p class="warning-message">{{$wt nofilter}}</p>
@@ -11,7 +11,7 @@
 
        <dl>
                <dt>{{$queues.label}}</dt>
-               <dd><a href="{{$baseurl}}/admin/deferred">{{$queues.deferred}}</a> - <a href="{{$baseurl}}/admin/workerqueue">{{$queues.workerq}}</a></dd>
+               <dd><a href="{{$baseurl}}/admin/queue/deferred">{{$queues.deferred}}</a> - <a href="{{$baseurl}}/admin/queue">{{$queues.workerq}}</a></dd>
        </dl>
        <dl>
                <dt>{{$pending.0}}</dt>
index 88feb6136a22148ede0f58f902620df5ea74d8d7..6ca85fe7aaf0740f353b623ec8320a499c491a25 100644 (file)
                                </tbody>
                        </table>
                        <div class='selectall'><a href='#' onclick="return selectall('users_ckbx');">{{$select_all}}</a></div>
-                       <div class="submit"><input type="submit" name="page_users_block" value="{{$block}}/{{$unblock}}" /> <input type="submit" name="page_users_delete" value="{{$delete}}" onclick="return confirm_delete_multi()" /></div>
+                       <div class="submit">
+                               <input type="submit" name="page_users_block" value="{{$block}}" />
+                               <input type="submit" name="page_users_unblock" value="{{$unblock}}" />
+                               <input type="submit" name="page_users_delete" value="{{$delete}}" onclick="return confirm_delete_multi()" />
+                       </div>
                {{else}}
                        NO USERS?!?
                {{/if}}
diff --git a/view/templates/admin/viewlogs.tpl b/view/templates/admin/viewlogs.tpl
deleted file mode 100644 (file)
index c80264c..0000000
+++ /dev/null
@@ -1,6 +0,0 @@
-<div id='adminpage'>
-       <h1>{{$title}} - {{$page}}</h1>
-       
-       <h3>{{$logname}}</h3>
-       <div style="width:100%; height:400px; overflow: auto; "><pre>{{$data}}</pre></div>
-</div>
diff --git a/view/templates/admin/workerqueue.tpl b/view/templates/admin/workerqueue.tpl
deleted file mode 100644 (file)
index 5bab58a..0000000
+++ /dev/null
@@ -1,21 +0,0 @@
-<div id='adminpage'>
-       <h1>{{$title}} - {{$page}} ({{$count}})</h1>
-       
-       <p>{{$info}}</p>
-       <table>
-               <tr>
-                       <th>{{$id_header}}</th>
-                       <th>{{$param_header}}</th>
-                       <th>{{$created_header}}</th>
-                       <th>{{$prio_header}}</th>
-               </tr>
-               {{foreach $entries as $e}}
-               <tr>
-                       <td>{{$e.id}}</td>
-                       <td>{{$e.parameter}}</td>
-                       <td>{{$e.created}}</td>
-                       <td>{{$e.priority}}</td>
-               </tr>
-               {{/foreach}}
-       </table>
-</div>
index 72aedd8b70aa02afc9a0f5e588a6eaa1401ea2e8..b6f24ec3b292ac182e618274dbe7b899dbc68e8d 100644 (file)
@@ -9,7 +9,6 @@
 <div id="photo-album-edit-name-end"></div>
 
 <input id="photo-album-edit-submit" type="submit" name="submit" value="{{$submit}}" />
-<input id="photo-album-edit-drop" type="submit" name="dropalbum" value="{{$dropsubmit}}" onclick="return confirmDelete();" />
 
 </form>
 </div>
diff --git a/view/templates/debug/itemsource.tpl b/view/templates/debug/itemsource.tpl
deleted file mode 100644 (file)
index 0d925b3..0000000
+++ /dev/null
@@ -1,65 +0,0 @@
-<h2>Item Source</h2>
-<form action="itemsource" method="get" class="panel panel-default">
-       <div class="panel-body">
-               <div class="form-group">
-                       {{include file="field_input.tpl" field=$guid}}
-               </div>
-               <p><button type="submit" class="btn btn-primary">Submit</button></p>
-       </div>
-</form>
-
-{{if $source}}
-<div class="itemsource-results">
-       <div class="panel panel-default">
-               <div class="panel-heading">
-                       <h3 class="panel-title">Item Id</h3>
-               </div>
-               <div class="panel-body">
-                       {{$item_id}}
-               </div>
-       </div>
-       <div class="panel panel-default">
-               <div class="panel-heading">
-                       <h3 class="panel-title">Item URI</h3>
-               </div>
-               <div class="panel-body">
-                       {{$item_uri}}
-               </div>
-       </div>
-       <div class="panel panel-default">
-               <div class="panel-heading">
-                       <h3 class="panel-title">Terms</h3>
-               </div>
-               <div class="panel-body">
-                       <table class="table table-condensed table-striped">
-                               <tr>
-                                       <th>Type</th>
-                                       <th>Term</th>
-                                       <th>URL</th>
-                               </tr>
-               {{foreach $terms as $term}}
-                               <tr>
-                                       <td>
-                       {{if $term.type == 1}}Tag{{/if}}
-                       {{if $term.type == 2}}Mention{{/if}}
-                       {{if $term.type == 8}}Implicit Mention{{/if}}
-                                       </td>
-                                       <td>
-                                               {{$term.term}}
-                                       </td>
-                                       <td>
-                                               {{$term.url}}
-                                       </td>
-                               </tr>
-               {{/foreach}}
-                       </table>
-               </div>
-       </div>
-       <div class="panel panel-default">
-               <div class="panel-heading">
-                       <h3 class="panel-title">Source</h3>
-               </div>
-               <pre><code class="language-php">{{$source}}</code></pre>
-       </div>
-</div>
-{{/if}}
diff --git a/view/templates/exception.tpl b/view/templates/exception.tpl
new file mode 100644 (file)
index 0000000..02b7648
--- /dev/null
@@ -0,0 +1,4 @@
+<div id="exception" class="generic-page-wrapper">
+    <h1>{{$title}}</h1>
+    <p>{{$message}}</p>
+</div>
diff --git a/view/templates/failed_updates.tpl b/view/templates/failed_updates.tpl
deleted file mode 100644 (file)
index 8a5e0c2..0000000
+++ /dev/null
@@ -1,19 +0,0 @@
-
-<div id="adminpage">
-       <h2>{{$banner}}</h2>
-
-       <div id="failed_updates_desc">{{$desc nofilter}}</div>
-
-       {{if $failed}}
-       {{foreach $failed as $f}}
-               <h4>{{$f}}</h4>
-
-               <ul>
-                       <li><a href="{{$base}}/admin/dbsync/mark/{{$f}}">{{$mark}}</a></li>
-                       <li><a href="{{$base}}/admin/dbsync/{{$f}}">{{$apply}}</a></li>
-               </ul>
-
-               <hr />
-       {{/foreach}}
-       {{/if}}
-</div>
index eb3f402fc634199e737efbf1cc30a13ef49295e0..d2ce589fdda0568b6f33e4c4f96752bc05a87249 100644 (file)
@@ -7,7 +7,7 @@
        {{if $customhome != false }}
                {{include file="$customhome"}}
        {{else}}
-               {{$defaultheader nofilter}}
+               <h1>{{$defaultheader nofilter}}</h1>
        {{/if}}
 
        {{$login nofilter}}
index cae3b868af01e6abd553a23e02ad723d70ff663e..5080663abd1bc374f88692fde7da82bde0714d70 100644 (file)
@@ -3,6 +3,12 @@
 {{if $edit}}
 <div id="album-edit-link"><a href="{{$edit.1}}" title="{{$edit.0}}">{{$edit.0}}</a></div>
 {{/if}}
+{{if $edit}}
+<div id="album-edit-link"><a href="{{$edit.1}}" title="{{$edit.0}}">{{$edit.0}}</a></div>
+{{/if}}
+{{if $drop}}
+<div id="album-drop-link"><a href="{{$drop.1}}" title="{{$drop.0}}">{{$drop.0}}</a></div>
+{{/if}}
 <div class="photos-upload-link" ><a href="{{$order.1}}" title="{{$order.0}}">{{$order.0}}</a></div>
 {{if $can_post}}
 <div class="photos-upload-link" ><a href="{{$upload.1}}">{{$upload.0}}</a></div>
index 8b22dfb44cd682756b382c891dbf6e9017ace0c1..49a550e42b310b89f8ac4e5fbd9dbd2ce14bdcfa 100644 (file)
@@ -1,6 +1,5 @@
 
-
-<form action="photos/{{$nickname}}/{{$resource_id}}" method="post" id="photo_edit_form" >
+<form action="photos/{{$nickname}}/image/{{$resource_id}}/edit" method="post" id="photo_edit_form" >
 
        <input type="hidden" name="item_id" value="{{$item_id}}" />
        <input type="hidden" name="origaname" value="{{$album.2}}" />
@@ -28,9 +27,6 @@
        <div id="photo-edit-perms-end"></div>
 
        <input id="photo-edit-submit-button" type="submit" name="submit" value="{{$submit}}" />
-       <input id="photo-edit-delete-button" type="submit" name="delete" value="{{$delete}}" onclick="return confirmDelete();" />
 
        <div id="photo-edit-end"></div>
 </form>
-
-
index 372bcb536ede123b32c3d7d7f3ad88d44dabeff7..7170ceb333a054db29d79897879e66e1601a4377 100644 (file)
@@ -4,11 +4,22 @@
 
 <div id="photo-edit-link-wrap">
 {{if $tools}}
-<a id="photo-edit-link" href="{{$tools.edit.0}}">{{$tools.edit.1}}</a>
-|
-<a id="photo-toprofile-link" href="{{$tools.profile.0}}">{{$tools.profile.1}}</a>
+       {{if $tools.view}}
+               <a id="photo-view-link" href="{{$tools.view.0}}">{{$tools.view.1}}</a>
+       {{/if}}
+       {{if $tools.edit}}
+               <a id="photo-edit-link" href="{{$tools.edit.0}}">{{$tools.edit.1}}</a>
+       {{/if}}
+       {{if $tools.delete}}
+               | <a id="photo-edit-link" href="{{$tools.delete.0}}">{{$tools.delete.1}}</a>
+       {{/if}}
+       {{if $tools.profile}}
+               | <a id="photo-toprofile-link" href="{{$tools.profile.0}}">{{$tools.profile.1}}</a>
+       {{/if}}
+       {{if $tools.lock}}
+               | <img src="images/lock_icon.gif" class="lockview" alt="{{$tools.lock}}" onclick="lockview(event,'photo/{{$id}}');" />
+       {{/if}}
 {{/if}}
-{{if $lock}} | <img src="images/lock_icon.gif" class="lockview" alt="{{$lock}}" onclick="lockview(event,'photo/{{$id}}');" /> {{/if}}
 </div>
 
 {{if $prevlink}}<div id="photo-prev-link"><a href="{{$prevlink.0}}">{{$prevlink.1 nofilter}}</a></div>{{/if}}
diff --git a/view/templates/rsd.tpl b/view/templates/rsd.tpl
new file mode 100644 (file)
index 0000000..c194e8f
--- /dev/null
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<rsd version="1.0" xmlns="http://archipelago.phrasewise.com/rsd">
+       <service>
+               <engineName>Friendica</engineName>
+               <engineLink>http://friendica.com/</engineLink>
+               <apis>
+                       <api name="Twitter" preferred="true" apiLink="{{$baseurl}}/api/" blogID="">
+                               <settings>
+                                       <docs>http://status.net/wiki/TwitterCompatibleAPI</docs>
+                                       <setting name="OAuth">false</setting>
+                               </settings>
+                       </api>
+               </apis>
+       </service>
+</rsd>
diff --git a/view/templates/structure_check.tpl b/view/templates/structure_check.tpl
deleted file mode 100644 (file)
index 7193d38..0000000
+++ /dev/null
@@ -1,8 +0,0 @@
-
-<div id="adminpage">
-       <h2>{{$banner}}</h2>
-
-       <p><a href="{{$base}}/admin/dbsync/check">{{$check}}</a></p>
-
-       <hr />
-</div>
diff --git a/view/templates/webfinger.tpl b/view/templates/webfinger.tpl
new file mode 100644 (file)
index 0000000..109a7fc
--- /dev/null
@@ -0,0 +1,16 @@
+<div class="generic-page-wrapper">
+       <h3>Webfinger Diagnostic</h3>
+
+       <form action="webfinger" method="get">
+               Lookup address: <input type="text" style="width: 250px;" name="addr" value="{{$addr}}" />
+               <input type="submit" name="submit" value="Submit" />
+       </form>
+
+       <br /><br />
+
+       {{if $res}}
+       <pre>
+               {{$res}}
+       </pre>
+       {{/if}}
+</div>
index 430fa7f60c59a679b3551be6534cf6a7beff5288..cd04455512d2dbd3f2a723661b05674365968c92 100644 (file)
@@ -70,7 +70,6 @@ function clean_form(App $a, &$colorset, $user)
        $t = Renderer::getMarkupTemplate("theme_settings.tpl");
        $o = Renderer::replaceMacros($t, [
                '$submit'   => L10n::t('Submit'),
-               '$baseurl'  => System::baseUrl(),
                '$title'    => L10n::t("Theme settings"),
                '$colorset' => ['duepuntozero_colorset', L10n::t('Variations'), $color, '', $colorset],
        ]);
index e327a1ec91a92c51da08dd17208006d9d7a41e03..7cda87c1e47660f5fc9232f84e3f28a543db298c 100644 (file)
@@ -3507,6 +3507,7 @@ div.jGrowl div.info {
                width: 100%;
                padding: 0.5em;
                height: auto;
+               box-sizing: border-box;
        }
        aside:before {
                content: ">>";
index 7ac7f489ef13a42337609bfeb797c7483a173a88..d1591273fbe65aef313c8cdf9ae76b1f72cfb6c1 100644 (file)
@@ -30,7 +30,7 @@ function theme_post(App $a)
 
 function theme_admin_post(App $a)
 {
-       if (!local_user()) {
+       if (!is_site_admin()) {
                return;
        }
 
@@ -119,7 +119,6 @@ function frio_form($arr)
        $t = Renderer::getMarkupTemplate('theme_settings.tpl');
        $ctx = [
                '$submit'           => L10n::t('Submit'),
-               '$baseurl'          => System::baseUrl(),
                '$title'            => L10n::t('Theme settings'),
                '$scheme'           => ['frio_scheme', L10n::t('Select color scheme'), $arr['scheme'], '', $scheme_choices],
                '$share_string'     => ['frio_share_string', L10n::t('Copy or paste schemestring'), $arr['share_string'], L10n::t('You can copy this string to share your theme with others. Pasting here applies the schemestring'), false, false],
index a07ec1b46b9e31cfbe174560336fca6253d3d5f5..e6b42e52eae9e890c124526a597727b9ffc548e6 100644 (file)
@@ -33,6 +33,10 @@ body {
     /*color: #555;*/
     font-family: 'Open Sans',sans-serif;
 }
+body.minimal {
+    padding: 15px;
+}
+
 body a {
     /*color: #555;*/
     /*color: #6fdbe8;*/
@@ -131,14 +135,6 @@ blockquote {
 * standard page elements
 */
 
-section.minimal {
-    top: 0px;
-    left: 0px;
-    position: absolute;
-    width: 100%;
-    height: 100%;
-}
-
 #back-to-top {
     display: none;
     cursor: pointer;
@@ -3240,53 +3236,6 @@ main .nav-tabs>li.active>a:hover {
  * Framework overwrite
  */
 
-/* jRange */
-.theme-frio .back-bar {
-    height: 5px !important;
-    border-radius: 2px;
-    background-color: #eeeeee;
-    background-color: #e7e7e7;
-    background-image: -moz-linear-gradient(top, #eeeeee, #dddddd);
-    background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#eeeeee), to(#dddddd));
-    background-image: -webkit-linear-gradient(top, #eeeeee, #dddddd);
-    background-image: -o-linear-gradient(top, #eeeeee, #dddddd);
-    background-image: linear-gradient(to bottom, #eeeeee, #dddddd);
-    background-repeat: repeat-x;
-    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffeeeeee', endColorstr='#ffdddddd', GradientType=0);
-}
-.theme-frio .back-bar .selected-bar {
-    border-radius: 2px;
-    background-color: $link_color;
-/*    background-image: -moz-linear-gradient(top, #bdfade, #76fabc);
-    background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#bdfade), to(#76fabc));
-    background-image: -webkit-linear-gradient(top, #bdfade, #76fabc);
-    background-image: -o-linear-gradient(top, #bdfade, #76fabc);
-    background-image: linear-gradient(to bottom, #bdfade, #76fabc);
-    background-repeat: repeat-x;
-    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffbdfade', endColorstr='#ff76fabc', GradientType=0);*/
-}
-.theme-frio .back-bar .pointer {
-    width: 14px !important;
-    height: 14px !important;
-    top: -5px;
-    -webkit-box-sizing: border-box;
-    -moz-box-sizing: border-box;
-    box-sizing: border-box;
-    border-radius: 10px;
-    border: 1px solid #AAA;
-    background-color: #e7e7e7 !important;
-    background-image: -moz-linear-gradient(top, #eeeeee, #dddddd);
-    background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#eeeeee), to(#dddddd));
-    background-image: -webkit-linear-gradient(top, #eeeeee, #dddddd);
-    background-image: -o-linear-gradient(top, #eeeeee, #dddddd);
-    background-image: linear-gradient(to bottom, #eeeeee, #dddddd);
-    background-repeat: repeat-x;
-    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffeeeeee', endColorstr='#ffdddddd', GradientType=0);
-}
-.theme-frio .back-bar .pointer-label {
-    color: #999;
-}
-
 /* textcomplete for contact filtering*/
 #contact-list ul.dropdown-menu.textcomplete-dropdown.media-list {
     position: relative !important;
@@ -3553,8 +3502,11 @@ section .profile-match-wrapper {
        body {
                padding-top: 95px;
        }
+    body.minimal {
+        padding: 15px;
+    }
 
-       #friendica-logo-mask {
+    #friendica-logo-mask {
                display: none;
        }
 
diff --git a/view/theme/frio/frameworks/jRange/LICENSE b/view/theme/frio/frameworks/jRange/LICENSE
deleted file mode 100644 (file)
index 8f47b9a..0000000
+++ /dev/null
@@ -1,21 +0,0 @@
-The MIT License (MIT)
-
-Copyright (c) 2014 Nitin Hayaran
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
\ No newline at end of file
diff --git a/view/theme/frio/frameworks/jRange/README.md b/view/theme/frio/frameworks/jRange/README.md
deleted file mode 100644 (file)
index 5cbfe6a..0000000
+++ /dev/null
@@ -1,5 +0,0 @@
-## jQuery plugin to create Range Selector
-
-![jRange Preview](http://i.imgur.com/da8uZwx.png)
-
-[Demo and Documentation](http://nitinhayaran.github.io/jRange/demo/)
\ No newline at end of file
diff --git a/view/theme/frio/frameworks/jRange/jquery.range-min.js b/view/theme/frio/frameworks/jRange/jquery.range-min.js
deleted file mode 100644 (file)
index 2bf854e..0000000
+++ /dev/null
@@ -1 +0,0 @@
-!function($,t,i,s){"use strict";var o=function(){return this.init.apply(this,arguments)};o.prototype={defaults:{onstatechange:function(){},ondragend:function(){},onbarclicked:function(){},isRange:!1,showLabels:!0,showScale:!0,step:1,format:"%s",theme:"theme-green",width:300,disable:!1,snap:!1},template:'<div class="slider-container">                        <div class="back-bar">                <div class="selected-bar"></div>                <div class="pointer low"></div><div class="pointer-label low">123456</div>                <div class="pointer high"></div><div class="pointer-label high">456789</div>                <div class="clickable-dummy"></div>            </div>            <div class="scale"></div>          </div>',init:function(t,i){this.options=$.extend({},this.defaults,i),this.inputNode=$(t),this.options.value=this.inputNode.val()||(this.options.isRange?this.options.from+","+this.options.from:this.options.from),this.domNode=$(this.template),this.domNode.addClass(this.options.theme),this.inputNode.after(this.domNode),this.domNode.on("change",this.onChange),this.pointers=$(".pointer",this.domNode),this.lowPointer=this.pointers.first(),this.highPointer=this.pointers.last(),this.labels=$(".pointer-label",this.domNode),this.lowLabel=this.labels.first(),this.highLabel=this.labels.last(),this.scale=$(".scale",this.domNode),this.bar=$(".selected-bar",this.domNode),this.clickableBar=this.domNode.find(".clickable-dummy"),this.interval=this.options.to-this.options.from,this.render()},render:function(){return 0!==this.inputNode.width()||this.options.width?(this.options.width=this.options.width||this.inputNode.width(),this.domNode.width(this.options.width),this.inputNode.hide(),this.isSingle()&&(this.lowPointer.hide(),this.lowLabel.hide()),this.options.showLabels||this.labels.hide(),this.attachEvents(),this.options.showScale&&this.renderScale(),void this.setValue(this.options.value)):void console.log("jRange : no width found, returning")},isSingle:function(){return"number"==typeof this.options.value?!0:-1!==this.options.value.indexOf(",")||this.options.isRange?!1:!0},attachEvents:function(){this.clickableBar.click($.proxy(this.barClicked,this)),this.pointers.on("mousedown touchstart",$.proxy(this.onDragStart,this)),this.pointers.bind("dragstart",function(t){t.preventDefault()})},onDragStart:function(t){if(!(this.options.disable||"mousedown"===t.type&&1!==t.which)){t.stopPropagation(),t.preventDefault();var s=$(t.target);this.pointers.removeClass("last-active"),s.addClass("focused last-active"),this[(s.hasClass("low")?"low":"high")+"Label"].addClass("focused"),$(i).on("mousemove.slider touchmove.slider",$.proxy(this.onDrag,this,s)),$(i).on("mouseup.slider touchend.slider touchcancel.slider",$.proxy(this.onDragEnd,this))}},onDrag:function(t,i){i.stopPropagation(),i.preventDefault(),i.originalEvent.touches&&i.originalEvent.touches.length?i=i.originalEvent.touches[0]:i.originalEvent.changedTouches&&i.originalEvent.changedTouches.length&&(i=i.originalEvent.changedTouches[0]);var s=i.clientX-this.domNode.offset().left;this.domNode.trigger("change",[this,t,s])},onDragEnd:function(t){this.pointers.removeClass("focused").trigger("rangeslideend"),this.labels.removeClass("focused"),$(i).off(".slider"),this.options.ondragend.call(this,this.options.value)},barClicked:function(t){if(!this.options.disable){var i=t.pageX-this.clickableBar.offset().left;if(this.isSingle())this.setPosition(this.pointers.last(),i,!0,!0);else{var s=Math.abs(parseFloat(this.pointers.first().css("left"),10)),o=this.pointers.first().width()/2,e=Math.abs(parseFloat(this.pointers.last().css("left"),10)),n=this.pointers.first().width()/2,a=Math.abs(s-i+o),h=Math.abs(e-i+n),l;l=a==h?s>i?this.pointers.first():this.pointers.last():h>a?this.pointers.first():this.pointers.last(),this.setPosition(l,i,!0,!0),this.options.onbarclicked.call(this,this.options.value)}}},onChange:function(t,i,s,o){var e,n;e=0,n=i.domNode.width(),i.isSingle()||(e=s.hasClass("high")?parseFloat(i.lowPointer.css("left"))+i.lowPointer.width()/2:0,n=s.hasClass("low")?parseFloat(i.highPointer.css("left"))+i.highPointer.width()/2:i.domNode.width());var a=Math.min(Math.max(o,e),n);i.setPosition(s,a,!0)},setPosition:function(t,i,s,o){var e,n,a=parseFloat(this.lowPointer.css("left")),h=parseFloat(this.highPointer.css("left"))||0,l=this.highPointer.width()/2;if(s||(i=this.prcToPx(i)),this.options.snap){var r=this.correctPositionForSnap(i);if(-1===r)return;i=r}t[0]===this.highPointer[0]?h=Math.round(i-l):a=Math.round(i-l),t[o?"animate":"css"]({left:Math.round(i-l)}),this.isSingle()?e=0:(e=a+l,n=h+l);var d=Math.round(h+l-e);this.bar[o?"animate":"css"]({width:Math.abs(d),left:d>0?e:e+d}),this.showPointerValue(t,i,o),this.isReadonly()},correctPositionForSnap:function(t){var i=this.positionToValue(t)-this.options.from,s=this.options.width/(this.interval/this.options.step),o=i/this.options.step*s;return o+s/2>=t&&t>=o-s/2?o:-1},setValue:function(t){var i=t.toString().split(",");i[0]=Math.min(Math.max(i[0],this.options.from),this.options.to)+"",i.length>1&&(i[1]=Math.min(Math.max(i[1],this.options.from),this.options.to)+""),this.options.value=t;var s=this.valuesToPrc(2===i.length?i:[0,i[0]]);this.isSingle()?this.setPosition(this.highPointer,s[1]):(this.setPosition(this.lowPointer,s[0]),this.setPosition(this.highPointer,s[1]))},renderScale:function(){for(var t=this.options.scale||[this.options.from,this.options.to],i=Math.round(100/(t.length-1)*10)/10,s="",o=0;o<t.length;o++)s+='<span style="left: '+o*i+'%">'+("|"!=t[o]?"<ins>"+t[o]+"</ins>":"")+"</span>";this.scale.html(s),$("ins",this.scale).each(function(){$(this).css({marginLeft:-$(this).outerWidth()/2})})},getBarWidth:function(){var t=this.options.value.split(",");return t.length>1?parseFloat(t[1])-parseFloat(t[0]):parseFloat(t[0])},showPointerValue:function(t,i,o){var e=$(".pointer-label",this.domNode)[t.hasClass("low")?"first":"last"](),n,a=this.positionToValue(i);if($.isFunction(this.options.format)){var h=this.isSingle()?s:t.hasClass("low")?"low":"high";n=this.options.format(a,h)}else n=this.options.format.replace("%s",a);var l=e.html(n).width(),r=i-l/2;r=Math.min(Math.max(r,0),this.options.width-l),e[o?"animate":"css"]({left:r}),this.setInputValue(t,a)},valuesToPrc:function(t){var i=100*(parseFloat(t[0])-parseFloat(this.options.from))/this.interval,s=100*(parseFloat(t[1])-parseFloat(this.options.from))/this.interval;return[i,s]},prcToPx:function(t){return this.domNode.width()*t/100},isDecimal:function(){return-1===(this.options.value+this.options.from+this.options.to).indexOf(".")?!1:!0},positionToValue:function(t){var i=t/this.domNode.width()*this.interval;if(i=parseFloat(i,10)+parseFloat(this.options.from,10),this.isDecimal()){var s=Math.round(Math.round(i/this.options.step)*this.options.step*100)/100;if(0!==s)for(s=""+s,-1===s.indexOf(".")&&(s+=".");s.length-s.indexOf(".")<3;)s+="0";else s="0.00";return s}return Math.round(i/this.options.step)*this.options.step},setInputValue:function(t,i){if(this.isSingle())this.options.value=i.toString();else{var s=this.options.value.split(",");t.hasClass("low")?this.options.value=i+","+s[1]:this.options.value=s[0]+","+i}this.inputNode.val()!==this.options.value&&(this.inputNode.val(this.options.value).trigger("change"),this.options.onstatechange.call(this,this.options.value))},getValue:function(){return this.options.value},getOptions:function(){return this.options},getRange:function(){return this.options.from+","+this.options.to},isReadonly:function(){this.domNode.toggleClass("slider-readonly",this.options.disable)},disable:function(){this.options.disable=!0,this.isReadonly()},enable:function(){this.options.disable=!1,this.isReadonly()},toggleDisable:function(){this.options.disable=!this.options.disable,this.isReadonly()},updateRange:function(t,i){var s=t.toString().split(",");this.interval=parseInt(s[1])-parseInt(s[0]),i?this.setValue(i):this.setValue(this.getValue())}};var e="jRange";$.fn[e]=function(i){var s=arguments,n;return this.each(function(){var a=$(this),h=$.data(this,"plugin_"+e),l="object"==typeof i&&i;h||(a.data("plugin_"+e,h=new o(this,l)),$(t).resize(function(){h.setValue(h.getValue())})),"string"==typeof i&&(n=h[i].apply(h,Array.prototype.slice.call(s,1)))}),n||this}}(jQuery,window,document);
\ No newline at end of file
diff --git a/view/theme/frio/frameworks/jRange/jquery.range.css b/view/theme/frio/frameworks/jRange/jquery.range.css
deleted file mode 100644 (file)
index 62dc15b..0000000
+++ /dev/null
@@ -1,173 +0,0 @@
-.slider-container {
-  width: 300px;
-  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
-}
-.slider-container .back-bar {
-  height: 10px;
-  position: relative;
-}
-.slider-container .back-bar .selected-bar {
-  position: absolute;
-  height: 100%;
-}
-.slider-container .back-bar .pointer {
-  position: absolute;
-  width: 10px;
-  height: 10px;
-  background-color: red;
-  cursor: col-resize;
-  opacity: 1;
-  z-index: 2;
-}
-.slider-container .back-bar .pointer.last-active {
-  z-index: 3;
-}
-.slider-container .back-bar .pointer-label {
-  position: absolute;
-  top: -17px;
-  font-size: 8px;
-  background: white;
-  white-space: nowrap;
-  line-height: 1;
-}
-.slider-container .back-bar .focused {
-  z-index: 10;
-}
-.slider-container .clickable-dummy {
-  cursor: pointer;
-  position: absolute;
-  width: 100%;
-  height: 100%;
-  z-index: 1;
-}
-.slider-container .scale {
-  top: 2px;
-  position: relative;
-}
-.slider-container .scale span {
-  position: absolute;
-  height: 5px;
-  border-left: 1px solid #999;
-  font-size: 0;
-}
-.slider-container .scale ins {
-  font-size: 9px;
-  text-decoration: none;
-  position: absolute;
-  left: 0;
-  top: 5px;
-  color: #999;
-  line-height: 1;
-}
-.slider-container.slider-readonly .clickable-dummy,
-.slider-container.slider-readonly .pointer {
-  cursor: auto;
-}
-.theme-green .back-bar {
-  height: 5px;
-  border-radius: 2px;
-  background-color: #eeeeee;
-  background-color: #e7e7e7;
-  background-image: -moz-linear-gradient(top, #eeeeee, #dddddd);
-  background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#eeeeee), to(#dddddd));
-  background-image: -webkit-linear-gradient(top, #eeeeee, #dddddd);
-  background-image: -o-linear-gradient(top, #eeeeee, #dddddd);
-  background-image: linear-gradient(to bottom, #eeeeee, #dddddd);
-  background-repeat: repeat-x;
-  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffeeeeee', endColorstr='#ffdddddd', GradientType=0);
-}
-.theme-green .back-bar .selected-bar {
-  border-radius: 2px;
-  background-color: #a1fad0;
-  background-image: -moz-linear-gradient(top, #bdfade, #76fabc);
-  background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#bdfade), to(#76fabc));
-  background-image: -webkit-linear-gradient(top, #bdfade, #76fabc);
-  background-image: -o-linear-gradient(top, #bdfade, #76fabc);
-  background-image: linear-gradient(to bottom, #bdfade, #76fabc);
-  background-repeat: repeat-x;
-  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffbdfade', endColorstr='#ff76fabc', GradientType=0);
-}
-.theme-green .back-bar .pointer {
-  width: 14px;
-  height: 14px;
-  top: -5px;
-  -webkit-box-sizing: border-box;
-  -moz-box-sizing: border-box;
-  box-sizing: border-box;
-  border-radius: 10px;
-  border: 1px solid #AAA;
-  background-color: #e7e7e7;
-  background-image: -moz-linear-gradient(top, #eeeeee, #dddddd);
-  background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#eeeeee), to(#dddddd));
-  background-image: -webkit-linear-gradient(top, #eeeeee, #dddddd);
-  background-image: -o-linear-gradient(top, #eeeeee, #dddddd);
-  background-image: linear-gradient(to bottom, #eeeeee, #dddddd);
-  background-repeat: repeat-x;
-  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffeeeeee', endColorstr='#ffdddddd', GradientType=0);
-}
-.theme-green .back-bar .pointer-label {
-  color: #999;
-}
-.theme-green .back-bar .focused {
-  color: #333;
-}
-.theme-green .scale span {
-  border-left: 1px solid #e5e5e5;
-}
-.theme-green .scale ins {
-  color: #999;
-}
-.theme-blue .back-bar {
-  height: 5px;
-  border-radius: 2px;
-  background-color: #eeeeee;
-  background-color: #e7e7e7;
-  background-image: -moz-linear-gradient(top, #eeeeee, #dddddd);
-  background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#eeeeee), to(#dddddd));
-  background-image: -webkit-linear-gradient(top, #eeeeee, #dddddd);
-  background-image: -o-linear-gradient(top, #eeeeee, #dddddd);
-  background-image: linear-gradient(to bottom, #eeeeee, #dddddd);
-  background-repeat: repeat-x;
-  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffeeeeee', endColorstr='#ffdddddd', GradientType=0);
-}
-.theme-blue .back-bar .selected-bar {
-  border-radius: 2px;
-  background-color: #92c1f9;
-  background-image: -moz-linear-gradient(top, #b1d1f9, #64a8f9);
-  background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#b1d1f9), to(#64a8f9));
-  background-image: -webkit-linear-gradient(top, #b1d1f9, #64a8f9);
-  background-image: -o-linear-gradient(top, #b1d1f9, #64a8f9);
-  background-image: linear-gradient(to bottom, #b1d1f9, #64a8f9);
-  background-repeat: repeat-x;
-  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffb1d1f9', endColorstr='#ff64a8f9', GradientType=0);
-}
-.theme-blue .back-bar .pointer {
-  width: 14px;
-  height: 14px;
-  top: -5px;
-  -webkit-box-sizing: border-box;
-  -moz-box-sizing: border-box;
-  box-sizing: border-box;
-  border-radius: 10px;
-  border: 1px solid #AAA;
-  background-color: #e7e7e7;
-  background-image: -moz-linear-gradient(top, #eeeeee, #dddddd);
-  background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#eeeeee), to(#dddddd));
-  background-image: -webkit-linear-gradient(top, #eeeeee, #dddddd);
-  background-image: -o-linear-gradient(top, #eeeeee, #dddddd);
-  background-image: linear-gradient(to bottom, #eeeeee, #dddddd);
-  background-repeat: repeat-x;
-  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffeeeeee', endColorstr='#ffdddddd', GradientType=0);
-}
-.theme-blue .back-bar .pointer-label {
-  color: #999;
-}
-.theme-blue .back-bar .focused {
-  color: #333;
-}
-.theme-blue .scale span {
-  border-left: 1px solid #e5e5e5;
-}
-.theme-blue .scale ins {
-  color: #999;
-}
diff --git a/view/theme/frio/frameworks/jRange/jquery.range.js b/view/theme/frio/frameworks/jRange/jquery.range.js
deleted file mode 100644 (file)
index 188ee74..0000000
+++ /dev/null
@@ -1,401 +0,0 @@
-/*jshint multistr:true, curly: false */
-/*global jQuery:false, define: false */
-/**
- * jRange - Awesome range control
- *
- * Written by
- * ----------
- * Nitin Hayaran (nitinhayaran@gmail.com)
- *
- * Licensed under the MIT (MIT-LICENSE.txt).
- *
- * @author Nitin Hayaran
- * @version 0.1-RELEASE
- *
- * Dependencies
- * ------------
- * jQuery (http://jquery.com)
- *
- **/
-;
-(function($, window, document, undefined) {
-       'use strict';
-
-       var jRange = function() {
-               return this.init.apply(this, arguments);
-       };
-       jRange.prototype = {
-               defaults: {
-                       onstatechange: function() {},
-      ondragend: function() {},
-      onbarclicked: function() {},
-                       isRange: false,
-                       showLabels: true,
-                       showScale: true,
-                       step: 1,
-                       format: '%s',
-                       theme: 'theme-green',
-                       width: 300,
-                       disable: false,
-                       snap: false
-               },
-               template: '<div class="slider-container">\
-                       <div class="back-bar">\
-                <div class="selected-bar"></div>\
-                <div class="pointer low"></div><div class="pointer-label low">123456</div>\
-                <div class="pointer high"></div><div class="pointer-label high">456789</div>\
-                <div class="clickable-dummy"></div>\
-            </div>\
-            <div class="scale"></div>\
-               </div>',
-               init: function(node, options) {
-                       this.options       = $.extend({}, this.defaults, options);
-                       this.inputNode     = $(node);
-                       this.options.value = this.inputNode.val() || (this.options.isRange ? this.options.from + ',' + this.options.from : this.options.from);
-                       this.domNode       = $(this.template);
-                       this.domNode.addClass(this.options.theme);
-                       this.inputNode.after(this.domNode);
-                       this.domNode.on('change', this.onChange);
-                       this.pointers      = $('.pointer', this.domNode);
-                       this.lowPointer    = this.pointers.first();
-                       this.highPointer   = this.pointers.last();
-                       this.labels        = $('.pointer-label', this.domNode);
-                       this.lowLabel      = this.labels.first();
-                       this.highLabel     = this.labels.last();
-                       this.scale         = $('.scale', this.domNode);
-                       this.bar           = $('.selected-bar', this.domNode);
-                       this.clickableBar  = this.domNode.find('.clickable-dummy');
-                       this.interval      = this.options.to - this.options.from;
-                       this.render();
-               },
-               render: function() {
-                       // Check if inputNode is visible, and have some width, so that we can set slider width accordingly.
-                       if (this.inputNode.width() === 0 && !this.options.width) {
-                               console.log('jRange : no width found, returning');
-                               return;
-                       } else {
-                               this.options.width = this.options.width || this.inputNode.width();
-                               this.domNode.width(this.options.width);
-                               this.inputNode.hide();
-                       }
-
-                       if (this.isSingle()) {
-                               this.lowPointer.hide();
-                               this.lowLabel.hide();
-                       }
-                       if (!this.options.showLabels) {
-                               this.labels.hide();
-                       }
-                       this.attachEvents();
-                       if (this.options.showScale) {
-                               this.renderScale();
-                       }
-                       this.setValue(this.options.value);
-               },
-               isSingle: function() {
-                       if (typeof(this.options.value) === 'number') {
-                               return true;
-                       }
-                       return (this.options.value.indexOf(',') !== -1 || this.options.isRange) ?
-                               false : true;
-               },
-               attachEvents: function() {
-                       this.clickableBar.click($.proxy(this.barClicked, this));
-                       this.pointers.on('mousedown touchstart', $.proxy(this.onDragStart, this));
-                       this.pointers.bind('dragstart', function(event) {
-                               event.preventDefault();
-                       });
-               },
-               onDragStart: function(e) {
-                       if ( this.options.disable || (e.type === 'mousedown' && e.which !== 1)) {
-                               return;
-                       }
-                       e.stopPropagation();
-                       e.preventDefault();
-                       var pointer = $(e.target);
-                       this.pointers.removeClass('last-active');
-                       pointer.addClass('focused last-active');
-                       this[(pointer.hasClass('low') ? 'low' : 'high') + 'Label'].addClass('focused');
-                       $(document).on('mousemove.slider touchmove.slider', $.proxy(this.onDrag, this, pointer));
-                       $(document).on('mouseup.slider touchend.slider touchcancel.slider', $.proxy(this.onDragEnd, this));
-               },
-               onDrag: function(pointer, e) {
-                       e.stopPropagation();
-                       e.preventDefault();
-
-                       if (e.originalEvent.touches && e.originalEvent.touches.length) {
-                               e = e.originalEvent.touches[0];
-                       } else if (e.originalEvent.changedTouches && e.originalEvent.changedTouches.length) {
-                               e = e.originalEvent.changedTouches[0];
-                       }
-
-                       var position = e.clientX - this.domNode.offset().left;
-                       this.domNode.trigger('change', [this, pointer, position]);
-               },
-               onDragEnd: function(e) {
-                       this.pointers.removeClass('focused')
-                               .trigger('rangeslideend');
-                       this.labels.removeClass('focused');
-                       $(document).off('.slider');
-                 this.options.ondragend.call(this, this.options.value);
-               },
-               barClicked: function(e) {
-                       if(this.options.disable) return;
-                       var x = e.pageX - this.clickableBar.offset().left;
-                       if (this.isSingle())
-                               this.setPosition(this.pointers.last(), x, true, true);
-                       else {
-                               var firstLeft           = Math.abs(parseFloat(this.pointers.first().css('left'), 10)),
-                                               firstHalfWidth  = this.pointers.first().width() / 2,
-                                               lastLeft                                = Math.abs(parseFloat(this.pointers.last().css('left'), 10)),
-                                               lastHalfWidth   = this.pointers.first().width() / 2,
-                                               leftSide        = Math.abs(firstLeft - x + firstHalfWidth),
-                                               rightSide       = Math.abs(lastLeft - x + lastHalfWidth),
-                                               pointer;
-
-                               if(leftSide == rightSide) {
-                                       pointer = x < firstLeft ? this.pointers.first() : this.pointers.last();
-                               } else {
-                                       pointer = leftSide < rightSide ? this.pointers.first() : this.pointers.last();
-                               }
-                               this.setPosition(pointer, x, true, true);
-                       }
-                       this.options.onbarclicked.call(this, this.options.value);
-               },
-               onChange: function(e, self, pointer, position) {
-                       var min, max;
-                       min = 0;
-                       max = self.domNode.width();
-
-                       if (!self.isSingle()) {
-                               min = pointer.hasClass('high') ? parseFloat(self.lowPointer.css("left")) + (self.lowPointer.width() / 2) : 0;
-                               max = pointer.hasClass('low') ? parseFloat(self.highPointer.css("left")) + (self.highPointer.width() / 2) : self.domNode.width();
-                       }
-
-                       var value = Math.min(Math.max(position, min), max);
-                       self.setPosition(pointer, value, true);
-               },
-               setPosition: function(pointer, position, isPx, animate) {
-                       var leftPos, rightPos,
-                               lowPos = parseFloat(this.lowPointer.css("left")),
-                               highPos = parseFloat(this.highPointer.css("left")) || 0,
-                               circleWidth = this.highPointer.width() / 2;
-                       if (!isPx) {
-                               position = this.prcToPx(position);
-                       }
-                       if(this.options.snap){
-                               var expPos = this.correctPositionForSnap(position);
-                               if(expPos === -1){
-                                       return;
-                               }else{
-                                       position = expPos;
-                               }
-                       }
-                       if (pointer[0] === this.highPointer[0]) {
-                               highPos = Math.round(position - circleWidth);
-                       } else {
-                               lowPos = Math.round(position - circleWidth);
-                       }
-                       pointer[animate ? 'animate' : 'css']({
-                               'left': Math.round(position - circleWidth)
-                       });
-                       if (this.isSingle()) {
-                               leftPos = 0;
-                       } else {
-                               leftPos = lowPos + circleWidth;
-                               rightPos = highPos + circleWidth;
-                       }
-                       var w = Math.round(highPos + circleWidth - leftPos);
-                       this.bar[animate ? 'animate' : 'css']({
-                               'width': Math.abs(w),
-                               'left': (w>0) ? leftPos : leftPos + w
-                       });
-                       this.showPointerValue(pointer, position, animate);
-                       this.isReadonly();
-               },
-               correctPositionForSnap: function(position){
-                       var currentValue = this.positionToValue(position) - this.options.from;
-                       var diff = this.options.width / (this.interval / this.options.step),
-                               expectedPosition = (currentValue / this.options.step) * diff;
-                       if( position <= expectedPosition + diff / 2 && position >= expectedPosition - diff / 2){
-                               return expectedPosition;
-                       }else{
-                               return -1;
-                       }
-               },
-               // will be called from outside
-               setValue: function(value) {
-                       var values = value.toString().split(',');
-                       values[0] = Math.min(Math.max(values[0], this.options.from), this.options.to) + '';
-                       if (values.length > 1){
-                               values[1] = Math.min(Math.max(values[1], this.options.from), this.options.to) + '';
-                       }
-                       this.options.value = value;
-                       var prc = this.valuesToPrc(values.length === 2 ? values : [0, values[0]]);
-                       if (this.isSingle()) {
-                               this.setPosition(this.highPointer, prc[1]);
-                       } else {
-                               this.setPosition(this.lowPointer, prc[0]);
-                               this.setPosition(this.highPointer, prc[1]);
-                       }
-               },
-               renderScale: function() {
-                       var s = this.options.scale || [this.options.from, this.options.to];
-                       var prc = Math.round((100 / (s.length - 1)) * 10) / 10;
-                       var str = '';
-                       for (var i = 0; i < s.length; i++) {
-                               str += '<span style="left: ' + i * prc + '%">' + (s[i] != '|' ? '<ins>' + s[i] + '</ins>' : '') + '</span>';
-                       }
-                       this.scale.html(str);
-
-                       $('ins', this.scale).each(function() {
-                               $(this).css({
-                                       marginLeft: -$(this).outerWidth() / 2
-                               });
-                       });
-               },
-               getBarWidth: function() {
-                       var values = this.options.value.split(',');
-                       if (values.length > 1) {
-                               return parseFloat(values[1]) - parseFloat(values[0]);
-                       } else {
-                               return parseFloat(values[0]);
-                       }
-               },
-               showPointerValue: function(pointer, position, animate) {
-                       var label = $('.pointer-label', this.domNode)[pointer.hasClass('low') ? 'first' : 'last']();
-                       var text;
-                       var value = this.positionToValue(position);
-                       // Is it higer or lower than it should be?
-
-                       if ($.isFunction(this.options.format)) {
-                               var type = this.isSingle() ? undefined : (pointer.hasClass('low') ? 'low' : 'high');
-                               text = this.options.format(value, type);
-                       } else {
-                               text = this.options.format.replace('%s', value);
-                       }
-
-                       var width = label.html(text).width(),
-                               left = position - width / 2;
-                       left = Math.min(Math.max(left, 0), this.options.width - width);
-                       label[animate ? 'animate' : 'css']({
-                               left: left
-                       });
-                       this.setInputValue(pointer, value);
-               },
-               valuesToPrc: function(values) {
-                       var lowPrc = ((parseFloat(values[0]) - parseFloat(this.options.from)) * 100 / this.interval),
-                               highPrc = ((parseFloat(values[1]) - parseFloat(this.options.from)) * 100 / this.interval);
-                       return [lowPrc, highPrc];
-               },
-               prcToPx: function(prc) {
-                       return (this.domNode.width() * prc) / 100;
-               },
-               isDecimal: function() {
-                       return ((this.options.value + this.options.from + this.options.to).indexOf(".")===-1) ? false : true;
-               },
-               positionToValue: function(pos) {
-                       var value = (pos / this.domNode.width()) * this.interval;
-                       value = parseFloat(value, 10) + parseFloat(this.options.from, 10);
-                       if (this.isDecimal()) {
-                               var final = Math.round(Math.round(value / this.options.step) * this.options.step *100)/100;
-                               if (final!==0.0) {
-                                       final = '' + final;
-                                       if (final.indexOf(".")===-1) {
-                                               final = final + ".";
-                                       }
-                                       while (final.length - final.indexOf('.')<3) {
-                                               final = final + "0";
-                                       }
-                               } else {
-                                       final = "0.00";
-                               }
-                               return final;
-                       } else {
-                               return Math.round(value / this.options.step) * this.options.step;
-                       }
-               },
-               setInputValue: function(pointer, v) {
-                       // if(!isChanged) return;
-                       if (this.isSingle()) {
-                               this.options.value = v.toString();
-                       } else {
-                               var values = this.options.value.split(',');
-                               if (pointer.hasClass('low')) {
-                                       this.options.value = v + ',' + values[1];
-                               } else {
-                                       this.options.value = values[0] + ',' + v;
-                               }
-                       }
-                       if (this.inputNode.val() !== this.options.value) {
-                               this.inputNode.val(this.options.value)
-                                       .trigger('change');
-                               this.options.onstatechange.call(this, this.options.value);
-                       }
-               },
-               getValue: function() {
-                       return this.options.value;
-               },
-               getOptions: function() {
-                       return this.options;
-               },
-               getRange: function() {
-                       return this.options.from + "," + this.options.to;
-               },
-               isReadonly: function(){
-                       this.domNode.toggleClass('slider-readonly', this.options.disable);
-               },
-               disable: function(){
-                       this.options.disable = true;
-                       this.isReadonly();
-               },
-               enable: function(){
-                       this.options.disable = false;
-                       this.isReadonly();
-               },
-               toggleDisable: function(){
-                       this.options.disable = !this.options.disable;
-                       this.isReadonly();
-               },
-               updateRange: function(range, value) {
-                       var values = range.toString().split(',');
-                       this.interval = parseInt(values[1]) - parseInt(values[0]);
-                       if(value){
-                               this.setValue(value);
-                       }else{
-                               this.setValue(this.getValue());
-                       }
-               }
-       };
-
-       var pluginName = 'jRange';
-       // A really lightweight plugin wrapper around the constructor,
-       // preventing against multiple instantiations
-       $.fn[pluginName] = function(option) {
-               var args = arguments,
-                       result;
-
-               this.each(function() {
-                       var $this = $(this),
-                               data = $.data(this, 'plugin_' + pluginName),
-                               options = typeof option === 'object' && option;
-                       if (!data) {
-                               $this.data('plugin_' + pluginName, (data = new jRange(this, options)));
-                               $(window).resize(function() {
-                                       data.setValue(data.getValue());
-                               }); // Update slider position when window is resized to keep it in sync with scale
-                       }
-                       // if first argument is a string, call silimarly named function
-                       // this gives flexibility to call functions of the plugin e.g.
-                       //   - $('.dial').plugin('destroy');
-                       //   - $('.dial').plugin('render', $('.new-child'));
-                       if (typeof option === 'string') {
-                               result = data[option].apply(data, Array.prototype.slice.call(args, 1));
-                       }
-               });
-
-               // To enable plugin returns values
-               return result || this;
-       };
-
-})(jQuery, window, document);
diff --git a/view/theme/frio/frameworks/jRange/jquery.range.less b/view/theme/frio/frameworks/jRange/jquery.range.less
deleted file mode 100644 (file)
index 4034bdd..0000000
+++ /dev/null
@@ -1,198 +0,0 @@
-#gradient {
-  .horizontal(@startColor: #555, @endColor: #333) {
-    background-color: @endColor;
-    background-image: -moz-linear-gradient(left, @startColor, @endColor); // FF 3.6+
-    background-image: -webkit-gradient(linear, 0 0, 100% 0, from(@startColor), to(@endColor)); // Safari 4+, Chrome 2+
-    background-image: -webkit-linear-gradient(left, @startColor, @endColor); // Safari 5.1+, Chrome 10+
-    background-image: -o-linear-gradient(left, @startColor, @endColor); // Opera 11.10
-    background-image: linear-gradient(to right, @startColor, @endColor); // Standard, IE10
-    background-repeat: repeat-x;
-    filter: e(%("progid:DXImageTransform.Microsoft.gradient(startColorstr='%d', endColorstr='%d', GradientType=1)",argb(@startColor),argb(@endColor))); // IE9 and down
-  }
-  .vertical(@startColor: #555, @endColor: #333) {
-    background-color: mix(@startColor, @endColor, 60%);
-    background-image: -moz-linear-gradient(top, @startColor, @endColor); // FF 3.6+
-    background-image: -webkit-gradient(linear, 0 0, 0 100%, from(@startColor), to(@endColor)); // Safari 4+, Chrome 2+
-    background-image: -webkit-linear-gradient(top, @startColor, @endColor); // Safari 5.1+, Chrome 10+
-    background-image: -o-linear-gradient(top, @startColor, @endColor); // Opera 11.10
-    background-image: linear-gradient(to bottom, @startColor, @endColor); // Standard, IE10
-    background-repeat: repeat-x;
-    filter: e(%("progid:DXImageTransform.Microsoft.gradient(startColorstr='%d', endColorstr='%d', GradientType=0)",argb(@startColor),argb(@endColor))); // IE9 and down
-  }
-  .directional(@startColor: #555, @endColor: #333, @deg: 45deg) {
-    background-color: @endColor;
-    background-repeat: repeat-x;
-    background-image: -moz-linear-gradient(@deg, @startColor, @endColor); // FF 3.6+
-    background-image: -webkit-linear-gradient(@deg, @startColor, @endColor); // Safari 5.1+, Chrome 10+
-    background-image: -o-linear-gradient(@deg, @startColor, @endColor); // Opera 11.10
-    background-image: linear-gradient(@deg, @startColor, @endColor); // Standard, IE10
-  }
-  .vertical-three-colors(@startColor: #00b3ee, @midColor: #7a43b6, @colorStop: 50%, @endColor: #c3325f) {
-    background-color: mix(@midColor, @endColor, 80%);
-    background-image: -webkit-gradient(linear, 0 0, 0 100%, from(@startColor), color-stop(@colorStop, @midColor), to(@endColor));
-    background-image: -webkit-linear-gradient(@startColor, @midColor @colorStop, @endColor);
-    background-image: -moz-linear-gradient(top, @startColor, @midColor @colorStop, @endColor);
-    background-image: -o-linear-gradient(@startColor, @midColor @colorStop, @endColor);
-    background-image: linear-gradient(@startColor, @midColor @colorStop, @endColor);
-    background-repeat: no-repeat;
-    filter: e(%("progid:DXImageTransform.Microsoft.gradient(startColorstr='%d', endColorstr='%d', GradientType=0)",argb(@startColor),argb(@endColor))); // IE9 and down, gets no color-stop at all for proper fallback
-  }
-  .radial(@innerColor: #555, @outerColor: #333)  {
-    background-color: @outerColor;
-    background-image: -webkit-gradient(radial, center center, 0, center center, 460, from(@innerColor), to(@outerColor));
-    background-image: -webkit-radial-gradient(circle, @innerColor, @outerColor);
-    background-image: -moz-radial-gradient(circle, @innerColor, @outerColor);
-    background-image: -o-radial-gradient(circle, @innerColor, @outerColor);
-    background-repeat: no-repeat;
-  }
-  .striped(@color: #555, @angle: 45deg) {
-    background-color: @color;
-    background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(.25, rgba(255,255,255,.15)), color-stop(.25, transparent), color-stop(.5, transparent), color-stop(.5, rgba(255,255,255,.15)), color-stop(.75, rgba(255,255,255,.15)), color-stop(.75, transparent), to(transparent));
-    background-image: -webkit-linear-gradient(@angle, rgba(255,255,255,.15) 25%, transparent 25%, transparent 50%, rgba(255,255,255,.15) 50%, rgba(255,255,255,.15) 75%, transparent 75%, transparent);
-    background-image: -moz-linear-gradient(@angle, rgba(255,255,255,.15) 25%, transparent 25%, transparent 50%, rgba(255,255,255,.15) 50%, rgba(255,255,255,.15) 75%, transparent 75%, transparent);
-    background-image: -o-linear-gradient(@angle, rgba(255,255,255,.15) 25%, transparent 25%, transparent 50%, rgba(255,255,255,.15) 50%, rgba(255,255,255,.15) 75%, transparent 75%, transparent);
-    background-image: linear-gradient(@angle, rgba(255,255,255,.15) 25%, transparent 25%, transparent 50%, rgba(255,255,255,.15) 50%, rgba(255,255,255,.15) 75%, transparent 75%, transparent);
-  }
-}
-
-.slider-container {
-    width: 300px;
-    font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
-    .back-bar {
-        height: 10px;
-        position: relative;
-        .selected-bar {
-            position: absolute;
-            height: 100%;
-        }
-        .pointer {
-            position: absolute;
-            width: 10px;
-            height: 10px;
-            background-color: red;
-            cursor: col-resize;
-            opacity: 1;
-            z-index: 2;
-            &.last-active{
-                z-index: 3;
-            }
-        }
-        .pointer-label {
-            position: absolute;
-            top: -17px;
-            font-size: 8px;
-            background: white;
-            white-space: nowrap;
-            line-height: 1;
-        }
-        .focused {
-            z-index: 10;
-        }
-    }
-    .clickable-dummy {
-        cursor: pointer;
-        position: absolute;
-        width: 100%;
-        height: 100%;
-        z-index: 1;
-    }
-    .scale {
-        top: 2px;
-        position: relative;
-        span {
-            position: absolute;
-            height: 5px;
-            border-left: 1px solid #999;
-            font-size: 0;
-        }
-        ins {
-            font-size: 9px;
-            text-decoration: none;
-            position: absolute;
-            left: 0;
-            top: 5px;
-            color: #999;
-            line-height: 1;
-        }
-    }
-    &.slider-readonly{
-        .clickable-dummy, .pointer {
-            cursor: auto;
-        }
-    }
-}
-.theme-green {
-    .back-bar {
-        height: 5px;
-        border-radius: 2px;
-        background-color: #eeeeee;
-        #gradient > .vertical(#eeeeee, #dddddd);
-        .selected-bar {
-            border-radius: 2px;
-            #gradient > .vertical(#bdfade, #76fabc);
-        }
-        .pointer {
-            width: 14px;
-            height: 14px;
-            top: -5px;
-            -webkit-box-sizing: border-box;
-            -moz-box-sizing: border-box;
-            box-sizing: border-box;
-            border-radius: 10px;
-            border: 1px solid #AAA;
-            #gradient > .vertical(#eeeeee, #dddddd);
-        }
-        .pointer-label {
-            color: #999;
-        }
-        .focused {
-            color: #333;
-        }
-    }
-    .scale {
-        span {
-            border-left: 1px solid #e5e5e5;
-        }
-        ins {
-            color: #999;
-        }
-    }
-}
-
-.theme-blue {
-    .back-bar {
-        height: 5px;
-        border-radius: 2px;
-        background-color: #eeeeee;
-        #gradient > .vertical(#eeeeee, #dddddd);
-        .selected-bar {
-            border-radius: 2px;
-            #gradient > .vertical(#b1d1f9, #64a8f9);
-        }
-        .pointer {
-            width: 14px;
-            height: 14px;
-            top: -5px;
-            -webkit-box-sizing: border-box;
-            -moz-box-sizing: border-box;
-            box-sizing: border-box;
-            border-radius: 10px;
-            border: 1px solid #AAA;
-            #gradient > .vertical(#eeeeee, #dddddd);
-        }
-        .pointer-label {
-            color: #999;
-        }
-        .focused {
-            color: #333;
-        }
-    }
-    .scale {
-        span {
-            border-left: 1px solid #e5e5e5;
-        }
-        ins {
-            color: #999;
-        }
-    }
-}
diff --git a/view/theme/frio/frameworks/jRange/package.json b/view/theme/frio/frameworks/jRange/package.json
deleted file mode 100644 (file)
index 25d0cd3..0000000
+++ /dev/null
@@ -1,23 +0,0 @@
-{
-  "name": "jquery-range",
-  "version": "1.0.0",
-  "description": "jQuery plugin to create range selector",
-  "main": "jquery.range-min.js",
-  "scripts": {
-    "test": "echo \"Error: no test specified\" && exit 1"
-  },
-  "repository": {
-    "type": "git",
-    "url": "git+https://github.com/nitinhayaran/jRange.git"
-  },
-  "keywords": [
-    "jquery",
-    "range"
-  ],
-  "author": "Nitin Hayaran <nitinhayaran@gmail.com>",
-  "license": "ISC",
-  "bugs": {
-    "url": "https://github.com/nitinhayaran/jRange/issues"
-  },
-  "homepage": "https://github.com/nitinhayaran/jRange#readme"
-}
index 40c0fbb7443bb9daecd3c7f4cd47f1da166548a9..16d60b61d1014585c781a99a47f16a61b624f978 100644 (file)
@@ -99,7 +99,7 @@ var FileBrowser = {
                // Click on album link\r
                $(".fbrowser").on("click", ".folders a, .path a", function(e) {\r
                        e.preventDefault();\r
-                       var url = baseurl + "/fbrowser/" + FileBrowser.type + "/" + this.dataset.folder + "?mode=none";\r
+                       var url = baseurl + "/fbrowser/" + FileBrowser.type + "/" + this.dataset.folder + "?mode=none&theme=frio";\r
                        FileBrowser.folder = this.dataset.folder;\r
 \r
                        FileBrowser.loadContent(url);\r
@@ -134,7 +134,7 @@ var FileBrowser = {
 \r
                        console.log(FileBrowser.event, this.dataset.filename, embed, FileBrowser.id);\r
 \r
-                       parent.$("body").trigger(FileBrowser.event, [\r
+                       $("body").trigger(FileBrowser.event, [\r
                                this.dataset.filename,\r
                                embed,\r
                                FileBrowser.id,\r
@@ -152,7 +152,7 @@ var FileBrowser = {
                        e.preventDefault();\r
                        FileBrowser.type = this.getAttribute("data-mode");\r
                        $(".fbrowser").removeClass().addClass("fbrowser " + FileBrowser.type);\r
-                       url = baseurl + "/fbrowser/" + FileBrowser.type + "?mode=none";\r
+                       url = baseurl + "/fbrowser/" + FileBrowser.type + "?mode=none&theme=frio";\r
 \r
                        FileBrowser.loadContent(url);\r
                });\r
@@ -183,10 +183,7 @@ var FileBrowser = {
                                                        return;\r
                                                }\r
 \r
-//                                             location = baseurl + "/fbrowser/image/?mode=none"+location['hash'];\r
-//                                             location.reload(true);\r
-\r
-                                               var url = baseurl + "/fbrowser/" + FileBrowser.type + "/" + FileBrowser.folder + "?mode=none";\r
+                                               var url = baseurl + "/fbrowser/" + FileBrowser.type + "/" + FileBrowser.folder + "?mode=none&theme=frio";\r
                                                // load new content to fbrowser window\r
                                                FileBrowser.loadContent(url);\r
                                        }\r
@@ -214,10 +211,7 @@ var FileBrowser = {
                                                        return;\r
                                                }\r
 \r
-//                                             location = baseurl + "/fbrowser/file/?mode=none"+location['hash'];\r
-//                                             location.reload(true);\r
-\r
-                                               var url = baseurl + "/fbrowser/" + FileBrowser.type + "?mode=none";\r
+                                               var url = baseurl + "/fbrowser/" + FileBrowser.type + "?mode=none&theme=frio";\r
                                                // Load new content to fbrowser window\r
                                                FileBrowser.loadContent(url);\r
                                        }\r
index 77173385b192ddf27bd6f555c934a126a6348dab..2e7160aafa9217b00f323911030c03da1e0c83ad 100644 (file)
@@ -23,6 +23,15 @@ $(document).ready(function() {
                        addToModal(modalUrl, 'photo-album-edit-wrapper');
                }
        });
+
+       // Click event listener for the album drop link/button.
+       $("body").on('click', '#album-drop-link', function() {
+               var modalUrl = $(this).attr("data-modal-url");
+
+               if (typeof modalUrl !== "undefined") {
+                       addToModal(modalUrl);
+               }
+       });
 });
 
 $(window).load(function() {
index 1c5314c4b410b6052a86830b44e867ffe01dddaf..ab263bc2ab76cb19082e7990b0d710fb56096fa4 100644 (file)
@@ -120,7 +120,7 @@ Dialog.show = function(url, title) {
 Dialog._get_url = function(type, name, id) {
        var hash = name;
        if (id !== undefined) hash = hash + "-" + id;
-       return "fbrowser/"+type+"/?mode=none#"+hash;
+       return "fbrowser/"+type+"/?mode=none&theme=frio#"+hash;
 };
 
 // Does load the filebrowser into the jot modal.
@@ -148,7 +148,7 @@ Dialog._load = function(url) {
        var type = $("#fb-type").attr("value");
 
        // Try to fetch the hash form the url.
-       var match = url.match(/fbrowser\/[a-z]+\/\?mode=none(.*)/);
+       var match = url.match(/fbrowser\/[a-z]+\/.*(#.*)/);
        if (match===null) return; //not fbrowser
        var hash = match[1];
 
index 5eeb14c75f4512373a3abd31cf3b56f02306f7c6..b297fcb48174629de382d2609c542ec5835e8039 100644 (file)
@@ -79,7 +79,8 @@ $is_singleuser_class = $is_singleuser ? "is-singleuser" : "is-not-singleuser";
        // special minimal style for modal dialogs
        if ($minimal) {
 ?>
-               <section class="minimal" style="margin:0px!important; padding:0px!important; float:none!important; display:block!important;">
+        <!-- <?php echo __FILE__ ?> -->
+               <section class="minimal">
                        <?php if (!empty($page['content'])) echo $page['content']; ?>
                        <div id="page-footer"></div>
                </section>
diff --git a/view/theme/frio/php/minimal.php b/view/theme/frio/php/minimal.php
new file mode 100644 (file)
index 0000000..e848665
--- /dev/null
@@ -0,0 +1,30 @@
+<!DOCTYPE html >\r
+<html>\r
+<head>\r
+       <title><?php if(!empty($page['title'])) echo $page['title'] ?></title>\r
+       <script>var baseurl="<?php echo Friendica\Core\System::baseUrl() ?>";</script>\r
+       <?php if(!empty($page['htmlhead'])) echo $page['htmlhead'] ?>\r
+</head>\r
+<body class="minimal">\r
+       <section><?php if(!empty($page['content'])) echo $page['content']; ?>\r
+               <div id="page-footer"></div>\r
+       </section>\r
+       <!-- Modal  -->\r
+       <div id="modal" class="modal fade" tabindex="-1" role="dialog" aria-hidden="true">\r
+               <div class="modal-dialog modal-full-screen">\r
+                       <div class="modal-content">\r
+                               <div id="modal-header" class="modal-header">\r
+                                       <button id="modal-cloase" type="button" class="close" data-dismiss="modal" aria-hidden="true">\r
+                                               &times;\r
+                                       </button>\r
+                                       <h4 id="modal-title" class="modal-title"></h4>\r
+                               </div>\r
+                               <div id="modal-body" class="modal-body">\r
+                                       <!-- /# content goes here -->\r
+                               </div>\r
+                       </div>\r
+               </div>\r
+       </div>\r
+</body>\r
+</html>\r
+\r
diff --git a/view/theme/frio/templates/admin/addons.tpl b/view/theme/frio/templates/admin/addons.tpl
deleted file mode 100644 (file)
index fa598f4..0000000
+++ /dev/null
@@ -1,22 +0,0 @@
-
-<div id='adminpage'>
-       <h1>{{$title}} - {{$page}}</h1>
-               {{if $pcount eq 0}}
-                   <div class="error-message">
-                   {{$noplugshint}}
-                   </div>
-               {{else}}
-               <a class="btn" href="{{$baseurl}}/admin/{{$function}}?a=r&amp;t={{$form_security_token}}">{{$reload}}</a>
-               <ul id='addonslist'>
-               {{foreach $addons as $p}}
-                       <li class="addon {{$p.1}}">
-                               <span class="offset-anchor" id="{{$p.0}}"></span>
-                               <a class='toggleaddon' href='{{$baseurl}}/admin/{{$function}}/{{$p.0}}?a=t&amp;t={{$form_security_token}}#{{$p.0}}' title="{{if $p.1==on}}Disable{{else}}Enable{{/if}}" ><span class='icon {{$p.1}}'></span></a>
-                               <a href='{{$baseurl}}/admin/{{$function}}/{{$p.0}}'><span class='name'>{{$p.2.name}}</span></a> - <span class="version">{{$p.2.version}}</span>
-                               {{if $p.2.experimental}} {{$experimental}} {{/if}}{{if $p.2.unsupported}} {{$unsupported}} {{/if}}
-                               <div class='desc'>{{$p.2.description nofilter}}</div>
-                       </li>
-               {{/foreach}}
-               </ul>
-               {{/if}}
-</div>
index 5da73e135da84d819310f7b1a24cf9f19ff75456..0ba58e5aecaada0ada71d257aa91594c3dcf0ac2 100644 (file)
@@ -43,9 +43,9 @@
        <h3>{{$plugadmtxt}}</h3>
        <ul role="menu">
                {{foreach $admin.addons_admin as $name => $item}}
-               <li role="menuitem" class="{{$item.2}}">
-                       <a href="{{$item.0}}" {{if $item.accesskey}}accesskey="{{$item.accesskey}}"{{/if}}>
-                               {{$item.1}}
+               <li role="menuitem" class="{{$item.class}}">
+                       <a href="{{$item.url}}" {{if $item.accesskey}}accesskey="{{$item.accesskey}}"{{/if}}>
+                               {{$item.name}}
                        </a>
                </li>
                {{/foreach}}
diff --git a/view/theme/frio/templates/admin/blocklist/contact.tpl b/view/theme/frio/templates/admin/blocklist/contact.tpl
new file mode 100644 (file)
index 0000000..53fde9a
--- /dev/null
@@ -0,0 +1,105 @@
+<script type="text/javascript" src="view/theme/frio/js/mod_admin.js"></script>
+<link rel="stylesheet" href="view/theme/frio/css/mod_admin.css" type="text/css" media="screen"/>
+
+<div id="admin-contactblock" class="adminpage generic-page-wrapper">
+       <h1>{{$title}} - {{$page}}</h1>
+       <p>{{$description nofilter}}</p>
+
+       {{* We organize the settings in collapsable panel-groups *}}
+       <div class="panel-group panel-group-settings" id="admin-settings" role="tablist" aria-multiselectable="true">
+               {{* The form for entering user profile which should be blocked *}}
+               <div class="panel">
+                       <div class="section-subtitle-wrapper" role="tab" id="admin-settings-contactblock-block">
+                               <h4>
+                                       <a class="accordion-toggle collapsed" data-toggle="collapse" data-parent="#admin-settings" href="#admin-settings-contactblock-block-collapse" aria-expanded="false" aria-controls="admin-settings-contactblock-block-collapse">
+                                               {{$h_newblock}}
+                                       </a>
+                               </h4>
+                       </div>
+
+                       <div id="admin-settings-contactblock-block-collapse" class="panel-collapse collapse" role="tabpanel" aria-labelledby="admin-settings-contactblock-block">
+                               <form action="{{$baseurl}}/admin/blocklist/contact" method="post">
+                                       <input type="hidden" name="form_security_token" value="{{$form_security_token}}">
+
+                                       {{include file="field_input.tpl" field=$contacturl}}
+
+                                       <div class="admin-settings-submit-wrapper form-group pull-right">
+                                               <button type="submit" class="btn btn-primary" name="page_contactblock_block" value="1">{{$submit}}</button>
+                                       </div>
+                                       <div class="clear"></div>
+                               </form>
+                       </div>
+               </div>
+
+               {{* The list of blocked user profiles with the possibility to unblock them *}}
+               <div class="panel">
+                       <div class="section-subtitle-wrapper" role="tab" id="admin-settings-contactblock-blocked">
+                               <h4>
+                                       <a class="accordion-toggle collapsed" data-toggle="collapse" data-parent="#admin-settings" href="#admin-settings-contactblock-blocked-collapse" aria-expanded="{{if count($contacts) > 0}}true{{else}}false{{/if}}" aria-controls="admin-settings-contactblock-blocked-collapse">
+                                               {{$h_contacts}} ({{count($contacts)}})
+                                       </a>
+                               </h4>
+                       </div>
+
+                       <div id="admin-settings-contactblock-blocked-collapse" class="panel-collapse collapse {{if count($contacts) > 0}}in{{/if}}" role="tabpanel" aria-labelledby="admin-settings-contactblock-blocked">
+                               <form action="{{$baseurl}}/admin/blocklist/contact" method="post">
+                                       <input type="hidden" name="form_security_token" value="{{$form_security_token}}">
+
+                                       {{if $contacts}}
+                                       <table id="contactblock" class="table table-condensed table-striped">
+                                               <thead>
+                                                       <tr>
+                                                               <th></th>
+                                                               {{foreach $th_contacts as $th}}
+                                                                       <th>
+                                                                               {{$th}}
+                                                                       </th>
+                                                               {{/foreach}}
+                                                               <th></th>
+                                                       </tr>
+                                               </thead>
+                                               <tbody>
+                                                       {{foreach $contacts as $contact}}
+                                                               <tr>
+                                                                       <td>
+                                                                               <div class="checkbox">
+                                                                                       <input type="checkbox" class="contacts_ckbx" id="id_contact_{{$contact.id}}" name="contacts[]" value="{{$contact.id}}"/>
+                                                                                       <label for="id_contact_{{$contact.id}}"></label>
+                                                                               </div>
+                                                                       </td>
+                                                                       <td><img class="icon" src="{{$contact.micro}}" alt="{{$contact.nickname}}" title="{{$contact.addr}}"></td>
+                                                                       <td class="name">{{$contact.name}}</td>
+                                                                       <td class="addr" colspan="3"><a href="{{$contact.url}}" title="{{$contact.addr}}" >{{$contact.url}}</a></td>
+                                                               </tr>
+                                                       {{/foreach}}
+                                               </tbody>
+                                               <tfoot>
+                                                       <tr>
+                                                               <td>
+                                                                       {{* Checkbox to select all blocked contacts *}}
+                                                                       <div class="checkbox">
+                                                                               <input type="checkbox" id="contactblock-select" class="selecttoggle contacts_ckbx" data-select-class="contacts_ckbx" data-select-all="{{$select_all}}" data-select-none="{{$select_none}}" title="{{$select_all}}"/>
+                                                                               <label for="contactblock-select"></label>
+                                                                       </div>
+                                                               </td>
+                                                               <td colspan="5">
+                                                                       {{$total_contacts}}
+                                                                       <div class="admin-settings-submit-wrapper form-group pull-right">
+                                                                               <button type="submit" class="btn btn-small btn-default pull-right" name="page_contactblock_unblock" value="1">{{$unblock}}</button>
+                                                                       </div>
+                                                                       <div class="clear"></div>
+                                                               </td>
+                                                       </tr>
+                                               </tfoot>
+                                       </table>
+
+                                       {{$paginate nofilter}}
+
+                                       {{else}}
+                                       <p>{{$no_data}}</p>
+                                       {{/if}}
+                               </form>
+                       </div>
+               </div>
+       </div>
+</div>
diff --git a/view/theme/frio/templates/admin/contactblock.tpl b/view/theme/frio/templates/admin/contactblock.tpl
deleted file mode 100644 (file)
index 7d187aa..0000000
+++ /dev/null
@@ -1,105 +0,0 @@
-<script type="text/javascript" src="view/theme/frio/js/mod_admin.js"></script>
-<link rel="stylesheet" href="view/theme/frio/css/mod_admin.css" type="text/css" media="screen"/>
-
-<div id="admin-contactblock" class="adminpage generic-page-wrapper">
-       <h1>{{$title}} - {{$page}}</h1>
-       <p>{{$description nofilter}}</p>
-
-       {{* We organize the settings in collapsable panel-groups *}}
-       <div class="panel-group panel-group-settings" id="admin-settings" role="tablist" aria-multiselectable="true">
-               {{* The form for entering user profile which should be blocked *}}
-               <div class="panel">
-                       <div class="section-subtitle-wrapper" role="tab" id="admin-settings-contactblock-block">
-                               <h4>
-                                       <a class="accordion-toggle collapsed" data-toggle="collapse" data-parent="#admin-settings" href="#admin-settings-contactblock-block-collapse" aria-expanded="false" aria-controls="admin-settings-contactblock-block-collapse">
-                                               {{$h_newblock}}
-                                       </a>
-                               </h4>
-                       </div>
-
-                       <div id="admin-settings-contactblock-block-collapse" class="panel-collapse collapse" role="tabpanel" aria-labelledby="admin-settings-contactblock-block">
-                               <form action="{{$baseurl}}/admin/contactblock" method="post">
-                                       <input type="hidden" name="form_security_token" value="{{$form_security_token}}">
-
-                                       {{include file="field_input.tpl" field=$contacturl}}
-
-                                       <div class="admin-settings-submit-wrapper form-group pull-right">
-                                               <button type="submit" class="btn btn-primary" name="page_contactblock_block" value="1">{{$submit}}</button>
-                                       </div>
-                                       <div class="clear"></div>
-                               </form>
-                       </div>
-               </div>
-
-               {{* The list of blocked user profiles with the possibility to unblock them *}}
-               <div class="panel">
-                       <div class="section-subtitle-wrapper" role="tab" id="admin-settings-contactblock-blocked">
-                               <h4>
-                                       <a class="accordion-toggle collapsed" data-toggle="collapse" data-parent="#admin-settings" href="#admin-settings-contactblock-blocked-collapse" aria-expanded="{{if count($contacts) > 0}}true{{else}}false{{/if}}" aria-controls="admin-settings-contactblock-blocked-collapse">
-                                               {{$h_contacts}} ({{count($contacts)}})
-                                       </a>
-                               </h4>
-                       </div>
-
-                       <div id="admin-settings-contactblock-blocked-collapse" class="panel-collapse collapse {{if count($contacts) > 0}}in{{/if}}" role="tabpanel" aria-labelledby="admin-settings-contactblock-blocked">
-                               <form action="{{$baseurl}}/admin/contactblock" method="post">
-                                       <input type="hidden" name="form_security_token" value="{{$form_security_token}}">
-
-                                       {{if $contacts}}
-                                       <table id="contactblock" class="table table-condensed table-striped">
-                                               <thead>
-                                                       <tr>
-                                                               <th></th>
-                                                               {{foreach $th_contacts as $th}}
-                                                                       <th>
-                                                                               {{$th}}
-                                                                       </th>
-                                                               {{/foreach}}
-                                                               <th></th>
-                                                       </tr>
-                                               </thead>
-                                               <tbody>
-                                                       {{foreach $contacts as $contact}}
-                                                               <tr>
-                                                                       <td>
-                                                                               <div class="checkbox">
-                                                                                       <input type="checkbox" class="contacts_ckbx" id="id_contact_{{$contact.id}}" name="contacts[]" value="{{$contact.id}}"/>
-                                                                                       <label for="id_contact_{{$contact.id}}"></label>
-                                                                               </div>
-                                                                       </td>
-                                                                       <td><img class="icon" src="{{$contact.micro}}" alt="{{$contact.nickname}}" title="{{$contact.addr}}"></td>
-                                                                       <td class="name">{{$contact.name}}</td>
-                                                                       <td class="addr" colspan="3"><a href="{{$contact.url}}" title="{{$contact.addr}}" >{{$contact.url}}</a></td>
-                                                               </tr>
-                                                       {{/foreach}}
-                                               </tbody>
-                                               <tfoot>
-                                                       <tr>
-                                                               <td>
-                                                                       {{* Checkbox to select all blocked contacts *}}
-                                                                       <div class="checkbox">
-                                                                               <input type="checkbox" id="contactblock-select" class="selecttoggle contacts_ckbx" data-select-class="contacts_ckbx" data-select-all="{{$select_all}}" data-select-none="{{$select_none}}" title="{{$select_all}}"/>
-                                                                               <label for="contactblock-select"></label>
-                                                                       </div>
-                                                               </td>
-                                                               <td colspan="5">
-                                                                       {{$total_contacts}}
-                                                                       <div class="admin-settings-submit-wrapper form-group pull-right">
-                                                                               <button type="submit" class="btn btn-small btn-default pull-right" name="page_contactblock_unblock" value="1">{{$unblock}}</button>
-                                                                       </div>
-                                                                       <div class="clear"></div>
-                                                               </td>
-                                                       </tr>
-                                               </tfoot>
-                                       </table>
-
-                                       {{$paginate nofilter}}
-
-                                       {{else}}
-                                       <p>{{$no_data}}</p>
-                                       {{/if}}
-                               </form>
-                       </div>
-               </div>
-       </div>
-</div>
index dde38639991636fe3fbcdf427e8f0e4551260bc9..ab076a0f73a78102dd8c5511136195e0b09cdf3b 100644 (file)
@@ -5,20 +5,16 @@
        <table class="table">
                <tr>
                        <th>{{$id_header}}</th>
-                       <th>{{$to_header}}</th>
-                       <th>{{$url_header}}</th>
-                       <th>{{$network_header}}</th>
+                       <th>{{$param_header}}</th>
                        <th>{{$created_header}}</th>
-                       <th>{{$last_header}}</th>
+                       <th>{{$prio_header}}</th>
                </tr>
                {{foreach $entries as $e}}
                <tr>
                        <td>{{$e.id}}</td>
-                       <td>{{$e.name}}</td>
-                       <td><a href="{{$e.nurl}}">{{$e.nurl}}</a></td>
-                       <td>{{$e.network}}</td>
+                       <td>{{$e.parameter}}</td>
                        <td>{{$e.created}}</td>
-                       <td>{{$e.last}}</td>
+                       <td>{{$e.priority}}</td>
                </tr>
                {{/foreach}}
        </table>
index 504d395e893aac6b0b6b7f54ba3e9f6fdf32ed1b..4c0a6ce06667a241cd9add9be8ac16547975e4d7 100644 (file)
@@ -1,44 +1,5 @@
 
 <script>
-       $(function(){
-
-               $("#cnftheme").click(function(){
-                       $.colorbox({
-                               width: 800,
-                               height: '90%',
-                               /*onOpen: function(){
-                                       var theme = $("#id_theme :selected").val();
-                                       $("#cnftheme").attr('href',"{{$baseurl}}/admin/themes/"+theme);
-                               },*/
-                iframe: true,
-                href: "{{$baseurl}}/admin/themes/" + $("#id_theme :selected").val() + "?mode=minimal",
-                               onComplete: function(){
-                                       $("div#fancybox-content form").submit(function(e){
-                                               var url = $(this).attr('action');
-                                               // can't get .serialize() to work...
-                                               var data={};
-                                               $(this).find("input").each(function(){
-                                                       data[$(this).attr('name')] = $(this).val();
-                                               });
-                                               $(this).find("select").each(function(){
-                                                       data[$(this).attr('name')] = $(this).children(":selected").val();
-                                               });
-                                               console.log(":)", url, data);
-
-                                               $.post(url, data, function(data) {
-                                                       if(timer) clearTimeout(timer);
-                                                       NavUpdate();
-                                                       $.colorbox.close();
-                                               })
-
-                                               return false;
-                                       });
-
-                               }
-                       });
-                       return false;
-               });
-       });
        $(function(){
                $(".collapse").on('show.bs.collapse', function(e) {
                        var id = $(e.target).attr('id');
                                $(element).addClass('in');
                        window.scroll(0, $(element).offset().top - 120);
                }
+
+               $("#cnftheme").click(function(){
+                       document.location.assign("{{$baseurl}}/admin/themes/" + $("#id_theme :selected").val());
+                       return false;
+               });
        });
 </script>
 <link rel="stylesheet" href="view/theme/frio/css/mod_admin.css" type="text/css" media="screen"/>
@@ -73,9 +39,7 @@
                                        </h4>
                                </div>
                                <div id="admin-settings-general-collapse" class="panel-collapse collapse" role="tabpanel" aria-labelledby="admin-settings-general">
-
                                        {{include file="field_input.tpl" field=$sitename}}
-                                       {{include file="field_input.tpl" field=$hostname}}
                                        {{include file="field_input.tpl" field=$sender_email}}
                                        {{include file="field_textarea.tpl" field=$banner}}
                                        {{include file="field_input.tpl" field=$shortcut_icon}}
index d183e3fa20ab674b2af2def3cca2433ccdff1068..0fd599b051b0d5be389bde23a928b344c9a947e3 100644 (file)
@@ -2,7 +2,7 @@
 <div id='adminpage-summery' class="adminpage generic-page-wrapper">
        <h1>{{$title}} - {{$page}}</h1>
 
-       {{if $showwarning}}
+       {{if $warningtext|count}}
        <div id="admin-warning-message-wrapper" class="alert alert-warning">
                {{foreach $warningtext as $wt}}
                <p>{{$wt nofilter}}</p>
@@ -14,7 +14,7 @@
                {{* The work queues short statistic. *}}
                <div id="admin-summary-queues" class="col-lg-12 col-md-12 col-sm-12 col-xs-12 admin-summary">
                        <div class="col-lg-4 col-md-4 col-sm-4 col-xs-12 admin-summary-label-name text-muted">{{$queues.label}}</div>
-                       <div class="col-lg-8 col-md-8 col-sm-8 col-xs-12 admin-summary-entry"><a href="{{$baseurl}}/admin/deferred">{{$queues.deferred}}</a> - <a href="{{$baseurl}}/admin/workerqueue">{{$queues.workerq}}</a></div>
+                       <div class="col-lg-8 col-md-8 col-sm-8 col-xs-12 admin-summary-entry"><a href="{{$baseurl}}/admin/queue/deferred">{{$queues.deferred}}</a> - <a href="{{$baseurl}}/admin/queue">{{$queues.workerq}}</a></div>
                </div>
 
                {{* Number of pending registrations. *}}
index 273eb81e68c65cabcb84cb7610d531ac07dd3e43..f2d407845b5b8dedd108fcf308acaed3e086caeb 100644 (file)
                                                                        </td>
                                                                        <td class="text-right">
                                                                                {{if $u.is_deletable}}
-                                                                               <a href="{{$baseurl}}/admin/users/block/{{$u.uid}}?t={{$form_security_token}}" class="admin-settings-action-link"title="{{if $u.blocked}}{{$unblock}}{{else}}{{$block}}{{/if}}">
-                                                                                       {{if $u.blocked == 0}}
-                                                                                       <i class="fa fa-ban" aria-hidden="true"></i>
-                                                                                       {{else}}
+                                                                                       {{if $u.blocked}}
+                                                                               <a href="{{$baseurl}}/admin/users/unblock/{{$u.uid}}?t={{$form_security_token}}" class="admin-settings-action-link" title="{{$unblock}}">
                                                                                        <i class="fa fa-circle-o" aria-hidden="true"></i>
-                                                                                       {{/if}}
                                                                                </a>
+                                                                                       {{else}}
+                                                                               <a href="{{$baseurl}}/admin/users/block/{{$u.uid}}?t={{$form_security_token}}" class="admin-settings-action-link" title="{{$block}}">
+                                                                                       <i class="fa fa-ban" aria-hidden="true"></i>
+                                                                               </a>
+                                                                                       {{/if}}
                                                                                <a href="{{$baseurl}}/admin/users/delete/{{$u.uid}}?t={{$form_security_token}}" class="admin-settings-action-link" title="{{$delete}}" onclick="return confirm_delete('{{$confirm_delete}}','{{$u.name}}')">
                                                                                        <i class="fa fa-trash" aria-hidden="true"></i>
                                                                                </a>
                                                        </div>
                                                        <div class="col-xs-9 admin-settings-footer-elements text-right">
                                                                <button type="submit" name="page_users_block" value="1" class="btn btn-warning">
-                                                                       <i class="fa fa-ban" aria-hidden="true"></i> {{$block}} / <i class="fa fa-circle-o" aria-hidden="true"></i> {{$unblock}}
+                                                                       <i class="fa fa-ban" aria-hidden="true"></i> {{$block}}
+                                                               </button>
+                                                               <button type="submit" name="page_users_unblock" value="1" class="btn btn-default">
+                                                                       <i class="fa fa-circle-o" aria-hidden="true"></i> {{$unblock}}
                                                                </button>
                                                                <button type="submit" name="page_users_delete" value="1" class="btn btn-danger" onclick="return confirm_delete('{{$confirm_delete_multi}}')">
                                                                        <i class="fa fa-trash" aria-hidden="true"></i> {{$delete}}
diff --git a/view/theme/frio/templates/admin/workerqueue.tpl b/view/theme/frio/templates/admin/workerqueue.tpl
deleted file mode 100644 (file)
index ab076a0..0000000
+++ /dev/null
@@ -1,21 +0,0 @@
-<div id="adminpage">
-       <h1>{{$title}} - {{$page}} ({{$count}})</h1>
-       
-       <p>{{$info}}</p>
-       <table class="table">
-               <tr>
-                       <th>{{$id_header}}</th>
-                       <th>{{$param_header}}</th>
-                       <th>{{$created_header}}</th>
-                       <th>{{$prio_header}}</th>
-               </tr>
-               {{foreach $entries as $e}}
-               <tr>
-                       <td>{{$e.id}}</td>
-                       <td>{{$e.parameter}}</td>
-                       <td>{{$e.created}}</td>
-                       <td>{{$e.priority}}</td>
-               </tr>
-               {{/foreach}}
-       </table>
-</div>
index 0b58d520d8b305f333a18cbd3bab072b69911dfe..4f240922a792ddaab9fbb611312e8260e6d262b0 100644 (file)
@@ -7,7 +7,6 @@
 
                <div class="pull-right">
                        <input class="btn-primary btn btn-small" id="photo-album-edit-submit" type="submit" name="submit" value="{{$submit}}" />
-                       <input class="btn-primary btn btn-small" id="photo-album-edit-drop" type="submit" name="dropalbum" value="{{$dropsubmit}}" onclick="return confirmDelete();" />
                </div>
        </form>
        <div class="clear"></div>
index 62611593c80dcc4fd1cb522e85dd3e5cdbd21813..36072a56b1b6227cd18dd394e43a6ff21ccc1876 100644 (file)
@@ -1,6 +1,5 @@
 
-<form action="{{$confirm_url}}" id="confirm-form" method="{{$method}}">
-
+<form action="{{$confirm_url}}" id="confirm-form" method="{{$method}}" class="generic-page-wrapper">
        <div id="confirm-message">{{$message}}</div>
        {{foreach $extra_inputs as $input}}
        <input type="hidden" name="{{$input.name}}" value="{{$input.value}}" />
@@ -10,5 +9,4 @@
                <button type="submit" name="{{$confirm_name}}" id="confirm-submit-button" class="btn btn-primary confirm-button" value="{{$confirm}}">{{$confirm}}</button>
                <button type="submit" name="canceled" id="confirm-cancel-button" class="btn confirm-button" data-dismiss="modal">{{$cancel}}</button>
        </div>
-
 </form>
index 285501ef3b669fdac5cfcb538fd34fa27b717388..c4affb7eeb4328c787cc2706b4d981335e113695 100644 (file)
@@ -2,9 +2,9 @@
 <div class="form-group field input color">
        <label for="id_{{$field.0}}" id="label_{{$field.0}}">{{$field.1}}</label>
        <div class="input-group" id="{{$field.0}}">
+               <span class="input-group-addon"><i></i></span>
                <input class="form-control color" name="{{$field.0}}" id="id_{{$field.0}}" type="text" value="{{$field.2 nofilter}}" aria-describedby="{{$field.0}}_tip">
                {{if $field.4}}<span class="required">{{$field.4}}</span>{{/if}}
-               <span class="input-group-addon"><i></i></span>
        </div>
        {{if $field.3}}
        <span class="help-block" id="{{$field.0}}_tip" role="tooltip">{{$field.3 nofilter}}</span>
index a34e8ea8616483c0e4683c90642e9aa5e415881c..a3b030477a17ce59c74d867d4d3033b736e24d1f 100644 (file)
                        <i class="fa fa-pencil"></i>
                </button>
                {{/if}}
+               {{if $drop}}
+               <span class="icon-padding"> </span>
+               <button id="album-drop-link" class="btn-link page-action faded-icon" type="button" data-modal-url="{{$drop.1}}" title="{{$drop.0}}" data-toggle="tooltip">
+                       <i class="fa fa-trash"></i>
+               </button>
+               {{/if}}
 
                {{if ! $noorder}}
                <span class="icon-padding"> </span>
index 359c42669622c9f334451048c163f9c3f8c41717..82bddcfc61c2870596fbefe523ef2377ccac7460 100644 (file)
                </a>
        </div>
        <div class="pull-right" id="photo-edit-link-wrap">
-               {{if $tools}}
+{{if $tools}}
+       {{if $tools.view}}
+               <span class="icon-padding"> </span>
+               <a id="photo-edit-link" href="{{$tools.view.0}}" title="{{$tools.view.1}}" data-toggle="tooltip">
+                       <i class="page-action faded-icon fa fa-image"></i>
+               </a>
+       {{/if}}
+       {{if $tools.edit}}
                <span class="icon-padding"> </span>
                <a id="photo-edit-link" href="{{$tools.edit.0}}" title="{{$tools.edit.1}}" data-toggle="tooltip">
                        <i class="page-action faded-icon fa fa-pencil"></i>
                </a>
+       {{/if}}
+       {{if $tools.delete}}
+               <span class="icon-padding"> </span>
+               <a id="photo-edit-link" href="{{$tools.delete.0}}" title="{{$tools.delete.1}}" data-toggle="tooltip">
+                       <i class="page-action faded-icon fa fa-trash"></i>
+               </a>
+       {{/if}}
+       {{if $tools.profile}}
                <span class="icon-padding"> </span>
                <a id="photo-toprofile-link" href="{{$tools.profile.0}}" title="{{$tools.profile.1}}" data-toggle="tooltip">
                        <i class="page-action faded-icon fa fa-user"></i>
                </a>
-               {{/if}}
-               {{if $lock}}
+       {{/if}}
+       {{if $tools.lock}}
                <span class="icon-padding"> </span>
-               <a id="photo-lock-link" onclick="lockview(event,'photo/{{$id}}');" title="{{$lock}}" data-toggle="tooltip">
+               <a id="photo-lock-link" onclick="lockview(event,'photo/{{$id}}');" title="{{$tools.lock}}" data-toggle="tooltip">
                        <i class="page-action faded-icon fa fa-lock"></i>
                </a>
-               {{/if}}
+       {{/if}}
+{{/if}}
        </div>
        <div class="clear"></div>
 
                <hr>
        </div>
 
+{{if !$edit}}
        {{* Insert the comments *}}
        <div id="photo-comment-wrapper-{{$id}}" class="photo-comment-wrapper">
                {{$comments nofilter}}
        </div>
 
        {{$paginate nofilter}}
+{{/if}}
 </div>
index b84f5f28a8ef6245df9b951537ada5d587262915..3ac6282cabc3f02df46f76fe305a6ea66c3b7122 100644 (file)
@@ -1,7 +1,4 @@
-
-<link rel="stylesheet" href="{{$baseurl}}/view/theme/frio/frameworks/jRange/jquery.range.css" type="text/css" media="screen" />
 <script src="{{$baseurl}}/view/theme/quattro/jquery.tools.min.js"></script>
-<script src="{{$baseurl}}/view/theme/frio/frameworks/jRange/jquery.range.js"></script>
 <script type="text/javascript" src="{{$baseurl}}/view/js/ajaxupload.js" ></script>
 
 {{include file="field_select.tpl" field=$scheme}}
 {{if $contentbg_transp}}
 <div class="form-group field input color">
        <label for="id_{{$contentbg_transp.0}}" id="label_{{$contentbg_transp.0}}">{{$contentbg_transp.1}}</label>
-       <input type="hidden" class="form-control color slider-input" name="{{$contentbg_transp.0}}" id="{{$contentbg_transp.0}}" type="text" value="{{$contentbg_transp.2}}" aria-describedby="{{$contentbg_transp.0}}_tip">
+
+       <div class="row">
+               <div class="col-xs-9">
+                       <input type="range" class="form-control color" id="{{$contentbg_transp.0}}_range" min="0" max="100" step="1" value="{{$contentbg_transp.2}}" onchange="{{$contentbg_transp.0}}.value = this.value" oninput="{{$contentbg_transp.0}}.value = this.value">
+               </div>
+               <div class="col-xs-3">
+                       <div class="input-group">
+                               <input type="text" class="form-control input-sm" name="{{$contentbg_transp.0}}" id="{{$contentbg_transp.0}}" value="{{$contentbg_transp.2}}" onchange="{{$contentbg_transp.0}}_range.value = this.value" oninput="{{$contentbg_transp.0}}_range.value = this.value" aria-describedby="{{$contentbg_transp.0}}_tip">
+                               <span class="input-group-addon image-select">%</span>
+                       </div>
+               </div>
+       </div>
+
        <span id="{{$contentbg_transp.0}}_tip" class="help-block" role="tooltip">{{$contentbg_transp.3}}</span>
        <div id="end_{{$contentbg_transp.0}}" class="field_end"></div>
 </div>
                if($("#id_frio_background_image").val().length != 0) {
                                $("#frio_bg_image_options").show();
                }
-
-               $('.slider-input').jRange({
-                       from: 0,
-                       to: 100,
-                       step: 1,
-                       scale: [0,10,20,30,40,50,60,70,80,90,100],
-                       format: '%s',
-                       width: '100%',
-                       showLabels: true,
-                       theme: 'theme-frio',
-               });
-
-               // The position of the slider is wrong calculated on hidden elements.
-               // So set an event listener toggle and update the jRange value.
-               $(document).on('click', '#custom-settings-title a', function() {
-                       var bgTransp = $('#frio_contentbg_transp').val();
-                       $('.slider-input').jRange('setValue', bgTransp);
-               });
-
        });
 </script>
 
        <button type="submit" value="{{$submit}}" class="settings-submit btn btn-primary" name="frio-settings-submit">{{$submit}}</button>
 </div>
 <div class="clearfix"></div>
-
-<script type="text/javascript">
-       $(".inputRange").rangeinput();
-</script>
index cdef0eeaacfe039d7080fb0658ea9a83bc140b18..bbe33a1e14f52ce0fdcb4c3f41d1dfa66c652352 100644 (file)
@@ -72,7 +72,6 @@ function quattro_form(App $a, $align, $color, $tfs, $pfs) {
        $t = Renderer::getMarkupTemplate("theme_settings.tpl" );
        $o = Renderer::replaceMacros($t, [
                '$submit'  => L10n::t('Submit'),
-               '$baseurl' => System::baseUrl(),
                '$title'   => L10n::t("Theme settings"),
                '$align'   => ['quattro_align', L10n::t('Alignment'), $align, '', ['left' => L10n::t('Left'), 'center' => L10n::t('Center')]],
                '$color'   => ['quattro_color', L10n::t('Color scheme'), $color, '', $colors],
index ddb395db9cdcbff166e6c993822f2420109cbd0d..97875a0771849d96bb3bfa1e176125f9415f339e 100644 (file)
                                </tbody>
                        </table>
                        <div class='selectall'><a href='#' onclick="return selectall('users_ckbx');">{{$select_all}}</a></div>
-                       <div class="submit"><input type="submit" name="page_users_block" value="{{$block}}/{{$unblock}}" /> <input type="submit" name="page_users_delete" value="{{$delete}}" onclick="return confirm_delete_multi()" /></div>                                          
+                       <div class="submit">
+                               <input type="submit" name="page_users_block" value="{{$block}}" />
+                               <input type="submit" name="page_users_unblock" value="{{$unblock}}" />
+                               <input type="submit" name="page_users_delete" value="{{$delete}}" onclick="return confirm_delete_multi()" />
+                       </div>
                {{else}}
                        NO USERS?!?
                {{/if}}
index a4787270fe4e18fb29ec3a448c7e3201c7ed8efc..1ce336b0a61b22bbac4c746cb5451cf72e4790a0 100644 (file)
@@ -3,11 +3,22 @@
 
 <div id="photo-edit-link-wrap">
 {{if $tools}}
-<a id="photo-edit-link" href="{{$tools.edit.0}}">{{$tools.edit.1}}</a>
-|
-<a id="photo-toprofile-link" href="{{$tools.profile.0}}">{{$tools.profile.1}}</a>
+    {{if $tools.view}}
+        <a id="photo-view-link" href="{{$tools.view.0}}">{{$tools.view.1}}</a>
+    {{/if}}
+    {{if $tools.edit}}
+        <a id="photo-edit-link" href="{{$tools.edit.0}}">{{$tools.edit.1}}</a>
+    {{/if}}
+    {{if $tools.delete}}
+        | <a id="photo-edit-link" href="{{$tools.delete.0}}">{{$tools.delete.1}}</a>
+    {{/if}}
+    {{if $tools.profile}}
+        | <a id="photo-toprofile-link" href="{{$tools.profile.0}}">{{$tools.profile.1}}</a>
+    {{/if}}
+    {{if $tools.lock}}
+        | <img src="images/lock_icon.gif" class="lockview" alt="{{$tools.lock}}" onclick="lockview(event,'photo/{{$id}}');" />
+    {{/if}}
 {{/if}}
-{{if $lock}} | <img src="images/lock_icon.gif" class="lockview" alt="{{$lock}}" onclick="lockview(event,'photo/{{$id}}');" /> {{/if}}
 </div>
 
 <div id="photo-photo"><a href="{{$photo.href}}" title="{{$photo.title}}"><img src="{{$photo.src}}" /></a></div>
index f709356535b48804634ee40db12bb26011cfb21c..d34a447d5eeca4f000c730617b2e2ac4658367f2 100644 (file)
@@ -118,7 +118,6 @@ function vier_form(App $a, $style, $show_pages, $show_profiles, $show_helpers, $
        $t = Renderer::getMarkupTemplate("theme_settings.tpl");
        $o = Renderer::replaceMacros($t, [
                '$submit' => L10n::t('Submit'),
-               '$baseurl' => System::baseUrl(),
                '$title' => L10n::t("Theme settings"),
                '$style' => ['vier_style', L10n::t('Set style'), $style, '', $styles],
                '$show_pages' => ['vier_show_pages', L10n::t('Community Pages'), $show_pages, '', $show_or_not],
index 617bcc5b25341b8a3ab85bbd67f4165981d6ddcb..f70ec5b561ed40bc5ad93b96cc3084f50c1e5f32 100644 (file)
@@ -4,11 +4,22 @@
 
 <div id="photo-edit-link-wrap">
 {{if $tools}}
-<a id="photo-edit-link" href="{{$tools.edit.0}}">{{$tools.edit.1}}</a>
-|
-<a id="photo-toprofile-link" href="{{$tools.profile.0}}">{{$tools.profile.1}}</a>
+       {{if $tools.view}}
+               <a id="photo-view-link" href="{{$tools.view.0}}">{{$tools.view.1}}</a>
+       {{/if}}
+       {{if $tools.edit}}
+               <a id="photo-edit-link" href="{{$tools.edit.0}}">{{$tools.edit.1}}</a>
+       {{/if}}
+       {{if $tools.delete}}
+               | <a id="photo-edit-link" href="{{$tools.delete.0}}">{{$tools.delete.1}}</a>
+       {{/if}}
+       {{if $tools.profile}}
+               | <a id="photo-toprofile-link" href="{{$tools.profile.0}}">{{$tools.profile.1}}</a>
+       {{/if}}
+       {{if $tools.lock}}
+               | <img src="images/lock_icon.gif" class="lockview" alt="{{$tools.lock}}" onclick="lockview(event,'photo/{{$id}}');" />
+       {{/if}}
 {{/if}}
-{{if $lock}} | <img src="images/lock_icon.gif" class="lockview" alt="{{$lock}}" onclick="lockview(event,'photo/{{$id}}');" /> {{/if}}
 </div>
 
 {{if $prevlink}}<div id="photo-prev-link"><a href="{{$prevlink.0}}">{{$prevlink.1 nofilter}}</a></div>{{/if}}