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