3 * @file src/Worker/Delivery.php
5 namespace Friendica\Worker;
8 use Friendica\Core\System;
9 use Friendica\Core\Config;
10 use Friendica\Core\L10n;
11 use Friendica\Database\DBM;
12 use Friendica\Model\Contact;
13 use Friendica\Model\Queue;
14 use Friendica\Model\User;
15 use Friendica\Protocol\Diaspora;
16 use Friendica\Protocol\DFRN;
17 use Friendica\Protocol\Email;
18 use Friendica\Util\Network;
21 require_once 'include/html2plain.php';
22 require_once 'include/datetime.php';
23 require_once 'include/items.php';
24 require_once 'include/bbcode.php';
26 /// @todo This is some ugly code that needs to be split into several methods
29 public static function execute($cmd, $item_id, $contact_id) {
32 logger('delivery: invoked: '.$cmd.': '.$item_id.' to '.$contact_id, LOGGER_DEBUG);
44 $recipients[] = $contact_id;
46 if ($cmd === 'mail') {
49 $message = q("SELECT * FROM `mail` WHERE `id` = %d LIMIT 1",
52 if (!count($message)) {
55 $uid = $message[0]['uid'];
56 $recipients[] = $message[0]['contact-id'];
58 } elseif ($cmd === 'suggest') {
62 $suggest = q("SELECT * FROM `fsuggest` WHERE `id` = %d LIMIT 1",
65 if (!count($suggest)) {
68 $uid = $suggest[0]['uid'];
69 $recipients[] = $suggest[0]['cid'];
71 } elseif ($cmd === 'relocate') {
77 $target_item = dba::fetch_first("SELECT `item`.*, `contact`.`uid` AS `cuid` FROM `item`
78 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
79 WHERE `item`.`id` = ? AND `visible` AND NOT `moderated`", $item_id);
81 if (!DBM::is_result($target_item) || !intval($target_item['parent'])) {
85 $parent_id = intval($target_item['parent']);
86 $uid = $target_item['cuid'];
87 $updated = $target_item['edited'];
89 $items = q("SELECT `item`.*, `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer`
90 FROM `item` LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id` WHERE `parent` = %d AND visible = 1 AND moderated = 0 ORDER BY `id` ASC",
100 foreach ($items as $item) {
101 if (!in_array($item['contact-id'],$contacts_arr)) {
102 $contacts_arr[] = intval($item['contact-id']);
105 if (count($contacts_arr)) {
106 $str_contacts = implode(',',$contacts_arr);
107 $icontacts = q("SELECT * FROM `contact`
108 WHERE `id` IN ( $str_contacts ) "
111 if ( !($icontacts && count($icontacts))) {
115 // avoid race condition with deleting entries
117 if ($items[0]['deleted']) {
118 foreach ($items as $item) {
119 $item['deleted'] = 1;
123 // When commenting too fast after delivery, a post wasn't recognized as top level post.
124 // The count then showed more than one entry. The additional check should help.
125 // The check for the "count" should be superfluous, but I'm not totally sure by now, so we keep it.
126 if ((($items[0]['id'] == $item_id) || (count($items) == 1)) && ($items[0]['uri'] === $items[0]['parent-uri'])) {
127 logger('delivery: top level post');
132 $owner = User::getOwnerDataById($uid);
137 $walltowall = (($top_level && ($owner['id'] != $items[0]['contact-id'])) ? true : false);
139 $public_message = true;
141 if (!$mail && !$fsuggest && !$relocate) {
144 // This is IMPORTANT!!!!
146 // We will only send a "notify owner to relay" or followup message if the referenced post
147 // originated on our system by virtue of having our hostname somewhere
148 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
149 // if $parent['wall'] == 1 we will already have the parent message in our array
150 // and we will relay the whole lot.
152 $localhost = $a->get_hostname();
153 if (strpos($localhost,':')) {
154 $localhost = substr($localhost,0,strpos($localhost,':'));
158 * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes
159 * have been known to cause runaway conditions which affected several servers, along with
160 * permissions issues.
164 $relay_to_owner = false;
166 if (!$top_level && ($parent['wall'] == 0) && stristr($target_item['uri'], $localhost)) {
167 $relay_to_owner = true;
170 if ($relay_to_owner) {
171 logger('followup '.$target_item["guid"], LOGGER_DEBUG);
172 // local followup to remote post
176 if (strlen($parent['allow_cid'])
177 || strlen($parent['allow_gid'])
178 || strlen($parent['deny_cid'])
179 || strlen($parent['deny_gid'])
180 || $parent["private"]) {
181 $public_message = false; // private recipients, not public
186 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `blocked` = 0 AND `pending` = 0",
190 if (DBM::is_result($r)) {
193 if ($contact['self']) {
198 // Transmit via Diaspora if not possible via Friendica
199 if (($item['uid'] == 0) && ($contact['network'] == NETWORK_DFRN)) {
200 $contact['network'] = NETWORK_DIASPORA;
203 logger("main delivery by delivery: followup=$followup mail=$mail fsuggest=$fsuggest relocate=$relocate - network ".$contact['network']);
205 switch ($contact['network']) {
208 logger('notifier: '.$target_item["guid"].' dfrndelivery: '.$contact['name']);
211 $item['body'] = fix_private_photos($item['body'],$owner['uid'],null,$message[0]['contact-id']);
212 $atom = DFRN::mail($item, $owner);
213 } elseif ($fsuggest) {
214 $atom = DFRN::fsuggest($item, $owner);
215 q("DELETE FROM `fsuggest` WHERE `id` = %d LIMIT 1", intval($item['id']));
216 } elseif ($relocate) {
217 $atom = DFRN::relocate($owner, $uid);
218 } elseif ($followup) {
220 foreach ($items as $item) { // there is only one item
221 if (!$item['parent']) {
224 if ($item['id'] == $item_id) {
225 logger('followup: item: '. print_r($item,true), LOGGER_DATA);
229 $atom = DFRN::entries($msgitems,$owner);
232 foreach ($items as $item) {
233 if (!$item['parent']) {
237 // private emails may be in included in public conversations. Filter them.
238 if ($public_message && $item['private']) {
242 $item_contact = self::getItemContact($item,$icontacts);
243 if (!$item_contact) {
248 if ($item_id == $item['id'] || $item['id'] == $item['parent']) {
249 $item["entry:comment-allow"] = true;
250 $item["entry:cid"] = (($top_level) ? $contact['id'] : 0);
254 $item["entry:comment-allow"] = true;
258 $atom = DFRN::entries($msgitems,$owner);
261 logger('notifier entry: '.$contact["url"].' '.$target_item["guid"].' entry: '.$atom, LOGGER_DEBUG);
263 logger('notifier: '.$atom, LOGGER_DATA);
264 $basepath = implode('/', array_slice(explode('/',$contact['url']),0,3));
266 // perform local delivery if we are on the same site
268 if (link_compare($basepath,System::baseUrl())) {
269 $nickname = basename($contact['url']);
270 if ($contact['issued-id']) {
271 $sql_extra = sprintf(" AND `dfrn-id` = '%s' ", dbesc($contact['issued-id']));
273 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($contact['dfrn-id']));
276 $x = q("SELECT `contact`.*, `contact`.`uid` AS `importer_uid`,
277 `contact`.`pubkey` AS `cpubkey`,
278 `contact`.`prvkey` AS `cprvkey`,
279 `contact`.`thumb` AS `thumb`,
280 `contact`.`url` as `url`,
281 `contact`.`name` as `senderName`,
284 INNER JOIN `user` ON `contact`.`uid` = `user`.`uid`
285 WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0
286 AND `contact`.`network` = '%s' AND `user`.`nickname` = '%s'
288 AND `user`.`account_expired` = 0 AND `user`.`account_removed` = 0 LIMIT 1",
293 if ($x && count($x)) {
294 $write_flag = ((($x[0]['rel']) && ($x[0]['rel'] != CONTACT_IS_SHARING)) ? true : false);
295 if ((($owner['page-flags'] == PAGE_COMMUNITY) || $write_flag) && !$x[0]['writable']) {
296 q("UPDATE `contact` SET `writable` = 1 WHERE `id` = %d",
299 $x[0]['writable'] = 1;
302 $ssl_policy = Config::get('system','ssl_policy');
303 Network::fixContactSslPolicy($x[0], $ssl_policy);
305 // If we are setup as a soapbox we aren't accepting top level posts from this person
307 if (($x[0]['page-flags'] == PAGE_SOAPBOX) && $top_level) {
310 logger('mod-delivery: local delivery');
311 DFRN::import($atom, $x[0]);
316 if (!Queue::wasDelayed($contact['id'])) {
317 $deliver_status = DFRN::deliver($owner, $contact, $atom);
319 $deliver_status = (-1);
322 logger('notifier: dfrn_delivery to '.$contact["url"].' with guid '.$target_item["guid"].' returns '.$deliver_status);
324 if ($deliver_status < 0) {
325 logger('notifier: delivery failed: queuing message');
326 Queue::add($contact['id'], NETWORK_DFRN, $atom);
328 // The message could not be delivered. We mark the contact as "dead"
329 Contact::markForArchival($contact);
331 // We successfully delivered a message, the contact is alive
332 Contact::unmarkForArchival($contact);
337 case NETWORK_OSTATUS:
338 // Do not send to otatus if we are not configured to send to public networks
339 if ($owner['prvnets']) {
342 if (Config::get('system','ostatus_disabled') || Config::get('system','dfrn_only')) {
346 // There is currently no code here to distribute anything to OStatus.
347 // This is done in "notifier.php" (See "url_recipients" and "push_notify")
352 if (Config::get('system','dfrn_only')) {
355 // WARNING: does not currently convert to RFC2047 header encodings, etc.
357 $addr = $contact['addr'];
358 if (!strlen($addr)) {
362 if ($cmd === 'wall-new' || $cmd === 'comment-new') {
364 if ($cmd === 'wall-new') {
367 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
370 if (DBM::is_result($r)) {
378 $local_user = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
381 if (!count($local_user)) {
386 $r1 = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
389 if ($r1 && $r1[0]['reply_to']) {
390 $reply_to = $r1[0]['reply_to'];
393 $subject = (($it['title']) ? Email::encodeHeader($it['title'],'UTF-8') : L10n::t("\x28no subject\x29")) ;
395 // only expose our real email address to true friends
397 if (($contact['rel'] == CONTACT_IS_FRIEND) && !$contact['blocked']) {
399 $headers = 'From: '.Email::encodeHeader($local_user[0]['username'],'UTF-8').' <'.$reply_to.'>'."\n";
400 $headers .= 'Sender: '.$local_user[0]['email']."\n";
402 $headers = 'From: '.Email::encodeHeader($local_user[0]['username'],'UTF-8').' <'.$local_user[0]['email'].'>'."\n";
405 $headers = 'From: '. Email::encodeHeader($local_user[0]['username'],'UTF-8') .' <'. L10n::t('noreply') .'@'.$a->get_hostname() .'>'. "\n";
409 // $headers .= 'Reply-to: '.$reply_to . "\n";
411 $headers .= 'Message-Id: <'. Email::iri2msgid($it['uri']).'>'. "\n";
413 //logger("Mail: uri: ".$it['uri']." parent-uri ".$it['parent-uri'], LOGGER_DEBUG);
414 //logger("Mail: Data: ".print_r($it, true), LOGGER_DEBUG);
415 //logger("Mail: Data: ".print_r($it, true), LOGGER_DATA);
417 if ($it['uri'] !== $it['parent-uri']) {
418 $headers .= "References: <".Email::iri2msgid($it["parent-uri"]).">";
420 // If Threading is enabled, write down the correct parent
421 if (($it["thr-parent"] != "") && ($it["thr-parent"] != $it["parent-uri"])) {
422 $headers .= " <".Email::iri2msgid($it["thr-parent"]).">";
427 $r = q("SELECT `title` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
428 dbesc($it['parent-uri']),
431 if (DBM::is_result($r) && ($r[0]['title'] != '')) {
432 $subject = $r[0]['title'];
434 $r = q("SELECT `title` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d LIMIT 1",
435 dbesc($it['parent-uri']),
438 if (DBM::is_result($r) && ($r[0]['title'] != '')) {
439 $subject = $r[0]['title'];
443 if (strncasecmp($subject,'RE:',3)) {
444 $subject = 'Re: '.$subject;
447 Email::send($addr, $subject, $headers, $it);
451 case NETWORK_DIASPORA:
452 if ($public_message) {
453 $loc = 'public batch '.$contact['batch'];
455 $loc = $contact['name'];
458 logger('delivery: diaspora batch deliver: '.$loc);
460 if (Config::get('system','dfrn_only') || !Config::get('system','diaspora_enabled')) {
464 Diaspora::sendMail($item,$owner,$contact);
471 if (!$contact['pubkey'] && !$public_message) {
474 if (($target_item['deleted']) && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
475 // top-level retraction
476 logger('diaspora retract: '.$loc);
477 Diaspora::sendRetraction($target_item,$owner,$contact,$public_message);
479 } elseif ($relocate) {
480 Diaspora::sendAccountMigration($owner, $contact, $uid);
482 } elseif ($followup) {
483 // send comments and likes to owner to relay
484 logger('diaspora followup: '.$loc);
485 Diaspora::sendFollowup($target_item,$owner,$contact,$public_message);
487 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
488 // we are the relay - send comments, likes and relayable_retractions to our conversants
489 logger('diaspora relay: '.$loc);
490 Diaspora::sendRelay($target_item,$owner,$contact,$public_message);
492 } elseif ($top_level && !$walltowall) {
493 // currently no workable solution for sending walltowall
494 logger('diaspora status: '.$loc);
495 Diaspora::sendStatus($target_item,$owner,$contact,$public_message);
499 logger('delivery: diaspora unknown mode: '.$contact['name']);
510 private static function getItemContact($item, $contacts)
512 if (!count($contacts) || !is_array($item)) {
515 foreach ($contacts as $contact) {
516 if ($contact['id'] == $item['contact-id']) {