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