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