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