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