]> git.mxchange.org Git - friendica.git/blob - include/diaspora2.php
Small cleanup
[friendica.git] / include / diaspora2.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/api.php");
15
16 /**
17  * @brief This class contain functions to work with XML data
18  *
19  */
20 class xml {
21         function from_array($array, &$xml) {
22
23                 if (!is_object($xml)) {
24                         foreach($array as $key => $value) {
25                                 $root = new SimpleXMLElement("<".$key."/>");
26                                 array_to_xml($value, $root);
27
28                                 $dom = dom_import_simplexml($root)->ownerDocument;
29                                 $dom->formatOutput = true;
30                                 return $dom->saveXML();
31                         }
32                 }
33
34                 foreach($array as $key => $value) {
35                         if (!is_array($value) AND !is_numeric($key))
36                                 $xml->addChild($key, $value);
37                         elseif (is_array($value))
38                                 array_to_xml($value, $xml->addChild($key));
39                 }
40         }
41
42         function copy(&$source, &$target, $elementname) {
43                 if (count($source->children()) == 0)
44                         $target->addChild($elementname, $source);
45                 else {
46                         $child = $target->addChild($elementname);
47                         foreach ($source->children() AS $childfield => $childentry)
48                                 self::copy($childentry, $child, $childfield);
49                 }
50         }
51 }
52
53 /**
54  * @brief This class contain functions to create and send Diaspora XML files
55  *
56  */
57 class diaspora {
58
59         /**
60          * @brief Dispatches public messages and find the fitting receivers
61          *
62          * @param array $msg The post that will be dispatched
63          *
64          * @return bool Was the message accepted?
65          */
66         public static function dispatch_public($msg) {
67
68                 $enabled = intval(get_config("system", "diaspora_enabled"));
69                 if (!$enabled) {
70                         logger("diaspora is disabled");
71                         return false;
72                 }
73
74                 // Use a dummy importer to import the data for the public copy
75                 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
76                 $item_id = self::dispatch($importer,$msg);
77
78                 // Now distribute it to the followers
79                 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
80                         (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
81                         AND NOT `account_expired` AND NOT `account_removed`",
82                         dbesc(NETWORK_DIASPORA),
83                         dbesc($msg["author"])
84                 );
85                 if($r) {
86                         foreach($r as $rr) {
87                                 logger("delivering to: ".$rr["username"]);
88                                 self::dispatch($rr,$msg);
89                         }
90                 } else
91                         logger("No subscribers for ".$msg["author"]." ".print_r($msg, true));
92
93                 return $item_id;
94         }
95
96         /**
97          * @brief Dispatches the different message types to the different functions
98          *
99          * @param array $importer Array of the importer user
100          * @param array $msg The post that will be dispatched
101          *
102          * @return bool Was the message accepted?
103          */
104         public static function dispatch($importer, $msg) {
105
106                 // The sender is the handle of the contact that sent the message.
107                 // This will often be different with relayed messages (for example "like" and "comment")
108                 $sender = $msg["author"];
109
110                 if (!diaspora::valid_posting($msg, $fields)) {
111                         logger("Invalid posting");
112                         return false;
113                 }
114
115                 $type = $fields->getName();
116
117                 switch ($type) {
118                         case "account_deletion": // Done
119                                 //return true;
120                                 return self::receive_account_deletion($importer, $fields);
121
122                         case "comment": // Done
123                                 //return true;
124                                 return self::receive_comment($importer, $sender, $fields);
125
126                         case "conversation": // Done
127                                 //return true;
128                                 return self::receive_conversation($importer, $msg, $fields);
129
130                         case "like": // Done
131                                 //return true;
132                                 return self::receive_like($importer, $sender, $fields);
133
134                         case "message": // Done
135                                 //return true;
136                                 return self::receive_message($importer, $fields);
137
138                         case "participation": // Not implemented
139                                 return self::receive_participation($importer, $fields);
140
141                         case "photo": // Not needed
142                                 return self::receive_photo($importer, $fields);
143
144                         case "poll_participation": // Not implemented
145                                 return self::receive_poll_participation($importer, $fields);
146
147                         case "profile": // Done
148                                 //return true;
149                                 return self::receive_profile($importer, $fields);
150
151                         case "request":
152                                 //return true;
153                                 return self::receive_request($importer, $fields);
154
155                         case "reshare": // Done
156                                 //return true;
157                                 return self::receive_reshare($importer, $fields);
158
159                         case "retraction": // Done
160                                 //return true;
161                                 return self::receive_retraction($importer, $sender, $fields);
162
163                         case "status_message": // Done
164                                 //return true;
165                                 return self::receive_status_message($importer, $fields);
166
167                         default:
168                                 logger("Unknown message type ".$type);
169                                 return false;
170                 }
171
172                 return true;
173         }
174
175         /**
176          * @brief Checks if a posting is valid and fetches the data fields.
177          *
178          * This function does not only check the signature.
179          * It also does the conversion between the old and the new diaspora format.
180          *
181          * @param array $msg Array with the XML, the sender handle and the sender signature
182          * @param object $fields SimpleXML object that contains the posting when it is valid
183          *
184          * @return bool Is the posting valid?
185          */
186         private function valid_posting($msg, &$fields) {
187
188                 $data = parse_xml_string($msg["message"], false);
189
190                 if (!is_object($data))
191                         return false;
192
193                 $first_child = $data->getName();
194
195                 // Is this the new or the old version?
196                 if ($data->getName() == "XML") {
197                         $oldXML = true;
198                         foreach ($data->post->children() as $child)
199                                 $element = $child;
200                 } else {
201                         $oldXML = false;
202                         $element = $data;
203                 }
204
205                 $type = $element->getName();
206                 $orig_type = $type;
207
208                 // All retractions are handled identically from now on.
209                 // In the new version there will only be "retraction".
210                 if (in_array($type, array("signed_retraction", "relayable_retraction")))
211                         $type = "retraction";
212
213                 $fields = new SimpleXMLElement("<".$type."/>");
214
215                 $signed_data = "";
216
217                 foreach ($element->children() AS $fieldname => $entry) {
218                         if ($oldXML) {
219                                 // Translation for the old XML structure
220                                 if ($fieldname == "diaspora_handle")
221                                         $fieldname = "author";
222
223                                 if ($fieldname == "participant_handles")
224                                         $fieldname = "participants";
225
226                                 if (in_array($type, array("like", "participation"))) {
227                                         if ($fieldname == "target_type")
228                                                 $fieldname = "parent_type";
229                                 }
230
231                                 if ($fieldname == "sender_handle")
232                                         $fieldname = "author";
233
234                                 if ($fieldname == "recipient_handle")
235                                         $fieldname = "recipient";
236
237                                 if ($fieldname == "root_diaspora_id")
238                                         $fieldname = "root_author";
239
240                                 if ($type == "retraction") {
241                                         if ($fieldname == "post_guid")
242                                                 $fieldname = "target_guid";
243
244                                         if ($fieldname == "type")
245                                                 $fieldname = "target_type";
246                                 }
247                         }
248
249                         if ($fieldname == "author_signature")
250                                 $author_signature = base64_decode($entry);
251                         elseif ($fieldname == "parent_author_signature")
252                                 $parent_author_signature = base64_decode($entry);
253                         elseif ($fieldname != "target_author_signature") {
254                                 if ($signed_data != "") {
255                                         $signed_data .= ";";
256                                         $signed_data_parent .= ";";
257                                 }
258
259                                 $signed_data .= $entry;
260                         }
261                         if (!in_array($fieldname, array("parent_author_signature", "target_author_signature")) OR
262                                 ($orig_type == "relayable_retraction"))
263                                 xml::copy($entry, $fields, $fieldname);
264                 }
265
266                 // This is something that shouldn't happen at all.
267                 if (in_array($type, array("status_message", "reshare", "profile")))
268                         if ($msg["author"] != $fields->author) {
269                                 logger("Message handle is not the same as envelope sender. Quitting this message.");
270                                 return false;
271                         }
272
273                 // Only some message types have signatures. So we quit here for the other types.
274                 if (!in_array($type, array("comment", "message", "like")))
275                         return true;
276
277                 // No author_signature? This is a must, so we quit.
278                 if (!isset($author_signature))
279                         return false;
280
281                 if (isset($parent_author_signature)) {
282                         $key = self::get_key($msg["author"]);
283
284                         if (!rsa_verify($signed_data, $parent_author_signature, $key, "sha256"))
285                                 return false;
286                 }
287
288                 $key = self::get_key($fields->author);
289
290                 return rsa_verify($signed_data, $author_signature, $key, "sha256");
291         }
292
293         /**
294          * @brief Fetches the public key for a given handle
295          *
296          * @param string $handle The handle
297          *
298          * @return string The public key
299          */
300         private function get_key($handle) {
301                 logger("Fetching diaspora key for: ".$handle);
302
303                 $r = self::get_person_by_handle($handle);
304                 if($r)
305                         return $r["pubkey"];
306
307                 return "";
308         }
309
310         /**
311          * @brief Fetches data for a given handle
312          *
313          * @param string $handle The handle
314          *
315          * @return array the queried data
316          */
317         private function get_person_by_handle($handle) {
318
319                 $r = q("SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
320                         dbesc(NETWORK_DIASPORA),
321                         dbesc($handle)
322                 );
323                 if ($r) {
324                         $person = $r[0];
325                         logger("In cache ".print_r($r,true), LOGGER_DEBUG);
326
327                         // update record occasionally so it doesn't get stale
328                         $d = strtotime($person["updated"]." +00:00");
329                         if ($d < strtotime("now - 14 days"))
330                                 $update = true;
331                 }
332
333                 if (!$person OR $update) {
334                         logger("create or refresh", LOGGER_DEBUG);
335                         $r = probe_url($handle, PROBE_DIASPORA);
336
337                         // Note that Friendica contacts will return a "Diaspora person"
338                         // if Diaspora connectivity is enabled on their server
339                         if ($r AND ($r["network"] === NETWORK_DIASPORA)) {
340                                 self::add_fcontact($r, $update);
341                                 $person = $r;
342                         }
343                 }
344                 return $person;
345         }
346
347         /**
348          * @brief Updates the fcontact table
349          *
350          * @param array $arr The fcontact data
351          * @param bool $update Update or insert?
352          *
353          * @return string The id of the fcontact entry
354          */
355         private function add_fcontact($arr, $update = false) {
356                 /// @todo Remove this function from include/network.php
357
358                 if($update) {
359                         $r = q("UPDATE `fcontact` SET
360                                         `name` = '%s',
361                                         `photo` = '%s',
362                                         `request` = '%s',
363                                         `nick` = '%s',
364                                         `addr` = '%s',
365                                         `batch` = '%s',
366                                         `notify` = '%s',
367                                         `poll` = '%s',
368                                         `confirm` = '%s',
369                                         `alias` = '%s',
370                                         `pubkey` = '%s',
371                                         `updated` = '%s'
372                                 WHERE `url` = '%s' AND `network` = '%s'",
373                                         dbesc($arr["name"]),
374                                         dbesc($arr["photo"]),
375                                         dbesc($arr["request"]),
376                                         dbesc($arr["nick"]),
377                                         dbesc($arr["addr"]),
378                                         dbesc($arr["batch"]),
379                                         dbesc($arr["notify"]),
380                                         dbesc($arr["poll"]),
381                                         dbesc($arr["confirm"]),
382                                         dbesc($arr["alias"]),
383                                         dbesc($arr["pubkey"]),
384                                         dbesc(datetime_convert()),
385                                         dbesc($arr["url"]),
386                                         dbesc($arr["network"])
387                                 );
388                 } else {
389                         $r = q("INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`,
390                                         `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
391                                 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
392                                         dbesc($arr["url"]),
393                                         dbesc($arr["name"]),
394                                         dbesc($arr["photo"]),
395                                         dbesc($arr["request"]),
396                                         dbesc($arr["nick"]),
397                                         dbesc($arr["addr"]),
398                                         dbesc($arr["batch"]),
399                                         dbesc($arr["notify"]),
400                                         dbesc($arr["poll"]),
401                                         dbesc($arr["confirm"]),
402                                         dbesc($arr["network"]),
403                                         dbesc($arr["alias"]),
404                                         dbesc($arr["pubkey"]),
405                                         dbesc(datetime_convert())
406                                 );
407                 }
408
409                 return $r;
410         }
411
412         private function get_contact_by_handle($uid, $handle) {
413                 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
414                         intval($uid),
415                         dbesc($handle)
416                 );
417
418                 if ($r)
419                         return $r[0];
420
421                 $handle_parts = explode("@", $handle);
422                 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
423                 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
424                         dbesc(NETWORK_DFRN),
425                         intval($uid),
426                         dbesc($nurl_sql)
427                 );
428                 if($r)
429                         return $r[0];
430
431                 return false;
432         }
433
434         private function post_allow($importer, $contact, $is_comment = false) {
435
436                 // perhaps we were already sharing with this person. Now they're sharing with us.
437                 // That makes us friends.
438                 // Normally this should have handled by getting a request - but this could get lost
439                 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
440                         q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
441                                 intval(CONTACT_IS_FRIEND),
442                                 intval($contact["id"]),
443                                 intval($importer["uid"])
444                         );
445                         $contact["rel"] = CONTACT_IS_FRIEND;
446                         logger("defining user ".$contact["nick"]." as friend");
447                 }
448
449                 if(($contact["blocked"]) || ($contact["readonly"]) || ($contact["archive"]))
450                         return false;
451                 if($contact["rel"] == CONTACT_IS_SHARING || $contact["rel"] == CONTACT_IS_FRIEND)
452                         return true;
453                 if($contact["rel"] == CONTACT_IS_FOLLOWER)
454                         if(($importer["page-flags"] == PAGE_COMMUNITY) OR $is_comment)
455                                 return true;
456
457                 // Messages for the global users are always accepted
458                 if ($importer["uid"] == 0)
459                         return true;
460
461                 return false;
462         }
463
464         private function get_allowed_contact_by_handle($importer, $handle, $is_comment = false) {
465                 $contact = self::get_contact_by_handle($importer["uid"], $handle);
466                 if (!$contact) {
467                         logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
468                         return false;
469                 }
470
471                 if (!self::post_allow($importer, $contact, false)) {
472                         logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
473                         return false;
474                 }
475                 return $contact;
476         }
477
478         private function message_exists($uid, $guid) {
479                 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
480                         intval($uid),
481                         dbesc($guid)
482                 );
483
484                 if($r) {
485                         logger("message ".$guid." already exists for user ".$uid);
486                         return false;
487                 }
488
489                 return true;
490         }
491
492         private function fetch_guid($item) {
493                 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
494                         function ($match) use ($item){
495                                 return(self::fetch_guid_sub($match, $item));
496                         },$item["body"]);
497         }
498
499         private function fetch_guid_sub($match, $item) {
500                 if (!self::store_by_guid($match[1], $item["author-link"]))
501                         self::store_by_guid($match[1], $item["owner-link"]);
502         }
503
504         private function store_by_guid($guid, $server, $uid = 0) {
505                 $serverparts = parse_url($server);
506                 $server = $serverparts["scheme"]."://".$serverparts["host"];
507
508                 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
509
510                 $msg = self::fetch_message($guid, $server);
511
512                 if (!$msg)
513                         return false;
514
515                 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
516
517                 // Now call the dispatcher
518                 return self::dispatch_public($msg);
519         }
520
521         private function fetch_message($guid, $server, $level = 0) {
522
523                 if ($level > 5)
524                         return false;
525
526                 // This will work for Diaspora and newer Friendica servers
527                 $source_url = $server."/p/".$guid.".xml";
528                 $x = fetch_url($source_url);
529                 if(!$x)
530                         return false;
531
532                 $source_xml = parse_xml_string($x, false);
533
534                 if (!is_object($source_xml))
535                         return false;
536
537                 if ($source_xml->post->reshare) {
538                         // Reshare of a reshare - old Diaspora version
539                         return self::fetch_message($source_xml->post->reshare->root_guid, $server, ++$level);
540                 } elseif ($source_xml->getName() == "reshare") {
541                         // Reshare of a reshare - new Diaspora version
542                         return self::fetch_message($source_xml->root_guid, $server, ++$level);
543                 }
544
545                 // Fetch the author - for the old and the new Diaspora version
546                 if ($source_xml->post->status_message->diaspora_handle)
547                         $author = (string)$source_xml->post->status_message->diaspora_handle;
548                 elseif ($source_xml->author)
549                         $author = (string)$source_xml->author;
550
551                 if (!$author)
552                         return false;
553
554                 $msg = array("message" => $x, "author" => $author);
555
556                 $msg["key"] = self::get_key($msg["author"]);
557
558                 return $msg;
559         }
560
561         private function fetch_parent_item($uid, $guid, $author, $contact) {
562                 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
563                                 `author-name`, `author-link`, `author-avatar`,
564                                 `owner-name`, `owner-link`, `owner-avatar`
565                         FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
566                         intval($uid), dbesc($guid));
567
568                 if(!$r) {
569                         $result = self::store_by_guid($guid, $contact["url"], $uid);
570
571                         if (!$result) {
572                                 $person = self::get_person_by_handle($author);
573                                 $result = self::store_by_guid($guid, $person["url"], $uid);
574                         }
575
576                         if ($result) {
577                                 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
578
579                                 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
580                                                 `author-name`, `author-link`, `author-avatar`,
581                                                 `owner-name`, `owner-link`, `owner-avatar`
582                                         FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
583                                         intval($uid), dbesc($guid));
584                         }
585                 }
586
587                 if (!$r) {
588                         logger("parent item not found: parent: ".$guid." item: ".$guid);
589                         return false;
590                 } else
591                         return $r[0];
592         }
593
594         private function get_author_contact_by_url($contact, $person, $uid) {
595
596                 $r = q("SELECT `id`, `network` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
597                         dbesc(normalise_link($person["url"])), intval($uid));
598                 if ($r) {
599                         $cid = $r[0]["id"];
600                         $network = $r[0]["network"];
601                 } else {
602                         $cid = $contact["id"];
603                         $network = NETWORK_DIASPORA;
604                 }
605
606                 return (array("cid" => $cid, "network" => $network));
607         }
608
609         public static function is_redmatrix($url) {
610                 return(strstr($url, "/channel/"));
611         }
612
613         private function plink($addr, $guid) {
614                 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
615
616                 // Fallback
617                 if (!$r)
618                         return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
619
620                 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
621                 // So we try another way as well.
622                 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
623                 if ($s)
624                         $r[0]["network"] = $s[0]["network"];
625
626                 if ($r[0]["network"] == NETWORK_DFRN)
627                         return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
628
629                 if (self::is_redmatrix($r[0]["url"]))
630                         return $r[0]["url"]."/?f=&mid=".$guid;
631
632                 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
633         }
634
635         private function receive_account_deletion($importer, $data) {
636                 $author = notags(unxmlify($data->author));
637
638                 $contact = self::get_contact_by_handle($importer["uid"], $author);
639                 if (!$contact) {
640                         logger("cannot find contact for author: ".$author);
641                         return false;
642                 }
643
644                 // We now remove the contact
645                 contact_remove($contact["id"]);
646                 return true;
647         }
648
649         private function receive_comment($importer, $sender, $data) {
650                 $guid = notags(unxmlify($data->guid));
651                 $parent_guid = notags(unxmlify($data->parent_guid));
652                 $text = unxmlify($data->text);
653                 $author = notags(unxmlify($data->author));
654
655                 $contact = self::get_allowed_contact_by_handle($importer, $sender, true);
656                 if (!$contact)
657                         return false;
658
659                 if (self::message_exists($importer["uid"], $guid))
660                         return false;
661
662                 $parent_item = self::fetch_parent_item($importer["uid"], $parent_guid, $author, $contact);
663                 if (!$parent_item)
664                         return false;
665
666                 $person = self::get_person_by_handle($author);
667                 if (!is_array($person)) {
668                         logger("unable to find author details");
669                         return false;
670                 }
671
672                 // Fetch the contact id - if we know this contact
673                 $author_contact = self::get_author_contact_by_url($contact, $person, $importer["uid"]);
674
675                 $datarray = array();
676
677                 $datarray["uid"] = $importer["uid"];
678                 $datarray["contact-id"] = $author_contact["cid"];
679                 $datarray["network"]  = $author_contact["network"];
680
681                 $datarray["author-name"] = $person["name"];
682                 $datarray["author-link"] = $person["url"];
683                 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
684
685                 $datarray["owner-name"] = $contact["name"];
686                 $datarray["owner-link"] = $contact["url"];
687                 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
688
689                 $datarray["guid"] = $guid;
690                 $datarray["uri"] = $author.":".$guid;
691
692                 $datarray["type"] = "remote-comment";
693                 $datarray["verb"] = ACTIVITY_POST;
694                 $datarray["gravity"] = GRAVITY_COMMENT;
695                 $datarray["parent-uri"] = $parent_item["uri"];
696
697                 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
698                 $datarray["object"] = json_encode($data);
699
700                 $datarray["body"] = diaspora2bb($text);
701
702                 self::fetch_guid($datarray);
703
704                 $message_id = item_store($datarray);
705                 // print_r($datarray);
706
707                 // If we are the origin of the parent we store the original data and notify our followers
708                 if($message_id AND $parent_item["origin"]) {
709
710                         // Formerly we stored the signed text, the signature and the author in different fields.
711                         // We now store the raw data so that we are more flexible.
712                         q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
713                                 intval($message_id),
714                                 dbesc(json_encode($data))
715                         );
716
717                         // notify others
718                         proc_run("php", "include/notifier.php", "comment-import", $message_id);
719                 }
720
721                 return $message_id;
722         }
723
724         private function receive_conversation_message($importer, $contact, $data, $msg, $mesg) {
725                 $guid = notags(unxmlify($data->guid));
726                 $subject = notags(unxmlify($data->subject));
727                 $author = notags(unxmlify($data->author));
728
729                 $reply = 0;
730
731                 $msg_guid = notags(unxmlify($mesg->guid));
732                 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
733                 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
734                 $msg_author_signature = notags(unxmlify($mesg->author_signature));
735                 $msg_text = unxmlify($mesg->text);
736                 $msg_created_at = datetime_convert("UTC", "UTC", notags(unxmlify($mesg->created_at)));
737
738                 // "diaspora_handle" is the element name from the old version
739                 // "author" is the element name from the new version
740                 if ($mesg->author)
741                         $msg_author = notags(unxmlify($mesg->author));
742                 elseif ($mesg->diaspora_handle)
743                         $msg_author = notags(unxmlify($mesg->diaspora_handle));
744                 else
745                         return false;
746
747                 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
748
749                 if($msg_conversation_guid != $guid) {
750                         logger("message conversation guid does not belong to the current conversation.");
751                         return false;
752                 }
753
754                 $body = diaspora2bb($msg_text);
755                 $message_uri = $msg_author.":".$msg_guid;
756
757                 $author_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
758
759                 $author_signature = base64_decode($msg_author_signature);
760
761                 if(strcasecmp($msg_author,$msg["author"]) == 0) {
762                         $person = $contact;
763                         $key = $msg["key"];
764                 } else {
765                         $person = self::get_person_by_handle($msg_author);
766
767                         if (is_array($person) && x($person, "pubkey"))
768                                 $key = $person["pubkey"];
769                         else {
770                                 logger("unable to find author details");
771                                         return false;
772                         }
773                 }
774
775                 if (!rsa_verify($author_signed_data, $author_signature, $key, "sha256")) {
776                         logger("verification failed.");
777                         return false;
778                 }
779
780                 if($msg_parent_author_signature) {
781                         $owner_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
782
783                         $parent_author_signature = base64_decode($msg_parent_author_signature);
784
785                         $key = $msg["key"];
786
787                         if (!rsa_verify($owner_signed_data, $parent_author_signature, $key, "sha256")) {
788                                 logger("owner verification failed.");
789                                 return false;
790                         }
791                 }
792
793                 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' LIMIT 1",
794                         dbesc($message_uri)
795                 );
796                 if($r) {
797                         logger("duplicate message already delivered.", LOGGER_DEBUG);
798                         return false;
799                 }
800
801                 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
802                         VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
803                         intval($importer["uid"]),
804                         dbesc($msg_guid),
805                         intval($conversation["id"]),
806                         dbesc($person["name"]),
807                         dbesc($person["photo"]),
808                         dbesc($person["url"]),
809                         intval($contact["id"]),
810                         dbesc($subject),
811                         dbesc($body),
812                         0,
813                         0,
814                         dbesc($message_uri),
815                         dbesc($author.":".$guid),
816                         dbesc($msg_created_at)
817                 );
818
819                 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
820                         dbesc(datetime_convert()),
821                         intval($conversation["id"])
822                 );
823
824                 notification(array(
825                         "type" => NOTIFY_MAIL,
826                         "notify_flags" => $importer["notify-flags"],
827                         "language" => $importer["language"],
828                         "to_name" => $importer["username"],
829                         "to_email" => $importer["email"],
830                         "uid" =>$importer["uid"],
831                         "item" => array("subject" => $subject, "body" => $body),
832                         "source_name" => $person["name"],
833                         "source_link" => $person["url"],
834                         "source_photo" => $person["thumb"],
835                         "verb" => ACTIVITY_POST,
836                         "otype" => "mail"
837                 ));
838         }
839
840         private function receive_conversation($importer, $msg, $data) {
841                 $guid = notags(unxmlify($data->guid));
842                 $subject = notags(unxmlify($data->subject));
843                 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
844                 $author = notags(unxmlify($data->author));
845                 $participants = notags(unxmlify($data->participants));
846
847                 $messages = $data->message;
848
849                 if (!count($messages)) {
850                         logger("empty conversation");
851                         return false;
852                 }
853
854                 $contact = self::get_allowed_contact_by_handle($importer, $msg["author"], true);
855                 if (!$contact)
856                         return false;
857
858                 $conversation = null;
859
860                 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
861                         intval($importer["uid"]),
862                         dbesc($guid)
863                 );
864                 if($c)
865                         $conversation = $c[0];
866                 else {
867                         $r = q("INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
868                                 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
869                                 intval($importer["uid"]),
870                                 dbesc($guid),
871                                 dbesc($author),
872                                 dbesc(datetime_convert("UTC", "UTC", $created_at)),
873                                 dbesc(datetime_convert()),
874                                 dbesc($subject),
875                                 dbesc($participants)
876                         );
877                         if($r)
878                                 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
879                                         intval($importer["uid"]),
880                                         dbesc($guid)
881                                 );
882
883                         if($c)
884                                 $conversation = $c[0];
885                 }
886                 if (!$conversation) {
887                         logger("unable to create conversation.");
888                         return;
889                 }
890
891                 foreach($messages as $mesg)
892                         self::receive_conversation_message($importer, $contact, $data, $msg, $mesg);
893
894                 return true;
895         }
896
897         private function construct_like_body($contact, $parent_item, $guid) {
898                 $bodyverb = t('%1$s likes %2$s\'s %3$s');
899
900                 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
901                 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
902                 $plink = "[url=".App::get_baseurl()."/display/".urlencode($guid)."]".t("status")."[/url]";
903
904                 return sprintf($bodyverb, $ulink, $alink, $plink);
905         }
906
907         private function construct_like_object($importer, $parent_item) {
908                 $objtype = ACTIVITY_OBJ_NOTE;
909                 $link = xmlify('<link rel="alternate" type="text/html" href="'.App::get_baseurl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />'."\n") ;
910                 $parent_body = $parent_item["body"];
911
912                 $obj = <<< EOT
913
914                 <object>
915                         <type>$objtype</type>
916                         <local>1</local>
917                         <id>{$parent_item["uri"]}</id>
918                         <link>$link</link>
919                         <title></title>
920                         <content>$parent_body</content>
921                 </object>
922 EOT;
923
924                 return $obj;
925         }
926
927         private function receive_like($importer, $sender, $data) {
928                 $positive = notags(unxmlify($data->positive));
929                 $guid = notags(unxmlify($data->guid));
930                 $parent_type = notags(unxmlify($data->parent_type));
931                 $parent_guid = notags(unxmlify($data->parent_guid));
932                 $author = notags(unxmlify($data->author));
933
934                 // likes on comments aren't supported by Diaspora - only on posts
935                 // But maybe this will be supported in the future, so we will accept it.
936                 if (!in_array($parent_type, array("Post", "Comment")))
937                         return false;
938
939                 $contact = self::get_allowed_contact_by_handle($importer, $sender, true);
940                 if (!$contact)
941                         return false;
942
943                 if (self::message_exists($importer["uid"], $guid))
944                         return false;
945
946                 $parent_item = self::fetch_parent_item($importer["uid"], $parent_guid, $author, $contact);
947                 if (!$parent_item)
948                         return false;
949
950                 $person = self::get_person_by_handle($author);
951                 if (!is_array($person)) {
952                         logger("unable to find author details");
953                         return false;
954                 }
955
956                 // Fetch the contact id - if we know this contact
957                 $author_contact = self::get_author_contact_by_url($contact, $person, $importer["uid"]);
958
959                 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
960                 // We would accept this anyhow.
961                 if ($positive === "true")
962                         $verb = ACTIVITY_LIKE;
963                 else
964                         $verb = ACTIVITY_DISLIKE;
965
966                 $datarray = array();
967
968                 $datarray["uid"] = $importer["uid"];
969                 $datarray["contact-id"] = $author_contact["cid"];
970                 $datarray["network"]  = $author_contact["network"];
971
972                 $datarray["author-name"] = $person["name"];
973                 $datarray["author-link"] = $person["url"];
974                 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
975
976                 $datarray["owner-name"] = $contact["name"];
977                 $datarray["owner-link"] = $contact["url"];
978                 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
979
980                 $datarray["guid"] = $guid;
981                 $datarray["uri"] = $author.":".$guid;
982
983                 $datarray["type"] = "activity";
984                 $datarray["verb"] = $verb;
985                 $datarray["gravity"] = GRAVITY_LIKE;
986                 $datarray["parent-uri"] = $parent_item["uri"];
987
988                 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
989                 $datarray["object"] = self::construct_like_object($importer, $parent_item);
990
991                 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
992
993                 $message_id = item_store($datarray);
994                 // print_r($datarray);
995
996                 // If we are the origin of the parent we store the original data and notify our followers
997                 if($message_id AND $parent_item["origin"]) {
998
999                         // Formerly we stored the signed text, the signature and the author in different fields.
1000                         // We now store the raw data so that we are more flexible.
1001                         q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1002                                 intval($message_id),
1003                                 dbesc(json_encode($data))
1004                         );
1005
1006                         // notify others
1007                         proc_run("php", "include/notifier.php", "comment-import", $message_id);
1008                 }
1009
1010                 return $message_id;
1011         }
1012
1013         private function receive_message($importer, $data) {
1014                 $guid = notags(unxmlify($data->guid));
1015                 $parent_guid = notags(unxmlify($data->parent_guid));
1016                 $text = unxmlify($data->text);
1017                 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1018                 $author = notags(unxmlify($data->author));
1019                 $conversation_guid = notags(unxmlify($data->conversation_guid));
1020
1021                 $contact = self::get_allowed_contact_by_handle($importer, $author, true);
1022                 if (!$contact)
1023                         return false;
1024
1025                 $conversation = null;
1026
1027                 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1028                         intval($importer["uid"]),
1029                         dbesc($conversation_guid)
1030                 );
1031                 if($c)
1032                         $conversation = $c[0];
1033                 else {
1034                         logger("conversation not available.");
1035                         return false;
1036                 }
1037
1038                 $reply = 0;
1039
1040                 $body = diaspora2bb($text);
1041                 $message_uri = $author.":".$guid;
1042
1043                 $person = self::get_person_by_handle($author);
1044                 if (!$person) {
1045                         logger("unable to find author details");
1046                         return false;
1047                 }
1048
1049                 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1050                         dbesc($message_uri),
1051                         intval($importer["uid"])
1052                 );
1053                 if($r) {
1054                         logger("duplicate message already delivered.", LOGGER_DEBUG);
1055                         return false;
1056                 }
1057
1058                 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1059                                 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1060                         intval($importer["uid"]),
1061                         dbesc($guid),
1062                         intval($conversation["id"]),
1063                         dbesc($person["name"]),
1064                         dbesc($person["photo"]),
1065                         dbesc($person["url"]),
1066                         intval($contact["id"]),
1067                         dbesc($conversation["subject"]),
1068                         dbesc($body),
1069                         0,
1070                         1,
1071                         dbesc($message_uri),
1072                         dbesc($author.":".$parent_guid),
1073                         dbesc($created_at)
1074                 );
1075
1076                 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1077                         dbesc(datetime_convert()),
1078                         intval($conversation["id"])
1079                 );
1080
1081                 return true;
1082         }
1083
1084         private function receive_participation($importer, $data) {
1085                 // I'm not sure if we can fully support this message type
1086                 return true;
1087         }
1088
1089         private function receive_photo($importer, $data) {
1090                 // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
1091                 return true;
1092         }
1093
1094         private function receive_poll_participation($importer, $data) {
1095                 // We don't support polls by now
1096                 return true;
1097         }
1098
1099         private function receive_profile($importer, $data) {
1100                 $author = notags(unxmlify($data->author));
1101
1102                 $contact = self::get_contact_by_handle($importer["uid"], $author);
1103                 if (!$contact)
1104                         return;
1105
1106                 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
1107                 $image_url = unxmlify($data->image_url);
1108                 $birthday = unxmlify($data->birthday);
1109                 $location = diaspora2bb(unxmlify($data->location));
1110                 $about = diaspora2bb(unxmlify($data->bio));
1111                 $gender = unxmlify($data->gender);
1112                 $searchable = (unxmlify($data->searchable) == "true");
1113                 $nsfw = (unxmlify($data->nsfw) == "true");
1114                 $tags = unxmlify($data->tag_string);
1115
1116                 $tags = explode("#", $tags);
1117
1118                 $keywords = array();
1119                 foreach ($tags as $tag) {
1120                         $tag = trim(strtolower($tag));
1121                         if ($tag != "")
1122                                 $keywords[] = $tag;
1123                 }
1124
1125                 $keywords = implode(", ", $keywords);
1126
1127                 $handle_parts = explode("@", $author);
1128                 $nick = $handle_parts[0];
1129
1130                 if($name === "")
1131                         $name = $handle_parts[0];
1132
1133                 if( preg_match("|^https?://|", $image_url) === 0)
1134                         $image_url = "http://".$handle_parts[1].$image_url;
1135
1136                 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
1137
1138                 // Generic birthday. We don't know the timezone. The year is irrelevant.
1139
1140                 $birthday = str_replace("1000", "1901", $birthday);
1141
1142                 if ($birthday != "")
1143                         $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
1144
1145                 // this is to prevent multiple birthday notifications in a single year
1146                 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
1147
1148                 if(substr($birthday,5) === substr($contact["bd"],5))
1149                         $birthday = $contact["bd"];
1150
1151                 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
1152                                 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
1153                         dbesc($name),
1154                         dbesc($nick),
1155                         dbesc($author),
1156                         dbesc(datetime_convert()),
1157                         dbesc($birthday),
1158                         dbesc($location),
1159                         dbesc($about),
1160                         dbesc($keywords),
1161                         dbesc($gender),
1162                         intval($contact["id"]),
1163                         intval($importer["uid"])
1164                 );
1165
1166                 if ($searchable) {
1167                         poco_check($contact["url"], $name, NETWORK_DIASPORA, $image_url, $about, $location, $gender, $keywords, "",
1168                                 datetime_convert(), 2, $contact["id"], $importer["uid"]);
1169                 }
1170
1171                 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
1172                                         "photo" => $image_url, "name" => $name, "location" => $location,
1173                                         "about" => $about, "birthday" => $birthday, "gender" => $gender,
1174                                         "addr" => $author, "nick" => $nick, "keywords" => $keywords,
1175                                         "hide" => !$searchable, "nsfw" => $nsfw);
1176
1177                 update_gcontact($gcontact);
1178
1179                 return true;
1180         }
1181
1182         private function receive_request_make_friend($importer, $contact) {
1183                 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1184                         q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
1185                                 intval(CONTACT_IS_FRIEND),
1186                                 intval($contact["id"]),
1187                                 intval($importer["uid"])
1188                         );
1189                 }
1190                 // send notification
1191
1192                 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
1193                         intval($importer["uid"])
1194                 );
1195
1196                 if($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(get_pconfig($importer["uid"], "system", "post_newfriend"))) {
1197
1198                         $self = q("SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
1199                                 intval($importer["uid"])
1200                         );
1201
1202                         // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
1203
1204                         if($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
1205
1206                                 $arr = array();
1207                                 $arr["uri"] = $arr["parent-uri"] = item_new_uri(App::get_hostname(), $importer["uid"]);
1208                                 $arr["uid"] = $importer["uid"];
1209                                 $arr["contact-id"] = $self[0]["id"];
1210                                 $arr["wall"] = 1;
1211                                 $arr["type"] = 'wall';
1212                                 $arr["gravity"] = 0;
1213                                 $arr["origin"] = 1;
1214                                 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
1215                                 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
1216                                 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
1217                                 $arr["verb"] = ACTIVITY_FRIEND;
1218                                 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
1219
1220                                 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
1221                                 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1222                                 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
1223                                 $arr["body"] = sprintf(t("%1$s is now friends with %2$s"), $A, $B)."\n\n\n".$Bphoto;
1224
1225                                 $arr["object"] = "<object><type>".ACTIVITY_OBJ_PERSON."</type><title>".$contact["name"]."</title>"
1226                                         ."<id>".$contact["url"]."/".$contact["name"]."</id>";
1227                                 $arr["object"] .= "<link>".xmlify('<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n");
1228                                 $arr["object"] .= xmlify('<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n");
1229                                 $arr["object"] .= "</link></object>\n";
1230                                 $arr["last-child"] = 1;
1231
1232                                 $arr["allow_cid"] = $user[0]["allow_cid"];
1233                                 $arr["allow_gid"] = $user[0]["allow_gid"];
1234                                 $arr["deny_cid"]  = $user[0]["deny_cid"];
1235                                 $arr["deny_gid"]  = $user[0]["deny_gid"];
1236
1237                                 $i = item_store($arr);
1238                                 if($i)
1239                                         proc_run("php", "include/notifier.php", "activity", $i);
1240
1241                         }
1242
1243                 }
1244         }
1245
1246         private function receive_request($importer, $data) {
1247                 $author = unxmlify($data->author);
1248                 $recipient = unxmlify($data->recipient);
1249
1250                 if (!$author || !$recipient)
1251                         return;
1252
1253                 $contact = self::get_contact_by_handle($importer["uid"],$author);
1254
1255                 if($contact) {
1256
1257                         // perhaps we were already sharing with this person. Now they're sharing with us.
1258                         // That makes us friends.
1259
1260                         self::receive_request_make_friend($importer, $contact);
1261                         return true;
1262                 }
1263
1264                 $ret = self::get_person_by_handle($author);
1265
1266                 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
1267                         logger("Cannot resolve diaspora handle ".$author ." for ".$recipient);
1268                         return false;
1269                 }
1270
1271                 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
1272
1273                 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
1274                         VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
1275                         intval($importer["uid"]),
1276                         dbesc($ret["network"]),
1277                         dbesc($ret["addr"]),
1278                         datetime_convert(),
1279                         dbesc($ret["url"]),
1280                         dbesc(normalise_link($ret["url"])),
1281                         dbesc($batch),
1282                         dbesc($ret["name"]),
1283                         dbesc($ret["nick"]),
1284                         dbesc($ret["photo"]),
1285                         dbesc($ret["pubkey"]),
1286                         dbesc($ret["notify"]),
1287                         dbesc($ret["poll"]),
1288                         1,
1289                         2
1290                 );
1291
1292                 // find the contact record we just created
1293
1294                 $contact_record = self::get_contact_by_handle($importer["uid"],$author);
1295
1296                 if (!$contact_record) {
1297                         logger("unable to locate newly created contact record.");
1298                         return;
1299                 }
1300
1301                 $g = q("SELECT `def_gid` FROM `user` WHERE `uid` = %d LIMIT 1",
1302                         intval($importer["uid"])
1303                 );
1304
1305                 if($g && intval($g[0]["def_gid"]))
1306                         group_add_member($importer["uid"], "", $contact_record["id"], $g[0]["def_gid"]);
1307
1308                 if($importer["page-flags"] == PAGE_NORMAL) {
1309
1310                         $hash = random_string().(string)time();   // Generate a confirm_key
1311
1312                         $ret = q("INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
1313                                 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
1314                                 intval($importer["uid"]),
1315                                 intval($contact_record["id"]),
1316                                 0,
1317                                 0,
1318                                 dbesc(t("Sharing notification from Diaspora network")),
1319                                 dbesc($hash),
1320                                 dbesc(datetime_convert())
1321                         );
1322                 } else {
1323
1324                         // automatic friend approval
1325
1326                         update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
1327
1328                         // technically they are sharing with us (CONTACT_IS_SHARING),
1329                         // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
1330                         // we are going to change the relationship and make them a follower.
1331
1332                         if($importer["page-flags"] == PAGE_FREELOVE)
1333                                 $new_relation = CONTACT_IS_FRIEND;
1334                         else
1335                                 $new_relation = CONTACT_IS_FOLLOWER;
1336
1337                         $r = q("UPDATE `contact` SET `rel` = %d,
1338                                 `name-date` = '%s',
1339                                 `uri-date` = '%s',
1340                                 `blocked` = 0,
1341                                 `pending` = 0,
1342                                 `writable` = 1
1343                                 WHERE `id` = %d
1344                                 ",
1345                                 intval($new_relation),
1346                                 dbesc(datetime_convert()),
1347                                 dbesc(datetime_convert()),
1348                                 intval($contact_record["id"])
1349                         );
1350
1351                         $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
1352                         if($u)
1353                                 $ret = diaspora_share($u[0], $contact_record);
1354                 }
1355
1356                 return true;
1357         }
1358
1359         private function get_original_item($guid, $orig_author, $author) {
1360
1361                 // Do we already have this item?
1362                 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1363                                 `author-name`, `author-link`, `author-avatar`
1364                                 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1365                         dbesc($guid));
1366
1367                 if($r) {
1368                         logger("reshared message ".$guid." already exists on system.");
1369
1370                         // Maybe it is already a reshared item?
1371                         // Then refetch the content, since there can be many side effects with reshared posts from other networks or reshares from reshares
1372                         if (api_share_as_retweet($r[0]))
1373                                 $r = array();
1374                         else
1375                                 return $r[0];
1376                 }
1377
1378                 if (!$r) {
1379                         $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
1380                         logger("1st try: reshared message ".$guid." will be fetched from original server: ".$server);
1381                         $item_id = self::store_by_guid($guid, $server);
1382
1383                         if (!$item_id) {
1384                                 $server = "https://".substr($author, strpos($author, "@") + 1);
1385                                 logger("2nd try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1386                                 $item = self::store_by_guid($guid, $server);
1387                         }
1388                         if (!$item_id) {
1389                                 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
1390                                 logger("3rd try: reshared message ".$guid." will be fetched from original server: ".$server);
1391                                 $item = self::store_by_guid($guid, $server);
1392                         }
1393                         if (!$item_id) {
1394                                 $server = "http://".substr($author, strpos($author, "@") + 1);
1395                                 logger("4th try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1396                                 $item = self::store_by_guid($guid, $server);
1397                         }
1398
1399                         if ($item_id) {
1400                                 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1401                                                 `author-name`, `author-link`, `author-avatar`
1402                                         FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1403                                         intval($item_id));
1404
1405                                 if ($r)
1406                                         return $r[0];
1407
1408                         }
1409                 }
1410                 return false;
1411         }
1412
1413         private function receive_reshare($importer, $data) {
1414                 $root_author = notags(unxmlify($data->root_author));
1415                 $root_guid = notags(unxmlify($data->root_guid));
1416                 $guid = notags(unxmlify($data->guid));
1417                 $author = notags(unxmlify($data->author));
1418                 $public = notags(unxmlify($data->public));
1419                 $created_at = notags(unxmlify($data->created_at));
1420
1421                 $contact = self::get_allowed_contact_by_handle($importer, $author, false);
1422                 if (!$contact)
1423                         return false;
1424
1425                 if (self::message_exists($importer["uid"], $guid))
1426                         return false;
1427
1428                 $original_item = self::get_original_item($root_guid, $root_author, $author);
1429                 if (!$original_item)
1430                         return false;
1431
1432                 $datarray = array();
1433
1434                 $datarray["uid"] = $importer["uid"];
1435                 $datarray["contact-id"] = $contact["id"];
1436                 $datarray["network"]  = NETWORK_DIASPORA;
1437
1438                 $datarray["author-name"] = $contact["name"];
1439                 $datarray["author-link"] = $contact["url"];
1440                 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1441
1442                 $datarray["owner-name"] = $datarray["author-name"];
1443                 $datarray["owner-link"] = $datarray["author-link"];
1444                 $datarray["owner-avatar"] = $datarray["author-avatar"];
1445
1446                 $datarray["guid"] = $guid;
1447                 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
1448
1449                 $datarray["verb"] = ACTIVITY_POST;
1450                 $datarray["gravity"] = GRAVITY_PARENT;
1451
1452                 $datarray["object"] = json_encode($data);
1453
1454                 $prefix = share_header($original_item["author-name"], $original_item["author-link"], $original_item["author-avatar"],
1455                                         $original_item["guid"], $original_item["created"], $original_item["uri"]);
1456                 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
1457
1458                 $datarray["tag"] = $original_item["tag"];
1459                 $datarray["app"]  = $original_item["app"];
1460
1461                 $datarray["plink"] = self::plink($author, $guid);
1462                 $datarray["private"] = (($public == "false") ? 1 : 0);
1463                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
1464
1465                 $datarray["object-type"] = $original_item["object-type"];
1466
1467                 self::fetch_guid($datarray);
1468                 $message_id = item_store($datarray);
1469                 // print_r($datarray);
1470
1471                 return $message_id;
1472         }
1473
1474         private function item_retraction($importer, $contact, $data) {
1475                 $target_type = notags(unxmlify($data->target_type));
1476                 $target_guid = notags(unxmlify($data->target_guid));
1477                 $author = notags(unxmlify($data->author));
1478
1479                 $person = self::get_person_by_handle($author);
1480                 if (!is_array($person)) {
1481                         logger("unable to find author detail for ".$author);
1482                         return false;
1483                 }
1484
1485                 $r = q("SELECT `id`, `parent`, `parent-uri`, `author-link` FROM `item` WHERE `guid` = '%s' AND `uid` = %d AND NOT `file` LIKE '%%[%%' LIMIT 1",
1486                         dbesc($target_guid),
1487                         intval($importer["uid"])
1488                 );
1489                 if (!$r)
1490                         return false;
1491
1492                 // Only delete it if the author really fits
1493                 if (!link_compare($r[0]["author-link"],$person["url"]))
1494                         return false;
1495
1496                 // Check if the sender is the thread owner
1497                 $p = q("SELECT `author-link`, `origin` FROM `item` WHERE `id` = %d",
1498                         intval($r[0]["parent"]));
1499
1500                 // Only delete it if the parent author really fits
1501                 if (!link_compare($p[0]["author-link"], $contact["url"]))
1502                         return false;
1503
1504                 // 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
1505                 q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' WHERE `id` = %d",
1506                         dbesc(datetime_convert()),
1507                         dbesc(datetime_convert()),
1508                         intval($r[0]["id"])
1509                 );
1510                 delete_thread($r[0]["id"], $r[0]["parent-uri"]);
1511
1512                 // Now check if the retraction needs to be relayed by us
1513                 if($p[0]["origin"]) {
1514
1515                         // Formerly we stored the signed text, the signature and the author in different fields.
1516                         // We now store the raw data so that we are more flexible.
1517                         q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1518                                 intval($r[0]["id"]),
1519                                 dbesc(json_encode($data))
1520                         );
1521
1522                         // notify others
1523                         proc_run("php", "include/notifier.php", "drop", $r[0]["id"]);
1524                 }
1525         }
1526
1527         private function receive_retraction($importer, $sender, $data) {
1528                 $target_type = notags(unxmlify($data->target_type));
1529
1530                 $contact = self::get_contact_by_handle($importer["uid"], $sender);
1531                 if (!$contact) {
1532                         logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
1533                         return false;
1534                 }
1535
1536                 switch ($target_type) {
1537                         case "Comment":
1538                         case "Like":
1539                         case "Post": // "Post" will be supported in a future version
1540                         case "Reshare":
1541                         case "StatusMessage":
1542                                 return self::item_retraction($importer, $contact, $data);;
1543
1544                         case "Person":
1545                                 contact_remove($contact["id"]);
1546                                 return true;
1547
1548                         default:
1549                                 logger("Unknown target type ".$target_type);
1550                                 return false;
1551                 }
1552                 return true;
1553         }
1554
1555         private function receive_status_message($importer, $data) {
1556
1557                 $raw_message = unxmlify($data->raw_message);
1558                 $guid = notags(unxmlify($data->guid));
1559                 $author = notags(unxmlify($data->author));
1560                 $public = notags(unxmlify($data->public));
1561                 $created_at = notags(unxmlify($data->created_at));
1562                 $provider_display_name = notags(unxmlify($data->provider_display_name));
1563
1564                 /// @todo enable support for polls
1565                 //if ($data->poll) {
1566                 //      foreach ($data->poll AS $poll)
1567                 //              print_r($poll);
1568                 //      die("poll!\n");
1569                 //}
1570                 $contact = self::get_allowed_contact_by_handle($importer, $author, false);
1571                 if (!$contact)
1572                         return false;
1573
1574                 if (self::message_exists($importer["uid"], $guid))
1575                         return false;
1576
1577                 $address = array();
1578                 if ($data->location)
1579                         foreach ($data->location->children() AS $fieldname => $data)
1580                                 $address[$fieldname] = notags(unxmlify($data));
1581
1582                 $body = diaspora2bb($raw_message);
1583
1584                 $datarray = array();
1585
1586                 if ($data->photo) {
1587                         foreach ($data->photo AS $photo)
1588                                 $body = "[img]".$photo->remote_photo_path.$photo->remote_photo_name."[/img]\n".$body;
1589
1590                         $datarray["object-type"] = ACTIVITY_OBJ_PHOTO;
1591                 } else {
1592                         $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1593
1594                         // Add OEmbed and other information to the body
1595                         if (!self::is_redmatrix($contact["url"]))
1596                                 $body = add_page_info_to_body($body, false, true);
1597                 }
1598
1599                 $datarray["uid"] = $importer["uid"];
1600                 $datarray["contact-id"] = $contact["id"];
1601                 $datarray["network"] = NETWORK_DIASPORA;
1602
1603                 $datarray["author-name"] = $contact["name"];
1604                 $datarray["author-link"] = $contact["url"];
1605                 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1606
1607                 $datarray["owner-name"] = $datarray["author-name"];
1608                 $datarray["owner-link"] = $datarray["author-link"];
1609                 $datarray["owner-avatar"] = $datarray["author-avatar"];
1610
1611                 $datarray["guid"] = $guid;
1612                 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
1613
1614                 $datarray["verb"] = ACTIVITY_POST;
1615                 $datarray["gravity"] = GRAVITY_PARENT;
1616
1617                 $datarray["object"] = json_encode($data);
1618
1619                 $datarray["body"] = $body;
1620
1621                 if ($provider_display_name != "")
1622                         $datarray["app"] = $provider_display_name;
1623
1624                 $datarray["plink"] = self::plink($author, $guid);
1625                 $datarray["private"] = (($public == "false") ? 1 : 0);
1626                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
1627
1628                 if (isset($address["address"]))
1629                         $datarray["location"] = $address["address"];
1630
1631                 if (isset($address["lat"]) AND isset($address["lng"]))
1632                         $datarray["coord"] = $address["lat"]." ".$address["lng"];
1633
1634                 self::fetch_guid($datarray);
1635                 $message_id = item_store($datarray);
1636                 // print_r($datarray);
1637
1638                 logger("Stored item with message id ".$message_id, LOGGER_DEBUG);
1639
1640                 return $message_id;
1641         }
1642 }
1643 ?>