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