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