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