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