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