Browse Source

Merge branch 'develop' into rewrites/coding-convention-split2

pull/3254/head
Roland Häder 3 years ago
committed by GitHub
parent
commit
49527b70d3
93 changed files with 11658 additions and 33486 deletions
  1. +1
    -1
      INSTALL.txt
  2. +0
    -1
      boot.php
  3. +0
    -1
      doc/Install.md
  4. +0
    -7
      doc/Settings.md
  5. +1
    -2
      doc/de/Install.md
  6. +2
    -3
      htconfig.php
  7. +64
    -31
      include/Probe.php
  8. +9
    -5
      include/api.php
  9. +0
    -9
      include/bb2diaspora.php
  10. +41
    -222
      include/cron.php
  11. +247
    -1
      include/cronjobs.php
  12. +59
    -152
      include/crypto.php
  13. +29
    -8
      include/dfrn.php
  14. +48
    -31
      include/diaspora.php
  15. +35
    -8
      include/discover_poco.php
  16. +29
    -8
      include/html2bbcode.php
  17. +7
    -18
      include/oembed.php
  18. +10
    -8
      include/ostatus.php
  19. +205
    -195
      include/socgraph.php
  20. +1
    -18
      include/user.php
  21. +3
    -3
      library/defuse/php-encryption-1.2.1/Crypto.php
  22. +4
    -11
      library/markdown.php
  23. +0
    -728
      library/oauth.php
  24. +3
    -3
      library/php-markdown/License.md
  25. +5
    -5
      library/php-markdown/Michelf/Markdown.inc.php
  26. +882
    -2137
      library/php-markdown/Michelf/Markdown.php
  27. +5
    -5
      library/php-markdown/Michelf/MarkdownExtra.inc.php
  28. +1775
    -28
      library/php-markdown/Michelf/MarkdownExtra.php
  29. +5
    -5
      library/php-markdown/Michelf/MarkdownInterface.inc.php
  30. +32
    -28
      library/php-markdown/Michelf/MarkdownInterface.php
  31. +86
    -17
      library/php-markdown/Readme.md
  32. +7
    -7
      library/php-markdown/Readme.php
  33. +3
    -8
      library/php-markdown/composer.json
  34. +0
    -479
      library/phpsec/Crypt/AES.php
  35. +0
    -945
      library/phpsec/Crypt/DES.php
  36. +0
    -816
      library/phpsec/Crypt/Hash.php
  37. +0
    -493
      library/phpsec/Crypt/RC4.php
  38. +0
    -2119
      library/phpsec/Crypt/RSA.php
  39. +0
    -130
      library/phpsec/Crypt/Random.php
  40. +0
    -1242
      library/phpsec/Crypt/Rijndael.php
  41. +0
    -690
      library/phpsec/Crypt/TripleDES.php
  42. +0
    -3545
      library/phpsec/Math/BigInteger.php
  43. +0
    -1461
      library/phpsec/Net/SFTP.php
  44. +0
    -1160
      library/phpsec/Net/SSH1.php
  45. +0
    -2302
      library/phpsec/Net/SSH2.php
  46. +0
    -43
      library/phpsec/PHP/Compat/Function/array_fill.php
  47. +0
    -67
      library/phpsec/PHP/Compat/Function/bcpowmod.php
  48. +0
    -59
      library/phpsec/PHP/Compat/Function/str_split.php
  49. +0
    -135
      library/phpsec/crypt.html
  50. +0
    -43
      library/phpsec/docbook.css
  51. +0
    -5
      library/phpsec/index.html
  52. +0
    -20
      library/phpsec/intro.html
  53. +0
    -157
      library/phpsec/math.html
  54. +0
    -155
      library/phpsec/misc_crypt.html
  55. +0
    -153
      library/phpsec/net.html
  56. +0
    -118
      library/phpsec/sym_crypt.html
  57. +0
    -12
      library/spam/README
  58. +0
    -503
      library/spam/b8/b8.php
  59. +0
    -503
      library/spam/b8/b8.php.ORIG
  60. +0
    -127
      library/spam/b8/degenerator/degenerator_default.php
  61. +0
    -205
      library/spam/b8/lexer/lexer_default.php
  62. +0
    -396
      library/spam/b8/storage/storage_base.php
  63. +0
    -395
      library/spam/b8/storage/storage_base.php.ORIG
  64. +0
    -198
      library/spam/b8/storage/storage_dba.php
  65. +0
    -313
      library/spam/b8/storage/storage_frndc.php
  66. +0
    -351
      library/spam/b8/storage/storage_mysql.php
  67. +0
    -504
      library/spam/doc/COPYING
  68. +0
    -179
      library/spam/doc/ChangeLog
  69. +0
    -707
      library/spam/doc/readme.htm
  70. +0
    -371
      library/spam/doc/readme.rst
  71. +0
    -241
      library/spam/example/index.php
  72. +0
    -240
      library/spam/install/setup_berkeleydb.php
  73. +0
    -27
      library/spam/install/setup_mysql.sql
  74. +51
    -64
      mod/admin.php
  75. +23
    -28
      mod/babel.php
  76. +20
    -23
      mod/community.php
  77. +2
    -2
      mod/dfrn_confirm.php
  78. +2
    -10
      mod/dfrn_notify.php
  79. +3
    -3
      mod/dirfind.php
  80. +0
    -24
      mod/install.php
  81. +135
    -134
      mod/nodeinfo.php
  82. +6508
    -6568
      view/lang/es/messages.po
  83. +1205
    -1218
      view/lang/es/strings.php
  84. +11
    -13
      view/templates/admin_site.tpl
  85. +2
    -3
      view/templates/htconfig.tpl
  86. +12
    -0
      view/theme/frio/css/style.css
  87. +47
    -20
      view/theme/frio/js/filebrowser.js
  88. +4
    -2
      view/theme/frio/js/modal.js
  89. +2
    -8
      view/theme/frio/php/default.php
  90. +2
    -9
      view/theme/frio/php/standard.php
  91. +31
    -32
      view/theme/frio/templates/filebrowser.tpl
  92. +0
    -1
      view/theme/frost-mobile/templates/admin_site.tpl
  93. +0
    -1
      view/theme/frost/templates/admin_site.tpl

+ 1
- 1
INSTALL.txt View File

@ -37,7 +37,7 @@ local .htaccess file
- PHP *command line* access with register_argc_argv set to true in the
php.ini file [or see 'poormancron' in section 8]
- curl, gd (with at least jpeg support), mysql, mbstring, mcrypt, and openssl extensions
- curl, gd (with at least jpeg support), mysql, mbstring and openssl extensions
- some form of email server or email gateway such that PHP mail() works


+ 0
- 1
boot.php View File

@ -649,7 +649,6 @@ class App {
set_include_path(
'include' . PATH_SEPARATOR
. 'library' . PATH_SEPARATOR
. 'library/phpsec' . PATH_SEPARATOR
. 'library/langdet' . PATH_SEPARATOR
. '.' );


+ 0
- 1
doc/Install.md View File

@ -30,7 +30,6 @@ Requirements
* PHP *command line* access with register_argc_argv set to true in the php.ini file
* curl, gd, mysql, hash and openssl extensions
* some form of email server or email gateway such that PHP mail() works
* mcrypt (optional; used for server-to-server message encryption)
* Mysql 5.5.3+ or an equivalant alternative for MySQL (MariaDB, Percona Server etc.)
* the ability to schedule jobs with cron (Linux/Mac) or Scheduled Tasks (Windows) (Note: other options are presented in Section 7 of this document.)
* Installation into a top-level domain or sub-domain (without a directory/path component in the URL) is preferred. Directory paths will not be as convenient to use and have not been thoroughly tested.


+ 0
- 7
doc/Settings.md View File

@ -152,13 +152,6 @@ Value is in seconds.
Default is 60 seconds.
Set to 0 for unlimited (not recommended).
#### UTF-8 Regular Expressions
During registrations, full names are checked using UTF-8 regular expressions.
This requires PHP to have been compiled with a special setting to allow UTF-8 expressions.
If you are completely unable to register accounts, set no_utf to true.
The default is set to false (meaning UTF8 regular expressions are supported and working).
#### Verify SSL Certitificates
By default Friendica allows SSL communication between websites that have "self-signed" SSL certificates.


+ 1
- 2
doc/de/Install.md View File

@ -26,7 +26,6 @@ Wir planen, diese Einschränkung in einer zukünftigen Version zu beheben.
- PHP *Kommandozeilen*-Zugang mit register_argc_argv auf "true" gesetzt in der php.ini-Datei
- curl, gd, mysql und openssl-Erweiterung
- etwas in der Art eines Email-Servers oder eines Gateways wie PHP mail()
- mcrypt (optional; wird für die Server-zu-Server Nachrichtenentschlüsselung benötigt)
- Mysql 5.x
- die Möglichkeit, wiederkehrende Aufgaben mit cron (Linux/Mac) oder "Scheduled Tasks" einzustellen (Windows) [Beachte: andere Optionen sind in Abschnitt 7 dieser Dokumentation zu finden]
- Installation in einer Top-Level-Domain oder Subdomain (ohne eine Verzeichnis/Pfad-Komponente in der URL) wird bevorzugt. Verzeichnispfade sind für diesen Zweck nicht so günstig und wurden auch nicht ausführlich getestet.
@ -37,7 +36,7 @@ Wir planen, diese Einschränkung in einer zukünftigen Version zu beheben.
1.1. APT-Pakete
- Apache: sudo apt-get install apache2
- PHP5: sudo apt-get install php5
- PHP5-Zusätzliche Pakete: sudo apt-get install php5-curl php5-gd php5-mysql php5-mcrypt
- PHP5-Zusätzliche Pakete: sudo apt-get install php5-curl php5-gd php5-mysql
- MySQL: sudo apt-get install mysql-server
2. Entpacke die Friendica-Daten in das Quellverzeichnis (root) des Dokumentenbereichs deines Webservers.


+ 2
- 3
htconfig.php View File

@ -65,9 +65,8 @@ $a->config['php_path'] = 'php';
$a->config['system']['huburl'] = '[internal]';
// Server-to-server private message encryption (RINO) is allowed by default.
// Encryption will only be provided if this setting is set to a non zero
// value and the PHP mcrypt extension is installed on both systems
// set to 0 to disable, 2 to enable, 1 is deprecated but wont need mcrypt
// Encryption will only be provided if this setting is set to a non zero value
// set to 0 to disable, 2 to enable, 1 is deprecated
$a->config['system']['rino_encrypt'] = 2;


+ 64
- 31
include/Probe.php View File

@ -18,6 +18,8 @@ require_once('include/network.php');
*/
class Probe {
private static $baseurl;
/**
* @brief Rearrange the array so that it always has the same order
*
@ -54,6 +56,9 @@ class Probe {
*/
private function xrd($host) {
// Reset the static variable
self::$baseurl = '';
$ssl_url = "https://".$host."/.well-known/host-meta";
$url = "http://".$host."/.well-known/host-meta";
@ -102,6 +107,9 @@ class Probe {
elseif ($attributes["rel"] == "lrdd")
$xrd_data["lrdd"] = $attributes["template"];
}
self::$baseurl = "http://".$host;
return $xrd_data;
}
@ -169,6 +177,8 @@ class Probe {
$path_parts = explode("/", trim($parts["path"], "/"));
$nick = array_pop($path_parts);
do {
$lrdd = self::xrd($host);
$host .= "/".array_shift($path_parts);
@ -192,6 +202,19 @@ class Probe {
$path = str_replace('{uri}', urlencode("acct:".$uri), $link);
$webfinger = self::webfinger($path);
}
// Special treatment for Mastodon
// Problem is that Mastodon uses an URL format like http://domain.tld/@nick
// But the webfinger for this format fails.
if (!$webfinger AND isset($nick)) {
// Mastodon uses a "@" as prefix for usernames in their url format
$nick = ltrim($nick, '@');
$addr = $nick."@".$host;
$path = str_replace('{uri}', urlencode("acct:".$addr), $link);
$webfinger = self::webfinger($path);
}
}
if (!is_array($webfinger["links"]))
@ -258,8 +281,13 @@ class Probe {
$data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
}
if (!isset($data["network"]))
if (self::$baseurl != "") {
$data["baseurl"] = self::$baseurl;
}
if (!isset($data["network"])) {
$data["network"] = NETWORK_PHANTOM;
}
$data = self::rearrange_data($data);
@ -286,6 +314,7 @@ class Probe {
dbesc(normalise_link($data['url']))
);
}
return $data;
}
@ -301,7 +330,34 @@ class Probe {
* @return array uri data
*/
private function detect($uri, $network, $uid) {
if (strstr($uri, '@')) {
$parts = parse_url($uri);
if (isset($parts["scheme"]) AND isset($parts["host"]) AND isset($parts["path"])) {
/// @todo: Ports?
$host = $parts["host"];
if ($host == 'twitter.com') {
return array("network" => NETWORK_TWITTER);
}
$lrdd = self::xrd($host);
$path_parts = explode("/", trim($parts["path"], "/"));
while (!$lrdd AND (sizeof($path_parts) > 1)) {
$host .= "/".array_shift($path_parts);
$lrdd = self::xrd($host);
}
if (!$lrdd) {
return self::feed($uri);
}
$nick = array_pop($path_parts);
// Mastodon uses a "@" as prefix for usernames in their url format
$nick = ltrim($nick, '@');
$addr = $nick."@".$host;
} elseif (strstr($uri, '@')) {
// If the URI starts with "mailto:" then jump directly to the mail detection
if (strpos($url,'mailto:') !== false) {
$uri = str_replace('mailto:', '', $url);
@ -317,42 +373,19 @@ class Probe {
$host = substr($uri,strpos($uri, '@') + 1);
$nick = substr($uri,0, strpos($uri, '@'));
if (strpos($uri, '@twitter.com'))
if (strpos($uri, '@twitter.com')) {
return array("network" => NETWORK_TWITTER);
}
$lrdd = self::xrd($host);
if (!$lrdd)
if (!$lrdd) {
return self::mail($uri, $uid);
}
$addr = $uri;
} else {
$parts = parse_url($uri);
if (!isset($parts["scheme"]) OR
!isset($parts["host"]) OR
!isset($parts["path"]))
return false;
/// @todo: Ports?
$host = $parts["host"];
if ($host == 'twitter.com')
return array("network" => NETWORK_TWITTER);
$lrdd = self::xrd($host);
$path_parts = explode("/", trim($parts["path"], "/"));
while (!$lrdd AND (sizeof($path_parts) > 1)) {
$host .= "/".array_shift($path_parts);
$lrdd = self::xrd($host);
}
if (!$lrdd)
return self::feed($uri);
$nick = array_pop($path_parts);
$addr = $nick."@".$host;
return false;
}
$webfinger = false;
/// @todo Do we need the prefix "acct:" or "acct://"?


+ 9
- 5
include/api.php View File

@ -352,6 +352,7 @@ use \Friendica\Core\Config;
}
}
}
logger('API call not implemented: '.$a->query_string);
throw new NotImplementedException();
} catch (HTTPException $e) {
header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
@ -2720,6 +2721,7 @@ use \Friendica\Core\Config;
return api_format_data('config', $type, array('config' => $config));
}
api_register_func('api/gnusocial/config','api_statusnet_config',false);
api_register_func('api/statusnet/config','api_statusnet_config',false);
function api_statusnet_version($type) {
@ -2728,6 +2730,7 @@ use \Friendica\Core\Config;
return api_format_data('version', $type, array('version' => $fake_statusnet_version));
}
api_register_func('api/gnusocial/version','api_statusnet_version',false);
api_register_func('api/statusnet/version','api_statusnet_version',false);
/**
@ -3963,7 +3966,7 @@ use \Friendica\Core\Config;
$multi_profiles = feature_enabled(api_user(),'multi_profiles');
$directory = get_config('system', 'directory');
// get data of the specified profile id or all profiles of the user if not specified
// get data of the specified profile id or all profiles of the user if not specified
if ($profileid != 0) {
$r = q("SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
intval(api_user()),
@ -3971,11 +3974,10 @@ use \Friendica\Core\Config;
// error message if specified gid is not in database
if (!dbm::is_result($r))
throw new BadRequestException("profile_id not available");
}
else
} else {
$r = q("SELECT * FROM `profile` WHERE `uid` = %d",
intval(api_user()));
}
// loop through all returned profiles and retrieve data and users
$k = 0;
foreach ($r as $rr) {
@ -4002,9 +4004,11 @@ use \Friendica\Core\Config;
}
// return settings, authenticated user and profiles data
$self = q("SELECT `nurl` FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
$result = array('multi_profiles' => $multi_profiles ? true : false,
'global_dir' => $directory,
'friendica_owner' => api_get_user($a, intval(api_user())),
'friendica_owner' => api_get_user($a, $self[0]['nurl']),
'profiles' => $profiles);
return api_format_data("friendica_profiles", $type, array('$result' => $result));
}


+ 0
- 9
include/bb2diaspora.php View File

@ -59,15 +59,6 @@ function diaspora2bb($s) {
$s = str_replace('#', '#', $s);
$search = array(" \n", "\n ");
$replace = array("\n", "\n");
do {
$oldtext = $s;
$s = str_replace($search, $replace, $s);
} while ($oldtext != $s);
$s = str_replace("\n\n", '<br>', $s);
$s = html2bbcode($s);
// protect the recycle symbol from turning into a tag, but without unescaping angles and naked ampersands


+ 41
- 222
include/cron.php View File

@ -1,28 +1,24 @@
<?php
use \Friendica\Core\Config;
require_once('include/photos.php');
require_once('include/user.php');
function cron_run(&$argv, &$argc){
global $a;
require_once('include/session.php');
require_once('include/datetime.php');
require_once('include/items.php');
require_once('include/Contact.php');
require_once('include/email.php');
require_once('include/socgraph.php');
require_once('mod/nodeinfo.php');
require_once('include/post_update.php');
// Poll contacts with specific parameters
if ($argc > 1) {
cron_poll_contacts($argc, $argv);
return;
}
$last = get_config('system','last_cron');
$poll_interval = intval(get_config('system','cron_interval'));
if(! $poll_interval)
if (! $poll_interval) {
$poll_interval = 10;
if($last) {
}
if ($last) {
$next = $last + ($poll_interval * 60);
if($next > time()) {
logger('cron intervall not reached');
@ -33,19 +29,16 @@ function cron_run(&$argv, &$argc){
logger('cron: start');
// run queue delivery process in the background
proc_run(PRIORITY_NEGLIGIBLE, "include/queue.php");
// run the process to discover global contacts in the background
proc_run(PRIORITY_LOW, "include/discover_poco.php");
// run the process to update locally stored global contacts in the background
proc_run(PRIORITY_LOW, "include/discover_poco.php", "checkcontact");
// Expire and remove user entries
cron_expire_and_remove_users();
proc_run(PRIORITY_MEDIUM, "include/cronjobs.php", "expire_and_remove_users");
// Check OStatus conversations
proc_run(PRIORITY_MEDIUM, "include/cronjobs.php", "ostatus_mentions");
@ -59,14 +52,22 @@ function cron_run(&$argv, &$argc){
// update nodeinfo data
proc_run(PRIORITY_LOW, "include/cronjobs.php", "nodeinfo");
// once daily run birthday_updates and then expire in background
// Clear cache entries
proc_run(PRIORITY_LOW, "include/cronjobs.php", "clear_cache");
// Repair missing Diaspora values in contacts
proc_run(PRIORITY_LOW, "include/cronjobs.php", "repair_diaspora");
// Repair entries in the database
proc_run(PRIORITY_LOW, "include/cronjobs.php", "repair_database");
// once daily run birthday_updates and then expire in background
$d1 = get_config('system','last_expire_day');
$d2 = intval(datetime_convert('UTC','UTC','now','d'));
if($d2 != intval($d1)) {
update_contact_birthdays();
proc_run(PRIORITY_LOW, "include/cronjobs.php", "update_contact_birthdays");
proc_run(PRIORITY_LOW, "include/discover_poco.php", "update_server");
@ -78,18 +79,9 @@ function cron_run(&$argv, &$argc){
proc_run(PRIORITY_MEDIUM, 'include/dbclean.php');
cron_update_photo_albums();
proc_run(PRIORITY_LOW, "include/cronjobs.php", "update_photo_albums");
}
// Clear cache entries
cron_clear_cache($a);
// Repair missing Diaspora values in contacts
cron_repair_diaspora($a);
// Repair entries in the database
cron_repair_database();
// Poll contacts
cron_poll_contacts($argc, $argv);
@ -100,39 +92,6 @@ function cron_run(&$argv, &$argc){
return;
}
/**
* @brief Update the cached values for the number of photo albums per user
*/
function cron_update_photo_albums() {
$r = q("SELECT `uid` FROM `user` WHERE NOT `account_expired` AND NOT `account_removed`");
if (!dbm::is_result($r)) {
return;
}
foreach ($r AS $user) {
photo_albums($user['uid'], true);
}
}
/**
* @brief Expire and remove user entries
*/
function cron_expire_and_remove_users() {
// expire any expired accounts
q("UPDATE user SET `account_expired` = 1 where `account_expired` = 0
AND `account_expires_on` > '%s'
AND `account_expires_on` < UTC_TIMESTAMP()", dbesc(NULL_DATE));
// delete user and contact records for recently removed accounts
$r = q("SELECT * FROM `user` WHERE `account_removed` AND `account_expires_on` < UTC_TIMESTAMP() - INTERVAL 3 DAY");
if ($r) {
foreach($r as $user) {
q("DELETE FROM `contact` WHERE `uid` = %d", intval($user['uid']));
q("DELETE FROM `user` WHERE `uid` = %d", intval($user['uid']));
}
}
}
/**
* @brief Poll contacts for unreceived messages
*
@ -145,14 +104,15 @@ function cron_poll_contacts($argc, $argv) {
$force = false;
$restart = false;
if (($argc > 1) && ($argv[1] == 'force'))
if (($argc > 1) && ($argv[1] == 'force')) {
$force = true;
}
if (($argc > 1) && ($argv[1] == 'restart')) {
$restart = true;
$generation = intval($argv[2]);
if (!$generation)
if (!$generation) {
killme();
}
}
if (($argc > 1) && intval($argv[1])) {
@ -171,9 +131,9 @@ function cron_poll_contacts($argc, $argv) {
// we are unable to match those posts with a Diaspora GUID and prevent duplicates.
$abandon_days = intval(get_config('system','account_abandon_days'));
if($abandon_days < 1)
if ($abandon_days < 1) {
$abandon_days = 0;
}
$abandon_sql = (($abandon_days)
? sprintf(" AND `user`.`login_date` > UTC_TIMESTAMP() - INTERVAL %d DAY ", intval($abandon_days))
: ''
@ -244,185 +204,44 @@ function cron_poll_contacts($argc, $argv) {
switch ($contact['priority']) {
case 5:
if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 month"))
if (datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 month")) {
$update = true;
}
break;
case 4:
if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 week"))
if (datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 week")) {
$update = true;
}
break;
case 3:
if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 day"))
if (datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 day")) {
$update = true;
}
break;
case 2:
if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 12 hour"))
if (datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 12 hour")) {
$update = true;
}
break;
case 1:
default:
if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 hour"))
if (datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 hour")) {
$update = true;
}
break;
}
if (!$update)
if (!$update) {
continue;
}
}
logger("Polling ".$contact["network"]." ".$contact["id"]." ".$contact["nick"]." ".$contact["name"]);
if (($contact['network'] == NETWORK_FEED) AND ($contact['priority'] <= 3)) {
proc_run(PRIORITY_MEDIUM, 'include/onepoll.php', $contact['id']);
proc_run(PRIORITY_MEDIUM, 'include/onepoll.php', intval($contact['id']));
} else {
proc_run(PRIORITY_LOW, 'include/onepoll.php', $contact['id']);
proc_run(PRIORITY_LOW, 'include/onepoll.php', intval($contact['id']));
}
}
}
}
/**
* @brief Clear cache entries
*
* @param App $a
*/
function cron_clear_cache(App $a) {
$last = get_config('system','cache_last_cleared');
if($last) {
$next = $last + (3600); // Once per hour
$clear_cache = ($next <= time());
} else
$clear_cache = true;
if (!$clear_cache)
return;
// clear old cache
Cache::clear();
// clear old item cache files
clear_cache();
// clear cache for photos
clear_cache($a->get_basepath(), $a->get_basepath()."/photo");
// clear smarty cache
clear_cache($a->get_basepath()."/view/smarty3/compiled", $a->get_basepath()."/view/smarty3/compiled");
// clear cache for image proxy
if (!get_config("system", "proxy_disabled")) {
clear_cache($a->get_basepath(), $a->get_basepath()."/proxy");
$cachetime = get_config('system','proxy_cache_time');
if (!$cachetime) $cachetime = PROXY_DEFAULT_TIME;
q('DELETE FROM `photo` WHERE `uid` = 0 AND `resource-id` LIKE "pic:%%" AND `created` < NOW() - INTERVAL %d SECOND', $cachetime);
}
// Delete the cached OEmbed entries that are older than one year
q("DELETE FROM `oembed` WHERE `created` < NOW() - INTERVAL 3 MONTH");
// Delete the cached "parse_url" entries that are older than one year
q("DELETE FROM `parsed_url` WHERE `created` < NOW() - INTERVAL 3 MONTH");
// Maximum table size in megabyte
$max_tablesize = intval(get_config('system','optimize_max_tablesize')) * 1000000;
if ($max_tablesize == 0)
$max_tablesize = 100 * 1000000; // Default are 100 MB
if ($max_tablesize > 0) {
// Minimum fragmentation level in percent
$fragmentation_level = intval(get_config('system','optimize_fragmentation')) / 100;
if ($fragmentation_level == 0)
$fragmentation_level = 0.3; // Default value is 30%
// Optimize some tables that need to be optimized
$r = q("SHOW TABLE STATUS");
foreach($r as $table) {
// Don't optimize tables that are too large
if ($table["Data_length"] > $max_tablesize)
continue;
// Don't optimize empty tables
if ($table["Data_length"] == 0)
continue;
// Calculate fragmentation
$fragmentation = $table["Data_free"] / ($table["Data_length"] + $table["Index_length"]);
logger("Table ".$table["Name"]." - Fragmentation level: ".round($fragmentation * 100, 2), LOGGER_DEBUG);
// Don't optimize tables that needn't to be optimized
if ($fragmentation < $fragmentation_level)
continue;
// So optimize it
logger("Optimize Table ".$table["Name"], LOGGER_DEBUG);
q("OPTIMIZE TABLE `%s`", dbesc($table["Name"]));
}
}
set_config('system','cache_last_cleared', time());
}
/**
* @brief Repair missing values in Diaspora contacts
*
* @param App $a
*/
function cron_repair_diaspora(App $a) {
$r = q("SELECT `id`, `url` FROM `contact`
WHERE `network` = '%s' AND (`batch` = '' OR `notify` = '' OR `poll` = '' OR pubkey = '')
ORDER BY RAND() LIMIT 50", dbesc(NETWORK_DIASPORA));
if (dbm::is_result($r)) {
foreach ($r AS $contact) {
if (poco_reachable($contact["url"])) {
$data = probe_url($contact["url"]);
if ($data["network"] == NETWORK_DIASPORA) {
logger("Repair contact ".$contact["id"]." ".$contact["url"], LOGGER_DEBUG);
q("UPDATE `contact` SET `batch` = '%s', `notify` = '%s', `poll` = '%s', pubkey = '%s' WHERE `id` = %d",
dbesc($data["batch"]), dbesc($data["notify"]), dbesc($data["poll"]), dbesc($data["pubkey"]),
intval($contact["id"]));
}
}
}
}
}
/**
* @brief Do some repairs in database entries
*
*/
function cron_repair_database() {
// Sometimes there seem to be issues where the "self" contact vanishes.
// We haven't found the origin of the problem by now.
$r = q("SELECT `uid` FROM `user` WHERE NOT EXISTS (SELECT `uid` FROM `contact` WHERE `contact`.`uid` = `user`.`uid` AND `contact`.`self`)");
if (dbm::is_result($r)) {
foreach ($r AS $user) {
logger('Create missing self contact for user '.$user['uid']);
user_create_self_contact($user['uid']);
}
}
// Set the parent if it wasn't set. (Shouldn't happen - but does sometimes)
// This call is very "cheap" so we can do it at any time without a problem
q("UPDATE `item` INNER JOIN `item` AS `parent` ON `parent`.`uri` = `item`.`parent-uri` AND `parent`.`uid` = `item`.`uid` SET `item`.`parent` = `parent`.`id` WHERE `item`.`parent` = 0");
// There was an issue where the nick vanishes from the contact table
q("UPDATE `contact` INNER JOIN `user` ON `contact`.`uid` = `user`.`uid` SET `nick` = `nickname` WHERE `self` AND `nick`=''");
// Update the global contacts for local users
$r = q("SELECT `uid` FROM `user` WHERE `verified` AND NOT `blocked` AND NOT `account_removed` AND NOT `account_expired`");
if (dbm::is_result($r))
foreach ($r AS $user)
update_gcontact_for_user($user["uid"]);
/// @todo
/// - remove thread entries without item
/// - remove sign entries without item
/// - remove children when parent got lost
/// - set contact-id in item when not present
}

+ 247
- 1
include/cronjobs.php View File

@ -8,10 +8,17 @@ function cronjobs_run(&$argv, &$argc){
require_once('include/ostatus.php');
require_once('include/post_update.php');
require_once('mod/nodeinfo.php');
require_once('include/photos.php');
require_once('include/user.php');
require_once('include/socgraph.php');
require_once('include/Probe.php');
// No parameter set? So return
if ($argc <= 1)
if ($argc <= 1) {
return;
}
logger("Starting cronjob ".$argv[1], LOGGER_DEBUG);
// Check OStatus conversations
// Check only conversations with mentions (for a longer time)
@ -39,5 +46,244 @@ function cronjobs_run(&$argv, &$argc){
return;
}
// Expire and remove user entries
if ($argv[1] == 'expire_and_remove_users') {
cron_expire_and_remove_users();
return;
}
if ($argv[1] == 'update_contact_birthdays') {
update_contact_birthdays();
return;
}
if ($argv[1] == 'update_photo_albums') {
cron_update_photo_albums();
return;
}
// Clear cache entries
if ($argv[1] == 'clear_cache') {
cron_clear_cache($a);
return;
}
// Repair missing Diaspora values in contacts
if ($argv[1] == 'repair_diaspora') {
cron_repair_diaspora($a);
return;
}
// Repair entries in the database
if ($argv[1] == 'repair_database') {
cron_repair_database();
return;
}
logger("Xronjob ".$argv[1]." is unknown.", LOGGER_DEBUG);
return;
}
/**
* @brief Update the cached values for the number of photo albums per user
*/
function cron_update_photo_albums() {
$r = q("SELECT `uid` FROM `user` WHERE NOT `account_expired` AND NOT `account_removed`");
if (!dbm::is_result($r)) {
return;
}
foreach ($r AS $user) {
photo_albums($user['uid'], true);
}
}
/**
* @brief Expire and remove user entries
*/
function cron_expire_and_remove_users() {
// expire any expired accounts
q("UPDATE user SET `account_expired` = 1 where `account_expired` = 0
AND `account_expires_on` > '%s'
AND `account_expires_on` < UTC_TIMESTAMP()", dbesc(NULL_DATE));
// delete user and contact records for recently removed accounts
$r = q("SELECT * FROM `user` WHERE `account_removed` AND `account_expires_on` < UTC_TIMESTAMP() - INTERVAL 3 DAY");
if (dbm::is_result($r)) {
foreach ($r as $user) {
q("DELETE FROM `contact` WHERE `uid` = %d", intval($user['uid']));
q("DELETE FROM `user` WHERE `uid` = %d", intval($user['uid']));
}
}
}
/**
* @brief Clear cache entries
*
* @param App $a
*/
function cron_clear_cache(App $a) {
$last = get_config('system','cache_last_cleared');
if ($last) {
$next = $last + (3600); // Once per hour
$clear_cache = ($next <= time());
} else {
$clear_cache = true;
}
if (!$clear_cache) {
return;
}
// clear old cache
Cache::clear();
// clear old item cache files
clear_cache();
// clear cache for photos
clear_cache($a->get_basepath(), $a->get_basepath()."/photo");
// clear smarty cache
clear_cache($a->get_basepath()."/view/smarty3/compiled", $a->get_basepath()."/view/smarty3/compiled");
// clear cache for image proxy
if (!get_config("system", "proxy_disabled")) {
clear_cache($a->get_basepath(), $a->get_basepath()."/proxy");
$cachetime = get_config('system','proxy_cache_time');
if (!$cachetime) {
$cachetime = PROXY_DEFAULT_TIME;
}
q('DELETE FROM `photo` WHERE `uid` = 0 AND `resource-id` LIKE "pic:%%" AND `created` < NOW() - INTERVAL %d SECOND', $cachetime);
}
// Delete the cached OEmbed entries that are older than one year
q("DELETE FROM `oembed` WHERE `created` < NOW() - INTERVAL 3 MONTH");
// Delete the cached "parse_url" entries that are older than one year
q("DELETE FROM `parsed_url` WHERE `created` < NOW() - INTERVAL 3 MONTH");
// Maximum table size in megabyte
$max_tablesize = intval(get_config('system','optimize_max_tablesize')) * 1000000;
if ($max_tablesize == 0) {
$max_tablesize = 100 * 1000000; // Default are 100 MB
}
if ($max_tablesize > 0) {
// Minimum fragmentation level in percent
$fragmentation_level = intval(get_config('system','optimize_fragmentation')) / 100;
if ($fragmentation_level == 0) {
$fragmentation_level = 0.3; // Default value is 30%
}
// Optimize some tables that need to be optimized
$r = q("SHOW TABLE STATUS");
foreach ($r as $table) {
// Don't optimize tables that are too large
if ($table["Data_length"] > $max_tablesize) {
continue;
}
// Don't optimize empty tables
if ($table["Data_length"] == 0) {
continue;
}
// Calculate fragmentation
$fragmentation = $table["Data_free"] / ($table["Data_length"] + $table["Index_length"]);
logger("Table ".$table["Name"]." - Fragmentation level: ".round($fragmentation * 100, 2), LOGGER_DEBUG);
// Don't optimize tables that needn't to be optimized
if ($fragmentation < $fragmentation_level) {
continue;
}
// So optimize it
logger("Optimize Table ".$table["Name"], LOGGER_DEBUG);
q("OPTIMIZE TABLE `%s`", dbesc($table["Name"]));
}
}
set_config('system','cache_last_cleared', time());
}
/**
* @brief Repair missing values in Diaspora contacts
*
* @param App $a
*/
function cron_repair_diaspora(App $a) {
$starttime = time();
$r = q("SELECT `id`, `url` FROM `contact`
WHERE `network` = '%s' AND (`batch` = '' OR `notify` = '' OR `poll` = '' OR pubkey = '')
ORDER BY RAND() LIMIT 50", dbesc(NETWORK_DIASPORA));
if (!dbm::is_result($r)) {
return;
}
foreach ($r AS $contact) {
// Quit the loop after 3 minutes
if (time() > ($starttime + 180)) {
return;
}
if (!poco_reachable($contact["url"])) {
continue;
}
$data = Probe::uri($contact["url"]);
if ($data["network"] != NETWORK_DIASPORA) {
continue;
}
logger("Repair contact ".$contact["id"]." ".$contact["url"], LOGGER_DEBUG);
q("UPDATE `contact` SET `batch` = '%s', `notify` = '%s', `poll` = '%s', pubkey = '%s' WHERE `id` = %d",
dbesc($data["batch"]), dbesc($data["notify"]), dbesc($data["poll"]), dbesc($data["pubkey"]),
intval($contact["id"]));
}
}
/**
* @brief Do some repairs in database entries
*
*/
function cron_repair_database() {
// Sometimes there seem to be issues where the "self" contact vanishes.
// We haven't found the origin of the problem by now.
$r = q("SELECT `uid` FROM `user` WHERE NOT EXISTS (SELECT `uid` FROM `contact` WHERE `contact`.`uid` = `user`.`uid` AND `contact`.`self`)");
if (dbm::is_result($r)) {
foreach ($r AS $user) {
logger('Create missing self contact for user '.$user['uid']);
user_create_self_contact($user['uid']);
}
}
// Set the parent if it wasn't set. (Shouldn't happen - but does sometimes)
// This call is very "cheap" so we can do it at any time without a problem
q("UPDATE `item` INNER JOIN `item` AS `parent` ON `parent`.`uri` = `item`.`parent-uri` AND `parent`.`uid` = `item`.`uid` SET `item`.`parent` = `parent`.`id` WHERE `item`.`parent` = 0");
// There was an issue where the nick vanishes from the contact table
q("UPDATE `contact` INNER JOIN `user` ON `contact`.`uid` = `user`.`uid` SET `nick` = `nickname` WHERE `self` AND `nick`=''");
// Update the global contacts for local users
$r = q("SELECT `uid` FROM `user` WHERE `verified` AND NOT `blocked` AND NOT `account_removed` AND NOT `account_expired`");
if (dbm::is_result($r)) {
foreach ($r AS $user) {
update_gcontact_for_user($user["uid"]);
}
}
/// @todo
/// - remove thread entries without item
/// - remove sign entries without item
/// - remove children when parent got lost
/// - set contact-id in item when not present
}

+ 59
- 152
include/crypto.php View File

@ -1,94 +1,52 @@
<?php
require_once('library/ASNValue.class.php');
require_once('library/asn1.php');
require_once 'library/ASNValue.class.php';
require_once 'library/asn1.php';
// supported algorithms are 'sha256', 'sha1'
function rsa_sign($data,$key,$alg = 'sha256') {
$sig = '';
if (version_compare(PHP_VERSION, '5.3.0', '>=') || $alg === 'sha1') {
openssl_sign($data,$sig,$key,(($alg == 'sha1') ? OPENSSL_ALGO_SHA1 : $alg));
}
else {
if(strlen($key) < 1024 || extension_loaded('gmp')) {
require_once('library/phpsec/Crypt/RSA.php');
$rsa = new CRYPT_RSA();
$rsa->signatureMode = CRYPT_RSA_SIGNATURE_PKCS1;
$rsa->setHash($alg);
$rsa->loadKey($key);
$sig = $rsa->sign($data);
}
else {
logger('rsa_sign: insecure algorithm used. Please upgrade PHP to 5.3');
openssl_private_encrypt(hex2bin('3031300d060960864801650304020105000420') . hash('sha256',$data,true), $sig, $key);
}
}
function rsa_sign($data, $key, $alg = 'sha256') {
openssl_sign($data, $sig, $key, (($alg == 'sha1') ? OPENSSL_ALGO_SHA1 : $alg));
return $sig;
}
function rsa_verify($data,$sig,$key,$alg = 'sha256') {
if (version_compare(PHP_VERSION, '5.3.0', '>=') || $alg === 'sha1') {
$verify = openssl_verify($data,$sig,$key,(($alg == 'sha1') ? OPENSSL_ALGO_SHA1 : $alg));
}
else {
if(strlen($key) <= 300 || extension_loaded('gmp')) {
require_once('library/phpsec/Crypt/RSA.php');
$rsa = new CRYPT_RSA();
$rsa->signatureMode = CRYPT_RSA_SIGNATURE_PKCS1;
$rsa->setHash($alg);
$rsa->loadKey($key);
$verify = $rsa->verify($data,$sig);
}
else {
// fallback sha256 verify for PHP < 5.3 and large key lengths
$rawsig = '';
openssl_public_decrypt($sig,$rawsig,$key);
$verify = (($rawsig && substr($rawsig,-32) === hash('sha256',$data,true)) ? true : false);
}
}
return $verify;
function rsa_verify($data, $sig, $key, $alg = 'sha256') {
return openssl_verify($data, $sig, $key, (($alg == 'sha1') ? OPENSSL_ALGO_SHA1 : $alg));
}
function DerToPem($Der, $Private=false)
{
//Encode:
$Der = base64_encode($Der);
//Split lines:
$lines = str_split($Der, 65);
$body = implode("\n", $lines);
//Get title:
$title = $Private? 'RSA PRIVATE KEY' : 'PUBLIC KEY';
//Add wrapping:
$result = "-----BEGIN {$title}-----\n";
$result .= $body . "\n";
$result .= "-----END {$title}-----\n";
return $result;
function DerToPem($Der, $Private = false) {
//Encode:
$Der = base64_encode($Der);
//Split lines:
$lines = str_split($Der, 65);
$body = implode("\n", $lines);
//Get title:
$title = $Private ? 'RSA PRIVATE KEY' : 'PUBLIC KEY';
//Add wrapping:
$result = "-----BEGIN {$title}-----\n";
$result .= $body . "\n";
$result .= "-----END {$title}-----\n";
return $result;
}
function DerToRsa($Der)
{
//Encode:
$Der = base64_encode($Der);
//Split lines:
$lines = str_split($Der, 64);
$body = implode("\n", $lines);
//Get title:
$title = 'RSA PUBLIC KEY';
//Add wrapping:
$result = "-----BEGIN {$title}-----\n";
$result .= $body . "\n";
$result .= "-----END {$title}-----\n";
return $result;
function DerToRsa($Der) {
//Encode:
$Der = base64_encode($Der);
//Split lines:
$lines = str_split($Der, 64);
$body = implode("\n", $lines);
//Get title:
$title = 'RSA PUBLIC KEY';
//Add wrapping:
$result = "-----BEGIN {$title}-----\n";
$result .= $body . "\n";
$result .= "-----END {$title}-----\n";
return $result;
}
function pkcs8_encode($Modulus,$PublicExponent) {
function pkcs8_encode($Modulus, $PublicExponent) {
//Encode key sequence
$modulus = new ASNValue(ASNValue::TAG_INTEGER);
$modulus->SetIntBuffer($Modulus);
@ -111,8 +69,7 @@ function pkcs8_encode($Modulus,$PublicExponent) {
return $PublicDER;
}
function pkcs1_encode($Modulus,$PublicExponent) {
function pkcs1_encode($Modulus, $PublicExponent) {
//Encode key sequence
$modulus = new ASNValue(ASNValue::TAG_INTEGER);
$modulus->SetIntBuffer($Modulus);
@ -126,22 +83,20 @@ function pkcs1_encode($Modulus,$PublicExponent) {
return $bitStringValue;
}
function metopem($m,$e) {
$der = pkcs8_encode($m,$e);
$key = DerToPem($der,false);
function metopem($m, $e) {
$der = pkcs8_encode($m, $e);
$key = DerToPem($der, false);
return $key;
}
}
function pubrsatome($key,&$m,&$e) {
require_once('library/asn1.php');
require_once('include/salmon.php');
$lines = explode("\n",$key);
$lines = explode("\n", $key);
unset($lines[0]);
unset($lines[count($lines)]);
$x = base64_decode(implode('',$lines));
$x = base64_decode(implode('', $lines));
$r = ASN_BASE::parseASNString($x);
@ -151,21 +106,21 @@ function pubrsatome($key,&$m,&$e) {
function rsatopem($key) {
pubrsatome($key,$m,$e);
return(metopem($m,$e));
pubrsatome($key, $m, $e);
return metopem($m, $e);
}
function pemtorsa($key) {
pemtome($key,$m,$e);
return(metorsa($m,$e));
pemtome($key, $m, $e);
return metorsa($m, $e);
}
function pemtome($key,&$m,&$e) {
function pemtome($key, &$m, &$e) {
require_once('include/salmon.php');
$lines = explode("\n",$key);
$lines = explode("\n", $key);
unset($lines[0]);
unset($lines[count($lines)]);
$x = base64_decode(implode('',$lines));
$x = base64_decode(implode('', $lines));
$r = ASN_BASE::parseASNString($x);
@ -173,82 +128,36 @@ function pemtome($key,&$m,&$e) {
$e = base64url_decode($r[0]->asnData[1]->asnData[0]->asnData[1]->asnData);
}
function metorsa($m,$e) {
$der = pkcs1_encode($m,$e);
function metorsa($m, $e) {
$der = pkcs1_encode($m, $e);
$key = DerToRsa($der);
return $key;
}
function salmon_key($pubkey) {
pemtome($pubkey,$m,$e);
return 'RSA' . '.' . base64url_encode($m,true) . '.' . base64url_encode($e,true) ;
}
if(! function_exists('aes_decrypt')) {
// DEPRECATED IN 3.4.1
function aes_decrypt($val,$ky)
{
$key="\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
for($a=0;$a<strlen($ky);$a++)
$key[$a%16]=chr(ord($key[$a%16]) ^ ord($ky[$a]));
$mode = MCRYPT_MODE_ECB;
$enc = MCRYPT_RIJNDAEL_128;
$dec = @mcrypt_decrypt($enc, $key, $val, $mode, @mcrypt_create_iv( @mcrypt_get_iv_size($enc, $mode), MCRYPT_DEV_URANDOM ) );
return rtrim($dec,(( ord(substr($dec,strlen($dec)-1,1))>=0 and ord(substr($dec, strlen($dec)-1,1))<=16)? chr(ord( substr($dec,strlen($dec)-1,1))):null));
}}
if(! function_exists('aes_encrypt')) {
// DEPRECATED IN 3.4.1
function aes_encrypt($val,$ky)
{
$key="\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
for($a=0;$a<strlen($ky);$a++)
$key[$a%16]=chr(ord($key[$a%16]) ^ ord($ky[$a]));
$mode=MCRYPT_MODE_ECB;
$enc=MCRYPT_RIJNDAEL_128;
$val=str_pad($val, (16*(floor(strlen($val) / 16)+(strlen($val) % 16==0?2:1))), chr(16-(strlen($val) % 16)));
return mcrypt_encrypt($enc, $key, $val, $mode, mcrypt_create_iv( mcrypt_get_iv_size($enc, $mode), MCRYPT_DEV_URANDOM));
}}
function pkcs5_pad ($text, $blocksize)
{
$pad = $blocksize - (strlen($text) % $blocksize);
return $text . str_repeat(chr($pad), $pad);
function salmon_key($pubkey) {
pemtome($pubkey, $m, $e);
return 'RSA' . '.' . base64url_encode($m, true) . '.' . base64url_encode($e, true) ;
}
function pkcs5_unpad($text)
{
$pad = ord($text{strlen($text)-1});
if ($pad > strlen($text)) return false;
if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) return false;
return substr($text, 0, -1 * $pad);
}
function new_keypair($bits) {
$openssl_options = array(
'digest_alg' => 'sha1',
'private_key_bits' => $bits,
'encrypt_key' => false
'encrypt_key' => false
);
$conf = get_config('system','openssl_conf_file');
if($conf)
$conf = get_config('system', 'openssl_conf_file');
if ($conf) {
$openssl_options['config'] = $conf;
}
$result = openssl_pkey_new($openssl_options);
if(empty($result)) {
if (empty($result)) {
logger('new_keypair: failed');
return false;
}
// Get private key
$response = array('prvkey' => '', 'pubkey' => '');
openssl_pkey_export($result, $response['prvkey']);
@ -258,6 +167,4 @@ function new_keypair($bits) {
$response['pubkey'] = $pkey["key"];
return $response;
}

+ 29
- 8
include/dfrn.php View File

@ -931,6 +931,30 @@ class dfrn {
return $entry;
}
/**
* @brief encrypts data via AES
*
* @param string $data The data that is to be encrypted
* @param string $key The AES key
*
* @return string encrypted data
*/
private static function aes_encrypt($data, $key) {
return openssl_encrypt($data, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
}
/**
* @brief decrypts data via AES
*
* @param string $encrypted The encrypted data
* @param string $key The AES key
*
* @return string decrypted data
*/
public static function aes_decrypt($encrypted, $key) {
return openssl_decrypt($encrypted, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
}
/**
* @brief Delivers the atom content to the contacts
*
@ -958,11 +982,6 @@ class dfrn {
$rino = get_config('system', 'rino_encrypt');
$rino = intval($rino);
// use RINO1 if mcrypt isn't installed and RINO2 was selected
if ($rino == 2 and !function_exists('mcrypt_create_iv')) {
$rino = 1;
}
logger("Local rino version: ". $rino, LOGGER_DEBUG);
$ssl_val = intval(get_config('system','ssl_policy'));
@ -1093,8 +1112,8 @@ class dfrn {
switch ($rino_remote_version) {
case 1:
// Deprecated rino version!
$key = substr(random_string(), 0, 16);
$data = aes_encrypt($postvars['data'],$key);
$key = openssl_random_pseudo_bytes(16);
$data = self::aes_encrypt($postvars['data'], $key);
break;
case 2:
// RINO 2 based on php-encryption
@ -1458,7 +1477,9 @@ class dfrn {
$poco["photo"] = $author["avatar"];
$poco["hide"] = $hide;
$poco["contact-type"] = $contact["contact-type"];
update_gcontact($poco);
$gcid = update_gcontact($poco);
link_gcontact($gcid, $importer["uid"], $contact["id"]);
}
return($author);


+ 48
- 31
include/diaspora.php View File

@ -10,17 +10,17 @@
use \Friendica\Core\Config;
require_once("include/items.php");
require_once("include/bb2diaspora.php");
require_once("include/Scrape.php");
require_once("include/Contact.php");
require_once("include/Photo.php");
require_once("include/socgraph.php");
require_once("include/group.php");
require_once("include/xml.php");
require_once("include/datetime.php");
require_once("include/queue_fn.php");
require_once("include/cache.php");
require_once 'include/items.php';
require_once 'include/bb2diaspora.php';
require_once 'include/Scrape.php';
require_once 'include/Contact.php';
require_once 'include/Photo.php';
require_once 'include/socgraph.php';
require_once 'include/group.php';
require_once 'include/xml.php';
require_once 'include/datetime.php';
require_once 'include/queue_fn.php';
require_once 'include/cache.php';
/**
* @brief This class contain functions to create and send Diaspora XML files
@ -160,6 +160,32 @@ class Diaspora {
return $data;
}
/**
* @brief encrypts data via AES
*
* @param string $key The AES key
* @param string $iv The IV (is used for CBC encoding)
* @param string $data The data that is to be encrypted
*
* @return string encrypted data
*/
private static function aes_encrypt($key, $iv, $data) {
return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
}
/**
* @brief decrypts data via AES
*
* @param string $key The AES key
* @param string $iv The IV (is used for CBC encoding)
* @param string $encrypted The encrypted data
*
* @return string decrypted data
*/
private static function aes_decrypt($key, $iv, $encrypted) {
return openssl_decrypt($encrypted,'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA,str_pad($iv, 16, "\0"));
}
/**
* @brief: Decodes incoming Diaspora message
*
@ -199,10 +225,7 @@ class Diaspora {
$outer_iv = base64_decode($j_outer_key_bundle->iv);
$outer_key = base64_decode($j_outer_key_bundle->key);
$decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
$decrypted = pkcs5_unpad($decrypted);
$decrypted = self::aes_decrypt($outer_key, $outer_iv, $ciphertext);
logger('decrypted: '.$decrypted, LOGGER_DEBUG);
$idom = parse_xml_string($decrypted,false);
@ -261,8 +284,7 @@ class Diaspora {
// Decode the encrypted blob
$inner_encrypted = base64_decode($data);
$inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
$inner_decrypted = pkcs5_unpad($inner_decrypted);
$inner_decrypted = self::aes_decrypt($inner_aes_key, $inner_iv, $inner_encrypted);
}
if (!$author_link) {
@ -1848,18 +1870,15 @@ class Diaspora {
intval($importer["uid"])
);
if ($searchable) {
poco_check($contact["url"], $name, NETWORK_DIASPORA, $image_url, $about, $location, $gender, $keywords, "",
datetime_convert(), 2, $contact["id"], $importer["uid"]);
}
$gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
"photo" => $image_url, "name" => $name, "location" => $location,
"about" => $about, "birthday" => $birthday, "gender" => $gender,
"addr" => $author, "nick" => $nick, "keywords" => $keywords,
"hide" => !$searchable, "nsfw" => $nsfw);
update_gcontact($gcontact);
$gcid = update_gcontact($gcontact);
link_gcontact($gcid, $importer["uid"], $contact["id"]);
logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
@ -2621,20 +2640,19 @@ class Diaspora {
return false;
}
$inner_aes_key = random_string(32);
$inner_aes_key = openssl_random_pseudo_bytes(32);
$b_inner_aes_key = base64_encode($inner_aes_key);
$inner_iv = random_string(16);
$inner_iv = openssl_random_pseudo_bytes(16);
$b_inner_iv = base64_encode($inner_iv);