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