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