]> git.mxchange.org Git - friendica.git/blob - include/diaspora.php
Merge pull request #2471 from annando/1604-diaspora-always-on
[friendica.git] / include / diaspora.php
1 <?php
2 /**
3  * @file include/diaspora.php
4  * @brief The implementation of the diaspora protocol
5  *
6  * Checklist:
7  *
8  * Checked:
9  * - send status
10  * - send comment
11  * - send like
12  * - send mail
13  * - send status retraction
14  * - send comment retraction on own post
15  * - send like retraction on own post
16  * - send comment retraction on diaspora post
17  * - send like retraction on diaspora post
18  * - receive status
19  * - receive reshare
20  * - receive comment
21  * - receive like
22  * - receive connect request
23  * - receive profile data
24  * - receive mail
25  * - receive comment retraction
26  * - receive like retraction
27  * - relay comment
28  * - relay like
29  * - relay comment retraction from diaspora
30  * - relay comment retraction from friendica
31  * - relay like retraction from diaspora
32  * - relay like retraction from friendica
33  * - send share
34  *
35  * Should work:
36  * - receive account deletion
37  * - send unshare
38  *
39  * Unchecked:
40  */
41
42 require_once("include/items.php");
43 require_once("include/bb2diaspora.php");
44 require_once("include/Scrape.php");
45 require_once("include/Contact.php");
46 require_once("include/Photo.php");
47 require_once("include/socgraph.php");
48 require_once("include/group.php");
49 require_once("include/xml.php");
50 require_once("include/datetime.php");
51 require_once("include/queue_fn.php");
52
53 /**
54  * @brief This class contain functions to create and send Diaspora XML files
55  *
56  */
57 class diaspora {
58
59         /**
60          * @brief Return a list of relay servers
61          *
62          * This is an experimental Diaspora feature.
63          *
64          * @return array of relay servers
65          */
66         public static function relay_list() {
67
68                 $serverdata = get_config("system", "relay_server");
69                 if ($serverdata == "")
70                         return array();
71
72                 $relay = array();
73
74                 $servers = explode(",", $serverdata);
75
76                 foreach($servers AS $server) {
77                         $server = trim($server);
78                         $batch = $server."/receive/public";
79
80                         $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
81
82                         if (!$relais) {
83                                 $addr = "relay@".str_replace("http://", "", normalise_link($server));
84
85                                 $r = q("INSERT INTO `contact` (`uid`, `created`, `name`, `nick`, `addr`, `url`, `nurl`, `batch`, `network`, `rel`, `blocked`, `pending`, `writable`, `name-date`, `uri-date`, `avatar-date`)
86                                         VALUES (0, '%s', '%s', 'relay', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, '%s', '%s', '%s')",
87                                         datetime_convert(),
88                                         dbesc($addr),
89                                         dbesc($addr),
90                                         dbesc($server),
91                                         dbesc(normalise_link($server)),
92                                         dbesc($batch),
93                                         dbesc(NETWORK_DIASPORA),
94                                         intval(CONTACT_IS_FOLLOWER),
95                                         dbesc(datetime_convert()),
96                                         dbesc(datetime_convert()),
97                                         dbesc(datetime_convert())
98                                 );
99
100                                 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
101                                 if ($relais)
102                                         $relay[] = $relais[0];
103                         } else
104                                 $relay[] = $relais[0];
105                 }
106
107                 return $relay;
108         }
109
110         /**
111          * @brief repairs a signature that was double encoded
112          *
113          * The function is unused at the moment. It was copied from the old implementation.
114          *
115          * @param string $signature The signature
116          * @param string $handle The handle of the signature owner
117          * @param integer $level This value is only set inside this function to avoid endless loops
118          *
119          * @return string the repaired signature
120          */
121         private function repair_signature($signature, $handle = "", $level = 1) {
122
123                 if ($signature == "")
124                         return ($signature);
125
126                 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
127                         $signature = base64_decode($signature);
128                         logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
129
130                         // Do a recursive call to be able to fix even multiple levels
131                         if ($level < 10)
132                                 $signature = self::repair_signature($signature, $handle, ++$level);
133                 }
134
135                 return($signature);
136         }
137
138         /**
139          * @brief: Decodes incoming Diaspora message
140          *
141          * @param array $importer Array of the importer user
142          * @param string $xml urldecoded Diaspora salmon
143          *
144          * @return array
145          * 'message' -> decoded Diaspora XML message
146          * 'author' -> author diaspora handle
147          * 'key' -> author public key (converted to pkcs#8)
148          */
149         public static function decode($importer, $xml) {
150
151                 $public = false;
152                 $basedom = parse_xml_string($xml);
153
154                 if (!is_object($basedom))
155                         return false;
156
157                 $children = $basedom->children('https://joindiaspora.com/protocol');
158
159                 if($children->header) {
160                         $public = true;
161                         $author_link = str_replace('acct:','',$children->header->author_id);
162                 } else {
163
164                         $encrypted_header = json_decode(base64_decode($children->encrypted_header));
165
166                         $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
167                         $ciphertext = base64_decode($encrypted_header->ciphertext);
168
169                         $outer_key_bundle = '';
170                         openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
171
172                         $j_outer_key_bundle = json_decode($outer_key_bundle);
173
174                         $outer_iv = base64_decode($j_outer_key_bundle->iv);
175                         $outer_key = base64_decode($j_outer_key_bundle->key);
176
177                         $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
178
179
180                         $decrypted = pkcs5_unpad($decrypted);
181
182                         logger('decrypted: '.$decrypted, LOGGER_DEBUG);
183                         $idom = parse_xml_string($decrypted,false);
184
185                         $inner_iv = base64_decode($idom->iv);
186                         $inner_aes_key = base64_decode($idom->aes_key);
187
188                         $author_link = str_replace('acct:','',$idom->author_id);
189                 }
190
191                 $dom = $basedom->children(NAMESPACE_SALMON_ME);
192
193                 // figure out where in the DOM tree our data is hiding
194
195                 if($dom->provenance->data)
196                         $base = $dom->provenance;
197                 elseif($dom->env->data)
198                         $base = $dom->env;
199                 elseif($dom->data)
200                         $base = $dom;
201
202                 if (!$base) {
203                         logger('unable to locate salmon data in xml');
204                         http_status_exit(400);
205                 }
206
207
208                 // Stash the signature away for now. We have to find their key or it won't be good for anything.
209                 $signature = base64url_decode($base->sig);
210
211                 // unpack the  data
212
213                 // strip whitespace so our data element will return to one big base64 blob
214                 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
215
216
217                 // stash away some other stuff for later
218
219                 $type = $base->data[0]->attributes()->type[0];
220                 $keyhash = $base->sig[0]->attributes()->keyhash[0];
221                 $encoding = $base->encoding;
222                 $alg = $base->alg;
223
224
225                 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
226
227
228                 // decode the data
229                 $data = base64url_decode($data);
230
231
232                 if($public)
233                         $inner_decrypted = $data;
234                 else {
235
236                         // Decode the encrypted blob
237
238                         $inner_encrypted = base64_decode($data);
239                         $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
240                         $inner_decrypted = pkcs5_unpad($inner_decrypted);
241                 }
242
243                 if (!$author_link) {
244                         logger('Could not retrieve author URI.');
245                         http_status_exit(400);
246                 }
247                 // Once we have the author URI, go to the web and try to find their public key
248                 // (first this will look it up locally if it is in the fcontact cache)
249                 // This will also convert diaspora public key from pkcs#1 to pkcs#8
250
251                 logger('Fetching key for '.$author_link);
252                 $key = self::key($author_link);
253
254                 if (!$key) {
255                         logger('Could not retrieve author key.');
256                         http_status_exit(400);
257                 }
258
259                 $verify = rsa_verify($signed_data,$signature,$key);
260
261                 if (!$verify) {
262                         logger('Message did not verify. Discarding.');
263                         http_status_exit(400);
264                 }
265
266                 logger('Message verified.');
267
268                 return array('message' => (string)$inner_decrypted,
269                                 'author' => unxmlify($author_link),
270                                 'key' => (string)$key);
271
272         }
273
274
275         /**
276          * @brief Dispatches public messages and find the fitting receivers
277          *
278          * @param array $msg The post that will be dispatched
279          *
280          * @return int The message id of the generated message, "true" or "false" if there was an error
281          */
282         public static function dispatch_public($msg) {
283
284                 $enabled = intval(get_config("system", "diaspora_enabled"));
285                 if (!$enabled) {
286                         logger("diaspora is disabled");
287                         return false;
288                 }
289
290                 // Use a dummy importer to import the data for the public copy
291                 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
292                 $message_id = self::dispatch($importer,$msg);
293
294                 // Now distribute it to the followers
295                 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
296                         (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
297                         AND NOT `account_expired` AND NOT `account_removed`",
298                         dbesc(NETWORK_DIASPORA),
299                         dbesc($msg["author"])
300                 );
301                 if($r) {
302                         foreach($r as $rr) {
303                                 logger("delivering to: ".$rr["username"]);
304                                 self::dispatch($rr,$msg);
305                         }
306                 } else
307                         logger("No subscribers for ".$msg["author"]." ".print_r($msg, true));
308
309                 return $message_id;
310         }
311
312         /**
313          * @brief Dispatches the different message types to the different functions
314          *
315          * @param array $importer Array of the importer user
316          * @param array $msg The post that will be dispatched
317          *
318          * @return int The message id of the generated message, "true" or "false" if there was an error
319          */
320         public static function dispatch($importer, $msg) {
321
322                 // The sender is the handle of the contact that sent the message.
323                 // This will often be different with relayed messages (for example "like" and "comment")
324                 $sender = $msg["author"];
325
326                 if (!diaspora::valid_posting($msg, $fields)) {
327                         logger("Invalid posting");
328                         return false;
329                 }
330
331                 $type = $fields->getName();
332
333                 logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
334
335                 switch ($type) {
336                         case "account_deletion":
337                                 return self::receive_account_deletion($importer, $fields);
338
339                         case "comment":
340                                 return self::receive_comment($importer, $sender, $fields, $msg["message"]);
341
342                         case "contact":
343                                 return self::receive_contact_request($importer, $fields);
344
345                         case "conversation":
346                                 return self::receive_conversation($importer, $msg, $fields);
347
348                         case "like":
349                                 return self::receive_like($importer, $sender, $fields);
350
351                         case "message":
352                                 return self::receive_message($importer, $fields);
353
354                         case "participation": // Not implemented
355                                 return self::receive_participation($importer, $fields);
356
357                         case "photo": // Not implemented
358                                 return self::receive_photo($importer, $fields);
359
360                         case "poll_participation": // Not implemented
361                                 return self::receive_poll_participation($importer, $fields);
362
363                         case "profile":
364                                 return self::receive_profile($importer, $fields);
365
366                         case "reshare":
367                                 return self::receive_reshare($importer, $fields, $msg["message"]);
368
369                         case "retraction":
370                                 return self::receive_retraction($importer, $sender, $fields);
371
372                         case "status_message":
373                                 return self::receive_status_message($importer, $fields, $msg["message"]);
374
375                         default:
376                                 logger("Unknown message type ".$type);
377                                 return false;
378                 }
379
380                 return true;
381         }
382
383         /**
384          * @brief Checks if a posting is valid and fetches the data fields.
385          *
386          * This function does not only check the signature.
387          * It also does the conversion between the old and the new diaspora format.
388          *
389          * @param array $msg Array with the XML, the sender handle and the sender signature
390          * @param object $fields SimpleXML object that contains the posting when it is valid
391          *
392          * @return bool Is the posting valid?
393          */
394         private function valid_posting($msg, &$fields) {
395
396                 $data = parse_xml_string($msg["message"], false);
397
398                 if (!is_object($data))
399                         return false;
400
401                 $first_child = $data->getName();
402
403                 // Is this the new or the old version?
404                 if ($data->getName() == "XML") {
405                         $oldXML = true;
406                         foreach ($data->post->children() as $child)
407                                 $element = $child;
408                 } else {
409                         $oldXML = false;
410                         $element = $data;
411                 }
412
413                 $type = $element->getName();
414                 $orig_type = $type;
415
416                 // All retractions are handled identically from now on.
417                 // In the new version there will only be "retraction".
418                 if (in_array($type, array("signed_retraction", "relayable_retraction")))
419                         $type = "retraction";
420
421                 if ($type == "request")
422                         $type = "contact";
423
424                 $fields = new SimpleXMLElement("<".$type."/>");
425
426                 $signed_data = "";
427
428                 foreach ($element->children() AS $fieldname => $entry) {
429                         if ($oldXML) {
430                                 // Translation for the old XML structure
431                                 if ($fieldname == "diaspora_handle")
432                                         $fieldname = "author";
433
434                                 if ($fieldname == "participant_handles")
435                                         $fieldname = "participants";
436
437                                 if (in_array($type, array("like", "participation"))) {
438                                         if ($fieldname == "target_type")
439                                                 $fieldname = "parent_type";
440                                 }
441
442                                 if ($fieldname == "sender_handle")
443                                         $fieldname = "author";
444
445                                 if ($fieldname == "recipient_handle")
446                                         $fieldname = "recipient";
447
448                                 if ($fieldname == "root_diaspora_id")
449                                         $fieldname = "root_author";
450
451                                 if ($type == "retraction") {
452                                         if ($fieldname == "post_guid")
453                                                 $fieldname = "target_guid";
454
455                                         if ($fieldname == "type")
456                                                 $fieldname = "target_type";
457                                 }
458                         }
459
460                         if ($fieldname == "author_signature")
461                                 $author_signature = base64_decode($entry);
462                         elseif ($fieldname == "parent_author_signature")
463                                 $parent_author_signature = base64_decode($entry);
464                         elseif ($fieldname != "target_author_signature") {
465                                 if ($signed_data != "") {
466                                         $signed_data .= ";";
467                                         $signed_data_parent .= ";";
468                                 }
469
470                                 $signed_data .= $entry;
471                         }
472                         if (!in_array($fieldname, array("parent_author_signature", "target_author_signature")) OR
473                                 ($orig_type == "relayable_retraction"))
474                                 xml::copy($entry, $fields, $fieldname);
475                 }
476
477                 // This is something that shouldn't happen at all.
478                 if (in_array($type, array("status_message", "reshare", "profile")))
479                         if ($msg["author"] != $fields->author) {
480                                 logger("Message handle is not the same as envelope sender. Quitting this message.");
481                                 return false;
482                         }
483
484                 // Only some message types have signatures. So we quit here for the other types.
485                 if (!in_array($type, array("comment", "message", "like")))
486                         return true;
487
488                 // No author_signature? This is a must, so we quit.
489                 if (!isset($author_signature))
490                         return false;
491
492                 if (isset($parent_author_signature)) {
493                         $key = self::key($msg["author"]);
494
495                         if (!rsa_verify($signed_data, $parent_author_signature, $key, "sha256"))
496                                 return false;
497                 }
498
499                 $key = self::key($fields->author);
500
501                 return rsa_verify($signed_data, $author_signature, $key, "sha256");
502         }
503
504         /**
505          * @brief Fetches the public key for a given handle
506          *
507          * @param string $handle The handle
508          *
509          * @return string The public key
510          */
511         private function key($handle) {
512                 $handle = strval($handle);
513
514                 logger("Fetching diaspora key for: ".$handle);
515
516                 $r = self::person_by_handle($handle);
517                 if($r)
518                         return $r["pubkey"];
519
520                 return "";
521         }
522
523         /**
524          * @brief Fetches data for a given handle
525          *
526          * @param string $handle The handle
527          *
528          * @return array the queried data
529          */
530         private function person_by_handle($handle) {
531
532                 $r = q("SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
533                         dbesc(NETWORK_DIASPORA),
534                         dbesc($handle)
535                 );
536                 if ($r) {
537                         $person = $r[0];
538                         logger("In cache ".print_r($r,true), LOGGER_DEBUG);
539
540                         // update record occasionally so it doesn't get stale
541                         $d = strtotime($person["updated"]." +00:00");
542                         if ($d < strtotime("now - 14 days"))
543                                 $update = true;
544                 }
545
546                 if (!$person OR $update) {
547                         logger("create or refresh", LOGGER_DEBUG);
548                         $r = probe_url($handle, PROBE_DIASPORA);
549
550                         // Note that Friendica contacts will return a "Diaspora person"
551                         // if Diaspora connectivity is enabled on their server
552                         if ($r AND ($r["network"] === NETWORK_DIASPORA)) {
553                                 self::add_fcontact($r, $update);
554                                 $person = $r;
555                         }
556                 }
557                 return $person;
558         }
559
560         /**
561          * @brief Updates the fcontact table
562          *
563          * @param array $arr The fcontact data
564          * @param bool $update Update or insert?
565          *
566          * @return string The id of the fcontact entry
567          */
568         private function add_fcontact($arr, $update = false) {
569
570                 if($update) {
571                         $r = q("UPDATE `fcontact` SET
572                                         `name` = '%s',
573                                         `photo` = '%s',
574                                         `request` = '%s',
575                                         `nick` = '%s',
576                                         `addr` = '%s',
577                                         `batch` = '%s',
578                                         `notify` = '%s',
579                                         `poll` = '%s',
580                                         `confirm` = '%s',
581                                         `alias` = '%s',
582                                         `pubkey` = '%s',
583                                         `updated` = '%s'
584                                 WHERE `url` = '%s' AND `network` = '%s'",
585                                         dbesc($arr["name"]),
586                                         dbesc($arr["photo"]),
587                                         dbesc($arr["request"]),
588                                         dbesc($arr["nick"]),
589                                         dbesc($arr["addr"]),
590                                         dbesc($arr["batch"]),
591                                         dbesc($arr["notify"]),
592                                         dbesc($arr["poll"]),
593                                         dbesc($arr["confirm"]),
594                                         dbesc($arr["alias"]),
595                                         dbesc($arr["pubkey"]),
596                                         dbesc(datetime_convert()),
597                                         dbesc($arr["url"]),
598                                         dbesc($arr["network"])
599                                 );
600                 } else {
601                         $r = q("INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`,
602                                         `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
603                                 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
604                                         dbesc($arr["url"]),
605                                         dbesc($arr["name"]),
606                                         dbesc($arr["photo"]),
607                                         dbesc($arr["request"]),
608                                         dbesc($arr["nick"]),
609                                         dbesc($arr["addr"]),
610                                         dbesc($arr["batch"]),
611                                         dbesc($arr["notify"]),
612                                         dbesc($arr["poll"]),
613                                         dbesc($arr["confirm"]),
614                                         dbesc($arr["network"]),
615                                         dbesc($arr["alias"]),
616                                         dbesc($arr["pubkey"]),
617                                         dbesc(datetime_convert())
618                                 );
619                 }
620
621                 return $r;
622         }
623
624         /**
625          * @brief get a handle (user@domain.tld) from a given contact id or gcontact id
626          *
627          * @param int $contact_id The id in the contact table
628          * @param int $gcontact_id The id in the gcontact table
629          *
630          * @return string the handle
631          */
632         public static function handle_from_contact($contact_id, $gcontact_id = 0) {
633                 $handle = False;
634
635                 logger("contact id is ".$contact_id." - gcontact id is ".$gcontact_id, LOGGER_DEBUG);
636
637                 if ($gcontact_id != 0) {
638                         $r = q("SELECT `addr` FROM `gcontact` WHERE `id` = %d AND `addr` != ''",
639                                 intval($gcontact_id));
640                         if ($r)
641                                 return $r[0]["addr"];
642                 }
643
644                 $r = q("SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
645                         intval($contact_id));
646                 if ($r) {
647                         $contact = $r[0];
648
649                         logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
650
651                         if($contact['addr'] != "")
652                                 $handle = $contact['addr'];
653                         else {
654                                 $baseurl_start = strpos($contact['url'],'://') + 3;
655                                 $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
656                                 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
657                                 $handle = $contact['nick'].'@'.$baseurl;
658                         }
659                 }
660
661                 return $handle;
662         }
663
664         /**
665          * @brief Get a contact id for a given handle
666          *
667          * @param int $uid The user id
668          * @param string $handle The handle in the format user@domain.tld
669          *
670          * @return The contact id
671          */
672         private function contact_by_handle($uid, $handle) {
673                 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
674                         intval($uid),
675                         dbesc($handle)
676                 );
677
678                 if ($r)
679                         return $r[0];
680
681                 $handle_parts = explode("@", $handle);
682                 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
683                 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
684                         dbesc(NETWORK_DFRN),
685                         intval($uid),
686                         dbesc($nurl_sql)
687                 );
688                 if($r)
689                         return $r[0];
690
691                 return false;
692         }
693
694         /**
695          * @brief Check if posting is allowed for this contact
696          *
697          * @param array $importer Array of the importer user
698          * @param array $contact The contact that is checked
699          * @param bool $is_comment Is the check for a comment?
700          *
701          * @return bool is the contact allowed to post?
702          */
703         private function post_allow($importer, $contact, $is_comment = false) {
704
705                 // perhaps we were already sharing with this person. Now they're sharing with us.
706                 // That makes us friends.
707                 // Normally this should have handled by getting a request - but this could get lost
708                 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
709                         q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
710                                 intval(CONTACT_IS_FRIEND),
711                                 intval($contact["id"]),
712                                 intval($importer["uid"])
713                         );
714                         $contact["rel"] = CONTACT_IS_FRIEND;
715                         logger("defining user ".$contact["nick"]." as friend");
716                 }
717
718                 if(($contact["blocked"]) || ($contact["readonly"]) || ($contact["archive"]))
719                         return false;
720                 if($contact["rel"] == CONTACT_IS_SHARING || $contact["rel"] == CONTACT_IS_FRIEND)
721                         return true;
722                 if($contact["rel"] == CONTACT_IS_FOLLOWER)
723                         if(($importer["page-flags"] == PAGE_COMMUNITY) OR $is_comment)
724                                 return true;
725
726                 // Messages for the global users are always accepted
727                 if ($importer["uid"] == 0)
728                         return true;
729
730                 return false;
731         }
732
733         /**
734          * @brief Fetches the contact id for a handle and checks if posting is allowed
735          *
736          * @param array $importer Array of the importer user
737          * @param string $handle The checked handle in the format user@domain.tld
738          * @param bool $is_comment Is the check for a comment?
739          *
740          * @return array The contact data
741          */
742         private function allowed_contact_by_handle($importer, $handle, $is_comment = false) {
743                 $contact = self::contact_by_handle($importer["uid"], $handle);
744                 if (!$contact) {
745                         logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
746                         return false;
747                 }
748
749                 if (!self::post_allow($importer, $contact, $is_comment)) {
750                         logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
751                         return false;
752                 }
753                 return $contact;
754         }
755
756         /**
757          * @brief Does the message already exists on the system?
758          *
759          * @param int $uid The user id
760          * @param string $guid The guid of the message
761          *
762          * @return int|bool message id if the message already was stored into the system - or false.
763          */
764         private function message_exists($uid, $guid) {
765                 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
766                         intval($uid),
767                         dbesc($guid)
768                 );
769
770                 if($r) {
771                         logger("message ".$guid." already exists for user ".$uid);
772                         return $r[0]["id"];
773                 }
774
775                 return false;
776         }
777
778         /**
779          * @brief Checks for links to posts in a message
780          *
781          * @param array $item The item array
782          */
783         private function fetch_guid($item) {
784                 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
785                         function ($match) use ($item){
786                                 return(self::fetch_guid_sub($match, $item));
787                         },$item["body"]);
788         }
789
790         /**
791          * @brief sub function of "fetch_guid" which checks for links in messages
792          *
793          * @param array $match array containing a link that has to be checked for a message link
794          * @param array $item The item array
795          */
796         private function fetch_guid_sub($match, $item) {
797                 if (!self::store_by_guid($match[1], $item["author-link"]))
798                         self::store_by_guid($match[1], $item["owner-link"]);
799         }
800
801         /**
802          * @brief Fetches an item with a given guid from a given server
803          *
804          * @param string $guid the message guid
805          * @param string $server The server address
806          * @param int $uid The user id of the user
807          *
808          * @return int the message id of the stored message or false
809          */
810         private function store_by_guid($guid, $server, $uid = 0) {
811                 $serverparts = parse_url($server);
812                 $server = $serverparts["scheme"]."://".$serverparts["host"];
813
814                 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
815
816                 $msg = self::message($guid, $server);
817
818                 if (!$msg)
819                         return false;
820
821                 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
822
823                 // Now call the dispatcher
824                 return self::dispatch_public($msg);
825         }
826
827         /**
828          * @brief Fetches a message from a server
829          *
830          * @param string $guid message guid
831          * @param string $server The url of the server
832          * @param int $level Endless loop prevention
833          *
834          * @return array
835          *      'message' => The message XML
836          *      'author' => The author handle
837          *      'key' => The public key of the author
838          */
839         private function message($guid, $server, $level = 0) {
840
841                 if ($level > 5)
842                         return false;
843
844                 // This will work for Diaspora and newer Friendica servers
845                 $source_url = $server."/p/".$guid.".xml";
846                 $x = fetch_url($source_url);
847                 if(!$x)
848                         return false;
849
850                 $source_xml = parse_xml_string($x, false);
851
852                 if (!is_object($source_xml))
853                         return false;
854
855                 if ($source_xml->post->reshare) {
856                         // Reshare of a reshare - old Diaspora version
857                         return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
858                 } elseif ($source_xml->getName() == "reshare") {
859                         // Reshare of a reshare - new Diaspora version
860                         return self::message($source_xml->root_guid, $server, ++$level);
861                 }
862
863                 $author = "";
864
865                 // Fetch the author - for the old and the new Diaspora version
866                 if ($source_xml->post->status_message->diaspora_handle)
867                         $author = (string)$source_xml->post->status_message->diaspora_handle;
868                 elseif ($source_xml->author AND ($source_xml->getName() == "status_message"))
869                         $author = (string)$source_xml->author;
870
871                 // If this isn't a "status_message" then quit
872                 if (!$author)
873                         return false;
874
875                 $msg = array("message" => $x, "author" => $author);
876
877                 $msg["key"] = self::key($msg["author"]);
878
879                 return $msg;
880         }
881
882         /**
883          * @brief Fetches the item record of a given guid
884          *
885          * @param int $uid The user id
886          * @param string $guid message guid
887          * @param string $author The handle of the item
888          * @param array $contact The contact of the item owner
889          *
890          * @return array the item record
891          */
892         private function parent_item($uid, $guid, $author, $contact) {
893                 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
894                                 `author-name`, `author-link`, `author-avatar`,
895                                 `owner-name`, `owner-link`, `owner-avatar`
896                         FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
897                         intval($uid), dbesc($guid));
898
899                 if(!$r) {
900                         $result = self::store_by_guid($guid, $contact["url"], $uid);
901
902                         if (!$result) {
903                                 $person = self::person_by_handle($author);
904                                 $result = self::store_by_guid($guid, $person["url"], $uid);
905                         }
906
907                         if ($result) {
908                                 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
909
910                                 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
911                                                 `author-name`, `author-link`, `author-avatar`,
912                                                 `owner-name`, `owner-link`, `owner-avatar`
913                                         FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
914                                         intval($uid), dbesc($guid));
915                         }
916                 }
917
918                 if (!$r) {
919                         logger("parent item not found: parent: ".$guid." - user: ".$uid);
920                         return false;
921                 } else {
922                         logger("parent item found: parent: ".$guid." - user: ".$uid);
923                         return $r[0];
924                 }
925         }
926
927         /**
928          * @brief returns contact details
929          *
930          * @param array $contact The default contact if the person isn't found
931          * @param array $person The record of the person
932          * @param int $uid The user id
933          *
934          * @return array
935          *      'cid' => contact id
936          *      'network' => network type
937          */
938         private function author_contact_by_url($contact, $person, $uid) {
939
940                 $r = q("SELECT `id`, `network` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
941                         dbesc(normalise_link($person["url"])), intval($uid));
942                 if ($r) {
943                         $cid = $r[0]["id"];
944                         $network = $r[0]["network"];
945                 } else {
946                         $cid = $contact["id"];
947                         $network = NETWORK_DIASPORA;
948                 }
949
950                 return (array("cid" => $cid, "network" => $network));
951         }
952
953         /**
954          * @brief Is the profile a hubzilla profile?
955          *
956          * @param string $url The profile link
957          *
958          * @return bool is it a hubzilla server?
959          */
960         public static function is_redmatrix($url) {
961                 return(strstr($url, "/channel/"));
962         }
963
964         /**
965          * @brief Generate a post link with a given handle and message guid
966          *
967          * @param string $addr The user handle
968          * @param string $guid message guid
969          *
970          * @return string the post link
971          */
972         private function plink($addr, $guid) {
973                 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
974
975                 // Fallback
976                 if (!$r)
977                         return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
978
979                 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
980                 // So we try another way as well.
981                 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
982                 if ($s)
983                         $r[0]["network"] = $s[0]["network"];
984
985                 if ($r[0]["network"] == NETWORK_DFRN)
986                         return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
987
988                 if (self::is_redmatrix($r[0]["url"]))
989                         return $r[0]["url"]."/?f=&mid=".$guid;
990
991                 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
992         }
993
994         /**
995          * @brief Processes an account deletion
996          *
997          * @param array $importer Array of the importer user
998          * @param object $data The message object
999          *
1000          * @return bool Success
1001          */
1002         private function receive_account_deletion($importer, $data) {
1003
1004                 /// @todo Account deletion should remove the contact from the global contacts as well
1005
1006                 $author = notags(unxmlify($data->author));
1007
1008                 $contact = self::contact_by_handle($importer["uid"], $author);
1009                 if (!$contact) {
1010                         logger("cannot find contact for author: ".$author);
1011                         return false;
1012                 }
1013
1014                 // We now remove the contact
1015                 contact_remove($contact["id"]);
1016                 return true;
1017         }
1018
1019         /**
1020          * @brief Processes an incoming comment
1021          *
1022          * @param array $importer Array of the importer user
1023          * @param string $sender The sender of the message
1024          * @param object $data The message object
1025          * @param string $xml The original XML of the message
1026          *
1027          * @return int The message id of the generated comment or "false" if there was an error
1028          */
1029         private function receive_comment($importer, $sender, $data, $xml) {
1030                 $guid = notags(unxmlify($data->guid));
1031                 $parent_guid = notags(unxmlify($data->parent_guid));
1032                 $text = unxmlify($data->text);
1033                 $author = notags(unxmlify($data->author));
1034
1035                 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1036                 if (!$contact)
1037                         return false;
1038
1039                 $message_id = self::message_exists($importer["uid"], $guid);
1040                 if ($message_id)
1041                         return $message_id;
1042
1043                 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1044                 if (!$parent_item)
1045                         return false;
1046
1047                 $person = self::person_by_handle($author);
1048                 if (!is_array($person)) {
1049                         logger("unable to find author details");
1050                         return false;
1051                 }
1052
1053                 // Fetch the contact id - if we know this contact
1054                 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1055
1056                 $datarray = array();
1057
1058                 $datarray["uid"] = $importer["uid"];
1059                 $datarray["contact-id"] = $author_contact["cid"];
1060                 $datarray["network"]  = $author_contact["network"];
1061
1062                 $datarray["author-name"] = $person["name"];
1063                 $datarray["author-link"] = $person["url"];
1064                 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1065
1066                 $datarray["owner-name"] = $contact["name"];
1067                 $datarray["owner-link"] = $contact["url"];
1068                 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1069
1070                 $datarray["guid"] = $guid;
1071                 $datarray["uri"] = $author.":".$guid;
1072
1073                 $datarray["type"] = "remote-comment";
1074                 $datarray["verb"] = ACTIVITY_POST;
1075                 $datarray["gravity"] = GRAVITY_COMMENT;
1076                 $datarray["parent-uri"] = $parent_item["uri"];
1077
1078                 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1079                 $datarray["object"] = $xml;
1080
1081                 $datarray["body"] = diaspora2bb($text);
1082
1083                 self::fetch_guid($datarray);
1084
1085                 $message_id = item_store($datarray);
1086
1087                 if ($message_id)
1088                         logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1089
1090                 // If we are the origin of the parent we store the original data and notify our followers
1091                 if($message_id AND $parent_item["origin"]) {
1092
1093                         // Formerly we stored the signed text, the signature and the author in different fields.
1094                         // We now store the raw data so that we are more flexible.
1095                         q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1096                                 intval($message_id),
1097                                 dbesc(json_encode($data))
1098                         );
1099
1100                         // notify others
1101                         proc_run("php", "include/notifier.php", "comment-import", $message_id);
1102                 }
1103
1104                 return $message_id;
1105         }
1106
1107         /**
1108          * @brief processes and stores private messages
1109          *
1110          * @param array $importer Array of the importer user
1111          * @param array $contact The contact of the message
1112          * @param object $data The message object
1113          * @param array $msg Array of the processed message, author handle and key
1114          * @param object $mesg The private message
1115          * @param array $conversation The conversation record to which this message belongs
1116          *
1117          * @return bool "true" if it was successful
1118          */
1119         private function receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation) {
1120                 $guid = notags(unxmlify($data->guid));
1121                 $subject = notags(unxmlify($data->subject));
1122                 $author = notags(unxmlify($data->author));
1123
1124                 $reply = 0;
1125
1126                 $msg_guid = notags(unxmlify($mesg->guid));
1127                 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1128                 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1129                 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1130                 $msg_text = unxmlify($mesg->text);
1131                 $msg_created_at = datetime_convert("UTC", "UTC", notags(unxmlify($mesg->created_at)));
1132
1133                 // "diaspora_handle" is the element name from the old version
1134                 // "author" is the element name from the new version
1135                 if ($mesg->author)
1136                         $msg_author = notags(unxmlify($mesg->author));
1137                 elseif ($mesg->diaspora_handle)
1138                         $msg_author = notags(unxmlify($mesg->diaspora_handle));
1139                 else
1140                         return false;
1141
1142                 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1143
1144                 if($msg_conversation_guid != $guid) {
1145                         logger("message conversation guid does not belong to the current conversation.");
1146                         return false;
1147                 }
1148
1149                 $body = diaspora2bb($msg_text);
1150                 $message_uri = $msg_author.":".$msg_guid;
1151
1152                 $author_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
1153
1154                 $author_signature = base64_decode($msg_author_signature);
1155
1156                 if(strcasecmp($msg_author,$msg["author"]) == 0) {
1157                         $person = $contact;
1158                         $key = $msg["key"];
1159                 } else {
1160                         $person = self::person_by_handle($msg_author);
1161
1162                         if (is_array($person) && x($person, "pubkey"))
1163                                 $key = $person["pubkey"];
1164                         else {
1165                                 logger("unable to find author details");
1166                                         return false;
1167                         }
1168                 }
1169
1170                 if (!rsa_verify($author_signed_data, $author_signature, $key, "sha256")) {
1171                         logger("verification failed.");
1172                         return false;
1173                 }
1174
1175                 if($msg_parent_author_signature) {
1176                         $owner_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
1177
1178                         $parent_author_signature = base64_decode($msg_parent_author_signature);
1179
1180                         $key = $msg["key"];
1181
1182                         if (!rsa_verify($owner_signed_data, $parent_author_signature, $key, "sha256")) {
1183                                 logger("owner verification failed.");
1184                                 return false;
1185                         }
1186                 }
1187
1188                 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' LIMIT 1",
1189                         dbesc($message_uri)
1190                 );
1191                 if($r) {
1192                         logger("duplicate message already delivered.", LOGGER_DEBUG);
1193                         return false;
1194                 }
1195
1196                 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1197                         VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1198                         intval($importer["uid"]),
1199                         dbesc($msg_guid),
1200                         intval($conversation["id"]),
1201                         dbesc($person["name"]),
1202                         dbesc($person["photo"]),
1203                         dbesc($person["url"]),
1204                         intval($contact["id"]),
1205                         dbesc($subject),
1206                         dbesc($body),
1207                         0,
1208                         0,
1209                         dbesc($message_uri),
1210                         dbesc($author.":".$guid),
1211                         dbesc($msg_created_at)
1212                 );
1213
1214                 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1215                         dbesc(datetime_convert()),
1216                         intval($conversation["id"])
1217                 );
1218
1219                 notification(array(
1220                         "type" => NOTIFY_MAIL,
1221                         "notify_flags" => $importer["notify-flags"],
1222                         "language" => $importer["language"],
1223                         "to_name" => $importer["username"],
1224                         "to_email" => $importer["email"],
1225                         "uid" =>$importer["uid"],
1226                         "item" => array("subject" => $subject, "body" => $body),
1227                         "source_name" => $person["name"],
1228                         "source_link" => $person["url"],
1229                         "source_photo" => $person["thumb"],
1230                         "verb" => ACTIVITY_POST,
1231                         "otype" => "mail"
1232                 ));
1233                 return true;
1234         }
1235
1236         /**
1237          * @brief Processes new private messages (answers to private messages are processed elsewhere)
1238          *
1239          * @param array $importer Array of the importer user
1240          * @param array $msg Array of the processed message, author handle and key
1241          * @param object $data The message object
1242          *
1243          * @return bool Success
1244          */
1245         private function receive_conversation($importer, $msg, $data) {
1246                 $guid = notags(unxmlify($data->guid));
1247                 $subject = notags(unxmlify($data->subject));
1248                 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1249                 $author = notags(unxmlify($data->author));
1250                 $participants = notags(unxmlify($data->participants));
1251
1252                 $messages = $data->message;
1253
1254                 if (!count($messages)) {
1255                         logger("empty conversation");
1256                         return false;
1257                 }
1258
1259                 $contact = self::allowed_contact_by_handle($importer, $msg["author"], true);
1260                 if (!$contact)
1261                         return false;
1262
1263                 $conversation = null;
1264
1265                 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1266                         intval($importer["uid"]),
1267                         dbesc($guid)
1268                 );
1269                 if($c)
1270                         $conversation = $c[0];
1271                 else {
1272                         $r = q("INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1273                                 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1274                                 intval($importer["uid"]),
1275                                 dbesc($guid),
1276                                 dbesc($author),
1277                                 dbesc(datetime_convert("UTC", "UTC", $created_at)),
1278                                 dbesc(datetime_convert()),
1279                                 dbesc($subject),
1280                                 dbesc($participants)
1281                         );
1282                         if($r)
1283                                 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1284                                         intval($importer["uid"]),
1285                                         dbesc($guid)
1286                                 );
1287
1288                         if($c)
1289                                 $conversation = $c[0];
1290                 }
1291                 if (!$conversation) {
1292                         logger("unable to create conversation.");
1293                         return;
1294                 }
1295
1296                 foreach($messages as $mesg)
1297                         self::receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation);
1298
1299                 return true;
1300         }
1301
1302         /**
1303          * @brief Creates the body for a "like" message
1304          *
1305          * @param array $contact The contact that send us the "like"
1306          * @param array $parent_item The item array of the parent item
1307          * @param string $guid message guid
1308          *
1309          * @return string the body
1310          */
1311         private function construct_like_body($contact, $parent_item, $guid) {
1312                 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1313
1314                 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1315                 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1316                 $plink = "[url=".App::get_baseurl()."/display/".urlencode($guid)."]".t("status")."[/url]";
1317
1318                 return sprintf($bodyverb, $ulink, $alink, $plink);
1319         }
1320
1321         /**
1322          * @brief Creates a XML object for a "like"
1323          *
1324          * @param array $importer Array of the importer user
1325          * @param array $parent_item The item array of the parent item
1326          *
1327          * @return string The XML
1328          */
1329         private function construct_like_object($importer, $parent_item) {
1330                 $objtype = ACTIVITY_OBJ_NOTE;
1331                 $link = '<link rel="alternate" type="text/html" href="'.App::get_baseurl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1332                 $parent_body = $parent_item["body"];
1333
1334                 $xmldata = array("object" => array("type" => $objtype,
1335                                                 "local" => "1",
1336                                                 "id" => $parent_item["uri"],
1337                                                 "link" => $link,
1338                                                 "title" => "",
1339                                                 "content" => $parent_body));
1340
1341                 return xml::from_array($xmldata, $xml, true);
1342         }
1343
1344         /**
1345          * @brief Processes "like" messages
1346          *
1347          * @param array $importer Array of the importer user
1348          * @param string $sender The sender of the message
1349          * @param object $data The message object
1350          *
1351          * @return int The message id of the generated like or "false" if there was an error
1352          */
1353         private function receive_like($importer, $sender, $data) {
1354                 $positive = notags(unxmlify($data->positive));
1355                 $guid = notags(unxmlify($data->guid));
1356                 $parent_type = notags(unxmlify($data->parent_type));
1357                 $parent_guid = notags(unxmlify($data->parent_guid));
1358                 $author = notags(unxmlify($data->author));
1359
1360                 // likes on comments aren't supported by Diaspora - only on posts
1361                 // But maybe this will be supported in the future, so we will accept it.
1362                 if (!in_array($parent_type, array("Post", "Comment")))
1363                         return false;
1364
1365                 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1366                 if (!$contact)
1367                         return false;
1368
1369                 $message_id = self::message_exists($importer["uid"], $guid);
1370                 if ($message_id)
1371                         return $message_id;
1372
1373                 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1374                 if (!$parent_item)
1375                         return false;
1376
1377                 $person = self::person_by_handle($author);
1378                 if (!is_array($person)) {
1379                         logger("unable to find author details");
1380                         return false;
1381                 }
1382
1383                 // Fetch the contact id - if we know this contact
1384                 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1385
1386                 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1387                 // We would accept this anyhow.
1388                 if ($positive == "true")
1389                         $verb = ACTIVITY_LIKE;
1390                 else
1391                         $verb = ACTIVITY_DISLIKE;
1392
1393                 $datarray = array();
1394
1395                 $datarray["uid"] = $importer["uid"];
1396                 $datarray["contact-id"] = $author_contact["cid"];
1397                 $datarray["network"]  = $author_contact["network"];
1398
1399                 $datarray["author-name"] = $person["name"];
1400                 $datarray["author-link"] = $person["url"];
1401                 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1402
1403                 $datarray["owner-name"] = $contact["name"];
1404                 $datarray["owner-link"] = $contact["url"];
1405                 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1406
1407                 $datarray["guid"] = $guid;
1408                 $datarray["uri"] = $author.":".$guid;
1409
1410                 $datarray["type"] = "activity";
1411                 $datarray["verb"] = $verb;
1412                 $datarray["gravity"] = GRAVITY_LIKE;
1413                 $datarray["parent-uri"] = $parent_item["uri"];
1414
1415                 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1416                 $datarray["object"] = self::construct_like_object($importer, $parent_item);
1417
1418                 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
1419
1420                 $message_id = item_store($datarray);
1421
1422                 if ($message_id)
1423                         logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1424
1425                 // If we are the origin of the parent we store the original data and notify our followers
1426                 if($message_id AND $parent_item["origin"]) {
1427
1428                         // Formerly we stored the signed text, the signature and the author in different fields.
1429                         // We now store the raw data so that we are more flexible.
1430                         q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1431                                 intval($message_id),
1432                                 dbesc(json_encode($data))
1433                         );
1434
1435                         // notify others
1436                         proc_run("php", "include/notifier.php", "comment-import", $message_id);
1437                 }
1438
1439                 return $message_id;
1440         }
1441
1442         /**
1443          * @brief Processes private messages
1444          *
1445          * @param array $importer Array of the importer user
1446          * @param object $data The message object
1447          *
1448          * @return bool Success?
1449          */
1450         private function receive_message($importer, $data) {
1451                 $guid = notags(unxmlify($data->guid));
1452                 $parent_guid = notags(unxmlify($data->parent_guid));
1453                 $text = unxmlify($data->text);
1454                 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1455                 $author = notags(unxmlify($data->author));
1456                 $conversation_guid = notags(unxmlify($data->conversation_guid));
1457
1458                 $contact = self::allowed_contact_by_handle($importer, $author, true);
1459                 if (!$contact)
1460                         return false;
1461
1462                 $conversation = null;
1463
1464                 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1465                         intval($importer["uid"]),
1466                         dbesc($conversation_guid)
1467                 );
1468                 if($c)
1469                         $conversation = $c[0];
1470                 else {
1471                         logger("conversation not available.");
1472                         return false;
1473                 }
1474
1475                 $reply = 0;
1476
1477                 $body = diaspora2bb($text);
1478                 $message_uri = $author.":".$guid;
1479
1480                 $person = self::person_by_handle($author);
1481                 if (!$person) {
1482                         logger("unable to find author details");
1483                         return false;
1484                 }
1485
1486                 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1487                         dbesc($message_uri),
1488                         intval($importer["uid"])
1489                 );
1490                 if($r) {
1491                         logger("duplicate message already delivered.", LOGGER_DEBUG);
1492                         return false;
1493                 }
1494
1495                 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1496                                 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1497                         intval($importer["uid"]),
1498                         dbesc($guid),
1499                         intval($conversation["id"]),
1500                         dbesc($person["name"]),
1501                         dbesc($person["photo"]),
1502                         dbesc($person["url"]),
1503                         intval($contact["id"]),
1504                         dbesc($conversation["subject"]),
1505                         dbesc($body),
1506                         0,
1507                         1,
1508                         dbesc($message_uri),
1509                         dbesc($author.":".$parent_guid),
1510                         dbesc($created_at)
1511                 );
1512
1513                 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1514                         dbesc(datetime_convert()),
1515                         intval($conversation["id"])
1516                 );
1517
1518                 return true;
1519         }
1520
1521         /**
1522          * @brief Processes participations - unsupported by now
1523          *
1524          * @param array $importer Array of the importer user
1525          * @param object $data The message object
1526          *
1527          * @return bool always true
1528          */
1529         private function receive_participation($importer, $data) {
1530                 // I'm not sure if we can fully support this message type
1531                 return true;
1532         }
1533
1534         /**
1535          * @brief Processes photos - unneeded
1536          *
1537          * @param array $importer Array of the importer user
1538          * @param object $data The message object
1539          *
1540          * @return bool always true
1541          */
1542         private function receive_photo($importer, $data) {
1543                 // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
1544                 return true;
1545         }
1546
1547         /**
1548          * @brief Processes poll participations - unssupported
1549          *
1550          * @param array $importer Array of the importer user
1551          * @param object $data The message object
1552          *
1553          * @return bool always true
1554          */
1555         private function receive_poll_participation($importer, $data) {
1556                 // We don't support polls by now
1557                 return true;
1558         }
1559
1560         /**
1561          * @brief Processes incoming profile updates
1562          *
1563          * @param array $importer Array of the importer user
1564          * @param object $data The message object
1565          *
1566          * @return bool Success
1567          */
1568         private function receive_profile($importer, $data) {
1569                 $author = notags(unxmlify($data->author));
1570
1571                 $contact = self::contact_by_handle($importer["uid"], $author);
1572                 if (!$contact)
1573                         return false;
1574
1575                 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
1576                 $image_url = unxmlify($data->image_url);
1577                 $birthday = unxmlify($data->birthday);
1578                 $location = diaspora2bb(unxmlify($data->location));
1579                 $about = diaspora2bb(unxmlify($data->bio));
1580                 $gender = unxmlify($data->gender);
1581                 $searchable = (unxmlify($data->searchable) == "true");
1582                 $nsfw = (unxmlify($data->nsfw) == "true");
1583                 $tags = unxmlify($data->tag_string);
1584
1585                 $tags = explode("#", $tags);
1586
1587                 $keywords = array();
1588                 foreach ($tags as $tag) {
1589                         $tag = trim(strtolower($tag));
1590                         if ($tag != "")
1591                                 $keywords[] = $tag;
1592                 }
1593
1594                 $keywords = implode(", ", $keywords);
1595
1596                 $handle_parts = explode("@", $author);
1597                 $nick = $handle_parts[0];
1598
1599                 if($name === "")
1600                         $name = $handle_parts[0];
1601
1602                 if( preg_match("|^https?://|", $image_url) === 0)
1603                         $image_url = "http://".$handle_parts[1].$image_url;
1604
1605                 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
1606
1607                 // Generic birthday. We don't know the timezone. The year is irrelevant.
1608
1609                 $birthday = str_replace("1000", "1901", $birthday);
1610
1611                 if ($birthday != "")
1612                         $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
1613
1614                 // this is to prevent multiple birthday notifications in a single year
1615                 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
1616
1617                 if(substr($birthday,5) === substr($contact["bd"],5))
1618                         $birthday = $contact["bd"];
1619
1620                 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
1621                                 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
1622                         dbesc($name),
1623                         dbesc($nick),
1624                         dbesc($author),
1625                         dbesc(datetime_convert()),
1626                         dbesc($birthday),
1627                         dbesc($location),
1628                         dbesc($about),
1629                         dbesc($keywords),
1630                         dbesc($gender),
1631                         intval($contact["id"]),
1632                         intval($importer["uid"])
1633                 );
1634
1635                 if ($searchable) {
1636                         poco_check($contact["url"], $name, NETWORK_DIASPORA, $image_url, $about, $location, $gender, $keywords, "",
1637                                 datetime_convert(), 2, $contact["id"], $importer["uid"]);
1638                 }
1639
1640                 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
1641                                         "photo" => $image_url, "name" => $name, "location" => $location,
1642                                         "about" => $about, "birthday" => $birthday, "gender" => $gender,
1643                                         "addr" => $author, "nick" => $nick, "keywords" => $keywords,
1644                                         "hide" => !$searchable, "nsfw" => $nsfw);
1645
1646                 update_gcontact($gcontact);
1647
1648                 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
1649
1650                 return true;
1651         }
1652
1653         /**
1654          * @brief Processes incoming friend requests
1655          *
1656          * @param array $importer Array of the importer user
1657          * @param array $contact The contact that send the request
1658          */
1659         private function receive_request_make_friend($importer, $contact) {
1660
1661                 $a = get_app();
1662
1663                 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1664                         q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
1665                                 intval(CONTACT_IS_FRIEND),
1666                                 intval($contact["id"]),
1667                                 intval($importer["uid"])
1668                         );
1669                 }
1670                 // send notification
1671
1672                 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
1673                         intval($importer["uid"])
1674                 );
1675
1676                 if($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(get_pconfig($importer["uid"], "system", "post_newfriend"))) {
1677
1678                         $self = q("SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
1679                                 intval($importer["uid"])
1680                         );
1681
1682                         // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
1683
1684                         if($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
1685
1686                                 $arr = array();
1687                                 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
1688                                 $arr["uid"] = $importer["uid"];
1689                                 $arr["contact-id"] = $self[0]["id"];
1690                                 $arr["wall"] = 1;
1691                                 $arr["type"] = 'wall';
1692                                 $arr["gravity"] = 0;
1693                                 $arr["origin"] = 1;
1694                                 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
1695                                 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
1696                                 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
1697                                 $arr["verb"] = ACTIVITY_FRIEND;
1698                                 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
1699
1700                                 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
1701                                 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1702                                 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
1703                                 $arr["body"] = sprintf(t("%1$s is now friends with %2$s"), $A, $B)."\n\n\n".$Bphoto;
1704
1705                                 $arr["object"] = self::construct_new_friend_object($contact);
1706
1707                                 $arr["last-child"] = 1;
1708
1709                                 $arr["allow_cid"] = $user[0]["allow_cid"];
1710                                 $arr["allow_gid"] = $user[0]["allow_gid"];
1711                                 $arr["deny_cid"]  = $user[0]["deny_cid"];
1712                                 $arr["deny_gid"]  = $user[0]["deny_gid"];
1713
1714                                 $i = item_store($arr);
1715                                 if($i)
1716                                         proc_run("php", "include/notifier.php", "activity", $i);
1717                         }
1718                 }
1719         }
1720
1721         /**
1722          * @brief Creates a XML object for a "new friend" message
1723          *
1724          * @param array $contact Array of the contact
1725          *
1726          * @return string The XML
1727          */
1728         private function construct_new_friend_object($contact) {
1729                 $objtype = ACTIVITY_OBJ_PERSON;
1730                 $link = '<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n".
1731                         '<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n";
1732
1733                 $xmldata = array("object" => array("type" => $objtype,
1734                                                 "title" => $contact["name"],
1735                                                 "id" => $contact["url"]."/".$contact["name"],
1736                                                 "link" => $link));
1737
1738                 return xml::from_array($xmldata, $xml, true);
1739         }
1740
1741         /**
1742          * @brief Processes incoming sharing notification
1743          *
1744          * @param array $importer Array of the importer user
1745          * @param object $data The message object
1746          *
1747          * @return bool Success
1748          */
1749         private function receive_contact_request($importer, $data) {
1750                 $author = unxmlify($data->author);
1751                 $recipient = unxmlify($data->recipient);
1752
1753                 if (!$author || !$recipient)
1754                         return false;
1755
1756                 // the current protocol version doesn't know these fields
1757                 // That means that we will assume their existance
1758                 if (isset($data->following))
1759                         $following = (unxmlify($data->following) == "true");
1760                 else
1761                         $following = true;
1762
1763                 if (isset($data->sharing))
1764                         $sharing = (unxmlify($data->sharing) == "true");
1765                 else
1766                         $sharing = true;
1767
1768                 $contact = self::contact_by_handle($importer["uid"],$author);
1769
1770                 // perhaps we were already sharing with this person. Now they're sharing with us.
1771                 // That makes us friends.
1772                 if ($contact) {
1773                         if ($following AND $sharing) {
1774                                 self::receive_request_make_friend($importer, $contact);
1775                                 return true;
1776                         } else /// @todo Handle all possible variations of adding and retracting of permissions
1777                                 return false;
1778                 }
1779
1780                 if (!$following AND $sharing AND in_array($importer["page-flags"], array(PAGE_SOAPBOX, PAGE_NORMAL))) {
1781                         logger("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", LOGGER_DEBUG);
1782                         return false;
1783                 } elseif (!$following AND !$sharing) {
1784                         logger("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", LOGGER_DEBUG);
1785                         return false;
1786                 }
1787
1788                 $ret = self::person_by_handle($author);
1789
1790                 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
1791                         logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
1792                         return false;
1793                 }
1794
1795                 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
1796
1797                 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
1798                         VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
1799                         intval($importer["uid"]),
1800                         dbesc($ret["network"]),
1801                         dbesc($ret["addr"]),
1802                         datetime_convert(),
1803                         dbesc($ret["url"]),
1804                         dbesc(normalise_link($ret["url"])),
1805                         dbesc($batch),
1806                         dbesc($ret["name"]),
1807                         dbesc($ret["nick"]),
1808                         dbesc($ret["photo"]),
1809                         dbesc($ret["pubkey"]),
1810                         dbesc($ret["notify"]),
1811                         dbesc($ret["poll"]),
1812                         1,
1813                         2
1814                 );
1815
1816                 // find the contact record we just created
1817
1818                 $contact_record = self::contact_by_handle($importer["uid"],$author);
1819
1820                 if (!$contact_record) {
1821                         logger("unable to locate newly created contact record.");
1822                         return;
1823                 }
1824
1825                 $def_gid = get_default_group($importer['uid'], $ret["network"]);
1826
1827                 if(intval($def_gid))
1828                         group_add_member($importer["uid"], "", $contact_record["id"], $def_gid);
1829
1830                 if($importer["page-flags"] == PAGE_NORMAL) {
1831
1832                         $hash = random_string().(string)time();   // Generate a confirm_key
1833
1834                         $ret = q("INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
1835                                 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
1836                                 intval($importer["uid"]),
1837                                 intval($contact_record["id"]),
1838                                 0,
1839                                 0,
1840                                 dbesc(t("Sharing notification from Diaspora network")),
1841                                 dbesc($hash),
1842                                 dbesc(datetime_convert())
1843                         );
1844                 } else {
1845
1846                         // automatic friend approval
1847
1848                         update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
1849
1850                         // technically they are sharing with us (CONTACT_IS_SHARING),
1851                         // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
1852                         // we are going to change the relationship and make them a follower.
1853
1854                         if (($importer["page-flags"] == PAGE_FREELOVE) AND $sharing AND $following)
1855                                 $new_relation = CONTACT_IS_FRIEND;
1856                         elseif (($importer["page-flags"] == PAGE_FREELOVE) AND $sharing)
1857                                 $new_relation = CONTACT_IS_SHARING;
1858                         else
1859                                 $new_relation = CONTACT_IS_FOLLOWER;
1860
1861                         $r = q("UPDATE `contact` SET `rel` = %d,
1862                                 `name-date` = '%s',
1863                                 `uri-date` = '%s',
1864                                 `blocked` = 0,
1865                                 `pending` = 0,
1866                                 `writable` = 1
1867                                 WHERE `id` = %d
1868                                 ",
1869                                 intval($new_relation),
1870                                 dbesc(datetime_convert()),
1871                                 dbesc(datetime_convert()),
1872                                 intval($contact_record["id"])
1873                         );
1874
1875                         $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
1876                         if($u)
1877                                 $ret = self::send_share($u[0], $contact_record);
1878                 }
1879
1880                 return true;
1881         }
1882
1883         /**
1884          * @brief Fetches a message with a given guid
1885          *
1886          * @param string $guid message guid
1887          * @param string $orig_author handle of the original post
1888          * @param string $author handle of the sharer
1889          *
1890          * @return array The fetched item
1891          */
1892         private function original_item($guid, $orig_author, $author) {
1893
1894                 // Do we already have this item?
1895                 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1896                                 `author-name`, `author-link`, `author-avatar`
1897                                 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1898                         dbesc($guid));
1899
1900                 if($r) {
1901                         logger("reshared message ".$guid." already exists on system.");
1902
1903                         // Maybe it is already a reshared item?
1904                         // Then refetch the content, if it is a reshare from a reshare.
1905                         // If it is a reshared post from another network then reformat to avoid display problems with two share elements
1906                         if (self::is_reshare($r[0]["body"], true))
1907                                 $r = array();
1908                         elseif (self::is_reshare($r[0]["body"], false)) {
1909                                 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
1910
1911                                 // Add OEmbed and other information to the body
1912                                 $r[0]["body"] = add_page_info_to_body($r[0]["body"], false, true);
1913
1914                                 return $r[0];
1915                         } else
1916                                 return $r[0];
1917                 }
1918
1919                 if (!$r) {
1920                         $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
1921                         logger("1st try: reshared message ".$guid." will be fetched from original server: ".$server);
1922                         $item_id = self::store_by_guid($guid, $server);
1923
1924                         if (!$item_id) {
1925                                 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
1926                                 logger("2nd try: reshared message ".$guid." will be fetched from original server: ".$server);
1927                                 $item_id = self::store_by_guid($guid, $server);
1928                         }
1929
1930                         // Deactivated by now since there is a risk that someone could manipulate postings through this method
1931 /*                      if (!$item_id) {
1932                                 $server = "https://".substr($author, strpos($author, "@") + 1);
1933                                 logger("3rd try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1934                                 $item_id = self::store_by_guid($guid, $server);
1935                         }
1936                         if (!$item_id) {
1937                                 $server = "http://".substr($author, strpos($author, "@") + 1);
1938                                 logger("4th try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1939                                 $item_id = self::store_by_guid($guid, $server);
1940                         }
1941 */
1942                         if ($item_id) {
1943                                 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1944                                                 `author-name`, `author-link`, `author-avatar`
1945                                         FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1946                                         intval($item_id));
1947
1948                                 if ($r)
1949                                         return $r[0];
1950
1951                         }
1952                 }
1953                 return false;
1954         }
1955
1956         /**
1957          * @brief Processes a reshare message
1958          *
1959          * @param array $importer Array of the importer user
1960          * @param object $data The message object
1961          * @param string $xml The original XML of the message
1962          *
1963          * @return int the message id
1964          */
1965         private function receive_reshare($importer, $data, $xml) {
1966                 $root_author = notags(unxmlify($data->root_author));
1967                 $root_guid = notags(unxmlify($data->root_guid));
1968                 $guid = notags(unxmlify($data->guid));
1969                 $author = notags(unxmlify($data->author));
1970                 $public = notags(unxmlify($data->public));
1971                 $created_at = notags(unxmlify($data->created_at));
1972
1973                 $contact = self::allowed_contact_by_handle($importer, $author, false);
1974                 if (!$contact)
1975                         return false;
1976
1977                 $message_id = self::message_exists($importer["uid"], $guid);
1978                 if ($message_id)
1979                         return $message_id;
1980
1981                 $original_item = self::original_item($root_guid, $root_author, $author);
1982                 if (!$original_item)
1983                         return false;
1984
1985                 $orig_url = App::get_baseurl()."/display/".$original_item["guid"];
1986
1987                 $datarray = array();
1988
1989                 $datarray["uid"] = $importer["uid"];
1990                 $datarray["contact-id"] = $contact["id"];
1991                 $datarray["network"]  = NETWORK_DIASPORA;
1992
1993                 $datarray["author-name"] = $contact["name"];
1994                 $datarray["author-link"] = $contact["url"];
1995                 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1996
1997                 $datarray["owner-name"] = $datarray["author-name"];
1998                 $datarray["owner-link"] = $datarray["author-link"];
1999                 $datarray["owner-avatar"] = $datarray["author-avatar"];
2000
2001                 $datarray["guid"] = $guid;
2002                 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
2003
2004                 $datarray["verb"] = ACTIVITY_POST;
2005                 $datarray["gravity"] = GRAVITY_PARENT;
2006
2007                 $datarray["object"] = $xml;
2008
2009                 $prefix = share_header($original_item["author-name"], $original_item["author-link"], $original_item["author-avatar"],
2010                                         $original_item["guid"], $original_item["created"], $orig_url);
2011                 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2012
2013                 $datarray["tag"] = $original_item["tag"];
2014                 $datarray["app"]  = $original_item["app"];
2015
2016                 $datarray["plink"] = self::plink($author, $guid);
2017                 $datarray["private"] = (($public == "false") ? 1 : 0);
2018                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
2019
2020                 $datarray["object-type"] = $original_item["object-type"];
2021
2022                 self::fetch_guid($datarray);
2023                 $message_id = item_store($datarray);
2024
2025                 if ($message_id)
2026                         logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2027
2028                 return $message_id;
2029         }
2030
2031         /**
2032          * @brief Processes retractions
2033          *
2034          * @param array $importer Array of the importer user
2035          * @param array $contact The contact of the item owner
2036          * @param object $data The message object
2037          *
2038          * @return bool success
2039          */
2040         private function item_retraction($importer, $contact, $data) {
2041                 $target_type = notags(unxmlify($data->target_type));
2042                 $target_guid = notags(unxmlify($data->target_guid));
2043                 $author = notags(unxmlify($data->author));
2044
2045                 $person = self::person_by_handle($author);
2046                 if (!is_array($person)) {
2047                         logger("unable to find author detail for ".$author);
2048                         return false;
2049                 }
2050
2051                 $r = q("SELECT `id`, `parent`, `parent-uri`, `author-link` FROM `item` WHERE `guid` = '%s' AND `uid` = %d AND NOT `file` LIKE '%%[%%' LIMIT 1",
2052                         dbesc($target_guid),
2053                         intval($importer["uid"])
2054                 );
2055                 if (!$r)
2056                         return false;
2057
2058                 // Only delete it if the author really fits
2059                 if (!link_compare($r[0]["author-link"], $person["url"])) {
2060                         logger("Item author ".$r[0]["author-link"]." doesn't fit to expected contact ".$person["url"], LOGGER_DEBUG);
2061                         return false;
2062                 }
2063
2064                 // Check if the sender is the thread owner
2065                 $p = q("SELECT `id`, `author-link`, `origin` FROM `item` WHERE `id` = %d",
2066                         intval($r[0]["parent"]));
2067
2068                 // Only delete it if the parent author really fits
2069                 if (!link_compare($p[0]["author-link"], $contact["url"]) AND !link_compare($r[0]["author-link"], $contact["url"])) {
2070                         logger("Thread author ".$p[0]["author-link"]." and item author ".$r[0]["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2071                         return false;
2072                 }
2073
2074                 // Currently we don't have a central deletion function that we could use in this case. The function "item_drop" doesn't work for that case
2075                 q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' WHERE `id` = %d",
2076                         dbesc(datetime_convert()),
2077                         dbesc(datetime_convert()),
2078                         intval($r[0]["id"])
2079                 );
2080                 delete_thread($r[0]["id"], $r[0]["parent-uri"]);
2081
2082                 logger("Deleted target ".$target_guid." (".$r[0]["id"].") from user ".$importer["uid"]." parent: ".$p[0]["id"], LOGGER_DEBUG);
2083
2084                 // Now check if the retraction needs to be relayed by us
2085                 if($p[0]["origin"]) {
2086                         // notify others
2087                         proc_run("php", "include/notifier.php", "drop", $r[0]["id"]);
2088                 }
2089
2090                 return true;
2091         }
2092
2093         /**
2094          * @brief Receives retraction messages
2095          *
2096          * @param array $importer Array of the importer user
2097          * @param string $sender The sender of the message
2098          * @param object $data The message object
2099          *
2100          * @return bool Success
2101          */
2102         private function receive_retraction($importer, $sender, $data) {
2103                 $target_type = notags(unxmlify($data->target_type));
2104
2105                 $contact = self::contact_by_handle($importer["uid"], $sender);
2106                 if (!$contact) {
2107                         logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2108                         return false;
2109                 }
2110
2111                 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2112
2113                 switch ($target_type) {
2114                         case "Comment":
2115                         case "Like":
2116                         case "Post": // "Post" will be supported in a future version
2117                         case "Reshare":
2118                         case "StatusMessage":
2119                                 return self::item_retraction($importer, $contact, $data);;
2120
2121                         case "Contact":
2122                         case "Person":
2123                                 /// @todo What should we do with an "unshare"?
2124                                 // Removing the contact isn't correct since we still can read the public items
2125                                 contact_remove($contact["id"]);
2126                                 return true;
2127
2128                         default:
2129                                 logger("Unknown target type ".$target_type);
2130                                 return false;
2131                 }
2132                 return true;
2133         }
2134
2135         /**
2136          * @brief Receives status messages
2137          *
2138          * @param array $importer Array of the importer user
2139          * @param object $data The message object
2140          * @param string $xml The original XML of the message
2141          *
2142          * @return int The message id of the newly created item
2143          */
2144         private function receive_status_message($importer, $data, $xml) {
2145
2146                 $raw_message = unxmlify($data->raw_message);
2147                 $guid = notags(unxmlify($data->guid));
2148                 $author = notags(unxmlify($data->author));
2149                 $public = notags(unxmlify($data->public));
2150                 $created_at = notags(unxmlify($data->created_at));
2151                 $provider_display_name = notags(unxmlify($data->provider_display_name));
2152
2153                 /// @todo enable support for polls
2154                 //if ($data->poll) {
2155                 //      foreach ($data->poll AS $poll)
2156                 //              print_r($poll);
2157                 //      die("poll!\n");
2158                 //}
2159                 $contact = self::allowed_contact_by_handle($importer, $author, false);
2160                 if (!$contact)
2161                         return false;
2162
2163                 $message_id = self::message_exists($importer["uid"], $guid);
2164                 if ($message_id)
2165                         return $message_id;
2166
2167                 $address = array();
2168                 if ($data->location)
2169                         foreach ($data->location->children() AS $fieldname => $data)
2170                                 $address[$fieldname] = notags(unxmlify($data));
2171
2172                 $body = diaspora2bb($raw_message);
2173
2174                 $datarray = array();
2175
2176                 // Attach embedded pictures to the body
2177                 if ($data->photo) {
2178                         foreach ($data->photo AS $photo)
2179                                 $body = "[img]".unxmlify($photo->remote_photo_path).
2180                                         unxmlify($photo->remote_photo_name)."[/img]\n".$body;
2181
2182                         $datarray["object-type"] = ACTIVITY_OBJ_PHOTO;
2183                 } else {
2184                         $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2185
2186                         // Add OEmbed and other information to the body
2187                         if (!self::is_redmatrix($contact["url"]))
2188                                 $body = add_page_info_to_body($body, false, true);
2189                 }
2190
2191                 $datarray["uid"] = $importer["uid"];
2192                 $datarray["contact-id"] = $contact["id"];
2193                 $datarray["network"] = NETWORK_DIASPORA;
2194
2195                 $datarray["author-name"] = $contact["name"];
2196                 $datarray["author-link"] = $contact["url"];
2197                 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2198
2199                 $datarray["owner-name"] = $datarray["author-name"];
2200                 $datarray["owner-link"] = $datarray["author-link"];
2201                 $datarray["owner-avatar"] = $datarray["author-avatar"];
2202
2203                 $datarray["guid"] = $guid;
2204                 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
2205
2206                 $datarray["verb"] = ACTIVITY_POST;
2207                 $datarray["gravity"] = GRAVITY_PARENT;
2208
2209                 $datarray["object"] = $xml;
2210
2211                 $datarray["body"] = $body;
2212
2213                 if ($provider_display_name != "")
2214                         $datarray["app"] = $provider_display_name;
2215
2216                 $datarray["plink"] = self::plink($author, $guid);
2217                 $datarray["private"] = (($public == "false") ? 1 : 0);
2218                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
2219
2220                 if (isset($address["address"]))
2221                         $datarray["location"] = $address["address"];
2222
2223                 if (isset($address["lat"]) AND isset($address["lng"]))
2224                         $datarray["coord"] = $address["lat"]." ".$address["lng"];
2225
2226                 self::fetch_guid($datarray);
2227                 $message_id = item_store($datarray);
2228
2229                 if ($message_id)
2230                         logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2231
2232                 return $message_id;
2233         }
2234
2235         /* ************************************************************************************** *
2236          * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2237          * ************************************************************************************** */
2238
2239         /**
2240          * @brief returnes the handle of a contact
2241          *
2242          * @param array $me contact array
2243          *
2244          * @return string the handle in the format user@domain.tld
2245          */
2246         private function my_handle($contact) {
2247                 if ($contact["addr"] != "")
2248                         return $contact["addr"];
2249
2250                 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2251                 // So - just in case - we build the the address here.
2252                 if ($contact["nickname"] != "")
2253                         $nick = $contact["nickname"];
2254                 else
2255                         $nick = $contact["nick"];
2256
2257                 return $nick."@".substr(App::get_baseurl(), strpos(App::get_baseurl(),"://") + 3);
2258         }
2259
2260         /**
2261          * @brief Creates the envelope for a public message
2262          *
2263          * @param string $msg The message that is to be transmitted
2264          * @param array $user The record of the sender
2265          * @param array $contact Target of the communication
2266          * @param string $prvkey The private key of the sender
2267          * @param string $pubkey The public key of the receiver
2268          *
2269          * @return string The envelope
2270          */
2271         private function build_public_message($msg, $user, $contact, $prvkey, $pubkey) {
2272
2273                 logger("Message: ".$msg, LOGGER_DATA);
2274
2275                 $handle = self::my_handle($user);
2276
2277                 $b64url_data = base64url_encode($msg);
2278
2279                 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2280
2281                 $type = "application/xml";
2282                 $encoding = "base64url";
2283                 $alg = "RSA-SHA256";
2284
2285                 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2286
2287                 $signature = rsa_sign($signable_data,$prvkey);
2288                 $sig = base64url_encode($signature);
2289
2290                 $xmldata = array("diaspora" => array("header" => array("author_id" => $handle),
2291                                                 "me:env" => array("me:encoding" => "base64url",
2292                                                                 "me:alg" => "RSA-SHA256",
2293                                                                 "me:data" => $data,
2294                                                                 "@attributes" => array("type" => "application/xml"),
2295                                                                 "me:sig" => $sig)));
2296
2297                 $namespaces = array("" => "https://joindiaspora.com/protocol",
2298                                 "me" => "http://salmon-protocol.org/ns/magic-env");
2299
2300                 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2301
2302                 logger("magic_env: ".$magic_env, LOGGER_DATA);
2303                 return $magic_env;
2304         }
2305
2306         /**
2307          * @brief Creates the envelope for a private message
2308          *
2309          * @param string $msg The message that is to be transmitted
2310          * @param array $user The record of the sender
2311          * @param array $contact Target of the communication
2312          * @param string $prvkey The private key of the sender
2313          * @param string $pubkey The public key of the receiver
2314          *
2315          * @return string The envelope
2316          */
2317         private function build_private_message($msg, $user, $contact, $prvkey, $pubkey) {
2318
2319                 logger("Message: ".$msg, LOGGER_DATA);
2320
2321                 // without a public key nothing will work
2322
2323                 if (!$pubkey) {
2324                         logger("pubkey missing: contact id: ".$contact["id"]);
2325                         return false;
2326                 }
2327
2328                 $inner_aes_key = random_string(32);
2329                 $b_inner_aes_key = base64_encode($inner_aes_key);
2330                 $inner_iv = random_string(16);
2331                 $b_inner_iv = base64_encode($inner_iv);
2332
2333                 $outer_aes_key = random_string(32);
2334                 $b_outer_aes_key = base64_encode($outer_aes_key);
2335                 $outer_iv = random_string(16);
2336                 $b_outer_iv = base64_encode($outer_iv);
2337
2338                 $handle = self::my_handle($user);
2339
2340                 $padded_data = pkcs5_pad($msg,16);
2341                 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
2342
2343                 $b64_data = base64_encode($inner_encrypted);
2344
2345
2346                 $b64url_data = base64url_encode($b64_data);
2347                 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2348
2349                 $type = "application/xml";
2350                 $encoding = "base64url";
2351                 $alg = "RSA-SHA256";
2352
2353                 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2354
2355                 $signature = rsa_sign($signable_data,$prvkey);
2356                 $sig = base64url_encode($signature);
2357
2358                 $xmldata = array("decrypted_header" => array("iv" => $b_inner_iv,
2359                                                         "aes_key" => $b_inner_aes_key,
2360                                                         "author_id" => $handle));
2361
2362                 $decrypted_header = xml::from_array($xmldata, $xml, true);
2363                 $decrypted_header = pkcs5_pad($decrypted_header,16);
2364
2365                 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
2366
2367                 $outer_json = json_encode(array("iv" => $b_outer_iv, "key" => $b_outer_aes_key));
2368
2369                 $encrypted_outer_key_bundle = "";
2370                 openssl_public_encrypt($outer_json, $encrypted_outer_key_bundle, $pubkey);
2371
2372                 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
2373
2374                 logger("outer_bundle: ".$b64_encrypted_outer_key_bundle." key: ".$pubkey, LOGGER_DATA);
2375
2376                 $encrypted_header_json_object = json_encode(array("aes_key" => base64_encode($encrypted_outer_key_bundle),
2377                                                                 "ciphertext" => base64_encode($ciphertext)));
2378                 $cipher_json = base64_encode($encrypted_header_json_object);
2379
2380                 $xmldata = array("diaspora" => array("encrypted_header" => $cipher_json,
2381                                                 "me:env" => array("me:encoding" => "base64url",
2382                                                                 "me:alg" => "RSA-SHA256",
2383                                                                 "me:data" => $data,
2384                                                                 "@attributes" => array("type" => "application/xml"),
2385                                                                 "me:sig" => $sig)));
2386
2387                 $namespaces = array("" => "https://joindiaspora.com/protocol",
2388                                 "me" => "http://salmon-protocol.org/ns/magic-env");
2389
2390                 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2391
2392                 logger("magic_env: ".$magic_env, LOGGER_DATA);
2393                 return $magic_env;
2394         }
2395
2396         /**
2397          * @brief Create the envelope for a message
2398          *
2399          * @param string $msg The message that is to be transmitted
2400          * @param array $user The record of the sender
2401          * @param array $contact Target of the communication
2402          * @param string $prvkey The private key of the sender
2403          * @param string $pubkey The public key of the receiver
2404          * @param bool $public Is the message public?
2405          *
2406          * @return string The message that will be transmitted to other servers
2407          */
2408         private function build_message($msg, $user, $contact, $prvkey, $pubkey, $public = false) {
2409
2410                 if ($public)
2411                         $magic_env =  self::build_public_message($msg,$user,$contact,$prvkey,$pubkey);
2412                 else
2413                         $magic_env =  self::build_private_message($msg,$user,$contact,$prvkey,$pubkey);
2414
2415                 // The data that will be transmitted is double encoded via "urlencode", strange ...
2416                 $slap = "xml=".urlencode(urlencode($magic_env));
2417                 return $slap;
2418         }
2419
2420         /**
2421          * @brief Creates a signature for a message
2422          *
2423          * @param array $owner the array of the owner of the message
2424          * @param array $message The message that is to be signed
2425          *
2426          * @return string The signature
2427          */
2428         private function signature($owner, $message) {
2429                 $sigmsg = $message;
2430                 unset($sigmsg["author_signature"]);
2431                 unset($sigmsg["parent_author_signature"]);
2432
2433                 $signed_text = implode(";", $sigmsg);
2434
2435                 return base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2436         }
2437
2438         /**
2439          * @brief Transmit a message to a target server
2440          *
2441          * @param array $owner the array of the item owner
2442          * @param array $contact Target of the communication
2443          * @param string $slap The message that is to be transmitted
2444          * @param bool $public_batch Is it a public post?
2445          * @param bool $queue_run Is the transmission called from the queue?
2446          * @param string $guid message guid
2447          *
2448          * @return int Result of the transmission
2449          */
2450         public static function transmit($owner, $contact, $slap, $public_batch, $queue_run=false, $guid = "") {
2451
2452                 $a = get_app();
2453
2454                 $enabled = intval(get_config("system", "diaspora_enabled"));
2455                 if(!$enabled)
2456                         return 200;
2457
2458                 $logid = random_string(4);
2459                 $dest_url = (($public_batch) ? $contact["batch"] : $contact["notify"]);
2460                 if (!$dest_url) {
2461                         logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
2462                         return 0;
2463                 }
2464
2465                 logger("transmit: ".$logid."-".$guid." ".$dest_url);
2466
2467                 if (!$queue_run && was_recently_delayed($contact["id"])) {
2468                         $return_code = 0;
2469                 } else {
2470                         if (!intval(get_config("system", "diaspora_test"))) {
2471                                 post_url($dest_url."/", $slap);
2472                                 $return_code = $a->get_curl_code();
2473                         } else {
2474                                 logger("test_mode");
2475                                 return 200;
2476                         }
2477                 }
2478
2479                 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
2480
2481                 if(!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
2482                         logger("queue message");
2483
2484                         $r = q("SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
2485                                 intval($contact["id"]),
2486                                 dbesc(NETWORK_DIASPORA),
2487                                 dbesc($slap),
2488                                 intval($public_batch)
2489                         );
2490                         if($r) {
2491                                 logger("add_to_queue ignored - identical item already in queue");
2492                         } else {
2493                                 // queue message for redelivery
2494                                 add_to_queue($contact["id"], NETWORK_DIASPORA, $slap, $public_batch);
2495                         }
2496                 }
2497
2498                 return(($return_code) ? $return_code : (-1));
2499         }
2500
2501
2502         /**
2503          * @brief Builds and transmit messages
2504          *
2505          * @param array $owner the array of the item owner
2506          * @param array $contact Target of the communication
2507          * @param string $type The message type
2508          * @param array $message The message data
2509          * @param bool $public_batch Is it a public post?
2510          * @param string $guid message guid
2511          * @param bool $spool Should the transmission be spooled or transmitted?
2512          *
2513          * @return int Result of the transmission
2514          */
2515         private function build_and_transmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false) {
2516
2517                 $data = array("XML" => array("post" => array($type => $message)));
2518
2519                 $msg = xml::from_array($data, $xml);
2520
2521                 logger('message: '.$msg, LOGGER_DATA);
2522                 logger('send guid '.$guid, LOGGER_DEBUG);
2523
2524                 $slap = self::build_message($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
2525
2526                 if ($spool) {
2527                         add_to_queue($contact['id'], NETWORK_DIASPORA, $slap, $public_batch);
2528                         return true;
2529                 } else
2530                         $return_code = self::transmit($owner, $contact, $slap, $public_batch, false, $guid);
2531
2532                 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
2533
2534                 return $return_code;
2535         }
2536
2537         /**
2538          * @brief Sends a "share" message
2539          *
2540          * @param array $owner the array of the item owner
2541          * @param array $contact Target of the communication
2542          *
2543          * @return int The result of the transmission
2544          */
2545         public static function send_share($owner,$contact) {
2546
2547                 $message = array("sender_handle" => self::my_handle($owner),
2548                                 "recipient_handle" => $contact["addr"]);
2549
2550                 return self::build_and_transmit($owner, $contact, "request", $message);
2551         }
2552
2553         /**
2554          * @brief sends an "unshare"
2555          *
2556          * @param array $owner the array of the item owner
2557          * @param array $contact Target of the communication
2558          *
2559          * @return int The result of the transmission
2560          */
2561         public static function send_unshare($owner,$contact) {
2562
2563                 $message = array("post_guid" => $owner["guid"],
2564                                 "diaspora_handle" => self::my_handle($owner),
2565                                 "type" => "Person");
2566
2567                 return self::build_and_transmit($owner, $contact, "retraction", $message);
2568         }
2569
2570         /**
2571          * @brief Checks a message body if it is a reshare
2572          *
2573          * @param string $body The message body that is to be check
2574          * @param bool $complete Should it be a complete check or a simple check?
2575          *
2576          * @return array|bool Reshare details or "false" if no reshare
2577          */
2578         public static function is_reshare($body, $complete = true) {
2579                 $body = trim($body);
2580
2581                 // Skip if it isn't a pure repeated messages
2582                 // Does it start with a share?
2583                 if (strpos($body, "[share") > 0)
2584                         return(false);
2585
2586                 // Does it end with a share?
2587                 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2588                         return(false);
2589
2590                 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2591                 // Skip if there is no shared message in there
2592                 if ($body == $attributes)
2593                         return(false);
2594
2595                 // If we don't do the complete check we quit here
2596                 if (!$complete)
2597                         return true;
2598
2599                 $guid = "";
2600                 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
2601                 if ($matches[1] != "")
2602                         $guid = $matches[1];
2603
2604                 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
2605                 if ($matches[1] != "")
2606                         $guid = $matches[1];
2607
2608                 if ($guid != "") {
2609                         $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
2610                                 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
2611                         if ($r) {
2612                                 $ret= array();
2613                                 $ret["root_handle"] = self::handle_from_contact($r[0]["contact-id"]);
2614                                 $ret["root_guid"] = $guid;
2615                                 return($ret);
2616                         }
2617                 }
2618
2619                 $profile = "";
2620                 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2621                 if ($matches[1] != "")
2622                         $profile = $matches[1];
2623
2624                 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2625                 if ($matches[1] != "")
2626                         $profile = $matches[1];
2627
2628                 $ret= array();
2629
2630                 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
2631                 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
2632                         return(false);
2633
2634                 $link = "";
2635                 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2636                 if ($matches[1] != "")
2637                         $link = $matches[1];
2638
2639                 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2640                 if ($matches[1] != "")
2641                         $link = $matches[1];
2642
2643                 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
2644                 if (($ret["root_guid"] == $link) OR (trim($ret["root_guid"]) == ""))
2645                         return(false);
2646
2647                 return($ret);
2648         }
2649
2650         /**
2651          * @brief Sends a post
2652          *
2653          * @param array $item The item that will be exported
2654          * @param array $owner the array of the item owner
2655          * @param array $contact Target of the communication
2656          * @param bool $public_batch Is it a public post?
2657          *
2658          * @return int The result of the transmission
2659          */
2660         public static function send_status($item, $owner, $contact, $public_batch = false) {
2661
2662                 $myaddr = self::my_handle($owner);
2663
2664                 $public = (($item["private"]) ? "false" : "true");
2665
2666                 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d H:i:s \U\T\C');
2667
2668                 // Detect a share element and do a reshare
2669                 if (!$item['private'] AND ($ret = self::is_reshare($item["body"]))) {
2670                         $message = array("root_diaspora_id" => $ret["root_handle"],
2671                                         "root_guid" => $ret["root_guid"],
2672                                         "guid" => $item["guid"],
2673                                         "diaspora_handle" => $myaddr,
2674                                         "public" => $public,
2675                                         "created_at" => $created,
2676                                         "provider_display_name" => $item["app"]);
2677
2678                         $type = "reshare";
2679                 } else {
2680                         $title = $item["title"];
2681                         $body = $item["body"];
2682
2683                         // convert to markdown
2684                         $body = html_entity_decode(bb2diaspora($body));
2685
2686                         // Adding the title
2687                         if(strlen($title))
2688                                 $body = "## ".html_entity_decode($title)."\n\n".$body;
2689
2690                         if ($item["attach"]) {
2691                                 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
2692                                 if(cnt) {
2693                                         $body .= "\n".t("Attachments:")."\n";
2694                                         foreach($matches as $mtch)
2695                                                 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
2696                                 }
2697                         }
2698
2699                         $location = array();
2700
2701                         if ($item["location"] != "")
2702                                 $location["address"] = $item["location"];
2703
2704                         if ($item["coord"] != "") {
2705                                 $coord = explode(" ", $item["coord"]);
2706                                 $location["lat"] = $coord[0];
2707                                 $location["lng"] = $coord[1];
2708                         }
2709
2710                         $message = array("raw_message" => $body,
2711                                         "location" => $location,
2712                                         "guid" => $item["guid"],
2713                                         "diaspora_handle" => $myaddr,
2714                                         "public" => $public,
2715                                         "created_at" => $created,
2716                                         "provider_display_name" => $item["app"]);
2717
2718                         if (count($location) == 0)
2719                                 unset($message["location"]);
2720
2721                         $type = "status_message";
2722                 }
2723
2724                 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2725         }
2726
2727         /**
2728          * @brief Creates a "like" object
2729          *
2730          * @param array $item The item that will be exported
2731          * @param array $owner the array of the item owner
2732          *
2733          * @return array The data for a "like"
2734          */
2735         private function construct_like($item, $owner) {
2736
2737                 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
2738                         dbesc($item["thr-parent"]));
2739                 if(!$p)
2740                         return false;
2741
2742                 $parent = $p[0];
2743
2744                 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
2745                 $positive = "true";
2746
2747                 return(array("positive" => $positive,
2748                                 "guid" => $item["guid"],
2749                                 "target_type" => $target_type,
2750                                 "parent_guid" => $parent["guid"],
2751                                 "author_signature" => "",
2752                                 "diaspora_handle" => self::my_handle($owner)));
2753         }
2754
2755         /**
2756          * @brief Creates the object for a comment
2757          *
2758          * @param array $item The item that will be exported
2759          * @param array $owner the array of the item owner
2760          *
2761          * @return array The data for a comment
2762          */
2763         private function construct_comment($item, $owner) {
2764
2765                 $p = q("SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
2766                         intval($item["parent"]),
2767                         intval($item["parent"])
2768                 );
2769
2770                 if (!$p)
2771                         return false;
2772
2773                 $parent = $p[0];
2774
2775                 $text = html_entity_decode(bb2diaspora($item["body"]));
2776
2777                 return(array("guid" => $item["guid"],
2778                                 "parent_guid" => $parent["guid"],
2779                                 "author_signature" => "",
2780                                 "text" => $text,
2781                                 "diaspora_handle" => self::my_handle($owner)));
2782         }
2783
2784         /**
2785          * @brief Send a like or a comment
2786          *
2787          * @param array $item The item that will be exported
2788          * @param array $owner the array of the item owner
2789          * @param array $contact Target of the communication
2790          * @param bool $public_batch Is it a public post?
2791          *
2792          * @return int The result of the transmission
2793          */
2794         public static function send_followup($item,$owner,$contact,$public_batch = false) {
2795
2796                 if($item['verb'] === ACTIVITY_LIKE) {
2797                         $message = self::construct_like($item, $owner);
2798                         $type = "like";
2799                 } else {
2800                         $message = self::construct_comment($item, $owner);
2801                         $type = "comment";
2802                 }
2803
2804                 if (!$message)
2805                         return false;
2806
2807                 $message["author_signature"] = self::signature($owner, $message);
2808
2809                 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2810         }
2811
2812         /**
2813          * @brief Creates a message from a signature record entry
2814          *
2815          * @param array $item The item that will be exported
2816          * @param array $signature The entry of the "sign" record
2817          *
2818          * @return string The message
2819          */
2820         private function message_from_signature($item, $signature) {
2821
2822                 // Split the signed text
2823                 $signed_parts = explode(";", $signature['signed_text']);
2824
2825                 if ($item["deleted"])
2826                         $message = array("parent_author_signature" => "",
2827                                         "target_guid" => $signed_parts[0],
2828                                         "target_type" => $signed_parts[1],
2829                                         "sender_handle" => $signature['signer'],
2830                                         "target_author_signature" => $signature['signature']);
2831                 elseif ($item['verb'] === ACTIVITY_LIKE)
2832                         $message = array("positive" => $signed_parts[0],
2833                                         "guid" => $signed_parts[1],
2834                                         "target_type" => $signed_parts[2],
2835                                         "parent_guid" => $signed_parts[3],
2836                                         "parent_author_signature" => "",
2837                                         "author_signature" => $signature['signature'],
2838                                         "diaspora_handle" => $signed_parts[4]);
2839                 else {
2840                         // Remove the comment guid
2841                         $guid = array_shift($signed_parts);
2842
2843                         // Remove the parent guid
2844                         $parent_guid = array_shift($signed_parts);
2845
2846                         // Remove the handle
2847                         $handle = array_pop($signed_parts);
2848
2849                         // Glue the parts together
2850                         $text = implode(";", $signed_parts);
2851
2852                         $message = array("guid" => $guid,
2853                                         "parent_guid" => $parent_guid,
2854                                         "parent_author_signature" => "",
2855                                         "author_signature" => $signature['signature'],
2856                                         "text" => implode(";", $signed_parts),
2857                                         "diaspora_handle" => $handle);
2858                 }
2859                 return $message;
2860         }
2861
2862         /**
2863          * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
2864          *
2865          * @param array $item The item that will be exported
2866          * @param array $owner the array of the item owner
2867          * @param array $contact Target of the communication
2868          * @param bool $public_batch Is it a public post?
2869          *
2870          * @return int The result of the transmission
2871          */
2872         public static function send_relay($item, $owner, $contact, $public_batch = false) {
2873
2874                 if ($item["deleted"])
2875                         return self::send_retraction($item, $owner, $contact, $public_batch, true);
2876                 elseif ($item['verb'] === ACTIVITY_LIKE)
2877                         $type = "like";
2878                 else
2879                         $type = "comment";
2880
2881                 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
2882
2883                 // fetch the original signature
2884
2885                 $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
2886                         intval($item["id"]));
2887
2888                 if (!$r) {
2889                         logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
2890                         return false;
2891                 }
2892
2893                 $signature = $r[0];
2894
2895                 // Old way - is used by the internal Friendica functions
2896                 /// @todo Change all signatur storing functions to the new format
2897                 if ($signature['signed_text'] AND $signature['signature'] AND $signature['signer'])
2898                         $message = self::message_from_signature($item, $signature);
2899                 else {// New way
2900                         $msg = json_decode($signature['signed_text'], true);
2901
2902                         $message = array();
2903                         if (is_array($msg)) {
2904                                 foreach ($msg AS $field => $data) {
2905                                         if (!$item["deleted"]) {
2906                                                 if ($field == "author")
2907                                                         $field = "diaspora_handle";
2908                                                 if ($field == "parent_type")
2909                                                         $field = "target_type";
2910                                         }
2911
2912                                         $message[$field] = $data;
2913                                 }
2914                         } else
2915                                 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
2916                 }
2917
2918                 $message["parent_author_signature"] = self::signature($owner, $message);
2919
2920                 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
2921
2922                 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2923         }
2924
2925         /**
2926          * @brief Sends a retraction (deletion) of a message, like or comment
2927          *
2928          * @param array $item The item that will be exported
2929          * @param array $owner the array of the item owner
2930          * @param array $contact Target of the communication
2931          * @param bool $public_batch Is it a public post?
2932          * @param bool $relay Is the retraction transmitted from a relay?
2933          *
2934          * @return int The result of the transmission
2935          */
2936         public static function send_retraction($item, $owner, $contact, $public_batch = false, $relay = false) {
2937
2938                 $itemaddr = self::handle_from_contact($item["contact-id"], $item["gcontact-id"]);
2939
2940                 // Check whether the retraction is for a top-level post or whether it's a relayable
2941                 if ($item["uri"] !== $item["parent-uri"]) {
2942                         $msg_type = "relayable_retraction";
2943                         $target_type = (($item["verb"] === ACTIVITY_LIKE) ? "Like" : "Comment");
2944                 } else {
2945                         $msg_type = "signed_retraction";
2946                         $target_type = "StatusMessage";
2947                 }
2948
2949                 if ($relay AND ($item["uri"] !== $item["parent-uri"]))
2950                         $signature = "parent_author_signature";
2951                 else
2952                         $signature = "target_author_signature";
2953
2954                 $signed_text = $item["guid"].";".$target_type;
2955
2956                 $message = array("target_guid" => $item['guid'],
2957                                 "target_type" => $target_type,
2958                                 "sender_handle" => $itemaddr,
2959                                 $signature => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')));
2960
2961                 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
2962
2963                 return self::build_and_transmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
2964         }
2965
2966         /**
2967          * @brief Sends a mail
2968          *
2969          * @param array $item The item that will be exported
2970          * @param array $owner The owner
2971          * @param array $contact Target of the communication
2972          *
2973          * @return int The result of the transmission
2974          */
2975         public static function send_mail($item, $owner, $contact) {
2976
2977                 $myaddr = self::my_handle($owner);
2978
2979                 $r = q("SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2980                         intval($item["convid"]),
2981                         intval($item["uid"])
2982                 );
2983
2984                 if (!$r) {
2985                         logger("conversation not found.");
2986                         return;
2987                 }
2988                 $cnv = $r[0];
2989
2990                 $conv = array(
2991                         "guid" => $cnv["guid"],
2992                         "subject" => $cnv["subject"],
2993                         "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d H:i:s \U\T\C'),
2994                         "diaspora_handle" => $cnv["creator"],
2995                         "participant_handles" => $cnv["recips"]
2996                 );
2997
2998                 $body = bb2diaspora($item["body"]);
2999                 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d H:i:s \U\T\C');
3000
3001                 $signed_text = $item["guid"].";".$cnv["guid"].";".$body.";".$created.";".$myaddr.";".$cnv['guid'];
3002                 $sig = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
3003
3004                 $msg = array(
3005                         "guid" => $item["guid"],
3006                         "parent_guid" => $cnv["guid"],
3007                         "parent_author_signature" => $sig,
3008                         "author_signature" => $sig,
3009                         "text" => $body,
3010                         "created_at" => $created,
3011                         "diaspora_handle" => $myaddr,
3012                         "conversation_guid" => $cnv["guid"]
3013                 );
3014
3015                 if ($item["reply"]) {
3016                         $message = $msg;
3017                         $type = "message";
3018                 } else {
3019                         $message = array("guid" => $cnv["guid"],
3020                                         "subject" => $cnv["subject"],
3021                                         "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d H:i:s \U\T\C'),
3022                                         "message" => $msg,
3023                                         "diaspora_handle" => $cnv["creator"],
3024                                         "participant_handles" => $cnv["recips"]);
3025
3026                         $type = "conversation";
3027                 }
3028
3029                 return self::build_and_transmit($owner, $contact, $type, $message, false, $item["guid"]);
3030         }
3031
3032         /**
3033          * @brief Sends profile data
3034          *
3035          * @param int $uid The user id
3036          */
3037         public static function send_profile($uid) {
3038
3039                 if (!$uid)
3040                         return;
3041
3042                 $recips = q("SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
3043                         AND `uid` = %d AND `rel` != %d",
3044                         dbesc(NETWORK_DIASPORA),
3045                         intval($uid),
3046                         intval(CONTACT_IS_SHARING)
3047                 );
3048                 if (!$recips)
3049                         return;
3050
3051                 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
3052                         FROM `profile`
3053                         INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
3054                         INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
3055                         WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
3056                         intval($uid)
3057                 );
3058
3059                 if (!$r)
3060                         return;
3061
3062                 $profile = $r[0];
3063
3064                 $handle = $profile["addr"];
3065                 $first = ((strpos($profile['name'],' ')
3066                         ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']));
3067                 $last = (($first === $profile['name']) ? '' : trim(substr($profile['name'], strlen($first))));
3068                 $large = App::get_baseurl().'/photo/custom/300/'.$profile['uid'].'.jpg';
3069                 $medium = App::get_baseurl().'/photo/custom/100/'.$profile['uid'].'.jpg';
3070                 $small = App::get_baseurl().'/photo/custom/50/'  .$profile['uid'].'.jpg';
3071                 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
3072
3073                 if ($searchable === 'true') {
3074                         $dob = '1000-00-00';
3075
3076                         if (($profile['dob']) && ($profile['dob'] != '0000-00-00'))
3077                                 $dob = ((intval($profile['dob'])) ? intval($profile['dob']) : '1000') .'-'. datetime_convert('UTC','UTC',$profile['dob'],'m-d');
3078
3079                         $about = $profile['about'];
3080                         $about = strip_tags(bbcode($about));
3081
3082                         $location = formatted_location($profile);
3083                         $tags = '';
3084                         if ($profile['pub_keywords']) {
3085                                 $kw = str_replace(',',' ',$profile['pub_keywords']);
3086                                 $kw = str_replace('  ',' ',$kw);
3087                                 $arr = explode(' ',$profile['pub_keywords']);
3088                                 if (count($arr)) {
3089                                         for($x = 0; $x < 5; $x ++) {
3090                                                 if (trim($arr[$x]))
3091                                                         $tags .= '#'. trim($arr[$x]) .' ';
3092                                         }
3093                                 }
3094                         }
3095                         $tags = trim($tags);
3096                 }
3097
3098                 $message = array("diaspora_handle" => $handle,
3099                                 "first_name" => $first,
3100                                 "last_name" => $last,
3101                                 "image_url" => $large,
3102                                 "image_url_medium" => $medium,
3103                                 "image_url_small" => $small,
3104                                 "birthday" => $dob,
3105                                 "gender" => $profile['gender'],
3106                                 "bio" => $about,
3107                                 "location" => $location,
3108                                 "searchable" => $searchable,
3109                                 "tag_string" => $tags);
3110
3111                 foreach($recips as $recip)
3112                         self::build_and_transmit($profile, $recip, "profile", $message, false, "", true);
3113         }
3114
3115         /**
3116          * @brief Stores the signature for likes that are created on our system
3117          *
3118          * @param array $contact The contact array of the "like"
3119          * @param int $post_id The post id of the "like"
3120          *
3121          * @return bool Success
3122          */
3123         public static function store_like_signature($contact, $post_id) {
3124
3125                 // Is the contact the owner? Then fetch the private key
3126                 if (!$contact['self'] OR ($contact['uid'] == 0)) {
3127                         logger("No owner post, so not storing signature", LOGGER_DEBUG);
3128                         return false;
3129                 }
3130
3131                 $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
3132                 if(!$r)
3133                         return false;
3134
3135                 $contact["uprvkey"] = $r[0]['prvkey'];
3136
3137                 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id));
3138                 if (!$r)
3139                         return false;
3140
3141                 if (!in_array($r[0]["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE)))
3142                         return false;
3143
3144                 $message = self::construct_like($r[0], $contact);
3145                 $message["author_signature"] = self::signature($contact, $message);
3146
3147                 // In the future we will store the signature more flexible to support new fields.
3148                 // Right now we cannot change this since old Friendica versions (prior to 3.5) can only handle this format.
3149                 // (We are transmitting this data here via DFRN)
3150
3151                 $signed_text = $message["positive"].";".$message["guid"].";".$message["target_type"].";".
3152                                 $message["parent_guid"].";".$message["diaspora_handle"];
3153
3154                 q("INSERT INTO `sign` (`iid`,`signed_text`,`signature`,`signer`) VALUES (%d,'%s','%s','%s')",
3155                         intval($post_id),
3156                         dbesc($signed_text),
3157                         dbesc($message["author_signature"]),
3158                         dbesc($message["diaspora_handle"])
3159                 );
3160
3161                 // This here will replace the lines above, once Diaspora changed its protocol
3162                 //q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
3163                 //      intval($message_id),
3164                 //      dbesc(json_encode($message))
3165                 //);
3166
3167                 logger('Stored diaspora like signature');
3168                 return true;
3169         }
3170
3171         /**
3172          * @brief Stores the signature for comments that are created on our system
3173          *
3174          * @param array $item The item array of the comment
3175          * @param array $contact The contact array of the item owner
3176          * @param string $uprvkey The private key of the sender
3177          * @param int $message_id The message id of the comment
3178          *
3179          * @return bool Success
3180          */
3181         public static function store_comment_signature($item, $contact, $uprvkey, $message_id) {
3182
3183                 if ($uprvkey == "") {
3184                         logger('No private key, so not storing comment signature', LOGGER_DEBUG);
3185                         return false;
3186                 }
3187
3188                 $contact["uprvkey"] = $uprvkey;
3189
3190                 $message = self::construct_comment($item, $contact);
3191                 $message["author_signature"] = self::signature($contact, $message);
3192
3193                 // In the future we will store the signature more flexible to support new fields.
3194                 // Right now we cannot change this since old Friendica versions (prior to 3.5) can only handle this format.
3195                 // (We are transmitting this data here via DFRN)
3196                 $signed_text = $message["guid"].";".$message["parent_guid"].";".
3197                                 $message["text"].";".$message["diaspora_handle"];
3198
3199                 q("INSERT INTO `sign` (`iid`,`signed_text`,`signature`,`signer`) VALUES (%d,'%s','%s','%s')",
3200                         intval($message_id),
3201                         dbesc($signed_text),
3202                         dbesc($message["author_signature"]),
3203                         dbesc($message["diaspora_handle"])
3204                 );
3205
3206                 // This here will replace the lines above, once Diaspora changed its protocol
3207                 //q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
3208                 //      intval($message_id),
3209                 //      dbesc(json_encode($message))
3210                 //);
3211
3212                 logger('Stored diaspora comment signature');
3213                 return true;
3214         }
3215 }
3216 ?>