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