]> git.mxchange.org Git - friendica.git/commitdiff
Merge pull request #5946 from JonnyTischbein/move_include_security
authorHypolite Petovan <hypolite@mrpetovan.com>
Fri, 19 Oct 2018 12:55:08 +0000 (08:55 -0400)
committerGitHub <noreply@github.com>
Fri, 19 Oct 2018 12:55:08 +0000 (08:55 -0400)
Move and Split include/security

1  2 
mod/admin.php
mod/community.php
mod/invite.php
mod/item.php
mod/register.php
src/Model/Item.php

diff --combined mod/admin.php
index b0fb6d47262a23024e8d0df63c464a2cd438f4c5,a60af3b1207d367e41ad4dad5122253564210f74..2714b0b86450e98d545a23e397f51f781a9b3208
@@@ -6,6 -6,7 +6,7 @@@
   */
  
  use Friendica\App;
+ use Friendica\BaseModule;
  use Friendica\Content\Feature;
  use Friendica\Content\Text\Markdown;
  use Friendica\Core\Addon;
@@@ -18,14 -19,13 +19,14 @@@ 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\Login;
  use Friendica\Module\Tos;
  use Friendica\Util\Arrays;
  use Friendica\Util\DateTimeFormat;
 -use Friendica\Util\Temporal;
  use Friendica\Util\Network;
 +use Friendica\Util\Temporal;
  
  require_once 'include/enotify.php';
  require_once 'include/text.php';
@@@ -34,11 -34,11 +35,11 @@@ require_once 'include/items.php'
  /**
   * @brief Process send data from the admin panels subpages
   *
 - * This function acts as relais for processing the data send from the 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 subsequencely function
 + * The function itself does not return anything, but the subsequently function
   * return the HTML for the pages of the admin panel.
   *
   * @param App $a
@@@ -314,7 -314,7 +315,7 @@@ function admin_page_tos(App $a
                '$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' => get_form_security_token("admin_tos"),
+               '$form_security_token' => BaseModule::getFormSecurityToken("admin_tos"),
                '$submit' => L10n::t('Save Settings'),
        ]);
  }
   */
  function admin_page_tos_post(App $a)
  {
-       check_form_security_token_redirectOnErr('/admin/tos', 'admin_tos');
+       BaseModule::checkFormSecurityTokenRedirectOnError('/admin/tos', 'admin_tos');
  
        if (!x($_POST, "page_tos")) {
                return;
@@@ -385,7 -385,7 +386,7 @@@ function admin_page_blocklist(App $a
                '$entries' => $blocklistform,
                '$baseurl' => System::baseUrl(true),
                '$confirm_delete' => L10n::t('Delete entry from blocklist?'),
-               '$form_security_token' => get_form_security_token("admin_blocklist")
+               '$form_security_token' => BaseModule::getFormSecurityToken("admin_blocklist")
        ]);
  }
  
@@@ -400,7 -400,7 +401,7 @@@ function admin_page_blocklist_post(App 
                return;
        }
  
-       check_form_security_token_redirectOnErr('/admin/blocklist', 'admin_blocklist');
+       BaseModule::checkFormSecurityTokenRedirectOnError('/admin/blocklist', 'admin_blocklist');
  
        if (x($_POST['page_blocklist_save'])) {
                //  Add new item to blocklist
@@@ -443,7 -443,7 +444,7 @@@ function admin_page_contactblock_post(A
        $contact_url = x($_POST, 'contact_url') ? $_POST['contact_url'] : '';
        $contacts    = x($_POST, 'contacts')    ? $_POST['contacts']    : [];
  
-       check_form_security_token_redirectOnErr('/admin/contactblock', 'admin_contactblock');
+       BaseModule::checkFormSecurityTokenRedirectOnError('/admin/contactblock', 'admin_contactblock');
  
        if (x($_POST, 'page_contactblock_block')) {
                $contact_id = Contact::getIdForURL($contact_url);
@@@ -500,7 -500,7 +501,7 @@@ function admin_page_contactblock(App $a
                '$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' => get_form_security_token("admin_contactblock"),
+               '$form_security_token' => BaseModule::getFormSecurityToken("admin_contactblock"),
  
                // values //
                '$baseurl'    => System::baseUrl(true),
@@@ -535,7 -535,7 +536,7 @@@ function admin_page_deleteitem(App $a
                '$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' => get_form_security_token("admin_deleteitem")
+               '$form_security_token' => BaseModule::getFormSecurityToken("admin_deleteitem")
        ]);
  }
  
@@@ -553,7 -553,7 +554,7 @@@ function admin_page_deleteitem_post(Ap
                return;
        }
  
-       check_form_security_token_redirectOnErr('/admin/deleteitem/', 'admin_deleteitem');
+       BaseModule::checkFormSecurityTokenRedirectOnError('/admin/deleteitem/', 'admin_deleteitem');
  
        if (x($_POST['page_deleteitem_submit'])) {
                $guid = trim(notags($_POST['deleteitemguid']));
@@@ -896,7 -896,8 +897,7 @@@ function admin_page_summary(App $a
  
        logger('accounts: ' . print_r($accounts, true), LOGGER_DATA);
  
 -      $r = q("SELECT COUNT(`id`) AS `count` FROM `register`");
 -      $pending = $r[0]['count'];
 +      $pending = Register::getPendingCount();
  
        $r = q("SELECT COUNT(*) AS `total` FROM `queue` WHERE 1");
        $queue = (($r) ? $r[0]['total'] : 0);
        $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')], 
 +      $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 = get_markup_template('admin/summary.tpl');
   */
  function admin_page_site_post(App $a)
  {
-       check_form_security_token_redirectOnErr('/admin/site', 'admin_site');
+       BaseModule::checkFormSecurityTokenRedirectOnError('/admin/site', 'admin_site');
  
        if (!empty($_POST['republish_directory'])) {
                Worker::add(PRIORITY_LOW, 'Directory');
@@@ -1541,7 -1542,7 +1542,7 @@@ function admin_page_site(App $a
                '$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'  => get_form_security_token("admin_site"),
+               '$form_security_token'  => BaseModule::getFormSecurityToken("admin_site"),
                '$relocate_button'      => L10n::t('Start Relocation'),
        ]);
  }
@@@ -1656,7 -1657,7 +1657,7 @@@ function admin_page_users_post(App $a
        $nu_email    = defaults($_POST, 'new_user_email'   , '');
        $nu_language = Config::get('system', 'language');
  
-       check_form_security_token_redirectOnErr('/admin/users', 'admin_users');
+       BaseModule::checkFormSecurityTokenRedirectOnError('/admin/users', 'admin_users');
  
        if (!($nu_name === "") && !($nu_email === "") && !($nu_nickname === "")) {
                try {
@@@ -1772,14 -1773,14 +1773,14 @@@ function admin_page_users(App $a
                }
                switch ($a->argv[2]) {
                        case "delete":
-                               check_form_security_token_redirectOnErr('/admin/users', 'admin_users', 't');
+                               BaseModule::checkFormSecurityTokenRedirectOnError('/admin/users', 'admin_users', 't');
                                // delete user
                                User::remove($uid);
  
                                notice(L10n::t("User '%s' deleted", $user['username']) . EOL);
                                break;
                        case "block":
-                               check_form_security_token_redirectOnErr('/admin/users', 'admin_users', 't');
+                               BaseModule::checkFormSecurityTokenRedirectOnError('/admin/users', 'admin_users', 't');
                                q("UPDATE `user` SET `blocked` = %d WHERE `uid` = %s",
                                        intval(1 - $user['blocked']),
                                        intval($uid)
        }
  
        /* get pending */
 -      $pending = q("SELECT `register`.*, `contact`.`name`, `user`.`email`
 -                               FROM `register`
 -                               INNER JOIN `contact` ON `register`.`uid` = `contact`.`uid`
 -                               INNER JOIN `user` ON `register`.`uid` = `user`.`uid`;");
 -
 +      $pending = Register::getPending();
  
        /* get users */
        $total = q("SELECT COUNT(*) AS `total` FROM `user` WHERE 1");
                '$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' => get_form_security_token("admin_users"),
+               '$form_security_token' => BaseModule::getFormSecurityToken("admin_users"),
  
                // values //
                '$baseurl' => System::baseUrl(true),
@@@ -1971,7 -1976,7 +1972,7 @@@ function admin_page_addons(App $a
                }
  
                if (x($_GET, "a") && $_GET['a'] == "t") {
-                       check_form_security_token_redirectOnErr('/admin/addons', 'admin_themes', 't');
+                       BaseModule::checkFormSecurityTokenRedirectOnError('/admin/addons', 'admin_themes', 't');
  
                        // Toggle addon status
                        $idx = array_search($addon, $a->addons);
                        '$screenshot' => '',
                        '$readme' => $readme,
  
-                       '$form_security_token' => get_form_security_token("admin_themes"),
+                       '$form_security_token' => BaseModule::getFormSecurityToken("admin_themes"),
                ]);
        }
  
         * List addons
         */
        if (x($_GET, "a") && $_GET['a'] == "r") {
-               check_form_security_token_redirectOnErr(System::baseUrl() . '/admin/addons', 'admin_themes', 't');
+               BaseModule::checkFormSecurityTokenRedirectOnError(System::baseUrl() . '/admin/addons', 'admin_themes', 't');
                Addon::reload();
                info("Addons reloaded");
                goaway(System::baseUrl() . '/admin/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' => get_form_security_token("admin_themes"),
+               '$form_security_token' => BaseModule::getFormSecurityToken("admin_themes"),
        ]);
  }
  
@@@ -2219,7 -2224,7 +2220,7 @@@ function admin_page_themes(App $a
                }
  
                if (x($_GET, "a") && $_GET['a'] == "t") {
-                       check_form_security_token_redirectOnErr('/admin/themes', 'admin_themes', 't');
+                       BaseModule::checkFormSecurityTokenRedirectOnError('/admin/themes', 'admin_themes', 't');
  
                        // Toggle theme status
  
                        '$screenshot' => $screenshot,
                        '$readme' => $readme,
  
-                       '$form_security_token' => get_form_security_token("admin_themes"),
+                       '$form_security_token' => BaseModule::getFormSecurityToken("admin_themes"),
                ]);
        }
  
        // reload active themes
        if (x($_GET, "a") && $_GET['a'] == "r") {
-               check_form_security_token_redirectOnErr(System::baseUrl() . '/admin/themes', 'admin_themes', 't');
+               BaseModule::checkFormSecurityTokenRedirectOnError(System::baseUrl() . '/admin/themes', 'admin_themes', 't');
                foreach ($themes as $th) {
                        if ($th['allowed']) {
                                Theme::uninstall($th['name']);
                '$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' => get_form_security_token("admin_themes"),
+               '$form_security_token' => BaseModule::getFormSecurityToken("admin_themes"),
        ]);
  }
  
  function admin_page_logs_post(App $a)
  {
        if (x($_POST, "page_logs")) {
-               check_form_security_token_redirectOnErr('/admin/logs', 'admin_logs');
+               BaseModule::checkFormSecurityTokenRedirectOnError('/admin/logs', 'admin_logs');
  
                $logfile   = ((x($_POST,'logfile'))   ? notags(trim($_POST['logfile']))  : '');
                $debugging = ((x($_POST,'debugging')) ? true                             : false);
@@@ -2414,7 -2419,7 +2415,7 @@@ function admin_page_logs(App $a
                '$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' => get_form_security_token("admin_logs"),
+               '$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');",
@@@ -2485,7 -2490,7 +2486,7 @@@ function admin_page_viewlogs(App $a
   */
  function admin_page_features_post(App $a)
  {
-       check_form_security_token_redirectOnErr('/admin/features', 'admin_manage_features');
+       BaseModule::checkFormSecurityTokenRedirectOnError('/admin/features', 'admin_manage_features');
  
        logger('postvars: ' . print_r($_POST, true), LOGGER_DATA);
  
@@@ -2550,7 -2555,7 +2551,7 @@@ function admin_page_features(App $a
  
                $tpl = get_markup_template('admin/settings_features.tpl');
                $o = replace_macros($tpl, [
-                       '$form_security_token' => get_form_security_token("admin_manage_features"),
+                       '$form_security_token' => BaseModule::getFormSecurityToken("admin_manage_features"),
                        '$title' => L10n::t('Manage Additional Features'),
                        '$features' => $arr,
                        '$submit' => L10n::t('Save Settings'),
diff --combined mod/community.php
index 4b2169fd0651954a46c3ef3805a6d415aa18118e,01cf3ec70b0807580e8caa30fbe32e0da48e4151..0eaccc0db0306ead6ead5241690d2f37e524408c
@@@ -11,7 -11,6 +11,7 @@@ use Friendica\Core\L10n
  use Friendica\Core\PConfig;
  use Friendica\Database\DBA;
  use Friendica\Model\Contact;
 +use Friendica\Model\Item;
  
  function community_init(App $a)
  {
@@@ -91,7 -90,6 +91,6 @@@ function community_content(App $a, $upd
                }
        }
  
-       require_once 'include/security.php';
        require_once 'include/conversation.php';
  
        if (!$update) {
@@@ -228,12 -226,19 +227,12 @@@ function community_getitems($start, $it
                return DBA::toArray($r);
        } elseif ($content == 'global') {
                if (!is_null($accounttype)) {
 -                      $sql_accounttype = " AND `owner`.`contact-type` = ?";
 -                      $values = [$accounttype, $start, $itemspage];
 +                      $condition = ["`uid` = ? AND `owner`.`contact-type` = ?", 0, $accounttype];
                } else {
 -                      $sql_accounttype = "";
 -                      $values = [$start, $itemspage];
 +                      $condition = ['uid' => 0];
                }
  
 -              $r = DBA::p("SELECT `uri` FROM `thread`
 -                              INNER JOIN `item` ON `item`.`id` = `thread`.`iid`
 -                              INNER JOIN `contact` AS `author` ON `author`.`id`=`item`.`author-id`
 -                              INNER JOIN `contact` AS `owner` ON `owner`.`id`=`item`.`owner-id`
 -                              WHERE `thread`.`uid` = 0 AND NOT `author`.`hidden` AND NOT `author`.`blocked` $sql_accounttype
 -                              ORDER BY `thread`.`commented` DESC LIMIT ?, ?", $values);
 +              $r = Item::selectThreadForUser(0, ['uri'], $condition, ['order' => ['commented' => true], 'limit' => [$start, $itemspage]]);
                return DBA::toArray($r);
        }
  
diff --combined mod/invite.php
index 7318b77ae9f78c6e3318a3fad8ad32fabb12eb21,e73ef01edb48b1c6091c71b7c392a8ab6076ef32..7f479157f81afbf93d0a7463c7d0d9a4dbc99fd6
@@@ -7,6 -7,7 +7,7 @@@
   */
  
  use Friendica\App;
+ use Friendica\BaseModule;
  use Friendica\Core\Config;
  use Friendica\Core\L10n;
  use Friendica\Core\PConfig;
@@@ -14,6 -15,7 +15,7 @@@ use Friendica\Core\System
  use Friendica\Database\DBA;
  use Friendica\Protocol\Email;
  use Friendica\Util\DateTimeFormat;
+ use Friendica\Util\Security;
  
  function invite_post(App $a)
  {
@@@ -22,7 -24,7 +24,7 @@@
                return;
        }
  
-       check_form_security_token_redirectOnErr('/', 'send_invite');
+       BaseModule::checkFormSecurityTokenRedirectOnError('/', 'send_invite');
  
        $max_invites = intval(Config::get('system', 'max_invites'));
        if (! $max_invites) {
                }
  
                if ($invitation_only && ($invites_remaining || is_site_admin())) {
 -                      $code = autoname(8) . srand(1000, 9999);
 +                      $code = Friendica\Model\Register::createForInvitation();
                        $nmessage = str_replace('$invite_code', $code, $message);
  
 -                      $r = q("INSERT INTO `register` (`hash`,`created`) VALUES ('%s', '%s') ",
 -                              DBA::escape($code),
 -                              DBA::escape(DateTimeFormat::utcNow())
 -                      );
 -
                        if (! is_site_admin()) {
                                $invites_remaining --;
                                if ($invites_remaining >= 0) {
@@@ -139,7 -146,7 +141,7 @@@ function invite_content(App $a) 
        }
  
        $o = replace_macros($tpl, [
-               '$form_security_token' => get_form_security_token("send_invite"),
+               '$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"
diff --combined mod/item.php
index 4d798ac1e55fac55bbf0351ce873781f4450170c,dc93a9f798aef0d560c8e1b6953528c2c0882f43..5d4a23caa7a28802a4c9f82210c07c5f640e9aa7
@@@ -32,6 -32,7 +32,7 @@@ use Friendica\Protocol\Diaspora
  use Friendica\Protocol\Email;
  use Friendica\Util\DateTimeFormat;
  use Friendica\Util\Emailer;
+ use Friendica\Util\Security;
  
  require_once 'include/enotify.php';
  require_once 'include/text.php';
@@@ -42,8 -43,6 +43,6 @@@ function item_post(App $a) 
                return 0;
        }
  
-       require_once 'include/security.php';
        $uid = local_user();
  
        if (!empty($_REQUEST['dropitems'])) {
        $allow_comment = local_user() && ($profile_uid == 0) && $parent && in_array($parent_item['network'], [Protocol::ACTIVITYPUB, Protocol::OSTATUS, Protocol::DIASPORA, Protocol::DFRN]);
  
        // Now check that valid personal details have been provided
-       if (!can_write_wall($profile_uid) && !$allow_comment) {
+       if (!Security::canWriteToUserWall($profile_uid) && !$allow_comment) {
                notice(L10n::t('Permission denied.') . EOL) ;
  
                if (!empty($_REQUEST['return'])) {
@@@ -871,8 -870,6 +870,6 @@@ function item_content(App $a
                return;
        }
  
-       require_once 'include/security.php';
        $o = '';
  
        if (($a->argc == 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
@@@ -1015,7 -1012,11 +1012,7 @@@ function handle_tag(App $a, &$body, &$i
  
                        $profile = $contact["url"];
                        $alias   = $contact["alias"];
 -                      $newname = $contact["nick"];
 -
 -                      if (($newname == "") || !in_array($contact["network"], [Protocol::ACTIVITYPUB, Protocol::OSTATUS, Protocol::TWITTER, Protocol::STATUSNET])) {
 -                              $newname = $contact["name"];
 -                      }
 +                      $newname = defaults($contact, "name", $contact["nick"]);
                }
  
                //if there is an url for this persons profile
diff --combined mod/register.php
index 48fe67afc5a828f56b0e66ebccd6a89acba2765e,1720e0ff3a385df8a8c1b99bd3013a11be466697..41d39f4158204b09792e084f9c732d790bd3066a
@@@ -4,6 -4,7 +4,7 @@@
   */
  
  use Friendica\App;
+ use Friendica\BaseModule;
  use Friendica\Content\Text\BBCode;
  use Friendica\Core\Addon;
  use Friendica\Core\Config;
@@@ -11,14 -12,16 +12,14 @@@ use Friendica\Core\L10n
  use Friendica\Core\PConfig;
  use Friendica\Core\System;
  use Friendica\Core\Worker;
 -use Friendica\Database\DBA;
 -use Friendica\Model\User;
 +use Friendica\Model;
  use Friendica\Module\Tos;
 -use Friendica\Util\DateTimeFormat;
  
  require_once 'include/enotify.php';
  
  function register_post(App $a)
  {
-       check_form_security_token_redirectOnErr('/register', 'register');
+       BaseModule::checkFormSecurityTokenRedirectOnError('/register', 'register');
  
        $verified = 0;
        $blocked  = 1;
@@@ -65,7 -68,7 +66,7 @@@
        $arr['language'] = L10n::getBrowserLanguage();
  
        try {
 -              $result = User::create($arr);
 +              $result = Model\User::create($arr);
        } catch (Exception $e) {
                notice($e->getMessage());
                return;
@@@ -74,7 -77,7 +75,7 @@@
        $user = $result['user'];
  
        if ($netpublish && intval(Config::get('config', 'register_policy')) !== REGISTER_APPROVE) {
 -              $url = System::baseUrl() . '/profile/' . $user['nickname'];
 +              $url = $a->getBaseUrl() . '/profile/' . $user['nickname'];
                Worker::add(PRIORITY_LOW, "Directory", $url);
        }
  
  
        if (intval(Config::get('config', 'register_policy')) === REGISTER_OPEN) {
                if ($using_invites && $invite_id) {
 -                      q("delete * from register where hash = '%s' limit 1", DBA::escape($invite_id));
 +                      Model\Register::deleteByHash($invite_id);
                        PConfig::set($user['uid'], 'system', 'invites_remaining', $num_invites);
                }
  
                // Only send a password mail when the password wasn't manually provided
                if (!x($_POST, 'password1') || !x($_POST, 'confirm')) {
 -                      $res = User::sendRegisterOpenEmail(
 -                                      $user['email'], Config::get('config', 'sitename'), System::baseUrl(), $user['username'], $result['password'], $user);
 +                      $res = Model\User::sendRegisterOpenEmail(
 +                              $user,
 +                              Config::get('config', 'sitename'),
 +                              $a->getBaseUrl(),
 +                              $result['password']
 +                      );
  
                        if ($res) {
                                info(L10n::t('Registration successful. Please check your email for further instructions.') . EOL);
 -                              goaway(System::baseUrl());
 +                              goaway();
                        } else {
                                notice(
                                        L10n::t('Failed to send email message. Here your accout details:<br> login: %s<br> password: %s<br><br>You can change your password after login.',
                        }
                } else {
                        info(L10n::t('Registration successful.') . EOL);
 -                      goaway(System::baseUrl());
 +                      goaway();
                }
        } elseif (intval(Config::get('config', 'register_policy')) === REGISTER_APPROVE) {
                if (!strlen(Config::get('config', 'admin_email'))) {
                        notice(L10n::t('Your registration can not be processed.') . EOL);
 -                      goaway(System::baseUrl());
 +                      goaway();
                }
  
 -              $hash = random_string();
 -              $r = q("INSERT INTO `register` ( `hash`, `created`, `uid`, `password`, `language`, `note` ) VALUES ( '%s', '%s', %d, '%s', '%s', '%s' ) ",
 -                      DBA::escape($hash),
 -                      DBA::escape(DateTimeFormat::utcNow()),
 -                      intval($user['uid']),
 -                      DBA::escape($result['password']),
 -                      DBA::escape(Config::get('system', 'language')),
 -                      DBA::escape($_POST['permonlybox'])
 -              );
 +              Model\Register::createForApproval($user['uid'], Config::get('system', 'language'), $_POST['permonlybox']);
  
                // invite system
                if ($using_invites && $invite_id) {
 -                      q("DELETE * FROM `register` WHERE `hash` = '%s' LIMIT 1", DBA::escape($invite_id));
 +                      Model\Register::deleteByHash($invite_id);
                        PConfig::set($user['uid'], 'system', 'invites_remaining', $num_invites);
                }
  
                                'source_name'  => $user['username'],
                                'source_mail'  => $user['email'],
                                'source_nick'  => $user['nickname'],
 -                              'source_link'  => System::baseUrl() . "/admin/users/",
 -                              'link'         => System::baseUrl() . "/admin/users/",
 -                              'source_photo' => System::baseUrl() . "/photo/avatar/" . $user['uid'] . ".jpg",
 +                              'source_link'  => $a->getBaseUrl() . "/admin/users/",
 +                              'link'         => $a->getBaseUrl() . "/admin/users/",
 +                              'source_photo' => $a->getBaseUrl() . "/photo/avatar/" . $user['uid'] . ".jpg",
                                'to_email'     => $admin['email'],
                                'uid'          => $admin['uid'],
                                'language'     => $admin['language'] ? $admin['language'] : 'en',
                        ]);
                }
                // send notification to the user, that the registration is pending
 -              User::sendRegisterPendingEmail(
 -                      $user['email'], Config::get('config', 'sitename'), $user['username']);
 +              Model\User::sendRegisterPendingEmail(
 +                      $user,
 +                      Config::get('config', 'sitename'),
 +                      $a->getBaseURL(),
 +                      $result['password']
 +              );
  
                info(L10n::t('Your registration is pending approval by the site owner.') . EOL);
 -              goaway(System::baseUrl());
 +              goaway();
        }
  
        return;
@@@ -289,7 -292,7 +290,7 @@@ function register_content(App $a
                '$showprivstatement' => Config::get('system', 'tosprivstatement'),
                '$privstatement' => $tos->privacy_complete,
                '$baseurl'   => System::baseurl(),
-               '$form_security_token' => get_form_security_token("register"),
+               '$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 --combined src/Model/Item.php
index 5cda415c52d895fa1c663af2a820d4bc8cc933fb,dd513d0008fe129766ae08d2b93b671f1106e469..1c0b11db4aae80c6b3db9c5e2782b08940b96e46
@@@ -24,6 -24,7 +24,7 @@@ use Friendica\Protocol\Diaspora
  use Friendica\Protocol\OStatus;
  use Friendica\Util\DateTimeFormat;
  use Friendica\Util\XML;
+ use Friendica\Util\Security;
  use Text_LanguageDetect;
  
  require_once 'boot.php';
@@@ -80,7 -81,7 +81,7 @@@ class Item extends BaseObjec
        // All fields in the item table
        const ITEM_FIELDLIST = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
                        'contact-id', 'type', 'wall', 'gravity', 'extid', 'icid', 'iaid', 'psid',
 -                      'uri-hash', 'created', 'edited', 'commented', 'received', 'changed', 'verb',
 +                      'created', 'edited', 'commented', 'received', 'changed', 'verb',
                        'postopts', 'plink', 'resource-id', 'event-id', 'tag', 'attach', 'inform',
                        'file', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'post-type',
                        'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
                        $usermode = true;
                }
  
 -              $fields = self::fieldlist($selected, $usermode);
 +              $fields = self::fieldlist($usermode);
  
                $select_fields = self::constructSelectFields($fields, $selected);
  
                        $usermode = true;
                }
  
 -              $fields = self::fieldlist($selected, $usermode);
 +              $fields = self::fieldlist($usermode);
  
                $fields['thread'] = ['mention', 'ignored', 'iid'];
  
         *
         * @return array field list
         */
 -      private static function fieldlist($selected, $usermode)
 +      private static function fieldlist($usermode)
        {
                $fields = [];
  
                $fields['item'] = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
                        'contact-id', 'owner-id', 'author-id', 'type', 'wall', 'gravity', 'extid',
 -                      'created', 'edited', 'commented', 'received', 'changed', 'psid', 'uri-hash',
 +                      'created', 'edited', 'commented', 'received', 'changed', 'psid',
                        'resource-id', 'event-id', 'tag', 'attach', 'post-type', 'file',
                        'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
                        'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global',
                }
  
                if (strpos($sql_commands, "`item-activity`.") !== false) {
 -                      $joins .= " LEFT JOIN `item-activity` ON `item-activity`.`id` = `item`.`iaid`";
 +                      $joins .= " LEFT JOIN `item-activity` ON `item-activity`.`uri-id` = `item`.`uri-id`";
                }
  
                if (strpos($sql_commands, "`item-content`.") !== false) {
 -                      $joins .= " LEFT JOIN `item-content` ON `item-content`.`id` = `item`.`icid`";
 +                      $joins .= " LEFT JOIN `item-content` ON `item-content`.`uri-id` = `item`.`uri-id`";
                }
  
                if (strpos($sql_commands, "`item-delivery-data`.") !== false) {
                return $query;
        }
  
 -      /**
 -       * @brief Generate a server unique item hash for linking between the item tables
 -       *
 -       * @param string $uri     Item URI
 -       * @param date   $created Item creation date
 -       *
 -       * @return string the item hash
 -       */
 -      private static function itemHash($uri, $created)
 -      {
 -              return round(strtotime($created) / 100) . hash('ripemd128', $uri);
 -      }
 -
        /**
         * @brief Update existing item entries
         *
                // We cannot simply expand the condition to check for origin entries
                // The condition needn't to be a simple array but could be a complex condition.
                // And we have to execute this query before the update to ensure to fetch the same data.
 -              $items = DBA::select('item', ['id', 'origin', 'uri', 'created', 'uri-hash', 'iaid', 'icid', 'tag', 'file'], $condition);
 +              $items = DBA::select('item', ['id', 'origin', 'uri', 'uri-id', 'iaid', 'icid', 'tag', 'file'], $condition);
  
                $content_fields = [];
                foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
                $rows = DBA::affectedRows();
  
                while ($item = DBA::fetch($items)) {
 -
 -                      // This part here can safely be removed when the legacy fields in the item had been removed
 -                      if (empty($item['uri-hash']) && !empty($item['uri']) && !empty($item['created'])) {
 -
 -                              // Fetch the uri-hash from an existing item entry if there is one
 -                              $item_condition = ["`uri` = ? AND `uri-hash` != ''", $item['uri']];
 -                              $existing = DBA::selectfirst('item', ['uri-hash'], $item_condition);
 -                              if (DBA::isResult($existing)) {
 -                                      $item['uri-hash'] = $existing['uri-hash'];
 -                              } else {
 -                                      $item['uri-hash'] = self::itemHash($item['uri'], $item['created']);
 -                              }
 -
 -                              DBA::update('item', ['uri-hash' => $item['uri-hash']], ['id' => $item['id']]);
 -                              DBA::update('item-activity', ['uri-hash' => $item['uri-hash']], ["`uri` = ? AND `uri-hash` = ''", $item['uri']]);
 -                              DBA::update('item-content', ['uri-plink-hash' => $item['uri-hash']], ["`uri` = ? AND `uri-plink-hash` = ''", $item['uri']]);
 -                      }
 -
                        if (!empty($item['iaid']) || (!empty($content_fields['verb']) && (self::activityToIndex($content_fields['verb']) >= 0))) {
 -                              if (!empty($item['iaid'])) {
 -                                      $update_condition = ['id' => $item['iaid']];
 -                              } else {
 -                                      $update_condition = ['uri-hash' => $item['uri-hash']];
 -                              }
 -                              self::updateActivity($content_fields, $update_condition);
 +                              self::updateActivity($content_fields, ['uri-id' => $item['uri-id']]);
  
                                if (empty($item['iaid'])) {
 -                                      $item_activity = DBA::selectFirst('item-activity', ['id'], ['uri-hash' => $item['uri-hash']]);
 +                                      $item_activity = DBA::selectFirst('item-activity', ['id'], ['uri-id' => $item['uri-id']]);
                                        if (DBA::isResult($item_activity)) {
                                                $item_fields = ['iaid' => $item_activity['id'], 'icid' => null];
                                                foreach (self::MIXED_CONTENT_FIELDLIST as $field) {
                                        }
                                }
                        } else {
 -                              if (!empty($item['icid'])) {
 -                                      $update_condition = ['id' => $item['icid']];
 -                              } else {
 -                                      $update_condition = ['uri-plink-hash' => $item['uri-hash']];
 -                              }
 -                              self::updateContent($content_fields, $update_condition);
 +                              self::updateContent($content_fields, ['uri-id' => $item['uri-id']]);
  
                                if (empty($item['icid'])) {
 -                                      $item_content = DBA::selectFirst('item-content', [], ['uri-plink-hash' => $item['uri-hash']]);
 +                                      $item_content = DBA::selectFirst('item-content', [], ['uri-id' => $item['uri-id']]);
                                        if (DBA::isResult($item_content)) {
                                                $item_fields = ['icid' => $item_content['id']];
                                                // Clear all fields in the item table that have a content in the item-content table
                        }
                }
  
 -              // Ensure to always have the same creation date.
 -              $existing = self::selectfirst(['created', 'uri-hash'], ['uri' => $item['uri']]);
 -              if (DBA::isResult($existing)) {
 -                      $item['created'] = $existing['created'];
 -                      $item['uri-hash'] = $existing['uri-hash'];
 -              }
 -
                $item['wall']          = intval(defaults($item, 'wall', 0));
                $item['extid']         = trim(defaults($item, 'extid', ''));
                $item['author-name']   = trim(defaults($item, 'author-name', ''));
                $item['inform']        = trim(defaults($item, 'inform', ''));
                $item['file']          = trim(defaults($item, 'file', ''));
  
 -              // Unique identifier to be linked against item-activities and item-content
 -              $item['uri-hash']      = defaults($item, 'uri-hash', self::itemHash($item['uri'], $item['created']));
 -
                // When there is no content then we don't post it
                if ($item['body'].$item['title'] == '') {
                        logger('No body, no title.');
                        return false;
                }
  
 -              $fields = ['uri' => $item['uri'], 'activity' => $activity_index,
 -                      'uri-hash' => $item['uri-hash'], 'uri-id' => $item['uri-id']];
 +              $fields = ['activity' => $activity_index, 'uri-hash' => (string)$item['uri-id'], 'uri-id' => $item['uri-id']];
  
                // We just remove everything that is content
                foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
                }
  
                // Do we already have this content?
 -              $item_activity = DBA::selectFirst('item-activity', ['id'], ['uri-hash' => $item['uri-hash']]);
 +              $item_activity = DBA::selectFirst('item-activity', ['id'], ['uri-id' => $item['uri-id']]);
                if (DBA::isResult($item_activity)) {
                        $item['iaid'] = $item_activity['id'];
                        logger('Fetched activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
         */
        private static function insertContent(&$item)
        {
 -              $fields = ['uri' => $item['uri'], 'uri-plink-hash' => $item['uri-hash'],
 -                      'uri-id' => $item['uri-id']];
 +              $fields = ['uri-plink-hash' => (string)$item['uri-id'], 'uri-id' => $item['uri-id']];
  
                foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
                        if (isset($item[$field])) {
                }
  
                // Do we already have this content?
 -              $item_content = DBA::selectFirst('item-content', ['id'], ['uri-plink-hash' => $item['uri-hash']]);
 +              $item_content = DBA::selectFirst('item-content', ['id'], ['uri-id' => $item['uri-id']]);
                if (DBA::isResult($item_content)) {
                        $item['icid'] = $item_content['id'];
                        logger('Fetched content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
                        $uid = local_user();
                }
  
-               if (!can_write_wall($uid)) {
+               if (!Security::canWriteToUserWall($uid)) {
                        logger('like: unable to write on wall ' . $uid);
                        return false;
                }
                        }
                }
        }
+       public static function getPermissionsSQLByUserId($owner_id, $remote_verified = false, $groups = null)
+       {
+               $local_user = local_user();
+               $remote_user = remote_user();
+               /*
+                * Construct permissions
+                *
+                * default permissions - anonymous user
+                */
+               $sql = " AND NOT `item`.`private`";
+               // Profile owner - everything is visible
+               if ($local_user && ($local_user == $owner_id)) {
+                       $sql = '';
+               } elseif ($remote_user) {
+                       /*
+                        * Authenticated visitor. Unless pre-verified,
+                        * check that the contact belongs to this $owner_id
+                        * and load the groups the visitor belongs to.
+                        * If pre-verified, the caller is expected to have already
+                        * done this and passed the groups into this function.
+                        */
+                       $set = PermissionSet::get($owner_id, $remote_user, $groups);
+                       if (!empty($set)) {
+                               $sql_set = " OR (`item`.`private` IN (1,2) AND `item`.`wall` AND `item`.`psid` IN (" . implode(',', $set) . "))";
+                       } else {
+                               $sql_set = '';
+                       }
+                       $sql = " AND (NOT `item`.`private`" . $sql_set . ")";
+               }
+               return $sql;
+       }
  }