]> git.mxchange.org Git - friendica.git/blob - include/diaspora.php
Merge pull request #2347 from annando/1602-dfrn-forum
[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                 update_contact_avatar($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 `rel` = %d,
744                         `name-date` = '%s',
745                         `uri-date` = '%s',
746                         `blocked` = 0,
747                         `pending` = 0,
748                         `writable` = 1
749                         WHERE `id` = %d
750                         ",
751                         intval($new_relation),
752                         dbesc(datetime_convert()),
753                         dbesc(datetime_convert()),
754                         intval($contact_record['id'])
755                 );
756
757                 $u = q("select * from user where uid = %d limit 1",intval($importer['uid']));
758                 if($u)
759                         $ret = diaspora_share($u[0],$contact_record);
760         }
761
762         return;
763 }
764
765 function diaspora_post_allow($importer,$contact, $is_comment = false) {
766
767         // perhaps we were already sharing with this person. Now they're sharing with us.
768         // That makes us friends.
769         // Normally this should have handled by getting a request - but this could get lost
770         if($contact['rel'] == CONTACT_IS_FOLLOWER && in_array($importer['page-flags'], array(PAGE_FREELOVE))) {
771                 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
772                         intval(CONTACT_IS_FRIEND),
773                         intval($contact['id']),
774                         intval($importer['uid'])
775                 );
776                 $contact['rel'] = CONTACT_IS_FRIEND;
777                 logger('diaspora_post_allow: defining user '.$contact["nick"].' as friend');
778         }
779
780         if(($contact['blocked']) || ($contact['readonly']) || ($contact['archive']))
781                 return false;
782         if($contact['rel'] == CONTACT_IS_SHARING || $contact['rel'] == CONTACT_IS_FRIEND)
783                 return true;
784         if($contact['rel'] == CONTACT_IS_FOLLOWER)
785                 if(($importer['page-flags'] == PAGE_COMMUNITY) OR $is_comment)
786                         return true;
787
788         // Messages for the global users are always accepted
789         if ($importer['uid'] == 0)
790                 return true;
791
792         return false;
793 }
794
795 function diaspora_is_redmatrix($url) {
796         return(strstr($url, "/channel/"));
797 }
798
799 function diaspora_plink($addr, $guid) {
800         $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
801
802         // Fallback
803         if (!$r)
804                 return 'https://'.substr($addr,strpos($addr,'@')+1).'/posts/'.$guid;
805
806         // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
807         // So we try another way as well.
808         $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
809         if ($s)
810                 $r[0]["network"] = $s[0]["network"];
811
812         if ($r[0]["network"] == NETWORK_DFRN)
813                 return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
814
815         if (diaspora_is_redmatrix($r[0]["url"]))
816                 return $r[0]["url"]."/?f=&mid=".$guid;
817
818         return 'https://'.substr($addr,strpos($addr,'@')+1).'/posts/'.$guid;
819 }
820
821 function diaspora_repair_signature($signature, $handle = "", $level = 1) {
822
823         if ($signature == "")
824                 return($signature);
825
826         if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
827                 $signature = base64_decode($signature);
828                 logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
829
830                 // Do a recursive call to be able to fix even multiple levels
831                 if ($level < 10)
832                         $signature = diaspora_repair_signature($signature, $handle, ++$level);
833         }
834
835         return($signature);
836 }
837
838 function diaspora_post($importer,$xml,$msg) {
839
840         $a = get_app();
841         $guid = notags(unxmlify($xml->guid));
842         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
843
844         if($diaspora_handle != $msg['author']) {
845                 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
846                 return 202;
847         }
848
849         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
850         if(! $contact) {
851                 logger('diaspora_post: A Contact for handle '.$diaspora_handle.' and user '.$importer['uid'].' was not found');
852                 return 203;
853         }
854
855         if(! diaspora_post_allow($importer,$contact, false)) {
856                 logger('diaspora_post: Ignoring this author.');
857                 return 202;
858         }
859
860         $message_id = $diaspora_handle . ':' . $guid;
861         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
862                 intval($importer['uid']),
863                 dbesc($guid)
864         );
865         if(count($r)) {
866                 logger('diaspora_post: message exists: ' . $guid);
867                 return 208;
868         }
869
870         $created = unxmlify($xml->created_at);
871         $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
872
873         $body = diaspora2bb($xml->raw_message);
874
875         $datarray = array();
876
877         $datarray["object"] = json_encode($xml);
878
879         if($xml->photo->remote_photo_path AND $xml->photo->remote_photo_name)
880                 $datarray["object-type"] = ACTIVITY_OBJ_PHOTO;
881         else {
882                 $datarray['object-type'] = ACTIVITY_OBJ_NOTE;
883                 // Add OEmbed and other information to the body
884                 if (!diaspora_is_redmatrix($contact['url']))
885                         $body = add_page_info_to_body($body, false, true);
886         }
887
888         $str_tags = '';
889
890         $cnt = preg_match_all('/@\[url=(.*?)\[\/url\]/ism',$body,$matches,PREG_SET_ORDER);
891         if($cnt) {
892                 foreach($matches as $mtch) {
893                         if(strlen($str_tags))
894                                 $str_tags .= ',';
895                         $str_tags .= '@[url=' . $mtch[1] . '[/url]';
896                 }
897         }
898
899         $plink = diaspora_plink($diaspora_handle, $guid);
900
901         $datarray['uid'] = $importer['uid'];
902         $datarray['contact-id'] = $contact['id'];
903         $datarray['wall'] = 0;
904         $datarray['network'] = NETWORK_DIASPORA;
905         $datarray['verb'] = ACTIVITY_POST;
906         $datarray['guid'] = $guid;
907         $datarray['uri'] = $datarray['parent-uri'] = $message_id;
908         $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
909         $datarray['private'] = $private;
910         $datarray['parent'] = 0;
911         $datarray['plink'] = $plink;
912         $datarray['owner-name'] = $contact['name'];
913         $datarray['owner-link'] = $contact['url'];
914         //$datarray['owner-avatar'] = $contact['thumb'];
915         $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
916         $datarray['author-name'] = $contact['name'];
917         $datarray['author-link'] = $contact['url'];
918         $datarray['author-avatar'] = $contact['thumb'];
919         $datarray['body'] = $body;
920         $datarray['tag'] = $str_tags;
921         if ($xml->provider_display_name)
922                 $datarray["app"] = unxmlify($xml->provider_display_name);
923         else
924                 $datarray['app']  = 'Diaspora';
925
926         // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible.
927
928         $datarray['visible'] = ((strlen($body)) ? 1 : 0);
929
930         DiasporaFetchGuid($datarray);
931         $message_id = item_store($datarray);
932
933         logger("Stored item with message id ".$message_id, LOGGER_DEBUG);
934
935         return 201;
936
937 }
938
939 function DiasporaFetchGuid($item) {
940         preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
941                 function ($match) use ($item){
942                         return(DiasporaFetchGuidSub($match, $item));
943                 },$item["body"]);
944 }
945
946 function DiasporaFetchGuidSub($match, $item) {
947         $a = get_app();
948
949         if (!diaspora_store_by_guid($match[1], $item["author-link"]))
950                 diaspora_store_by_guid($match[1], $item["owner-link"]);
951 }
952
953 function diaspora_store_by_guid($guid, $server, $uid = 0) {
954         require_once("include/Contact.php");
955
956         $serverparts = parse_url($server);
957         $server = $serverparts["scheme"]."://".$serverparts["host"];
958
959         logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
960
961         $item = diaspora_fetch_message($guid, $server);
962
963         if (!$item)
964                 return false;
965
966         logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
967
968         $body = $item["body"];
969         $str_tags = $item["tag"];
970         $app = $item["app"];
971         $created = $item["created"];
972         $author = $item["author"];
973         $guid = $item["guid"];
974         $private = $item["private"];
975         $object = $item["object"];
976         $objecttype = $item["object-type"];
977
978         $message_id = $author.':'.$guid;
979         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
980                 intval($uid),
981                 dbesc($guid)
982         );
983         if(count($r))
984                 return $r[0]["id"];
985
986         $person = find_diaspora_person_by_handle($author);
987
988         $contact_id = get_contact($person['url'], $uid);
989
990         $contacts = q("SELECT * FROM `contact` WHERE `id` = %d", intval($contact_id));
991         $importers = q("SELECT * FROM `user` WHERE `uid` = %d", intval($uid));
992
993         if ($contacts AND $importers)
994                 if(!diaspora_post_allow($importers[0],$contacts[0], false)) {
995                         logger('Ignoring author '.$person['url'].' for uid '.$uid);
996                         return false;
997                 } else
998                         logger('Author '.$person['url'].' is allowed for uid '.$uid);
999
1000         $datarray = array();
1001         $datarray['uid'] = $uid;
1002         $datarray['contact-id'] = $contact_id;
1003         $datarray['wall'] = 0;
1004         $datarray['network']  = NETWORK_DIASPORA;
1005         $datarray['guid'] = $guid;
1006         $datarray['uri'] = $datarray['parent-uri'] = $message_id;
1007         $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
1008         $datarray['private'] = $private;
1009         $datarray['parent'] = 0;
1010         $datarray['plink'] = diaspora_plink($author, $guid);
1011         $datarray['author-name'] = $person['name'];
1012         $datarray['author-link'] = $person['url'];
1013         $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1014         $datarray['owner-name'] = $datarray['author-name'];
1015         $datarray['owner-link'] = $datarray['author-link'];
1016         $datarray['owner-avatar'] = $datarray['author-avatar'];
1017         $datarray['body'] = $body;
1018         $datarray['tag'] = $str_tags;
1019         $datarray['app']  = $app;
1020         $datarray['visible'] = ((strlen($body)) ? 1 : 0);
1021         $datarray['object'] = $object;
1022         $datarray['object-type'] = $objecttype;
1023
1024         if ($datarray['contact-id'] == 0)
1025                 return false;
1026
1027         DiasporaFetchGuid($datarray);
1028         $message_id = item_store($datarray);
1029
1030         /// @TODO
1031         /// Looking if there is some subscribe mechanism in Diaspora to get all comments for this post
1032
1033         return $message_id;
1034 }
1035
1036 function diaspora_fetch_message($guid, $server, $level = 0) {
1037
1038         if ($level > 5)
1039                 return false;
1040
1041         $a = get_app();
1042
1043         // This will not work if the server is not a Diaspora server
1044         $source_url = $server.'/p/'.$guid.'.xml';
1045         $x = fetch_url($source_url);
1046         if(!$x)
1047                 return false;
1048
1049         $x = str_replace(array('<activity_streams-photo>','</activity_streams-photo>'),array('<asphoto>','</asphoto>'),$x);
1050         $source_xml = parse_xml_string($x,false);
1051
1052         $item = array();
1053         $item["app"] = 'Diaspora';
1054         $item["guid"] = $guid;
1055         $body = "";
1056
1057         if ($source_xml->post->status_message->created_at)
1058                 $item["created"] = unxmlify($source_xml->post->status_message->created_at);
1059
1060         if ($source_xml->post->status_message->provider_display_name)
1061                 $item["app"] = unxmlify($source_xml->post->status_message->provider_display_name);
1062
1063         if ($source_xml->post->status_message->diaspora_handle)
1064                 $item["author"] = unxmlify($source_xml->post->status_message->diaspora_handle);
1065
1066         if ($source_xml->post->status_message->guid)
1067                 $item["guid"] = unxmlify($source_xml->post->status_message->guid);
1068
1069         $item["private"] = (unxmlify($source_xml->post->status_message->public) == 'false');
1070         $item["object"] = json_encode($source_xml->post);
1071
1072         if(strlen($source_xml->post->asphoto->objectId) && ($source_xml->post->asphoto->objectId != 0) && ($source_xml->post->asphoto->image_url)) {
1073                 $item["object-type"] = ACTIVITY_OBJ_PHOTO;
1074                 $body = '[url=' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '][img]' . notags(unxmlify($source_xml->post->asphoto->objectId)) . '[/img][/url]' . "\n";
1075                 $body = scale_external_images($body,false);
1076         } elseif($source_xml->post->asphoto->image_url) {
1077                 $item["object-type"] = ACTIVITY_OBJ_PHOTO;
1078                 $body = '[img]' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '[/img]' . "\n";
1079                 $body = scale_external_images($body);
1080         } elseif($source_xml->post->status_message) {
1081                 $body = diaspora2bb($source_xml->post->status_message->raw_message);
1082
1083                 // Checking for embedded pictures
1084                 if($source_xml->post->status_message->photo->remote_photo_path AND
1085                         $source_xml->post->status_message->photo->remote_photo_name) {
1086
1087                         $item["object-type"] = ACTIVITY_OBJ_PHOTO;
1088
1089                         $remote_photo_path = notags(unxmlify($source_xml->post->status_message->photo->remote_photo_path));
1090                         $remote_photo_name = notags(unxmlify($source_xml->post->status_message->photo->remote_photo_name));
1091
1092                         $body = '[img]'.$remote_photo_path.$remote_photo_name.'[/img]'."\n".$body;
1093
1094                         logger('embedded picture link found: '.$body, LOGGER_DEBUG);
1095                 } else
1096                         $item["object-type"] = ACTIVITY_OBJ_NOTE;
1097
1098                 $body = scale_external_images($body);
1099
1100                 // Add OEmbed and other information to the body
1101                 /// @TODO It could be a repeated redmatrix item
1102                 /// Then we shouldn't add further data to it
1103                 if ($item["object-type"] == ACTIVITY_OBJ_NOTE)
1104                         $body = add_page_info_to_body($body, false, true);
1105
1106         } elseif($source_xml->post->reshare) {
1107                 // Reshare of a reshare
1108                 return diaspora_fetch_message($source_xml->post->reshare->root_guid, $server, ++$level);
1109         } else {
1110                 // Maybe it is a reshare of a photo that will be delivered at a later time (testing)
1111                 logger('no content found: '.print_r($source_xml,true));
1112                 return false;
1113         }
1114
1115         if (trim($body) == "")
1116                 return false;
1117
1118         $item["tag"] = '';
1119         $item["body"] = $body;
1120
1121         return $item;
1122 }
1123
1124 function diaspora_reshare($importer,$xml,$msg) {
1125
1126         logger('diaspora_reshare: init: ' . print_r($xml,true));
1127
1128         $a = get_app();
1129         $guid = notags(unxmlify($xml->guid));
1130         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1131
1132
1133         if($diaspora_handle != $msg['author']) {
1134                 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
1135                 return 202;
1136         }
1137
1138         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1139         if(! $contact)
1140                 return;
1141
1142         if(! diaspora_post_allow($importer,$contact, false)) {
1143                 logger('diaspora_reshare: Ignoring this author: ' . $diaspora_handle . ' ' . print_r($xml,true));
1144                 return 202;
1145         }
1146
1147         $message_id = $diaspora_handle . ':' . $guid;
1148         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1149                 intval($importer['uid']),
1150                 dbesc($guid)
1151         );
1152         if(count($r)) {
1153                 logger('diaspora_reshare: message exists: ' . $guid);
1154                 return;
1155         }
1156
1157         $orig_author = notags(unxmlify($xml->root_diaspora_id));
1158         $orig_guid = notags(unxmlify($xml->root_guid));
1159         $orig_url = $a->get_baseurl()."/display/".$orig_guid;
1160
1161         $create_original_post = false;
1162
1163         // Do we already have this item?
1164         $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",
1165                 dbesc($orig_guid),
1166                 dbesc(NETWORK_DIASPORA)
1167         );
1168         if(count($r)) {
1169                 logger('reshared message '.$orig_guid." reshared by ".$guid.' already exists on system.');
1170
1171                 // Maybe it is already a reshared item?
1172                 // Then refetch the content, since there can be many side effects with reshared posts from other networks or reshares from reshares
1173                 require_once('include/api.php');
1174                 if (api_share_as_retweet($r[0]))
1175                         $r = array();
1176                 else {
1177                         $body = $r[0]["body"];
1178                         $str_tags = $r[0]["tag"];
1179                         $app = $r[0]["app"];
1180                         $orig_created = $r[0]["created"];
1181                         $orig_plink = $r[0]["plink"];
1182                         $orig_uri = $r[0]["uri"];
1183                         $object = $r[0]["object"];
1184                         $objecttype = $r[0]["object-type"];
1185                 }
1186         }
1187
1188         if (!count($r)) {
1189                 $body = "";
1190                 $str_tags = "";
1191                 $app = "";
1192
1193                 $server = 'https://'.substr($orig_author,strpos($orig_author,'@')+1);
1194                 logger('1st try: reshared message '.$orig_guid." reshared by ".$guid.' will be fetched from original server: '.$server);
1195                 $item = diaspora_fetch_message($orig_guid, $server);
1196
1197                 if (!$item) {
1198                         $server = 'https://'.substr($diaspora_handle,strpos($diaspora_handle,'@')+1);
1199                         logger('2nd try: reshared message '.$orig_guid." reshared by ".$guid." will be fetched from sharer's server: ".$server);
1200                         $item = diaspora_fetch_message($orig_guid, $server);
1201                 }
1202                 if (!$item) {
1203                         $server = 'http://'.substr($orig_author,strpos($orig_author,'@')+1);
1204                         logger('3rd try: reshared message '.$orig_guid." reshared by ".$guid.' will be fetched from original server: '.$server);
1205                         $item = diaspora_fetch_message($orig_guid, $server);
1206                 }
1207                 if (!$item) {
1208                         $server = 'http://'.substr($diaspora_handle,strpos($diaspora_handle,'@')+1);
1209                         logger('4th try: reshared message '.$orig_guid." reshared by ".$guid." will be fetched from sharer's server: ".$server);
1210                         $item = diaspora_fetch_message($orig_guid, $server);
1211                 }
1212
1213                 if ($item) {
1214                         $body = $item["body"];
1215                         $str_tags = $item["tag"];
1216                         $app = $item["app"];
1217                         $orig_created = $item["created"];
1218                         $orig_author = $item["author"];
1219                         $orig_guid = $item["guid"];
1220                         $orig_plink = diaspora_plink($orig_author, $orig_guid);
1221                         $orig_uri = $orig_author.':'.$orig_guid;
1222                         $create_original_post = ($body != "");
1223                         $object = $item["object"];
1224                         $objecttype = $item["object-type"];
1225                 }
1226         }
1227
1228         $plink = diaspora_plink($diaspora_handle, $guid);
1229
1230         $person = find_diaspora_person_by_handle($orig_author);
1231
1232         $created = unxmlify($xml->created_at);
1233         $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
1234
1235         $datarray = array();
1236
1237         $datarray['uid'] = $importer['uid'];
1238         $datarray['contact-id'] = $contact['id'];
1239         $datarray['wall'] = 0;
1240         $datarray['network']  = NETWORK_DIASPORA;
1241         $datarray['guid'] = $guid;
1242         $datarray['uri'] = $datarray['parent-uri'] = $message_id;
1243         $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
1244         $datarray['private'] = $private;
1245         $datarray['parent'] = 0;
1246         $datarray['plink'] = $plink;
1247         $datarray['owner-name'] = $contact['name'];
1248         $datarray['owner-link'] = $contact['url'];
1249         $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
1250         if (!intval(get_config('system','wall-to-wall_share'))) {
1251                 $prefix = share_header($person['name'], $person['url'], ((x($person,'thumb')) ? $person['thumb'] : $person['photo']), $orig_guid, $orig_created, $orig_url);
1252
1253                 $datarray['author-name'] = $contact['name'];
1254                 $datarray['author-link'] = $contact['url'];
1255                 $datarray['author-avatar'] = $contact['thumb'];
1256                 $datarray['body'] = $prefix.$body."[/share]";
1257         } else {
1258                 // Let reshared messages look like wall-to-wall posts
1259                 $datarray['author-name'] = $person['name'];
1260                 $datarray['author-link'] = $person['url'];
1261                 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1262                 $datarray['body'] = $body;
1263         }
1264
1265         $datarray["object"] = json_encode($xml);
1266         $datarray['object-type'] = $objecttype;
1267
1268         $datarray['tag'] = $str_tags;
1269         $datarray['app']  = $app;
1270
1271         // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible. (testing)
1272         $datarray['visible'] = ((strlen($body)) ? 1 : 0);
1273
1274         // Store the original item of a reshare
1275         if ($create_original_post) {
1276                 require_once("include/Contact.php");
1277
1278                 $datarray2 = $datarray;
1279
1280                 $datarray2['uid'] = 0;
1281                 $datarray2['contact-id'] = get_contact($person['url'], 0);
1282                 $datarray2['guid'] = $orig_guid;
1283                 $datarray2['uri'] = $datarray2['parent-uri'] = $orig_uri;
1284                 $datarray2['changed'] = $datarray2['created'] = $datarray2['edited'] = $datarray2['commented'] = $datarray2['received'] = datetime_convert('UTC','UTC',$orig_created);
1285                 $datarray2['parent'] = 0;
1286                 $datarray2['plink'] = $orig_plink;
1287
1288                 $datarray2['author-name'] = $person['name'];
1289                 $datarray2['author-link'] = $person['url'];
1290                 $datarray2['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1291                 $datarray2['owner-name'] = $datarray2['author-name'];
1292                 $datarray2['owner-link'] = $datarray2['author-link'];
1293                 $datarray2['owner-avatar'] = $datarray2['author-avatar'];
1294                 $datarray2['body'] = $body;
1295                 $datarray2["object"] = $object;
1296
1297                 DiasporaFetchGuid($datarray2);
1298                 $message_id = item_store($datarray2);
1299
1300                 logger("Store original item ".$orig_guid." under message id ".$message_id);
1301         }
1302
1303         DiasporaFetchGuid($datarray);
1304         $message_id = item_store($datarray);
1305
1306         return;
1307
1308 }
1309
1310
1311 function diaspora_asphoto($importer,$xml,$msg) {
1312         logger('diaspora_asphoto called');
1313
1314         $a = get_app();
1315         $guid = notags(unxmlify($xml->guid));
1316         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1317
1318         if($diaspora_handle != $msg['author']) {
1319                 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
1320                 return 202;
1321         }
1322
1323         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1324         if(! $contact)
1325                 return;
1326
1327         if(! diaspora_post_allow($importer,$contact, false)) {
1328                 logger('diaspora_asphoto: Ignoring this author.');
1329                 return 202;
1330         }
1331
1332         $message_id = $diaspora_handle . ':' . $guid;
1333         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1334                 intval($importer['uid']),
1335                 dbesc($guid)
1336         );
1337         if(count($r)) {
1338                 logger('diaspora_asphoto: message exists: ' . $guid);
1339                 return;
1340         }
1341
1342         $created = unxmlify($xml->created_at);
1343         $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
1344
1345         if(strlen($xml->objectId) && ($xml->objectId != 0) && ($xml->image_url)) {
1346                 $body = '[url=' . notags(unxmlify($xml->image_url)) . '][img]' . notags(unxmlify($xml->objectId)) . '[/img][/url]' . "\n";
1347                 $body = scale_external_images($body,false);
1348         }
1349         elseif($xml->image_url) {
1350                 $body = '[img]' . notags(unxmlify($xml->image_url)) . '[/img]' . "\n";
1351                 $body = scale_external_images($body);
1352         }
1353         else {
1354                 logger('diaspora_asphoto: no photo url found.');
1355                 return;
1356         }
1357
1358         $plink = diaspora_plink($diaspora_handle, $guid);
1359
1360         $datarray = array();
1361
1362         $datarray['uid'] = $importer['uid'];
1363         $datarray['contact-id'] = $contact['id'];
1364         $datarray['wall'] = 0;
1365         $datarray['network']  = NETWORK_DIASPORA;
1366         $datarray['guid'] = $guid;
1367         $datarray['uri'] = $datarray['parent-uri'] = $message_id;
1368         $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
1369         $datarray['private'] = $private;
1370         $datarray['parent'] = 0;
1371         $datarray['plink'] = $plink;
1372         $datarray['owner-name'] = $contact['name'];
1373         $datarray['owner-link'] = $contact['url'];
1374         //$datarray['owner-avatar'] = $contact['thumb'];
1375         $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
1376         $datarray['author-name'] = $contact['name'];
1377         $datarray['author-link'] = $contact['url'];
1378         $datarray['author-avatar'] = $contact['thumb'];
1379         $datarray['body'] = $body;
1380         $datarray["object"] = json_encode($xml);
1381         $datarray['object-type'] = ACTIVITY_OBJ_PHOTO;
1382
1383         $datarray['app']  = 'Diaspora/Cubbi.es';
1384
1385         DiasporaFetchGuid($datarray);
1386         $message_id = item_store($datarray);
1387
1388         //if($message_id) {
1389         //      q("update item set plink = '%s' where id = %d",
1390         //              dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1391         //              intval($message_id)
1392         //      );
1393         //}
1394
1395         return;
1396
1397 }
1398
1399 function diaspora_comment($importer,$xml,$msg) {
1400
1401         $a = get_app();
1402         $guid = notags(unxmlify($xml->guid));
1403         $parent_guid = notags(unxmlify($xml->parent_guid));
1404         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1405         $target_type = notags(unxmlify($xml->target_type));
1406         $text = unxmlify($xml->text);
1407         $author_signature = notags(unxmlify($xml->author_signature));
1408
1409         $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1410
1411         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1412         if(! $contact) {
1413                 logger('diaspora_comment: cannot find contact: ' . $msg['author']);
1414                 return;
1415         }
1416
1417         if(! diaspora_post_allow($importer,$contact, true)) {
1418                 logger('diaspora_comment: Ignoring this author.');
1419                 return 202;
1420         }
1421
1422         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1423                 intval($importer['uid']),
1424                 dbesc($guid)
1425         );
1426         if(count($r)) {
1427                 logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid);
1428                 return;
1429         }
1430
1431         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1432                 intval($importer['uid']),
1433                 dbesc($parent_guid)
1434         );
1435
1436         if(!count($r)) {
1437                 $result = diaspora_store_by_guid($parent_guid, $contact['url'], $importer['uid']);
1438
1439                 if (!$result) {
1440                         $person = find_diaspora_person_by_handle($diaspora_handle);
1441                         $result = diaspora_store_by_guid($parent_guid, $person['url'], $importer['uid']);
1442                 }
1443
1444                 if ($result) {
1445                         logger("Fetched missing item ".$parent_guid." - result: ".$result, LOGGER_DEBUG);
1446
1447                         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1448                                 intval($importer['uid']),
1449                                 dbesc($parent_guid)
1450                         );
1451                 }
1452         }
1453
1454         if(! count($r)) {
1455                 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
1456                 return;
1457         }
1458         $parent_item = $r[0];
1459
1460
1461         /* How Diaspora performs comment signature checking:
1462
1463            - If an item has been sent by the comment author to the top-level post owner to relay on
1464              to the rest of the contacts on the top-level post, the top-level post owner should check
1465              the author_signature, then create a parent_author_signature before relaying the comment on
1466            - If an item has been relayed on by the top-level post owner, the contacts who receive it
1467              check only the parent_author_signature. Basically, they trust that the top-level post
1468              owner has already verified the authenticity of anything he/she sends out
1469            - In either case, the signature that get checked is the signature created by the person
1470              who sent the salmon
1471         */
1472
1473         $signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
1474         $key = $msg['key'];
1475
1476         if($parent_author_signature) {
1477                 // If a parent_author_signature exists, then we've received the comment
1478                 // relayed from the top-level post owner. There's no need to check the
1479                 // author_signature if the parent_author_signature is valid
1480
1481                 $parent_author_signature = base64_decode($parent_author_signature);
1482
1483                 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
1484                         logger('diaspora_comment: top-level owner verification failed.');
1485                         return;
1486                 }
1487         }
1488         else {
1489                 // If there's no parent_author_signature, then we've received the comment
1490                 // from the comment creator. In that case, the person is commenting on
1491                 // our post, so he/she must be a contact of ours and his/her public key
1492                 // should be in $msg['key']
1493
1494                 $author_signature = base64_decode($author_signature);
1495
1496                 if(! rsa_verify($signed_data,$author_signature,$key,'sha256')) {
1497                         logger('diaspora_comment: comment author verification failed.');
1498                         return;
1499                 }
1500         }
1501
1502         // Phew! Everything checks out. Now create an item.
1503
1504         // Find the original comment author information.
1505         // We need this to make sure we display the comment author
1506         // information (name and avatar) correctly.
1507         if(strcasecmp($diaspora_handle,$msg['author']) == 0)
1508                 $person = $contact;
1509         else {
1510                 $person = find_diaspora_person_by_handle($diaspora_handle);
1511
1512                 if(! is_array($person)) {
1513                         logger('diaspora_comment: unable to find author details');
1514                         return;
1515                 }
1516         }
1517
1518         // Fetch the contact id - if we know this contact
1519         $r = q("SELECT `id`, `network` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1520                 dbesc(normalise_link($person['url'])), intval($importer['uid']));
1521         if ($r) {
1522                 $cid = $r[0]['id'];
1523                 $network = $r[0]['network'];
1524         } else {
1525                 $cid = $contact['id'];
1526                 $network = NETWORK_DIASPORA;
1527         }
1528
1529         $body = diaspora2bb($text);
1530         $message_id = $diaspora_handle . ':' . $guid;
1531
1532         $datarray = array();
1533
1534         $datarray['uid'] = $importer['uid'];
1535         $datarray['contact-id'] = $cid;
1536         $datarray['type'] = 'remote-comment';
1537         $datarray['wall'] = $parent_item['wall'];
1538         $datarray['network']  = $network;
1539         $datarray['verb'] = ACTIVITY_POST;
1540         $datarray['gravity'] = GRAVITY_COMMENT;
1541         $datarray['guid'] = $guid;
1542         $datarray['uri'] = $message_id;
1543         $datarray['parent-uri'] = $parent_item['uri'];
1544
1545         // No timestamps for comments? OK, we'll the use current time.
1546         $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert();
1547         $datarray['private'] = $parent_item['private'];
1548
1549         $datarray['owner-name'] = $parent_item['owner-name'];
1550         $datarray['owner-link'] = $parent_item['owner-link'];
1551         $datarray['owner-avatar'] = $parent_item['owner-avatar'];
1552
1553         $datarray['author-name'] = $person['name'];
1554         $datarray['author-link'] = $person['url'];
1555         $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1556         $datarray['body'] = $body;
1557         $datarray["object"] = json_encode($xml);
1558         $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1559
1560         // We can't be certain what the original app is if the message is relayed.
1561         if(($parent_item['origin']) && (! $parent_author_signature))
1562                 $datarray['app']  = 'Diaspora';
1563
1564         DiasporaFetchGuid($datarray);
1565         $message_id = item_store($datarray);
1566
1567         $datarray['id'] = $message_id;
1568
1569         //if($message_id) {
1570                 //q("update item set plink = '%s' where id = %d",
1571                 //      //dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1572                 //      dbesc($a->get_baseurl().'/display/'.$datarray['guid']),
1573                 //      intval($message_id)
1574                 //);
1575         //}
1576
1577         // If we are the origin of the parent we store the original signature and notify our followers
1578         if($parent_item['origin']) {
1579                 $author_signature_base64 = base64_encode($author_signature);
1580                 $author_signature_base64 = diaspora_repair_signature($author_signature_base64, $diaspora_handle);
1581
1582                 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1583                         intval($message_id),
1584                         dbesc($signed_data),
1585                         dbesc($author_signature_base64),
1586                         dbesc($diaspora_handle)
1587                 );
1588
1589                 // notify others
1590                 proc_run('php','include/notifier.php','comment-import',$message_id);
1591         }
1592
1593         return;
1594 }
1595
1596
1597
1598
1599 function diaspora_conversation($importer,$xml,$msg) {
1600
1601         $a = get_app();
1602
1603         $guid = notags(unxmlify($xml->guid));
1604         $subject = notags(unxmlify($xml->subject));
1605         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1606         $participant_handles = notags(unxmlify($xml->participant_handles));
1607         $created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1608
1609         $parent_uri = $diaspora_handle . ':' . $guid;
1610
1611         $messages = $xml->message;
1612
1613         if(! count($messages)) {
1614                 logger('diaspora_conversation: empty conversation');
1615                 return;
1616         }
1617
1618         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1619         if(! $contact) {
1620                 logger('diaspora_conversation: cannot find contact: ' . $msg['author']);
1621                 return;
1622         }
1623
1624         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1625                 logger('diaspora_conversation: Ignoring this author.');
1626                 return 202;
1627         }
1628
1629         $conversation = null;
1630
1631         $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1632                 intval($importer['uid']),
1633                 dbesc($guid)
1634         );
1635         if(count($c))
1636                 $conversation = $c[0];
1637         else {
1638                 $r = q("insert into conv (uid,guid,creator,created,updated,subject,recips) values(%d, '%s', '%s', '%s', '%s', '%s', '%s') ",
1639                         intval($importer['uid']),
1640                         dbesc($guid),
1641                         dbesc($diaspora_handle),
1642                         dbesc(datetime_convert('UTC','UTC',$created_at)),
1643                         dbesc(datetime_convert()),
1644                         dbesc($subject),
1645                         dbesc($participant_handles)
1646                 );
1647                 if($r)
1648                         $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1649                 intval($importer['uid']),
1650             dbesc($guid)
1651         );
1652             if(count($c))
1653             $conversation = $c[0];
1654         }
1655         if(! $conversation) {
1656                 logger('diaspora_conversation: unable to create conversation.');
1657                 return;
1658         }
1659
1660         foreach($messages as $mesg) {
1661
1662                 $reply = 0;
1663
1664                 $msg_guid = notags(unxmlify($mesg->guid));
1665                 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1666                 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1667                 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1668                 $msg_text = unxmlify($mesg->text);
1669                 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($mesg->created_at)));
1670                 $msg_diaspora_handle = notags(unxmlify($mesg->diaspora_handle));
1671                 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1672                 if($msg_conversation_guid != $guid) {
1673                         logger('diaspora_conversation: message conversation guid does not belong to the current conversation. ' . $xml);
1674                         continue;
1675                 }
1676
1677                 $body = diaspora2bb($msg_text);
1678                 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1679
1680                 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1681
1682                 $author_signature = base64_decode($msg_author_signature);
1683
1684                 if(strcasecmp($msg_diaspora_handle,$msg['author']) == 0) {
1685                         $person = $contact;
1686                         $key = $msg['key'];
1687                 }
1688                 else {
1689                         $person = find_diaspora_person_by_handle($msg_diaspora_handle); 
1690
1691                         if(is_array($person) && x($person,'pubkey'))
1692                                 $key = $person['pubkey'];
1693                         else {
1694                                 logger('diaspora_conversation: unable to find author details');
1695                                 continue;
1696                         }
1697                 }
1698
1699                 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1700                         logger('diaspora_conversation: verification failed.');
1701                         continue;
1702                 }
1703
1704                 if($msg_parent_author_signature) {
1705                         $owner_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1706
1707                         $parent_author_signature = base64_decode($msg_parent_author_signature);
1708
1709                         $key = $msg['key'];
1710
1711                         if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1712                                 logger('diaspora_conversation: owner verification failed.');
1713                                 continue;
1714                         }
1715                 }
1716
1717                 $r = q("select id from mail where `uri` = '%s' limit 1",
1718                         dbesc($message_id)
1719                 );
1720                 if(count($r)) {
1721                         logger('diaspora_conversation: duplicate message already delivered.', LOGGER_DEBUG);
1722                         continue;
1723                 }
1724
1725                 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')",
1726                         intval($importer['uid']),
1727                         dbesc($msg_guid),
1728                         intval($conversation['id']),
1729                         dbesc($person['name']),
1730                         dbesc($person['photo']),
1731                         dbesc($person['url']),
1732                         intval($contact['id']),
1733                         dbesc($subject),
1734                         dbesc($body),
1735                         0,
1736                         0,
1737                         dbesc($message_id),
1738                         dbesc($parent_uri),
1739                         dbesc($msg_created_at)
1740                 );
1741
1742                 q("update conv set updated = '%s' where id = %d",
1743                         dbesc(datetime_convert()),
1744                         intval($conversation['id'])
1745                 );
1746
1747                 notification(array(
1748                         'type' => NOTIFY_MAIL,
1749                         'notify_flags' => $importer['notify-flags'],
1750                         'language' => $importer['language'],
1751                         'to_name' => $importer['username'],
1752                         'to_email' => $importer['email'],
1753                         'uid' =>$importer['uid'],
1754                         'item' => array('subject' => $subject, 'body' => $body),
1755                         'source_name' => $person['name'],
1756                         'source_link' => $person['url'],
1757                         'source_photo' => $person['thumb'],
1758                         'verb' => ACTIVITY_POST,
1759                         'otype' => 'mail'
1760                 ));
1761         }
1762
1763         return;
1764 }
1765
1766 function diaspora_message($importer,$xml,$msg) {
1767
1768         $a = get_app();
1769
1770         $msg_guid = notags(unxmlify($xml->guid));
1771         $msg_parent_guid = notags(unxmlify($xml->parent_guid));
1772         $msg_parent_author_signature = notags(unxmlify($xml->parent_author_signature));
1773         $msg_author_signature = notags(unxmlify($xml->author_signature));
1774         $msg_text = unxmlify($xml->text);
1775         $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1776         $msg_diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1777         $msg_conversation_guid = notags(unxmlify($xml->conversation_guid));
1778
1779         $parent_uri = $msg_diaspora_handle . ':' . $msg_parent_guid;
1780
1781         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg_diaspora_handle);
1782         if(! $contact) {
1783                 logger('diaspora_message: cannot find contact: ' . $msg_diaspora_handle);
1784                 return;
1785         }
1786
1787         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
1788                 logger('diaspora_message: Ignoring this author.');
1789                 return 202;
1790         }
1791
1792         $conversation = null;
1793
1794         $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1795                 intval($importer['uid']),
1796                 dbesc($msg_conversation_guid)
1797         );
1798         if(count($c))
1799                 $conversation = $c[0];
1800         else {
1801                 logger('diaspora_message: conversation not available.');
1802                 return;
1803         }
1804
1805         $reply = 0;
1806
1807         $body = diaspora2bb($msg_text);
1808         $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1809
1810         $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($xml->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1811
1812
1813         $author_signature = base64_decode($msg_author_signature);
1814
1815         $person = find_diaspora_person_by_handle($msg_diaspora_handle);
1816         if(is_array($person) && x($person,'pubkey'))
1817                 $key = $person['pubkey'];
1818         else {
1819                 logger('diaspora_message: unable to find author details');
1820                 return;
1821         }
1822
1823         if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1824                 logger('diaspora_message: verification failed.');
1825                 return;
1826         }
1827
1828         $r = q("select id from mail where `uri` = '%s' and uid = %d limit 1",
1829                 dbesc($message_id),
1830                 intval($importer['uid'])
1831         );
1832         if(count($r)) {
1833                 logger('diaspora_message: duplicate message already delivered.', LOGGER_DEBUG);
1834                 return;
1835         }
1836
1837         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')",
1838                 intval($importer['uid']),
1839                 dbesc($msg_guid),
1840                 intval($conversation['id']),
1841                 dbesc($person['name']),
1842                 dbesc($person['photo']),
1843                 dbesc($person['url']),
1844                 intval($contact['id']),
1845                 dbesc($conversation['subject']),
1846                 dbesc($body),
1847                 0,
1848                 1,
1849                 dbesc($message_id),
1850                 dbesc($parent_uri),
1851                 dbesc($msg_created_at)
1852         );
1853
1854         q("update conv set updated = '%s' where id = %d",
1855                 dbesc(datetime_convert()),
1856                 intval($conversation['id'])
1857         );
1858
1859         return;
1860 }
1861
1862 function diaspora_participation($importer,$xml) {
1863         logger("Unsupported message type 'participation' ".print_r($xml, true));
1864 }
1865
1866 function diaspora_photo($importer,$xml,$msg,$attempt=1) {
1867
1868         $a = get_app();
1869
1870         logger('diaspora_photo: init',LOGGER_DEBUG);
1871
1872         $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
1873
1874         $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
1875
1876         $status_message_guid = notags(unxmlify($xml->status_message_guid));
1877
1878         $guid = notags(unxmlify($xml->guid));
1879
1880         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1881
1882         $public = notags(unxmlify($xml->public));
1883
1884         $created_at = notags(unxmlify($xml_created_at));
1885
1886         logger('diaspora_photo: status_message_guid: ' . $status_message_guid, LOGGER_DEBUG);
1887
1888         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1889         if(! $contact) {
1890                 logger('diaspora_photo: contact record not found: ' . $msg['author'] . ' handle: ' . $diaspora_handle);
1891                 return;
1892         }
1893
1894         if(! diaspora_post_allow($importer,$contact, false)) {
1895                 logger('diaspora_photo: Ignoring this author.');
1896                 return 202;
1897         }
1898
1899         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1900                 intval($importer['uid']),
1901                 dbesc($status_message_guid)
1902         );
1903
1904 /*      deactivated by now since it can lead to multiplicated pictures in posts.
1905         if(!count($r)) {
1906                 $result = diaspora_store_by_guid($status_message_guid, $contact['url'], $importer['uid']);
1907
1908                 if (!$result) {
1909                         $person = find_diaspora_person_by_handle($diaspora_handle);
1910                         $result = diaspora_store_by_guid($status_message_guid, $person['url'], $importer['uid']);
1911                 }
1912
1913                 if ($result) {
1914                         logger("Fetched missing item ".$status_message_guid." - result: ".$result, LOGGER_DEBUG);
1915
1916                         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1917                                 intval($importer['uid']),
1918                                 dbesc($status_message_guid)
1919                         );
1920                 }
1921         }
1922 */
1923         if(!count($r)) {
1924                 if($attempt <= 3) {
1925                         q("INSERT INTO dsprphotoq (uid, msg, attempt) VALUES (%d, '%s', %d)",
1926                            intval($importer['uid']),
1927                            dbesc(serialize($msg)),
1928                            intval($attempt + 1)
1929                         );
1930                 }
1931
1932                 logger('diaspora_photo: attempt = ' . $attempt . '; status message not found: ' . $status_message_guid . ' for photo: ' . $guid);
1933                 return;
1934         }
1935
1936         $parent_item = $r[0];
1937
1938         $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
1939
1940         $link_text = scale_external_images($link_text, true,
1941                                            array($remote_photo_name, 'scaled_full_' . $remote_photo_name));
1942
1943         if(strpos($parent_item['body'],$link_text) === false) {
1944
1945                 $parent_item['body'] = $link_text . $parent_item['body'];
1946
1947                 $r = q("UPDATE `item` SET `body` = '%s', `visible` = 1 WHERE `id` = %d AND `uid` = %d",
1948                         dbesc($parent_item['body']),
1949                         intval($parent_item['id']),
1950                         intval($parent_item['uid'])
1951                 );
1952                 put_item_in_cache($parent_item, true);
1953                 update_thread($parent_item['id']);
1954         }
1955
1956         return;
1957 }
1958
1959
1960
1961
1962 function diaspora_like($importer,$xml,$msg) {
1963
1964         $a = get_app();
1965         $guid = notags(unxmlify($xml->guid));
1966         $parent_guid = notags(unxmlify($xml->parent_guid));
1967         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1968         $target_type = notags(unxmlify($xml->target_type));
1969         $positive = notags(unxmlify($xml->positive));
1970         $author_signature = notags(unxmlify($xml->author_signature));
1971
1972         $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1973
1974         // likes on comments not supported here and likes on photos not supported by Diaspora
1975
1976 //      if($target_type !== 'Post')
1977 //              return;
1978
1979         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1980         if(! $contact) {
1981                 logger('diaspora_like: cannot find contact: ' . $msg['author']);
1982                 return;
1983         }
1984
1985         if(! diaspora_post_allow($importer,$contact, false)) {
1986                 logger('diaspora_like: Ignoring this author.');
1987                 return 202;
1988         }
1989
1990         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1991                 intval($importer['uid']),
1992                 dbesc($parent_guid)
1993         );
1994
1995         if(!count($r)) {
1996                 $result = diaspora_store_by_guid($parent_guid, $contact['url'], $importer['uid']);
1997
1998                 if (!$result) {
1999                         $person = find_diaspora_person_by_handle($diaspora_handle);
2000                         $result = diaspora_store_by_guid($parent_guid, $person['url'], $importer['uid']);
2001                 }
2002
2003                 if ($result) {
2004                         logger("Fetched missing item ".$parent_guid." - result: ".$result, LOGGER_DEBUG);
2005
2006                         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
2007                                 intval($importer['uid']),
2008                                 dbesc($parent_guid)
2009                         );
2010                 }
2011         }
2012
2013         if(! count($r)) {
2014                 logger('diaspora_like: parent item not found: ' . $guid);
2015                 return;
2016         }
2017
2018         $parent_item = $r[0];
2019
2020         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
2021                 intval($importer['uid']),
2022                 dbesc($guid)
2023         );
2024         if(count($r)) {
2025                 if($positive === 'true') {
2026                         logger('diaspora_like: duplicate like: ' . $guid);
2027                         return;
2028                 }
2029                 // Note: I don't think "Like" objects with positive = "false" are ever actually used
2030                 // It looks like "RelayableRetractions" are used for "unlike" instead
2031                 if($positive === 'false') {
2032                         logger('diaspora_like: received a like with positive set to "false"...ignoring');
2033 /*                      q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d",
2034                                 intval($r[0]['id']),
2035                                 intval($importer['uid'])
2036                         );*/
2037                         // FIXME--actually don't unless it turns out that Diaspora does indeed send out "false" likes
2038                         //  send notification via proc_run()
2039                         return;
2040                 }
2041         }
2042         // Note: I don't think "Like" objects with positive = "false" are ever actually used
2043         // It looks like "RelayableRetractions" are used for "unlike" instead
2044         if($positive === 'false') {
2045                 logger('diaspora_like: received a like with positive set to "false"');
2046                 logger('diaspora_like: unlike received with no corresponding like...ignoring');
2047                 return;
2048         }
2049
2050
2051         /* How Diaspora performs "like" signature checking:
2052
2053            - If an item has been sent by the like author to the top-level post owner to relay on
2054              to the rest of the contacts on the top-level post, the top-level post owner should check
2055              the author_signature, then create a parent_author_signature before relaying the like on
2056            - If an item has been relayed on by the top-level post owner, the contacts who receive it
2057              check only the parent_author_signature. Basically, they trust that the top-level post
2058              owner has already verified the authenticity of anything he/she sends out
2059            - In either case, the signature that get checked is the signature created by the person
2060              who sent the salmon
2061         */
2062
2063         // Diaspora has changed the way they are signing the likes.
2064         // Just to make sure that we don't miss any likes we will check the old and the current way.
2065         $old_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
2066
2067         $signed_data = $positive . ';' . $guid . ';' . $target_type . ';' . $parent_guid . ';' . $diaspora_handle;
2068
2069         $key = $msg['key'];
2070
2071         if ($parent_author_signature) {
2072                 // If a parent_author_signature exists, then we've received the like
2073                 // relayed from the top-level post owner. There's no need to check the
2074                 // author_signature if the parent_author_signature is valid
2075
2076                 $parent_author_signature = base64_decode($parent_author_signature);
2077
2078                 if (!rsa_verify($signed_data,$parent_author_signature,$key,'sha256') AND
2079                         !rsa_verify($old_signed_data,$parent_author_signature,$key,'sha256')) {
2080
2081                         logger('diaspora_like: top-level owner verification failed.');
2082                         return;
2083                 }
2084         } else {
2085                 // If there's no parent_author_signature, then we've received the like
2086                 // from the like creator. In that case, the person is "like"ing
2087                 // our post, so he/she must be a contact of ours and his/her public key
2088                 // should be in $msg['key']
2089
2090                 $author_signature = base64_decode($author_signature);
2091
2092                 if (!rsa_verify($signed_data,$author_signature,$key,'sha256') AND
2093                         !rsa_verify($old_signed_data,$author_signature,$key,'sha256')) {
2094
2095                         logger('diaspora_like: like creator verification failed.');
2096                         return;
2097                 }
2098         }
2099
2100         // Phew! Everything checks out. Now create an item.
2101
2102         // Find the original comment author information.
2103         // We need this to make sure we display the comment author
2104         // information (name and avatar) correctly.
2105         if(strcasecmp($diaspora_handle,$msg['author']) == 0)
2106                 $person = $contact;
2107         else {
2108                 $person = find_diaspora_person_by_handle($diaspora_handle);
2109
2110                 if(! is_array($person)) {
2111                         logger('diaspora_like: unable to find author details');
2112                         return;
2113                 }
2114         }
2115
2116         $uri = $diaspora_handle . ':' . $guid;
2117
2118         $activity = ACTIVITY_LIKE;
2119         $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
2120         $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE );
2121         $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
2122         $body = $parent_item['body'];
2123
2124         $obj = <<< EOT
2125
2126         <object>
2127                 <type>$objtype</type>
2128                 <local>1</local>
2129                 <id>{$parent_item['uri']}</id>
2130                 <link>$link</link>
2131                 <title></title>
2132                 <content>$body</content>
2133         </object>
2134 EOT;
2135         $bodyverb = t('%1$s likes %2$s\'s %3$s');
2136
2137         // Fetch the contact id - if we know this contact
2138         $r = q("SELECT `id`, `network` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
2139                 dbesc(normalise_link($person['url'])), intval($importer['uid']));
2140         if ($r) {
2141                 $cid = $r[0]['id'];
2142                 $network = $r[0]['network'];
2143         } else {
2144                 $cid = $contact['id'];
2145                 $network = NETWORK_DIASPORA;
2146         }
2147
2148         $arr = array();
2149
2150         $arr['uri'] = $uri;
2151         $arr['uid'] = $importer['uid'];
2152         $arr['guid'] = $guid;
2153         $arr['network']  = $network;
2154         $arr['contact-id'] = $cid;
2155         $arr['type'] = 'activity';
2156         $arr['wall'] = $parent_item['wall'];
2157         $arr['gravity'] = GRAVITY_LIKE;
2158         $arr['parent'] = $parent_item['id'];
2159         $arr['parent-uri'] = $parent_item['uri'];
2160
2161         $arr['owner-name'] = $parent_item['name'];
2162         $arr['owner-link'] = $parent_item['url'];
2163         //$arr['owner-avatar'] = $parent_item['thumb'];
2164         $arr['owner-avatar'] = ((x($parent_item,'thumb')) ? $parent_item['thumb'] : $parent_item['photo']);
2165
2166         $arr['author-name'] = $person['name'];
2167         $arr['author-link'] = $person['url'];
2168         $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
2169
2170         $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
2171         $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
2172         //$plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
2173         $plink = '[url='.$a->get_baseurl().'/display/'.urlencode($guid).']'.$post_type.'[/url]';
2174         $arr['body'] =  sprintf( $bodyverb, $ulink, $alink, $plink );
2175
2176         $arr['app']  = 'Diaspora';
2177
2178         $arr['private'] = $parent_item['private'];
2179         $arr['verb'] = $activity;
2180         $arr['object-type'] = $objtype;
2181         $arr['object'] = $obj;
2182         $arr['visible'] = 1;
2183         $arr['unseen'] = 1;
2184         $arr['last-child'] = 0;
2185
2186         $message_id = item_store($arr);
2187
2188
2189         //if($message_id) {
2190         //      q("update item set plink = '%s' where id = %d",
2191         //              //dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
2192         //              dbesc($a->get_baseurl().'/display/'.$guid),
2193         //              intval($message_id)
2194         //      );
2195         //}
2196
2197         // If we are the origin of the parent we store the original signature and notify our followers
2198         if($parent_item['origin']) {
2199                 $author_signature_base64 = base64_encode($author_signature);
2200                 $author_signature_base64 = diaspora_repair_signature($author_signature_base64, $diaspora_handle);
2201
2202                 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
2203                         intval($message_id),
2204                         dbesc($signed_data),
2205                         dbesc($author_signature_base64),
2206                         dbesc($diaspora_handle)
2207                 );
2208
2209                 // notify others
2210                 proc_run('php','include/notifier.php','comment-import',$message_id);
2211         }
2212
2213         return;
2214 }
2215
2216 function diaspora_retraction($importer,$xml) {
2217
2218
2219         $guid = notags(unxmlify($xml->guid));
2220         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
2221         $type = notags(unxmlify($xml->type));
2222
2223         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2224         if(! $contact)
2225                 return;
2226
2227         if($type === 'Person') {
2228                 require_once('include/Contact.php');
2229                 contact_remove($contact['id']);
2230         } elseif($type === 'StatusMessage') {
2231                 $guid = notags(unxmlify($xml->post_guid));
2232
2233                 $r = q("SELECT * FROM `item` WHERE `guid` = '%s' AND `uid` = %d AND NOT `file` LIKE '%%[%%' LIMIT 1",
2234                         dbesc($guid),
2235                         intval($importer['uid'])
2236                 );
2237                 if(count($r)) {
2238                         if(link_compare($r[0]['author-link'],$contact['url'])) {
2239                                 q("UPDATE `item` SET `deleted` = 1, `changed` = '%s' WHERE `id` = %d",
2240                                         dbesc(datetime_convert()),
2241                                         intval($r[0]['id'])
2242                                 );
2243                                 delete_thread($r[0]['id'], $r[0]['parent-uri']);
2244                         }
2245                 }
2246         } elseif($type === 'Post') {
2247                 $r = q("select * from item where guid = '%s' and uid = %d and not file like '%%[%%' limit 1",
2248                         dbesc('guid'),
2249                         intval($importer['uid'])
2250                 );
2251                 if(count($r)) {
2252                         if(link_compare($r[0]['author-link'],$contact['url'])) {
2253                                 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d",
2254                                         dbesc(datetime_convert()),
2255                                         intval($r[0]['id'])
2256                                 );
2257                                 delete_thread($r[0]['id'], $r[0]['parent-uri']);
2258                         }
2259                 }
2260         }
2261
2262         return 202;
2263         // NOTREACHED
2264 }
2265
2266 function diaspora_signed_retraction($importer,$xml,$msg) {
2267
2268
2269         $guid = notags(unxmlify($xml->target_guid));
2270         $diaspora_handle = notags(unxmlify($xml->sender_handle));
2271         $type = notags(unxmlify($xml->target_type));
2272         $sig = notags(unxmlify($xml->target_author_signature));
2273
2274         $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
2275
2276         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2277         if(! $contact) {
2278                 logger('diaspora_signed_retraction: no contact ' . $diaspora_handle . ' for ' . $importer['uid']);
2279                 return;
2280         }
2281
2282
2283         $signed_data = $guid . ';' . $type ;
2284         $key = $msg['key'];
2285
2286         /* How Diaspora performs relayable_retraction signature checking:
2287
2288            - If an item has been sent by the item author to the top-level post owner to relay on
2289              to the rest of the contacts on the top-level post, the top-level post owner checks
2290              the author_signature, then creates a parent_author_signature before relaying the item on
2291            - If an item has been relayed on by the top-level post owner, the contacts who receive it
2292              check only the parent_author_signature. Basically, they trust that the top-level post
2293              owner has already verified the authenticity of anything he/she sends out
2294            - In either case, the signature that get checked is the signature created by the person
2295              who sent the salmon
2296         */
2297
2298         if($parent_author_signature) {
2299
2300                 $parent_author_signature = base64_decode($parent_author_signature);
2301
2302                 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
2303                         logger('diaspora_signed_retraction: top-level post owner verification failed');
2304                         return;
2305                 }
2306
2307         } else {
2308
2309                 $sig_decode = base64_decode($sig);
2310
2311                 if(! rsa_verify($signed_data,$sig_decode,$key,'sha256')) {
2312                         logger('diaspora_signed_retraction: retraction owner verification failed.' . print_r($msg,true));
2313                         return;
2314                 }
2315         }
2316
2317         if($type === 'StatusMessage' || $type === 'Comment' || $type === 'Like') {
2318                 $r = q("select * from item where guid = '%s' and uid = %d and not file like '%%[%%' limit 1",
2319                         dbesc($guid),
2320                         intval($importer['uid'])
2321                 );
2322                 if(count($r)) {
2323                         if(link_compare($r[0]['author-link'],$contact['url'])) {
2324                                 q("update item set `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' where `id` = %d",
2325                                         dbesc(datetime_convert()),
2326                                         dbesc(datetime_convert()),
2327                                         intval($r[0]['id'])
2328                                 );
2329                                 delete_thread($r[0]['id'], $r[0]['parent-uri']);
2330
2331                                 // Now check if the retraction needs to be relayed by us
2332                                 //
2333                                 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2334                                 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2335                                 // The only item with `parent` and `id` as the parent id is the parent item.
2336                                 $p = q("SELECT `origin` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
2337                                         intval($r[0]['parent']),
2338                                         intval($r[0]['parent'])
2339                                 );
2340                                 if(count($p)) {
2341                                         if($p[0]['origin']) {
2342                                                 q("insert into sign (`retract_iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
2343                                                         $r[0]['id'],
2344                                                         dbesc($signed_data),
2345                                                         dbesc($sig),
2346                                                         dbesc($diaspora_handle)
2347                                                 );
2348
2349                                                 // the existence of parent_author_signature would have meant the parent_author or owner
2350                                                 // is already relaying.
2351                                                 logger('diaspora_signed_retraction: relaying relayable_retraction');
2352
2353                                                 proc_run('php','include/notifier.php','drop',$r[0]['id']);
2354                                         }
2355                                 }
2356                         }
2357                 }
2358         }
2359         else
2360                 logger('diaspora_signed_retraction: unknown type: ' . $type);
2361
2362         return 202;
2363         // NOTREACHED
2364 }
2365
2366 function diaspora_profile($importer,$xml,$msg) {
2367
2368         $a = get_app();
2369         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
2370
2371
2372         if($diaspora_handle != $msg['author']) {
2373                 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
2374                 return 202;
2375         }
2376
2377         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2378         if(! $contact)
2379                 return;
2380
2381         //if($contact['blocked']) {
2382         //      logger('diaspora_post: Ignoring this author.');
2383         //      return 202;
2384         //}
2385
2386         $name = unxmlify($xml->first_name) . ((strlen($xml->last_name)) ? ' ' . unxmlify($xml->last_name) : '');
2387         $image_url = unxmlify($xml->image_url);
2388         $birthday = unxmlify($xml->birthday);
2389         $location = diaspora2bb(unxmlify($xml->location));
2390         $about = diaspora2bb(unxmlify($xml->bio));
2391         $gender = unxmlify($xml->gender);
2392         $searchable = (unxmlify($xml->searchable) == "true");
2393         $nsfw = (unxmlify($xml->nsfw) == "true");
2394         $tags = unxmlify($xml->tag_string);
2395
2396         $tags = explode("#", $tags);
2397
2398         $keywords = array();
2399         foreach ($tags as $tag) {
2400                 $tag = trim(strtolower($tag));
2401                 if ($tag != "")
2402                         $keywords[] = $tag;
2403         }
2404
2405         $keywords = implode(", ", $keywords);
2406
2407         $handle_parts = explode("@", $diaspora_handle);
2408         $nick = $handle_parts[0];
2409
2410         if($name === '') {
2411                 $name = $handle_parts[0];
2412         }
2413
2414         if( preg_match("|^https?://|", $image_url) === 0) {
2415                 $image_url = "http://" . $handle_parts[1] . $image_url;
2416         }
2417
2418 /*      $r = q("SELECT DISTINCT ( `resource-id` ) FROM `photo` WHERE  `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' ",
2419                 intval($importer['uid']),
2420                 intval($contact['id'])
2421         );
2422         $oldphotos = ((count($r)) ? $r : null);*/
2423
2424         require_once('include/Photo.php');
2425
2426         update_contact_avatar($image_url,$importer['uid'],$contact['id']);
2427
2428         // Generic birthday. We don't know the timezone. The year is irrelevant.
2429
2430         $birthday = str_replace('1000','1901',$birthday);
2431
2432         if ($birthday != "")
2433                 $birthday = datetime_convert('UTC','UTC',$birthday,'Y-m-d');
2434
2435         // this is to prevent multiple birthday notifications in a single year
2436         // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2437
2438         if(substr($birthday,5) === substr($contact['bd'],5))
2439                 $birthday = $contact['bd'];
2440
2441         /// @TODO Update name on item['author-name'] if the name changed. See consume_feed()
2442         /// (Not doing this currently because D* protocol is scheduled for revision soon).
2443
2444         $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
2445                         `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
2446                 dbesc($name),
2447                 dbesc($nick),
2448                 dbesc($diaspora_handle),
2449                 dbesc(datetime_convert()),
2450                 dbesc($birthday),
2451                 dbesc($location),
2452                 dbesc($about),
2453                 dbesc($keywords),
2454                 dbesc($gender),
2455                 intval($contact['id']),
2456                 intval($importer['uid'])
2457         );
2458
2459         if ($searchable) {
2460                 require_once('include/socgraph.php');
2461                 poco_check($contact['url'], $name, NETWORK_DIASPORA, $image_url, $about, $location, $gender, $keywords, "",
2462                         datetime_convert(), 2, $contact['id'], $importer['uid']);
2463         }
2464
2465         update_gcontact(array("url" => $contact['url'], "network" => NETWORK_DIASPORA, "generation" => 2,
2466                                 "photo" => $image_url, "name" => $name, "location" => $location,
2467                                 "about" => $about, "birthday" => $birthday, "gender" => $gender,
2468                                 "addr" => $diaspora_handle, "nick" => $nick, "keywords" => $keywords,
2469                                 "hide" => !$searchable, "nsfw" => $nsfw));
2470
2471 /*      if($r) {
2472                 if($oldphotos) {
2473                         foreach($oldphotos as $ph) {
2474                                 q("DELETE FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' AND `resource-id` = '%s' ",
2475                                         intval($importer['uid']),
2476                                         intval($contact['id']),
2477                                         dbesc($ph['resource-id'])
2478                                 );
2479                         }
2480                 }
2481         }       */
2482
2483         return;
2484
2485 }
2486
2487 function diaspora_share($me,$contact) {
2488         $a = get_app();
2489         $myaddr = $me['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2490         $theiraddr = $contact['addr'];
2491
2492         $tpl = get_markup_template('diaspora_share.tpl');
2493         $msg = replace_macros($tpl, array(
2494                 '$sender' => $myaddr,
2495                 '$recipient' => $theiraddr
2496         ));
2497
2498         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
2499         //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
2500
2501         return(diaspora_transmit($owner,$contact,$slap, false));
2502 }
2503
2504 function diaspora_unshare($me,$contact) {
2505
2506         $a = get_app();
2507         $myaddr = $me['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2508
2509         $tpl = get_markup_template('diaspora_retract.tpl');
2510         $msg = replace_macros($tpl, array(
2511                 '$guid'   => $me['guid'],
2512                 '$type'   => 'Person',
2513                 '$handle' => $myaddr
2514         ));
2515
2516         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
2517         //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
2518
2519         return(diaspora_transmit($owner,$contact,$slap, false));
2520
2521 }
2522
2523
2524 function diaspora_send_status($item,$owner,$contact,$public_batch = false) {
2525
2526         $a = get_app();
2527         $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2528         $theiraddr = $contact['addr'];
2529
2530         $images = array();
2531
2532         $title = $item['title'];
2533         $body = $item['body'];
2534
2535 /*
2536         // We're trying to match Diaspora's split message/photo protocol but
2537         // all the photos are displayed on D* as links and not img's - even
2538         // though we're sending pretty much precisely what they send us when
2539         // doing the same operation.  
2540         // Commented out for now, we'll use bb2diaspora to convert photos to markdown
2541         // which seems to get through intact.
2542
2543         $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
2544         if($cnt) {
2545                 foreach($matches as $mtch) {
2546                         $detail = array();
2547                         $detail['str'] = $mtch[0];
2548                         $detail['path'] = dirname($mtch[1]) . '/';
2549                         $detail['file'] = basename($mtch[1]);
2550                         $detail['guid'] = $item['guid'];
2551                         $detail['handle'] = $myaddr;
2552                         $images[] = $detail;
2553                         $body = str_replace($detail['str'],$mtch[1],$body);
2554                 }
2555         }
2556 */
2557
2558         //if(strlen($title))
2559         //      $body = "[b]".html_entity_decode($title)."[/b]\n\n".$body;
2560
2561         // convert to markdown
2562         $body = xmlify(html_entity_decode(bb2diaspora($body)));
2563         //$body = bb2diaspora($body);
2564
2565         // Adding the title
2566         if(strlen($title))
2567                 $body = "## ".html_entity_decode($title)."\n\n".$body;
2568
2569         if($item['attach']) {
2570                 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism',$item['attach'],$matches,PREG_SET_ORDER);
2571                 if(cnt) {
2572                         $body .= "\n" . t('Attachments:') . "\n";
2573                         foreach($matches as $mtch) {
2574                                 $body .= '[' . $mtch[3] . '](' . $mtch[1] . ')' . "\n";
2575                         }
2576                 }
2577         }
2578
2579
2580         $public = (($item['private']) ? 'false' : 'true');
2581
2582         require_once('include/datetime.php');
2583         $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
2584
2585         // Detect a share element and do a reshare
2586         // see: https://github.com/Raven24/diaspora-federation/blob/master/lib/diaspora-federation/entities/reshare.rb
2587         if (!$item['private'] AND ($ret = diaspora_is_reshare($item["body"]))) {
2588                 $tpl = get_markup_template('diaspora_reshare.tpl');
2589                 $msg = replace_macros($tpl, array(
2590                         '$root_handle' => xmlify($ret['root_handle']),
2591                         '$root_guid' => $ret['root_guid'],
2592                         '$guid' => $item['guid'],
2593                         '$handle' => xmlify($myaddr),
2594                         '$public' => $public,
2595                         '$created' => $created,
2596                         '$provider' => $item["app"]
2597                 ));
2598         } else {
2599                 $tpl = get_markup_template('diaspora_post.tpl');
2600                 $msg = replace_macros($tpl, array(
2601                         '$body' => $body,
2602                         '$guid' => $item['guid'],
2603                         '$handle' => xmlify($myaddr),
2604                         '$public' => $public,
2605                         '$created' => $created,
2606                         '$provider' => $item["app"]
2607                 ));
2608         }
2609
2610         logger('diaspora_send_status: '.$owner['username'].' -> '.$contact['name'].' base message: '.$msg, LOGGER_DATA);
2611         logger('send guid '.$item['guid'], LOGGER_DEBUG);
2612
2613         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2614         //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2615
2616         $return_code = diaspora_transmit($owner,$contact,$slap,$public_batch,false,$item['guid']);
2617
2618         logger('diaspora_send_status: guid: '.$item['guid'].' result '.$return_code, LOGGER_DEBUG);
2619
2620         if(count($images)) {
2621                 diaspora_send_images($item,$owner,$contact,$images,$public_batch);
2622         }
2623
2624         return $return_code;
2625 }
2626
2627 function diaspora_is_reshare($body) {
2628         $body = trim($body);
2629
2630         // Skip if it isn't a pure repeated messages
2631         // Does it start with a share?
2632         if (strpos($body, "[share") > 0)
2633                 return(false);
2634
2635         // Does it end with a share?
2636         if (strlen($body) > (strrpos($body, "[/share]") + 8))
2637                 return(false);
2638
2639         $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2640         // Skip if there is no shared message in there
2641         if ($body == $attributes)
2642                 return(false);
2643
2644         $guid = "";
2645         preg_match("/guid='(.*?)'/ism", $attributes, $matches);
2646         if ($matches[1] != "")
2647                 $guid = $matches[1];
2648
2649         preg_match('/guid="(.*?)"/ism', $attributes, $matches);
2650         if ($matches[1] != "")
2651                 $guid = $matches[1];
2652
2653         if ($guid != "") {
2654                 $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
2655                         dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
2656                 if ($r) {
2657                         $ret= array();
2658                         $ret["root_handle"] = diaspora_handle_from_contact($r[0]["contact-id"]);
2659                         $ret["root_guid"] = $guid;
2660                         return($ret);
2661                 }
2662         }
2663
2664         $profile = "";
2665         preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2666         if ($matches[1] != "")
2667                 $profile = $matches[1];
2668
2669         preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2670         if ($matches[1] != "")
2671                 $profile = $matches[1];
2672
2673         $ret= array();
2674
2675         $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
2676         if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
2677                 return(false);
2678
2679         $link = "";
2680         preg_match("/link='(.*?)'/ism", $attributes, $matches);
2681         if ($matches[1] != "")
2682                 $link = $matches[1];
2683
2684         preg_match('/link="(.*?)"/ism', $attributes, $matches);
2685         if ($matches[1] != "")
2686                 $link = $matches[1];
2687
2688         $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
2689         if (($ret["root_guid"] == $link) OR ($ret["root_guid"] == ""))
2690                 return(false);
2691
2692         return($ret);
2693 }
2694
2695 function diaspora_send_images($item,$owner,$contact,$images,$public_batch = false) {
2696         $a = get_app();
2697         if(! count($images))
2698                 return;
2699         $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
2700
2701         $tpl = get_markup_template('diaspora_photo.tpl');
2702         foreach($images as $image) {
2703                 if(! stristr($image['path'],$mysite))
2704                         continue;
2705                 $resource = str_replace('.jpg','',$image['file']);
2706                 $resource = substr($resource,0,strpos($resource,'-'));
2707
2708                 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
2709                         dbesc($resource),
2710                         intval($owner['uid'])
2711                 );
2712                 if(! count($r))
2713                         continue;
2714                 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
2715                 $msg = replace_macros($tpl,array(
2716                         '$path' => xmlify($image['path']),
2717                         '$filename' => xmlify($image['file']),
2718                         '$msg_guid' => xmlify($image['guid']),
2719                         '$guid' => xmlify($r[0]['guid']),
2720                         '$handle' => xmlify($image['handle']),
2721                         '$public' => xmlify($public),
2722                         '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d H:i:s \U\T\C'))
2723                 ));
2724
2725
2726                 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
2727                 logger('send guid '.$r[0]['guid'], LOGGER_DEBUG);
2728
2729                 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2730                 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2731
2732                 diaspora_transmit($owner,$contact,$slap,$public_batch,false,$r[0]['guid']);
2733         }
2734
2735 }
2736
2737 function diaspora_send_followup($item,$owner,$contact,$public_batch = false) {
2738
2739         $a = get_app();
2740         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2741 //      $theiraddr = $contact['addr'];
2742
2743         // Diaspora doesn't support threaded comments, but some
2744         // versions of Diaspora (i.e. Diaspora-pistos) support
2745         // likes on comments
2746         if($item['verb'] === ACTIVITY_LIKE && $item['thr-parent']) {
2747                 $p = q("select guid, type, uri, `parent-uri` from item where uri = '%s' limit 1",
2748                         dbesc($item['thr-parent'])
2749                       );
2750         }
2751         else {
2752                 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2753                 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2754                 // The only item with `parent` and `id` as the parent id is the parent item.
2755                 $p = q("select guid, type, uri, `parent-uri` from item where parent = %d and id = %d limit 1",
2756                         intval($item['parent']),
2757                         intval($item['parent'])
2758                 );
2759         }
2760         if(count($p))
2761                 $parent = $p[0];
2762         else
2763                 return;
2764
2765         if($item['verb'] === ACTIVITY_LIKE) {
2766                 $tpl = get_markup_template('diaspora_like.tpl');
2767                 $like = true;
2768                 $target_type = ( $parent['uri'] === $parent['parent-uri']  ? 'Post' : 'Comment');
2769 //              $target_type = (strpos($parent['type'], 'comment') ? 'Comment' : 'Post');
2770 //              $positive = (($item['deleted']) ? 'false' : 'true');
2771                 $positive = 'true';
2772
2773                 if(($item['deleted']))
2774                         logger('diaspora_send_followup: received deleted "like". Those should go to diaspora_send_retraction');
2775         }
2776         else {
2777                 $tpl = get_markup_template('diaspora_comment.tpl');
2778                 $like = false;
2779         }
2780
2781         $text = html_entity_decode(bb2diaspora($item['body']));
2782
2783         // sign it
2784
2785         if($like)
2786                 $signed_text =  $positive . ';' . $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $myaddr;
2787         else
2788                 $signed_text = $item['guid'] . ';' . $parent['guid'] . ';' . $text . ';' . $myaddr;
2789
2790         $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2791
2792         $msg = replace_macros($tpl,array(
2793                 '$guid' => xmlify($item['guid']),
2794                 '$parent_guid' => xmlify($parent['guid']),
2795                 '$target_type' =>xmlify($target_type),
2796                 '$authorsig' => xmlify($authorsig),
2797                 '$body' => xmlify($text),
2798                 '$positive' => xmlify($positive),
2799                 '$handle' => xmlify($myaddr)
2800         ));
2801
2802         logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
2803         logger('send guid '.$item['guid'], LOGGER_DEBUG);
2804
2805         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2806         //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2807
2808         return(diaspora_transmit($owner,$contact,$slap,$public_batch,false,$item['guid']));
2809 }
2810
2811
2812 function diaspora_send_relay($item,$owner,$contact,$public_batch = false) {
2813
2814
2815         $a = get_app();
2816         $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2817 //      $theiraddr = $contact['addr'];
2818
2819         // Diaspora doesn't support threaded comments, but some
2820         // versions of Diaspora (i.e. Diaspora-pistos) support
2821         // likes on comments
2822         if($item['verb'] === ACTIVITY_LIKE && $item['thr-parent']) {
2823                 $p = q("select guid, type, uri, `parent-uri` from item where uri = '%s' limit 1",
2824                         dbesc($item['thr-parent'])
2825                       );
2826         }
2827         else {
2828                 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2829                 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2830                 // The only item with `parent` and `id` as the parent id is the parent item.
2831                 $p = q("select guid, type, uri, `parent-uri` from item where parent = %d and id = %d limit 1",
2832                        intval($item['parent']),
2833                        intval($item['parent'])
2834                       );
2835         }
2836         if(count($p))
2837                 $parent = $p[0];
2838         else
2839                 return;
2840
2841         $like = false;
2842         $relay_retract = false;
2843         $sql_sign_id = 'iid';
2844         if( $item['deleted']) {
2845                 $relay_retract = true;
2846
2847                 $target_type = ( ($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2848
2849                 $sql_sign_id = 'retract_iid';
2850                 $tpl = get_markup_template('diaspora_relayable_retraction.tpl');
2851         }
2852         elseif($item['verb'] === ACTIVITY_LIKE) {
2853                 $like = true;
2854
2855                 $target_type = ( $parent['uri'] === $parent['parent-uri']  ? 'Post' : 'Comment');
2856 //              $positive = (($item['deleted']) ? 'false' : 'true');
2857                 $positive = 'true';
2858
2859                 $tpl = get_markup_template('diaspora_like_relay.tpl');
2860         }
2861         else { // item is a comment
2862                 $tpl = get_markup_template('diaspora_comment_relay.tpl');
2863         }
2864
2865
2866         // fetch the original signature if the relayable was created by a Diaspora
2867         // or DFRN user. Relayables for other networks are not supported.
2868
2869         $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE " . $sql_sign_id . " = %d LIMIT 1",
2870                 intval($item['id'])
2871         );
2872         if(count($r)) {
2873                 $orig_sign = $r[0];
2874                 $signed_text = $orig_sign['signed_text'];
2875                 $authorsig = $orig_sign['signature'];
2876                 $handle = $orig_sign['signer'];
2877
2878                 // Split the signed text
2879                 $signed_parts = explode(";", $signed_text);
2880
2881                 // Remove the parent guid
2882                 array_shift($signed_parts);
2883
2884                 // Remove the comment guid
2885                 array_shift($signed_parts);
2886
2887                 // Remove the handle
2888                 array_pop($signed_parts);
2889
2890                 // Glue the parts together
2891                 $text = implode(";", $signed_parts);
2892         }
2893         else {
2894                 // This part is meant for cases where we don't have the signatur. (Which shouldn't happen with posts from Diaspora and Friendica)
2895                 // This means that the comment won't be accepted by newer Diaspora servers
2896
2897                 $body = $item['body'];
2898                 $text = html_entity_decode(bb2diaspora($body));
2899
2900                 $handle = diaspora_handle_from_contact($item['contact-id']);
2901                 if(! $handle)
2902                         return;
2903
2904                 if($relay_retract)
2905                         $signed_text = $item['guid'] . ';' . $target_type;
2906                 elseif($like)
2907                         $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $positive . ';' . $handle;
2908                 else
2909                         $signed_text = $item['guid'] . ';' . $parent['guid'] . ';' . $text . ';' . $handle;
2910
2911                 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2912         }
2913
2914         // Sign the relayable with the top-level owner's signature
2915         $parentauthorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2916
2917         $msg = replace_macros($tpl,array(
2918                 '$guid' => xmlify($item['guid']),
2919                 '$parent_guid' => xmlify($parent['guid']),
2920                 '$target_type' =>xmlify($target_type),
2921                 '$authorsig' => xmlify($authorsig),
2922                 '$parentsig' => xmlify($parentauthorsig),
2923                 '$body' => xmlify($text),
2924                 '$positive' => xmlify($positive),
2925                 '$handle' => xmlify($handle)
2926         ));
2927
2928         logger('diaspora_send_relay: base message: ' . $msg, LOGGER_DATA);
2929         logger('send guid '.$item['guid'], LOGGER_DEBUG);
2930
2931         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2932         //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2933
2934         return(diaspora_transmit($owner,$contact,$slap,$public_batch,false,$item['guid']));
2935
2936 }
2937
2938
2939
2940 function diaspora_send_retraction($item,$owner,$contact,$public_batch = false) {
2941
2942         $a = get_app();
2943         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2944
2945         // Check whether the retraction is for a top-level post or whether it's a relayable
2946         if( $item['uri'] !== $item['parent-uri'] ) {
2947
2948                 $tpl = get_markup_template('diaspora_relay_retraction.tpl');
2949                 $target_type = (($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2950         }
2951         else {
2952
2953                 $tpl = get_markup_template('diaspora_signed_retract.tpl');
2954                 $target_type = 'StatusMessage';
2955         }
2956
2957         $signed_text = $item['guid'] . ';' . $target_type;
2958
2959         $msg = replace_macros($tpl, array(
2960                 '$guid'   => xmlify($item['guid']),
2961                 '$type'   => xmlify($target_type),
2962                 '$handle' => xmlify($myaddr),
2963                 '$signature' => xmlify(base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')))
2964         ));
2965
2966         logger('send guid '.$item['guid'], LOGGER_DEBUG);
2967
2968         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2969         //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2970
2971         return(diaspora_transmit($owner,$contact,$slap,$public_batch,false,$item['guid']));
2972 }
2973
2974 function diaspora_send_mail($item,$owner,$contact) {
2975
2976         $a = get_app();
2977         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2978
2979         $r = q("select * from conv where id = %d and uid = %d limit 1",
2980                 intval($item['convid']),
2981                 intval($item['uid'])
2982         );
2983
2984         if(! count($r)) {
2985                 logger('diaspora_send_mail: conversation not found.');
2986                 return;
2987         }
2988         $cnv = $r[0];
2989
2990         $conv = array(
2991                 'guid' => xmlify($cnv['guid']),
2992                 'subject' => xmlify($cnv['subject']),
2993                 'created_at' => xmlify(datetime_convert('UTC','UTC',$cnv['created'],'Y-m-d H:i:s \U\T\C')),
2994                 'diaspora_handle' => xmlify($cnv['creator']),
2995                 'participant_handles' => xmlify($cnv['recips'])
2996         );
2997
2998         $body = bb2diaspora($item['body']);
2999         $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
3000
3001         $signed_text =  $item['guid'] . ';' . $cnv['guid'] . ';' . $body .  ';'
3002                 . $created . ';' . $myaddr . ';' . $cnv['guid'];
3003
3004         $sig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
3005
3006         $msg = array(
3007                 'guid' => xmlify($item['guid']),
3008                 'parent_guid' => xmlify($cnv['guid']),
3009                 'parent_author_signature' => xmlify($sig),
3010                 'author_signature' => xmlify($sig),
3011                 'text' => xmlify($body),
3012                 'created_at' => xmlify($created),
3013                 'diaspora_handle' => xmlify($myaddr),
3014                 'conversation_guid' => xmlify($cnv['guid'])
3015         );
3016
3017         if($item['reply']) {
3018                 $tpl = get_markup_template('diaspora_message.tpl');
3019                 $xmsg = replace_macros($tpl, array('$msg' => $msg));
3020         }
3021         else {
3022                 $conv['messages'] = array($msg);
3023                 $tpl = get_markup_template('diaspora_conversation.tpl');
3024                 $xmsg = replace_macros($tpl, array('$conv' => $conv));
3025         }
3026
3027         logger('diaspora_conversation: ' . print_r($xmsg,true), LOGGER_DATA);
3028         logger('send guid '.$item['guid'], LOGGER_DEBUG);
3029
3030         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false)));
3031         //$slap = 'xml=' . urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false));
3032
3033         return(diaspora_transmit($owner,$contact,$slap,false,false,$item['guid']));
3034
3035
3036 }
3037
3038 function diaspora_transmit($owner,$contact,$slap,$public_batch,$queue_run=false,$guid = "") {
3039
3040         $enabled = intval(get_config('system','diaspora_enabled'));
3041         if(! $enabled) {
3042                 return 200;
3043         }
3044
3045         $a = get_app();
3046         $logid = random_string(4);
3047         $dest_url = (($public_batch) ? $contact['batch'] : $contact['notify']);
3048         if(! $dest_url) {
3049                 logger('diaspora_transmit: no url for contact: ' . $contact['id'] . ' batch mode =' . $public_batch);
3050                 return 0;
3051         }
3052
3053         logger('diaspora_transmit: '.$logid.'-'.$guid.' '.$dest_url);
3054
3055         if( (! $queue_run) && (was_recently_delayed($contact['id'])) ) {
3056                 $return_code = 0;
3057         }
3058         else {
3059                 if (!intval(get_config('system','diaspora_test'))) {
3060                         post_url($dest_url . '/', $slap);
3061                         $return_code = $a->get_curl_code();
3062                 } else {
3063                         logger('diaspora_transmit: test_mode');
3064                         return 200;
3065                 }
3066         }
3067
3068         logger('diaspora_transmit: '.$logid.'-'.$guid.' returns: '.$return_code);
3069
3070         if((! $return_code) || (($return_code == 503) && (stristr($a->get_curl_headers(),'retry-after')))) {
3071                 logger('diaspora_transmit: queue message');
3072
3073                 $r = q("SELECT id from queue where cid = %d and network = '%s' and content = '%s' and batch = %d limit 1",
3074                         intval($contact['id']),
3075                         dbesc(NETWORK_DIASPORA),
3076                         dbesc($slap),
3077                         intval($public_batch)
3078                 );
3079                 if(count($r)) {
3080                         logger('diaspora_transmit: add_to_queue ignored - identical item already in queue');
3081                 }
3082                 else {
3083                         // queue message for redelivery
3084                         add_to_queue($contact['id'],NETWORK_DIASPORA,$slap,$public_batch);
3085                 }
3086         }
3087
3088
3089         return(($return_code) ? $return_code : (-1));
3090 }
3091
3092 function diaspora_fetch_relay() {
3093
3094         $serverdata = get_config("system", "relay_server");
3095         if ($serverdata == "")
3096                 return array();
3097
3098         $relay = array();
3099
3100         $servers = explode(",", $serverdata);
3101
3102         foreach($servers AS $server) {
3103                 $server = trim($server);
3104                 $batch = $server."/receive/public";
3105
3106                 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
3107
3108                 if (!$relais) {
3109                         $addr = "relay@".str_replace("http://", "", normalise_link($server));
3110
3111                         $r = q("INSERT INTO `contact` (`uid`, `created`, `name`, `nick`, `addr`, `url`, `nurl`, `batch`, `network`, `rel`, `blocked`, `pending`, `writable`, `name-date`, `uri-date`, `avatar-date`)
3112                                 VALUES (0, '%s', '%s', 'relay', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, '%s', '%s', '%s')",
3113                                 datetime_convert(),
3114                                 dbesc($addr),
3115                                 dbesc($addr),
3116                                 dbesc($server),
3117                                 dbesc(normalise_link($server)),
3118                                 dbesc($batch),
3119                                 dbesc(NETWORK_DIASPORA),
3120                                 intval(CONTACT_IS_FOLLOWER),
3121                                 dbesc(datetime_convert()),
3122                                 dbesc(datetime_convert()),
3123                                 dbesc(datetime_convert())
3124                         );
3125
3126                         $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
3127                         if ($relais)
3128                                 $relay[] = $relais[0];
3129                 } else
3130                         $relay[] = $relais[0];
3131         }
3132
3133         return $relay;
3134 }