+ // Now we are collecting all relay contacts
+ foreach ($serverlist as $server_url) {
+ // We don't send messages to ourselves
+ if (link_compare($server_url, System::baseUrl())) {
+ continue;
+ }
+ $contact = self::getRelayContact($server_url);
+ if (is_bool($contact)) {
+ continue;
+ }
+
+ $exists = false;
+ foreach ($contacts as $entry) {
+ if ($entry['batch'] == $contact['batch']) {
+ $exists = true;
+ }
+ }
+
+ if (!$exists) {
+ $contacts[] = $contact;
+ }
+ }
+
+ return $contacts;
+ }
+
+ /**
+ * @brief Return a contact for a given server address or creates a dummy entry
+ *
+ * @param string $server_url The url of the server
+ * @return array with the contact
+ */
+ private static function getRelayContact($server_url)
+ {
+ $fields = ['batch', 'id', 'name', 'network', 'archive', 'blocked'];
+
+ // Fetch the relay contact
+ $condition = ['uid' => 0, 'nurl' => normalise_link($server_url),
+ 'contact-type' => Contact::ACCOUNT_TYPE_RELAY];
+ $contact = DBA::selectFirst('contact', $fields, $condition);
+
+ if (DBA::isResult($contact)) {
+ if ($contact['archive'] || $contact['blocked']) {
+ return false;
+ }
+ return $contact;
+ } else {
+ self::setRelayContact($server_url);
+
+ $contact = DBA::selectFirst('contact', $fields, $condition);
+ if (DBA::isResult($contact)) {
+ return $contact;
+ }
+ }
+
+ // It should never happen that we arrive here
+ return [];
+ }
+
+ /**
+ * @brief Update or insert a relay contact
+ *
+ * @param string $server_url The url of the server
+ * @param array $network_fields Optional network specific fields
+ */
+ public static function setRelayContact($server_url, array $network_fields = [])
+ {
+ $fields = ['created' => DateTimeFormat::utcNow(),
+ 'name' => 'relay', 'nick' => 'relay',
+ 'url' => $server_url, 'network' => Protocol::DIASPORA,
+ 'batch' => $server_url . '/receive/public',
+ 'rel' => Contact::FOLLOWER, 'blocked' => false,
+ 'pending' => false, 'writable' => true];
+
+ $fields = array_merge($fields, $network_fields);
+
+ $condition = ['uid' => 0, 'nurl' => normalise_link($server_url),
+ 'contact-type' => Contact::ACCOUNT_TYPE_RELAY];
+
+ if (DBA::exists('contact', $condition)) {
+ unset($fields['created']);
+ }
+
+ DBA::update('contact', $fields, $condition, true);