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