]> git.mxchange.org Git - friendica.git/blob - include/diaspora.php
d* pm
[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
9
10 function diaspora_dispatch_public($msg) {
11
12         $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN ( SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s' ) AND `account_expired` = 0 ",
13                 dbesc(NETWORK_DIASPORA),
14                 dbesc($msg['author'])
15         );
16         if(count($r)) {
17                 foreach($r as $rr) {
18                         logger('diaspora_public: delivering to: ' . $rr['username']);
19                         diaspora_dispatch($rr,$msg);
20                 }
21         }
22         else
23                 logger('diaspora_public: no subscribers');
24 }
25
26
27
28 function diaspora_dispatch($importer,$msg) {
29
30         $ret = 0;
31
32         // php doesn't like dashes in variable names
33
34         $msg['message'] = str_replace(
35                         array('<activity_streams-photo>','</activity_streams-photo>'),
36                         array('<asphoto>','</asphoto>'),
37                         $msg['message']);
38
39
40         $parsed_xml = parse_xml_string($msg['message'],false);
41
42         $xmlbase = $parsed_xml->post;
43
44         logger('diaspora_dispatch: ' . print_r($xmlbase,true), LOGGER_DEBUG);
45
46
47         if($xmlbase->request) {
48                 $ret = diaspora_request($importer,$xmlbase->request);
49         }
50         elseif($xmlbase->status_message) {
51                 $ret = diaspora_post($importer,$xmlbase->status_message);
52         }
53         elseif($xmlbase->profile) {
54                 $ret = diaspora_profile($importer,$xmlbase->profile);
55         }
56         elseif($xmlbase->comment) {
57                 $ret = diaspora_comment($importer,$xmlbase->comment,$msg);
58         }
59         elseif($xmlbase->like) {
60                 $ret = diaspora_like($importer,$xmlbase->like,$msg);
61         }
62         elseif($xmlbase->asphoto) {
63                 $ret = diaspora_asphoto($importer,$xmlbase->asphoto);
64         }
65         elseif($xmlbase->reshare) {
66                 $ret = diaspora_reshare($importer,$xmlbase->reshare);
67         }
68         elseif($xmlbase->retraction) {
69                 $ret = diaspora_retraction($importer,$xmlbase->retraction,$msg);
70         }
71         elseif($xmlbase->signed_retraction) {
72                 $ret = diaspora_signed_retraction($importer,$xmlbase->retraction,$msg);
73         }
74         elseif($xmlbase->photo) {
75                 $ret = diaspora_photo($importer,$xmlbase->photo,$msg);
76         }
77         elseif($xmlbase->conversation) {
78                 $ret = diaspora_conversation($importer,$xmlbase->conversation,$msg);
79         }
80         else {
81                 logger('diaspora_dispatch: unknown message type: ' . print_r($xmlbase,true));
82         }
83         return $ret;
84 }
85
86 function diaspora_get_contact_by_handle($uid,$handle) {
87         $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `addr` = '%s' LIMIT 1",
88                 dbesc(NETWORK_DIASPORA),
89                 intval($uid),
90                 dbesc($handle)
91         );
92         if($r && count($r))
93                 return $r[0];
94         return false;
95 }
96
97 function find_diaspora_person_by_handle($handle) {
98         $update = false;
99         $r = q("select * from fcontact where network = '%s' and addr = '%s' limit 1",
100                 dbesc(NETWORK_DIASPORA),
101                 dbesc($handle)
102         );
103         if(count($r)) {
104                 logger('find_diaspora_person_by handle: in cache ' . print_r($r,true), LOGGER_DEBUG);
105                 // update record occasionally so it doesn't get stale
106                 $d = strtotime($r[0]['updated'] . ' +00:00');
107                 if($d > strtotime('now - 14 days'))
108                         return $r[0];
109                 $update = true;
110         }
111         logger('find_diaspora_person_by_handle: refresh',LOGGER_DEBUG);
112         require_once('include/Scrape.php');
113         $r = probe_url($handle, PROBE_DIASPORA);
114         if((count($r)) && ($r['network'] === NETWORK_DIASPORA)) {
115                 add_fcontact($r,$update);
116                 return ($r);
117         }
118         return false;
119 }
120
121
122 function get_diaspora_key($uri) {
123         logger('Fetching diaspora key for: ' . $uri);
124
125         $r = find_diaspora_person_by_handle($uri);
126         if($r)
127                 return $r['pubkey'];
128         return '';
129 }
130
131
132 function diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey) {
133         $a = get_app();
134
135         logger('diaspora_pubmsg_build: ' . $msg, LOGGER_DATA);
136
137         
138         $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
139
140 //      $b64_data = base64_encode($msg);
141 //      $b64url_data = base64url_encode($b64_data);
142
143         $b64url_data = base64url_encode($msg);
144
145         $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
146
147         $type = 'application/xml';
148         $encoding = 'base64url';
149         $alg = 'RSA-SHA256';
150
151         $signable_data = $data  . '.' . base64url_encode($type) . '.' 
152                 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
153
154         $signature = rsa_sign($signable_data,$prvkey);
155         $sig = base64url_encode($signature);
156
157 $magic_env = <<< EOT
158 <?xml version='1.0' encoding='UTF-8'?>
159 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
160   <header>
161     <author_id>$handle</author_id>
162   </header>
163   <me:env>
164     <me:encoding>base64url</me:encoding>
165     <me:alg>RSA-SHA256</me:alg>
166     <me:data type="application/xml">$data</me:data>
167     <me:sig>$sig</me:sig>
168   </me:env>
169 </diaspora>
170 EOT;
171
172         logger('diaspora_pubmsg_build: magic_env: ' . $magic_env, LOGGER_DATA);
173         return $magic_env;
174
175 }
176
177
178
179
180 function diaspora_msg_build($msg,$user,$contact,$prvkey,$pubkey,$public = false) {
181         $a = get_app();
182
183         if($public)
184                 return diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey);
185
186         logger('diaspora_msg_build: ' . $msg, LOGGER_DATA);
187
188         $inner_aes_key = random_string(32);
189         $b_inner_aes_key = base64_encode($inner_aes_key);
190         $inner_iv = random_string(16);
191         $b_inner_iv = base64_encode($inner_iv);
192
193         $outer_aes_key = random_string(32);
194         $b_outer_aes_key = base64_encode($outer_aes_key);
195         $outer_iv = random_string(16);
196         $b_outer_iv = base64_encode($outer_iv);
197         
198         $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
199
200         $padded_data = pkcs5_pad($msg,16);
201         $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
202
203         $b64_data = base64_encode($inner_encrypted);
204
205
206         $b64url_data = base64url_encode($b64_data);
207         $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
208
209         $type = 'application/xml';
210         $encoding = 'base64url';
211         $alg = 'RSA-SHA256';
212
213         $signable_data = $data  . '.' . base64url_encode($type) . '.' 
214                 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
215
216         $signature = rsa_sign($signable_data,$prvkey);
217         $sig = base64url_encode($signature);
218
219 $decrypted_header = <<< EOT
220 <decrypted_header>
221   <iv>$b_inner_iv</iv>
222   <aes_key>$b_inner_aes_key</aes_key>
223   <author_id>$handle</author_id>
224 </decrypted_header>
225 EOT;
226
227         $decrypted_header = pkcs5_pad($decrypted_header,16);
228
229         $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
230
231         $outer_json = json_encode(array('iv' => $b_outer_iv,'key' => $b_outer_aes_key));
232
233         $encrypted_outer_key_bundle = '';
234         openssl_public_encrypt($outer_json,$encrypted_outer_key_bundle,$pubkey);
235
236         $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
237
238         logger('outer_bundle: ' . $b64_encrypted_outer_key_bundle . ' key: ' . $pubkey, LOGGER_DATA);
239
240         $encrypted_header_json_object = json_encode(array('aes_key' => base64_encode($encrypted_outer_key_bundle), 
241                 'ciphertext' => base64_encode($ciphertext)));
242         $cipher_json = base64_encode($encrypted_header_json_object);
243
244         $encrypted_header = '<encrypted_header>' . $cipher_json . '</encrypted_header>';
245
246 $magic_env = <<< EOT
247 <?xml version='1.0' encoding='UTF-8'?>
248 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
249   $encrypted_header
250   <me:env>
251     <me:encoding>base64url</me:encoding>
252     <me:alg>RSA-SHA256</me:alg>
253     <me:data type="application/xml">$data</me:data>
254     <me:sig>$sig</me:sig>
255   </me:env>
256 </diaspora>
257 EOT;
258
259         logger('diaspora_msg_build: magic_env: ' . $magic_env, LOGGER_DATA);
260         return $magic_env;
261
262 }
263
264 /**
265  *
266  * diaspora_decode($importer,$xml)
267  *   array $importer -> from user table
268  *   string $xml -> urldecoded Diaspora salmon 
269  *
270  * Returns array
271  * 'message' -> decoded Diaspora XML message
272  * 'author' -> author diaspora handle
273  * 'key' -> author public key (converted to pkcs#8)
274  *
275  * Author and key are used elsewhere to save a lookup for verifying replies and likes
276  */
277
278
279 function diaspora_decode($importer,$xml) {
280
281         $public = false;
282         $basedom = parse_xml_string($xml);
283
284         $children = $basedom->children('https://joindiaspora.com/protocol');
285
286         if($children->header) {
287                 $public = true;
288                 $author_link = str_replace('acct:','',$children->header->author_id);
289         }
290         else {
291
292                 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
293         
294                 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
295                 $ciphertext = base64_decode($encrypted_header->ciphertext);
296
297                 $outer_key_bundle = '';
298                 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
299
300                 $j_outer_key_bundle = json_decode($outer_key_bundle);
301
302                 $outer_iv = base64_decode($j_outer_key_bundle->iv);
303                 $outer_key = base64_decode($j_outer_key_bundle->key);
304
305                 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
306
307
308                 $decrypted = pkcs5_unpad($decrypted);
309
310                 /**
311                  * $decrypted now contains something like
312                  *
313                  *  <decrypted_header>
314                  *     <iv>8e+G2+ET8l5BPuW0sVTnQw==</iv>
315                  *     <aes_key>UvSMb4puPeB14STkcDWq+4QE302Edu15oaprAQSkLKU=</aes_key>
316
317 ***** OBSOLETE
318
319                  *     <author>
320                  *       <name>Ryan Hughes</name>
321                  *       <uri>acct:galaxor@diaspora.pirateship.org</uri>
322                  *     </author>
323
324 ***** CURRENT
325
326                  *     <author_id>galaxor@diaspora.priateship.org</author_id>
327
328 ***** END DIFFS
329
330                  *  </decrypted_header>
331                  */
332
333                 logger('decrypted: ' . $decrypted, LOGGER_DEBUG);
334                 $idom = parse_xml_string($decrypted,false);
335
336                 $inner_iv = base64_decode($idom->iv);
337                 $inner_aes_key = base64_decode($idom->aes_key);
338
339                 $author_link = str_replace('acct:','',$idom->author_id);
340
341         }
342
343         $dom = $basedom->children(NAMESPACE_SALMON_ME);
344
345         // figure out where in the DOM tree our data is hiding
346
347         if($dom->provenance->data)
348                 $base = $dom->provenance;
349         elseif($dom->env->data)
350                 $base = $dom->env;
351         elseif($dom->data)
352                 $base = $dom;
353         
354         if(! $base) {
355                 logger('mod-diaspora: unable to locate salmon data in xml ');
356                 http_status_exit(400);
357         }
358
359
360         // Stash the signature away for now. We have to find their key or it won't be good for anything.
361         $signature = base64url_decode($base->sig);
362
363         // unpack the  data
364
365         // strip whitespace so our data element will return to one big base64 blob
366         $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
367
368
369         // stash away some other stuff for later
370
371         $type = $base->data[0]->attributes()->type[0];
372         $keyhash = $base->sig[0]->attributes()->keyhash[0];
373         $encoding = $base->encoding;
374         $alg = $base->alg;
375
376
377         $signed_data = $data  . '.' . base64url_encode($type) . '.' . base64url_encode($encoding) . '.' . base64url_encode($alg);
378
379
380         // decode the data
381         $data = base64url_decode($data);
382
383
384         if($public) {
385                 $inner_decrypted = $data;
386         }
387         else {
388
389                 // Decode the encrypted blob
390
391                 $inner_encrypted = base64_decode($data);
392                 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
393                 $inner_decrypted = pkcs5_unpad($inner_decrypted);
394         }
395
396         if(! $author_link) {
397                 logger('mod-diaspora: Could not retrieve author URI.');
398                 http_status_exit(400);
399         }
400
401         // Once we have the author URI, go to the web and try to find their public key
402         // (first this will look it up locally if it is in the fcontact cache)
403         // This will also convert diaspora public key from pkcs#1 to pkcs#8
404
405         logger('mod-diaspora: Fetching key for ' . $author_link );
406         $key = get_diaspora_key($author_link);
407
408         if(! $key) {
409                 logger('mod-diaspora: Could not retrieve author key.');
410                 http_status_exit(400);
411         }
412
413         $verify = rsa_verify($signed_data,$signature,$key);
414
415         if(! $verify) {
416                 logger('mod-diaspora: Message did not verify. Discarding.');
417                 http_status_exit(400);
418         }
419
420         logger('mod-diaspora: Message verified.');
421
422         return array('message' => $inner_decrypted, 'author' => $author_link, 'key' => $key);
423
424 }
425
426         
427 function diaspora_request($importer,$xml) {
428
429         $a = get_app();
430
431         $sender_handle = unxmlify($xml->sender_handle);
432         $recipient_handle = unxmlify($xml->recipient_handle);
433
434         if(! $sender_handle || ! $recipient_handle)
435                 return;
436          
437         $contact = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
438
439         if($contact) {
440
441                 // perhaps we were already sharing with this person. Now they're sharing with us.
442                 // That makes us friends.
443
444                 if($contact['rel'] == CONTACT_IS_FOLLOWER) {
445                         q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
446                                 intval(CONTACT_IS_FRIEND),
447                                 intval($contact['id']),
448                                 intval($importer['uid'])
449                         );
450                 }
451                 // send notification
452
453                 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
454                         intval($importer['uid'])
455                 );
456
457                 if((count($r)) && ($r[0]['hide-friends'] == 0)) {
458                         require_once('include/items.php');
459
460                         $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
461                                 intval($importer['uid'])
462                         );
463
464                         // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
465
466                         if(count($self) && $contact['rel'] == CONTACT_IS_FOLLOWER) {
467
468                                 $arr = array();
469                                 $arr['uri'] = $arr['parent-uri'] = item_new_uri($a->get_hostname(), $importer['uid']); 
470                                 $arr['uid'] = $importer['uid'];
471                                 $arr['contact-id'] = $self[0]['id'];
472                                 $arr['wall'] = 1;
473                                 $arr['type'] = 'wall';
474                                 $arr['gravity'] = 0;
475                                 $arr['origin'] = 1;
476                                 $arr['author-name'] = $arr['owner-name'] = $self[0]['name'];
477                                 $arr['author-link'] = $arr['owner-link'] = $self[0]['url'];
478                                 $arr['author-avatar'] = $arr['owner-avatar'] = $self[0]['thumb'];
479                                 $arr['verb'] = ACTIVITY_FRIEND;
480                                 $arr['object-type'] = ACTIVITY_OBJ_PERSON;
481                                 
482                                 $A = '[url=' . $self[0]['url'] . ']' . $self[0]['name'] . '[/url]';
483                                 $B = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
484                                 $BPhoto = '[url=' . $contact['url'] . ']' . '[img]' . $contact['thumb'] . '[/img][/url]';
485                                 $arr['body'] =  sprintf( t('%1$s is now friends with %2$s'), $A, $B)."\n\n\n".$Bphoto;
486
487                                 $arr['object'] = '<object><type>' . ACTIVITY_OBJ_PERSON . '</type><title>' . $contact['name'] . '</title>'
488                                         . '<id>' . $contact['url'] . '/' . $contact['name'] . '</id>';
489                                 $arr['object'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $contact['url'] . '" />' . "\n");
490                                 $arr['object'] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $contact['thumb'] . '" />' . "\n");
491                                 $arr['object'] .= '</link></object>' . "\n";
492                                 $arr['last-child'] = 1;
493
494                                 $arr['allow_cid'] = $user[0]['allow_cid'];
495                                 $arr['allow_gid'] = $user[0]['allow_gid'];
496                                 $arr['deny_cid']  = $user[0]['deny_cid'];
497                                 $arr['deny_gid']  = $user[0]['deny_gid'];
498
499                                 $i = item_store($arr);
500                                 if($i)
501                                 proc_run('php',"include/notifier.php","activity","$i");
502
503                         }
504
505                 }
506
507                 return;
508         }
509         
510         $ret = find_diaspora_person_by_handle($sender_handle);
511
512
513         if((! count($ret)) || ($ret['network'] != NETWORK_DIASPORA)) {
514                 logger('diaspora_request: Cannot resolve diaspora handle ' . $sender_handle . ' for ' . $recipient_handle);
515                 return;
516         }
517
518         $batch = (($ret['batch']) ? $ret['batch'] : implode('/', array_slice(explode('/',$ret['url']),0,3)) . '/receive/public');
519
520         $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
521                 VALUES ( %d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d) ",
522                 intval($importer['uid']),
523                 dbesc($ret['network']),
524                 dbesc($ret['addr']),
525                 datetime_convert(),
526                 dbesc($ret['url']),
527                 dbesc(normalise_link($ret['url'])),
528                 dbesc($batch),
529                 dbesc($ret['name']),
530                 dbesc($ret['nick']),
531                 dbesc($ret['photo']),
532                 dbesc($ret['pubkey']),
533                 dbesc($ret['notify']),
534                 dbesc($ret['poll']),
535                 1,
536                 2
537         );
538                  
539         // find the contact record we just created
540
541         $contact_record = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
542
543         $hash = random_string() . (string) time();   // Generate a confirm_key
544         
545         if($contact_record) {
546                 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime` )
547                         VALUES ( %d, %d, %d, %d, '%s', '%s', '%s' )",
548                         intval($importer['uid']),
549                         intval($contact_record['id']),
550                         0,
551                         0,
552                         dbesc( t('Sharing notification from Diaspora network')),
553                         dbesc($hash),
554                         dbesc(datetime_convert())
555                 );
556         }
557
558         return;
559 }
560
561 function diaspora_post($importer,$xml) {
562
563         $a = get_app();
564         $guid = notags(unxmlify($xml->guid));
565         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
566
567         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
568         if(! $contact)
569                 return;
570
571         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
572                 logger('diaspora_post: Ignoring this author.');
573                 return 202;
574         }
575
576         $message_id = $diaspora_handle . ':' . $guid;
577         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
578                 intval($importer['uid']),
579                 dbesc($message_id),
580                 dbesc($guid)
581         );
582         if(count($r)) {
583                 logger('diaspora_post: message exists: ' . $guid);
584                 return;
585         }
586
587     // allocate a guid on our system - we aren't fixing any collisions.
588         // we're ignoring them
589
590         $g = q("select * from guid where guid = '%s' limit 1",
591                 dbesc($guid)
592         );
593         if(! count($g)) {
594                 q("insert into guid ( guid ) values ( '%s' )",
595                         dbesc($guid)
596                 );
597         }
598
599         $created = unxmlify($xml->created_at);
600         $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
601
602         $body = diaspora2bb($xml->raw_message);
603
604         $datarray = array();
605
606         $str_tags = '';
607
608         $tags = get_tags($body);
609
610         if(count($tags)) {
611                 foreach($tags as $tag) {
612                         if(strpos($tag,'#') === 0) {
613                                 if(strpos($tag,'[url='))
614                                         continue;
615                                 $basetag = str_replace('_',' ',substr($tag,1));
616                                 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
617                                 if(strlen($str_tags))
618                                         $str_tags .= ',';
619                                 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
620                                 continue;
621                         }
622                 }
623         }
624         
625         $datarray['uid'] = $importer['uid'];
626         $datarray['contact-id'] = $contact['id'];
627         $datarray['wall'] = 0;
628         $datarray['guid'] = $guid;
629         $datarray['uri'] = $datarray['parent-uri'] = $message_id;
630         $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
631         $datarray['private'] = $private;
632         $datarray['parent'] = 0;
633         $datarray['owner-name'] = $contact['name'];
634         $datarray['owner-link'] = $contact['url'];
635         $datarray['owner-avatar'] = $contact['thumb'];
636         $datarray['author-name'] = $contact['name'];
637         $datarray['author-link'] = $contact['url'];
638         $datarray['author-avatar'] = $contact['thumb'];
639         $datarray['body'] = $body;
640         $datarray['tag'] = $str_tags;
641         $datarray['app']  = 'Diaspora';
642
643         // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible.
644
645         $datarray['visible'] = ((strlen($body)) ? 1 : 0);
646
647         $message_id = item_store($datarray);
648
649         if($message_id) {
650                 q("update item set plink = '%s' where id = %d limit 1",
651                         dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
652                         intval($message_id)
653                 );
654         }
655
656         return;
657
658 }
659
660 function diaspora_reshare($importer,$xml) {
661
662         logger('diaspora_reshare: init: ' . print_r($xml,true));
663
664         $a = get_app();
665         $guid = notags(unxmlify($xml->guid));
666         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
667
668
669         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
670         if(! $contact)
671                 return;
672
673         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
674                 logger('diaspora_reshare: Ignoring this author: ' . $diaspora_handle . ' ' . print_r($xml,true));
675                 return 202;
676         }
677
678         $message_id = $diaspora_handle . ':' . $guid;
679         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
680                 intval($importer['uid']),
681                 dbesc($message_id),
682                 dbesc($guid)
683         );
684         if(count($r)) {
685                 logger('diaspora_reshare: message exists: ' . $guid);
686                 return;
687         }
688
689         $orig_author = notags(unxmlify($xml->root_diaspora_id));
690         $orig_guid = notags(unxmlify($xml->root_guid));
691
692         $source_url = 'https://' . substr($orig_author,strpos($orig_author,'@')+1) . '/p/' . $orig_guid . '.xml';
693         $x = fetch_url($source_url);
694         if(! $x)
695                 $x = fetch_url(str_replace('https://','http://',$source_url));
696         if(! $x) {
697                 logger('diaspora_reshare: unable to fetch source url ' . $source_url);
698                 return;
699         }
700         logger('diaspora_reshare: source: ' . $x);
701
702         $x = str_replace(array('<activity_streams-photo>','</activity_streams-photo>'),array('<asphoto>','</asphoto>'),$x);
703         $source_xml = parse_xml_string($x,false);
704
705         if(strlen($source_xml->post->asphoto->objectId) && ($source_xml->post->asphoto->objectId != 0) && ($source_xml->post->asphoto->image_url)) {
706                 $body = '[url=' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '][img]' . notags(unxmlify($source_xml->post->asphoto->objectId)) . '[/img][/url]' . "\n";
707                 $body = scale_diaspora_images($body,false);
708         }
709         elseif($source_xml->post->asphoto->image_url) {
710                 $body = '[img]' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '[/img]' . "\n";
711                 $body = scale_diaspora_images($body);
712         }
713         elseif($source_xml->post->status_message) {
714                 $body = diaspora2bb($source_xml->post->status_message->raw_message);
715                 $body = scale_diaspora_images($body);
716
717         }
718         else {
719                 logger('diaspora_reshare: no reshare content found: ' . print_r($source_xml,true));
720                 return;
721         }
722         if(! $body) {
723                 logger('diaspora_reshare: empty body: source= ' . $x);
724                 return;
725         }
726
727         $person = find_diaspora_person_by_handle($orig_author);
728
729         if(is_array($person) && x($person,'name') && x($person,'url'))
730                 $details = '[url=' . $person['url'] . ']' . $person['name'] . '[/url]';
731         else
732                 $details = $orig_author;
733         
734         $prefix = '&#x2672; ' . $details . "\n"; 
735
736
737     // allocate a guid on our system - we aren't fixing any collisions.
738         // we're ignoring them
739
740         $g = q("select * from guid where guid = '%s' limit 1",
741                 dbesc($guid)
742         );
743         if(! count($g)) {
744                 q("insert into guid ( guid ) values ( '%s' )",
745                         dbesc($guid)
746                 );
747         }
748
749         $created = unxmlify($xml->created_at);
750         $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
751
752         $datarray = array();
753
754         $str_tags = '';
755
756         $tags = get_tags($body);
757
758         if(count($tags)) {
759                 foreach($tags as $tag) {
760                         if(strpos($tag,'#') === 0) {
761                                 if(strpos($tag,'[url='))
762                                         continue;
763                                 $basetag = str_replace('_',' ',substr($tag,1));
764                                 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
765                                 if(strlen($str_tags))
766                                         $str_tags .= ',';
767                                 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
768                                 continue;
769                         }
770                 }
771         }
772         
773         $datarray['uid'] = $importer['uid'];
774         $datarray['contact-id'] = $contact['id'];
775         $datarray['wall'] = 0;
776         $datarray['guid'] = $guid;
777         $datarray['uri'] = $datarray['parent-uri'] = $message_id;
778         $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
779         $datarray['private'] = $private;
780         $datarray['parent'] = 0;
781         $datarray['owner-name'] = $contact['name'];
782         $datarray['owner-link'] = $contact['url'];
783         $datarray['owner-avatar'] = $contact['thumb'];
784         $datarray['author-name'] = $contact['name'];
785         $datarray['author-link'] = $contact['url'];
786         $datarray['author-avatar'] = $contact['thumb'];
787         $datarray['body'] = $prefix . $body;
788         $datarray['tag'] = $str_tags;
789         $datarray['app']  = 'Diaspora';
790
791         $message_id = item_store($datarray);
792
793         if($message_id) {
794                 q("update item set plink = '%s' where id = %d limit 1",
795                         dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
796                         intval($message_id)
797                 );
798         }
799
800         return;
801
802 }
803
804
805 function diaspora_asphoto($importer,$xml) {
806         logger('diaspora_asphoto called');
807
808         $a = get_app();
809         $guid = notags(unxmlify($xml->guid));
810         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
811
812         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
813         if(! $contact)
814                 return;
815
816         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
817                 logger('diaspora_asphoto: Ignoring this author.');
818                 return 202;
819         }
820
821         $message_id = $diaspora_handle . ':' . $guid;
822         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
823                 intval($importer['uid']),
824                 dbesc($message_id),
825                 dbesc($guid)
826         );
827         if(count($r)) {
828                 logger('diaspora_asphoto: message exists: ' . $guid);
829                 return;
830         }
831
832     // allocate a guid on our system - we aren't fixing any collisions.
833         // we're ignoring them
834
835         $g = q("select * from guid where guid = '%s' limit 1",
836                 dbesc($guid)
837         );
838         if(! count($g)) {
839                 q("insert into guid ( guid ) values ( '%s' )",
840                         dbesc($guid)
841                 );
842         }
843
844         $created = unxmlify($xml->created_at);
845         $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
846
847         if(strlen($xml->objectId) && ($xml->objectId != 0) && ($xml->image_url)) {
848                 $body = '[url=' . notags(unxmlify($xml->image_url)) . '][img]' . notags(unxmlify($xml->objectId)) . '[/img][/url]' . "\n";
849                 $body = scale_diaspora_images($body,false);
850         }
851         elseif($xml->image_url) {
852                 $body = '[img]' . notags(unxmlify($xml->image_url)) . '[/img]' . "\n";
853                 $body = scale_diaspora_images($body);
854         }
855         else {
856                 logger('diaspora_asphoto: no photo url found.');
857                 return;
858         }
859
860         $datarray = array();
861
862         
863         $datarray['uid'] = $importer['uid'];
864         $datarray['contact-id'] = $contact['id'];
865         $datarray['wall'] = 0;
866         $datarray['guid'] = $guid;
867         $datarray['uri'] = $datarray['parent-uri'] = $message_id;
868         $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
869         $datarray['private'] = $private;
870         $datarray['parent'] = 0;
871         $datarray['owner-name'] = $contact['name'];
872         $datarray['owner-link'] = $contact['url'];
873         $datarray['owner-avatar'] = $contact['thumb'];
874         $datarray['author-name'] = $contact['name'];
875         $datarray['author-link'] = $contact['url'];
876         $datarray['author-avatar'] = $contact['thumb'];
877         $datarray['body'] = $body;
878         
879         $datarray['app']  = 'Diaspora/Cubbi.es';
880
881         $message_id = item_store($datarray);
882
883         if($message_id) {
884                 q("update item set plink = '%s' where id = %d limit 1",
885                         dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
886                         intval($message_id)
887                 );
888         }
889
890         return;
891
892 }
893
894
895
896
897
898
899 function diaspora_comment($importer,$xml,$msg) {
900
901         $a = get_app();
902         $guid = notags(unxmlify($xml->guid));
903         $parent_guid = notags(unxmlify($xml->parent_guid));
904         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
905         $target_type = notags(unxmlify($xml->target_type));
906         $text = unxmlify($xml->text);
907         $author_signature = notags(unxmlify($xml->author_signature));
908
909         $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
910
911         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
912         if(! $contact) {
913                 logger('diaspora_comment: cannot find contact: ' . $msg['author']);
914                 return;
915         }
916
917         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
918                 logger('diaspora_comment: Ignoring this author.');
919                 return 202;
920         }
921
922         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
923                 intval($importer['uid']),
924                 dbesc($guid)
925         );
926         if(count($r)) {
927                 logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid);
928                 return;
929         }
930
931         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
932                 intval($importer['uid']),
933                 dbesc($parent_guid)
934         );
935         if(! count($r)) {
936                 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
937                 return;
938         }
939         $parent_item = $r[0];
940
941         $author_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
942
943         $author_signature = base64_decode($author_signature);
944
945         if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
946                 $person = $contact;
947                 $key = $msg['key'];
948         }
949         else {
950                 $person = find_diaspora_person_by_handle($diaspora_handle);     
951
952                 if(is_array($person) && x($person,'pubkey'))
953                         $key = $person['pubkey'];
954                 else {
955                         logger('diaspora_comment: unable to find author details');
956                         return;
957                 }
958         }
959
960         if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
961                 logger('diaspora_comment: verification failed.');
962                 return;
963         }
964
965         if($parent_author_signature) {
966                 $owner_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
967
968                 $parent_author_signature = base64_decode($parent_author_signature);
969
970                 $key = $msg['key'];
971
972                 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
973                         logger('diaspora_comment: owner verification failed.');
974                         return;
975                 }
976         }
977
978         // Phew! Everything checks out. Now create an item.
979
980         $body = diaspora2bb($text);
981
982         $message_id = $diaspora_handle . ':' . $guid;
983
984         $datarray = array();
985
986         $str_tags = '';
987
988         $tags = get_tags($body);
989
990         if(count($tags)) {
991                 foreach($tags as $tag) {
992                         if(strpos($tag,'#') === 0) {
993                                 if(strpos($tag,'[url='))
994                                         continue;
995                                 $basetag = str_replace('_',' ',substr($tag,1));
996                                 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
997                                 if(strlen($str_tags))
998                                         $str_tags .= ',';
999                                 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1000                                 continue;
1001                         }
1002                 }
1003         }
1004
1005         $datarray['uid'] = $importer['uid'];
1006         $datarray['contact-id'] = $contact['id'];
1007         $datarray['wall'] = $parent_item['wall'];
1008         $datarray['gravity'] = GRAVITY_COMMENT;
1009         $datarray['guid'] = $guid;
1010         $datarray['uri'] = $message_id;
1011         $datarray['parent-uri'] = $parent_item['uri'];
1012
1013         // No timestamps for comments? OK, we'll the use current time.
1014         $datarray['created'] = $datarray['edited'] = datetime_convert();
1015         $datarray['private'] = $parent_item['private'];
1016
1017         $datarray['owner-name'] = $parent_item['owner-name'];
1018         $datarray['owner-link'] = $parent_item['owner-link'];
1019         $datarray['owner-avatar'] = $parent_item['owner-avatar'];
1020
1021         $datarray['author-name'] = $person['name'];
1022         $datarray['author-link'] = $person['url'];
1023         $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1024         $datarray['body'] = $body;
1025         $datarray['tag'] = $str_tags;
1026
1027         // We can't be certain what the original app is if the message is relayed.
1028         if(($parent_item['origin']) && (! $parent_author_signature)) 
1029                 $datarray['app']  = 'Diaspora';
1030
1031         $message_id = item_store($datarray);
1032
1033         if($message_id) {
1034                 q("update item set plink = '%s' where id = %d limit 1",
1035                         dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1036                         intval($message_id)
1037                 );
1038         }
1039
1040         if(($parent_item['origin']) && (! $parent_author_signature)) {
1041                 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1042                         intval($message_id),
1043                         dbesc($author_signed_data),
1044                         dbesc(base64_encode($author_signature)),
1045                         dbesc($diaspora_handle)
1046                 );
1047
1048                 // if the message isn't already being relayed, notify others
1049                 // the existence of parent_author_signature means the parent_author or owner
1050                 // is already relaying.
1051
1052                 proc_run('php','include/notifier.php','comment',$message_id);
1053         }
1054         return;
1055 }
1056
1057
1058
1059
1060 function diaspora_conversation($importer,$xml,$msg) {
1061
1062         $a = get_app();
1063
1064         $guid = notags(unxmlify($xml->guid));
1065         $subject = notags(unxmlify($xml->subject));
1066         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1067         $participant_handles = notags(unxmlify($xml->participant_handles));
1068         $created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1069
1070         $parent_uri = $diaspora_handle . ':' . $guid;
1071  
1072         $messages = $xml->message;
1073
1074         if(! count($messages)) {
1075                 logger('diaspora_conversation: empty conversation');
1076                 return;
1077         }
1078
1079         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1080         if(! $contact) {
1081                 logger('diaspora_conversation: cannot find contact: ' . $msg['author']);
1082                 return;
1083         }
1084
1085         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
1086                 logger('diaspora_conversation: Ignoring this author.');
1087                 return 202;
1088         }
1089
1090         $conversation = null;
1091
1092         $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1093                 intval($importer['uid']),
1094                 dbesc($guid)
1095         );
1096         if(count($c))
1097                 $conversation = $c[0];
1098         else {
1099                 $r = q("insert into conv (uid,guid,creator,created,updated,subject,recips) values(%d, '%s', '%s', '%s', '%s', '%s', '%s') ",
1100                         intval($importer['uid']),
1101                         dbesc($guid),
1102                         dbesc($diaspora_handle),
1103                         dbesc(datetime_convert('UTC','UTC',$created_at)),
1104                         dbesc(datetime_convert()),
1105                         dbesc($subject),
1106                         dbesc($participant_handles)
1107                 );
1108                 if($r)
1109                         $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1110                 intval($importer['uid']),
1111             dbesc($guid)
1112         );
1113             if(count($c))
1114             $conversation = $c[0];
1115         }
1116         if(! $conversation) {
1117                 logger('diaspora_conversation: unable to create conversation.');
1118                 return;
1119         }
1120
1121
1122         foreach($messages as $mesg) {
1123
1124                 $reply = 0;
1125
1126                 $msg_guid = notags(unxmlify($mesg->guid));
1127                 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1128                 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1129                 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1130                 $msg_text = unxmlify($mesg->text);
1131                 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($mesg->created_at)));
1132                 $msg_diaspora_handle = notags(unxmlify($mesg->diaspora_handle));
1133                 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1134                 if($msg_conversation_guid != $guid) {
1135                         logger('diaspora_conversation: message conversation guid does not belong to the current conversation. ' . $xml);
1136                         continue;
1137                 }
1138
1139                 // Is this right?
1140
1141                 if($msg_parent_guid != $guid)
1142                         $reply = 1;
1143                         
1144                 $body = diaspora2bb($msg_text);
1145                 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1146
1147                 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1148 //              $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . $msg_diaspora_handle;
1149
1150                 $author_signature = base64_decode($msg_author_signature);
1151
1152                 if(strcasecmp($msg_diaspora_handle,$msg['author']) == 0) {
1153                         $person = $contact;
1154                         $key = $msg['key'];
1155                 }
1156                 else {
1157                         $person = find_diaspora_person_by_handle($msg_diaspora_handle); 
1158
1159                         if(is_array($person) && x($person,'pubkey'))
1160                                 $key = $person['pubkey'];
1161                         else {
1162                                 logger('diaspora_conversation: unable to find author details');
1163                                 continue;
1164                         }
1165                 }
1166
1167                 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1168                         logger('diaspora_conversation: verification failed.');
1169                         continue;
1170                 }
1171
1172                 if($msg_parent_author_signature) {
1173                         $owner_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1174
1175                         $parent_author_signature = base64_decode($msg_parent_author_signature);
1176
1177                         $key = $msg['key'];
1178
1179                         if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1180                                 logger('diaspora_conversation: owner verification failed.');
1181                                 continue;
1182                         }
1183                 }
1184
1185                 $r = q("select id from mail where `uri` = '%s' limit 1",
1186                         dbesc($message_id)
1187                 );
1188                 if(count($r)) {
1189                         logger('diaspora_conversation: duplicate message already delivered.', LOGGER_DEBUG);
1190                         continue;
1191                 }
1192
1193                 q("insert into mail ( `uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`replied`,`uri`,`parent-uri`,`created`) values ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1194                         intval($importer['uid']),
1195                         dbesc($msg_guid),
1196                         intval($conversation['id']),
1197                         dbesc($person['name']),
1198                         dbesc($person['photo']),
1199                         dbesc($person['url']),
1200                         intval($contact['id']),  
1201                         dbesc($subject),
1202                         dbesc($body),
1203                         0,
1204                         intval($reply),
1205                         dbesc($message_id),
1206                         dbesc($parent_uri),
1207                         dbesc($msg_created_at)
1208                 );                      
1209
1210                 q("updated conv set updated = '%s' where id = %d limit 1",
1211                         dbesc(datetime_convert()),
1212                         intval($conversation['id'])
1213                 );              
1214         }       
1215
1216         return;
1217 }
1218
1219
1220
1221
1222
1223
1224 function diaspora_photo($importer,$xml,$msg) {
1225
1226         $a = get_app();
1227         $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
1228
1229         $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
1230
1231         $status_message_guid = notags(unxmlify($xml->status_message_guid));
1232
1233         $guid = notags(unxmlify($xml->guid));
1234
1235         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1236
1237         $public = notags(unxmlify($xml->public));
1238
1239         $created_at = notags(unxmlify($xml_created_at));
1240
1241
1242         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1243         if(! $contact)
1244                 return;
1245
1246         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
1247                 logger('diaspora_photo: Ignoring this author.');
1248                 return 202;
1249         }
1250
1251         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1252                 intval($importer['uid']),
1253                 dbesc($status_message_guid)
1254         );
1255         if(! count($r)) {
1256                 logger('diaspora_photo: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
1257                 return;
1258         }
1259         $parent_item = $r[0];
1260
1261         $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
1262
1263         $link_text = scale_diaspora_images($link_text);
1264
1265         if(strpos($parent_item['body'],$link_text) === false) {
1266                 $r = q("update item set `body` = '%s', `visible` = 1 where `id` = %d and `uid` = %d limit 1",
1267                         dbesc($link_text . $parent_item['body']),
1268                         intval($parent_item['id']),
1269                         intval($parent_item['uid'])
1270                 );
1271         }
1272
1273         return;
1274 }
1275
1276
1277
1278
1279 function diaspora_like($importer,$xml,$msg) {
1280
1281         $a = get_app();
1282         $guid = notags(unxmlify($xml->guid));
1283         $parent_guid = notags(unxmlify($xml->parent_guid));
1284         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1285         $target_type = notags(unxmlify($xml->target_type));
1286         $positive = notags(unxmlify($xml->positive));
1287         $author_signature = notags(unxmlify($xml->author_signature));
1288
1289         $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1290
1291         // likes on comments not supported here and likes on photos not supported by Diaspora
1292
1293         if($target_type !== 'Post')
1294                 return;
1295
1296         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1297         if(! $contact) {
1298                 logger('diaspora_like: cannot find contact: ' . $msg['author']);
1299                 return;
1300         }
1301
1302         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
1303                 logger('diaspora_like: Ignoring this author.');
1304                 return 202;
1305         }
1306
1307         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1308                 intval($importer['uid']),
1309                 dbesc($parent_guid)
1310         );
1311         if(! count($r)) {
1312                 logger('diaspora_like: parent item not found: ' . $guid);
1313                 return;
1314         }
1315
1316         $parent_item = $r[0];
1317
1318         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1319                 intval($importer['uid']),
1320                 dbesc($guid)
1321         );
1322         if(count($r)) {
1323                 if($positive === 'true') {
1324                         logger('diaspora_like: duplicate like: ' . $guid);
1325                         return;
1326                 } 
1327                 if($positive === 'false') {
1328                         q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
1329                                 intval($r[0]['id']),
1330                                 intval($importer['uid'])
1331                         );
1332                         // FIXME
1333                         //  send notification via proc_run()
1334                         return;
1335                 }
1336         }
1337         if($positive === 'false') {
1338                 logger('diaspora_like: unlike received with no corresponding like');
1339                 return; 
1340         }
1341
1342         $author_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
1343
1344         $author_signature = base64_decode($author_signature);
1345
1346         if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
1347                 $person = $contact;
1348                 $key = $msg['key'];
1349         }
1350         else {
1351                 $person = find_diaspora_person_by_handle($diaspora_handle);     
1352                 if(is_array($person) && x($person,'pubkey'))
1353                         $key = $person['pubkey'];
1354                 else {
1355                         logger('diaspora_like: unable to find author details');
1356                         return;
1357                 }
1358         }
1359
1360         if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1361                 logger('diaspora_like: verification failed.');
1362                 return;
1363         }
1364
1365         if($parent_author_signature) {
1366
1367                 $owner_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
1368
1369                 $parent_author_signature = base64_decode($parent_author_signature);
1370
1371                 $key = $msg['key'];
1372
1373                 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1374                         logger('diaspora_like: owner verification failed.');
1375                         return;
1376                 }
1377         }
1378
1379         // Phew! Everything checks out. Now create an item.
1380
1381         $uri = $diaspora_handle . ':' . $guid;
1382
1383         $activity = ACTIVITY_LIKE;
1384         $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
1385         $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE ); 
1386         $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
1387         $body = $parent_item['body'];
1388
1389         $obj = <<< EOT
1390
1391         <object>
1392                 <type>$objtype</type>
1393                 <local>1</local>
1394                 <id>{$parent_item['uri']}</id>
1395                 <link>$link</link>
1396                 <title></title>
1397                 <content>$body</content>
1398         </object>
1399 EOT;
1400         $bodyverb = t('%1$s likes %2$s\'s %3$s');
1401
1402         $arr = array();
1403
1404         $arr['uri'] = $uri;
1405         $arr['uid'] = $importer['uid'];
1406         $arr['guid'] = $guid;
1407         $arr['contact-id'] = $contact['id'];
1408         $arr['type'] = 'activity';
1409         $arr['wall'] = $parent_item['wall'];
1410         $arr['gravity'] = GRAVITY_LIKE;
1411         $arr['parent'] = $parent_item['id'];
1412         $arr['parent-uri'] = $parent_item['uri'];
1413
1414         $arr['owner-name'] = $parent_item['name'];
1415         $arr['owner-link'] = $parent_item['url'];
1416         $arr['owner-avatar'] = $parent_item['thumb'];
1417
1418         $arr['author-name'] = $person['name'];
1419         $arr['author-link'] = $person['url'];
1420         $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1421         
1422         $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
1423         $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
1424         $plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
1425         $arr['body'] =  sprintf( $bodyverb, $ulink, $alink, $plink );
1426
1427         $arr['app']  = 'Diaspora';
1428
1429         $arr['private'] = $parent_item['private'];
1430         $arr['verb'] = $activity;
1431         $arr['object-type'] = $objtype;
1432         $arr['object'] = $obj;
1433         $arr['visible'] = 1;
1434         $arr['unseen'] = 1;
1435         $arr['last-child'] = 0;
1436
1437         $message_id = item_store($arr);
1438
1439
1440         if($message_id) {
1441                 q("update item set plink = '%s' where id = %d limit 1",
1442                         dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1443                         intval($message_id)
1444                 );
1445         }
1446
1447         if(! $parent_author_signature) {
1448                 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1449                         intval($message_id),
1450                         dbesc($author_signed_data),
1451                         dbesc(base64_encode($author_signature)),
1452                         dbesc($diaspora_handle)
1453                 );
1454         }
1455
1456         // if the message isn't already being relayed, notify others
1457         // the existence of parent_author_signature means the parent_author or owner
1458         // is already relaying. The parent_item['origin'] indicates the message was created on our system
1459
1460         if(($parent_item['origin']) && (! $parent_author_signature))
1461                 proc_run('php','include/notifier.php','comment',$message_id);
1462
1463         return;
1464 }
1465
1466 function diaspora_retraction($importer,$xml) {
1467
1468         $guid = notags(unxmlify($xml->guid));
1469         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1470         $type = notags(unxmlify($xml->type));
1471
1472         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1473         if(! $contact)
1474                 return;
1475
1476         if($type === 'Person') {
1477                 require_once('include/Contact.php');
1478                 contact_remove($contact['id']);
1479         }
1480         elseif($type === 'Post') {
1481                 $r = q("select * from item where guid = '%s' and uid = %d limit 1",
1482                         dbesc('guid'),
1483                         intval($importer['uid'])
1484                 );
1485                 if(count($r)) {
1486                         if(link_compare($r[0]['author-link'],$contact['url'])) {
1487                                 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d limit 1",
1488                                         dbesc(datetime_convert()),                      
1489                                         intval($r[0]['id'])
1490                                 );
1491                         }
1492                 }
1493         }
1494
1495         return 202;
1496         // NOTREACHED
1497 }
1498
1499 function diaspora_signed_retraction($importer,$xml) {
1500
1501         $guid = notags(unxmlify($xml->target_guid));
1502         $diaspora_handle = notags(unxmlify($xml->sender_handle));
1503         $type = notags(unxmlify($xml->target_type));
1504         $sig = notags(unxmlify($xml->target_author_signature));
1505
1506         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1507         if(! $contact)
1508                 return;
1509
1510         // this may not yet work for comments. Need to see how the relaying works
1511         // and figure out who signs it.
1512
1513
1514         $signed_data = $guid . ';' . $type ;
1515
1516         $sig = base64_decode($sig);
1517
1518         $key = $msg['key'];
1519
1520         if(! rsa_verify($signed_data,$sig,$key,'sha256')) {
1521                 logger('diaspora_signed_retraction: owner verification failed.' . print_r($msg,true));
1522                 return;
1523         }
1524
1525         if($type === 'StatusMessage') {
1526                 $r = q("select * from item where guid = '%s' and uid = %d limit 1",
1527                         dbesc('guid'),
1528                         intval($importer['uid'])
1529                 );
1530                 if(count($r)) {
1531                         if(link_compare($r[0]['author-link'],$contact['url'])) {
1532                                 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d limit 1",
1533                                         dbesc(datetime_convert()),                      
1534                                         intval($r[0]['id'])
1535                                 );
1536                         }
1537                 }
1538         }
1539
1540         return 202;
1541         // NOTREACHED
1542 }
1543
1544 function diaspora_profile($importer,$xml) {
1545
1546         $a = get_app();
1547         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1548
1549         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1550         if(! $contact)
1551                 return;
1552
1553         if($contact['blocked']) {
1554                 logger('diaspora_post: Ignoring this author.');
1555                 return 202;
1556         }
1557
1558         $name = unxmlify($xml->first_name) . ((strlen($xml->last_name)) ? ' ' . unxmlify($xml->last_name) : '');
1559         $image_url = unxmlify($xml->image_url);
1560         $birthday = unxmlify($xml->birthday);
1561
1562         $r = q("SELECT DISTINCT ( `resource-id` ) FROM `photo` WHERE  `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' ",
1563                 intval($importer['uid']),
1564                 intval($contact['id'])
1565         );
1566         $oldphotos = ((count($r)) ? $r : null);
1567
1568         require_once('include/Photo.php');
1569
1570         $images = import_profile_photo($image_url,$importer['uid'],$contact['id']);
1571         
1572         // Generic birthday. We don't know the timezone. The year is irrelevant. 
1573
1574         $birthday = str_replace('1000','1901',$birthday);
1575
1576         $birthday = datetime_convert('UTC','UTC',$birthday,'Y-m-d');
1577
1578         $r = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s', `avatar-date` = '%s' , `bd` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
1579                 dbesc($name),
1580                 dbesc(datetime_convert()),
1581                 dbesc($images[0]),
1582                 dbesc($images[1]),
1583                 dbesc($images[2]),
1584                 dbesc(datetime_convert()),
1585                 dbesc($birthday),
1586                 intval($contact['id']),
1587                 intval($importer['uid'])
1588         ); 
1589
1590         if($r) {
1591                 if($oldphotos) {
1592                         foreach($oldphotos as $ph) {
1593                                 q("DELETE FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' AND `resource-id` = '%s' ",
1594                                         intval($importer['uid']),
1595                                         intval($contact['id']),
1596                                         dbesc($ph['resource-id'])
1597                                 );
1598                         }
1599                 }
1600         }       
1601
1602         return;
1603
1604 }
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627 function diaspora_share($me,$contact) {
1628         $a = get_app();
1629         $myaddr = $me['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1630         $theiraddr = $contact['addr'];
1631
1632         $tpl = get_markup_template('diaspora_share.tpl');
1633         $msg = replace_macros($tpl, array(
1634                 '$sender' => $myaddr,
1635                 '$recipient' => $theiraddr
1636         ));
1637
1638         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
1639
1640         return(diaspora_transmit($owner,$contact,$slap, false));
1641 }
1642
1643 function diaspora_unshare($me,$contact) {
1644
1645         $a = get_app();
1646         $myaddr = $me['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1647
1648         $tpl = get_markup_template('diaspora_retract.tpl');
1649         $msg = replace_macros($tpl, array(
1650                 '$guid'   => $me['guid'],
1651                 '$type'   => 'Person',
1652                 '$handle' => $myaddr
1653         ));
1654
1655         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
1656
1657         return(diaspora_transmit($owner,$contact,$slap, false));
1658
1659 }
1660
1661
1662
1663 function diaspora_send_status($item,$owner,$contact,$public_batch = false) {
1664
1665         $a = get_app();
1666         $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1667         $theiraddr = $contact['addr'];
1668
1669         $images = array();
1670
1671         $body = $item['body'];
1672
1673 /*
1674         // We're trying to match Diaspora's split message/photo protocol but
1675         // all the photos are displayed on D* as links and not img's - even
1676         // though we're sending pretty much precisely what they send us when
1677         // doing the same operation.  
1678         // Commented out for now, we'll use bb2diaspora to convert photos to markdown
1679         // which seems to get through intact.
1680
1681         $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
1682         if($cnt) {
1683                 foreach($matches as $mtch) {
1684                         $detail = array();
1685                         $detail['str'] = $mtch[0];
1686                         $detail['path'] = dirname($mtch[1]) . '/';
1687                         $detail['file'] = basename($mtch[1]);
1688                         $detail['guid'] = $item['guid'];
1689                         $detail['handle'] = $myaddr;
1690                         $images[] = $detail;
1691                         $body = str_replace($detail['str'],$mtch[1],$body);
1692                 }
1693         }       
1694 */
1695
1696         $body = xmlify(html_entity_decode(bb2diaspora($body)));
1697
1698         if($item['attach']) {
1699                 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism',$item['attach'],$matches,PREG_SET_ORDER);
1700                 if(cnt) {
1701                         $body .= "\n" . t('Attachments:') . "\n";
1702                         foreach($matches as $mtch) {
1703                                 $body .= '[' . $mtch[3] . '](' . $mtch[1] . ')' . "\n";
1704                         }
1705                 }
1706         }       
1707
1708
1709         $public = (($item['private']) ? 'false' : 'true');
1710
1711         require_once('include/datetime.php');
1712         $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
1713
1714         $tpl = get_markup_template('diaspora_post.tpl');
1715         $msg = replace_macros($tpl, array(
1716                 '$body' => $body,
1717                 '$guid' => $item['guid'],
1718                 '$handle' => xmlify($myaddr),
1719                 '$public' => $public,
1720                 '$created' => $created
1721         ));
1722
1723         logger('diaspora_send_status: ' . $owner['username'] . ' -> ' . $contact['name'] . ' base message: ' . $msg, LOGGER_DATA);
1724
1725         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1726
1727         $return_code = diaspora_transmit($owner,$contact,$slap,$public_batch);
1728
1729         if(count($images)) {
1730                 diaspora_send_images($item,$owner,$contact,$images,$public_batch);
1731         }
1732
1733         return $return_code;
1734 }
1735
1736
1737 function diaspora_send_images($item,$owner,$contact,$images,$public_batch = false) {
1738         $a = get_app();
1739         if(! count($images))
1740                 return;
1741         $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
1742
1743         $tpl = get_markup_template('diaspora_photo.tpl');
1744         foreach($images as $image) {
1745                 if(! stristr($image['path'],$mysite))
1746                         continue;
1747                 $resource = str_replace('.jpg','',$image['file']);
1748                 $resource = substr($resource,0,strpos($resource,'-'));
1749
1750                 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
1751                         dbesc($resource),
1752                         intval($owner['uid'])
1753                 );
1754                 if(! count($r))
1755                         continue;
1756                 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
1757                 $msg = replace_macros($tpl,array(               
1758                         '$path' => xmlify($image['path']),
1759                         '$filename' => xmlify($image['file']),
1760                         '$msg_guid' => xmlify($image['guid']),
1761                         '$guid' => xmlify($r[0]['guid']),
1762                         '$handle' => xmlify($image['handle']),
1763                         '$public' => xmlify($public),
1764                         '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d H:i:s \U\T\C'))
1765                 ));
1766
1767
1768                 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
1769                 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1770
1771                 diaspora_transmit($owner,$contact,$slap,$public_batch);
1772         }
1773
1774 }
1775
1776 function diaspora_send_followup($item,$owner,$contact,$public_batch = false) {
1777
1778         $a = get_app();
1779         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1780         $theiraddr = $contact['addr'];
1781
1782         $p = q("select guid from item where parent = %d limit 1",
1783                 $item['parent']
1784         );
1785         if(count($p))
1786                 $parent_guid = $p[0]['guid'];
1787         else
1788                 return;
1789
1790         if($item['verb'] === ACTIVITY_LIKE) {
1791                 $tpl = get_markup_template('diaspora_like.tpl');
1792                 $like = true;
1793                 $target_type = 'Post';
1794                 $positive = (($item['deleted']) ? 'false' : 'true');
1795         }
1796         else {
1797                 $tpl = get_markup_template('diaspora_comment.tpl');
1798                 $like = false;
1799         }
1800
1801         $text = html_entity_decode(bb2diaspora($item['body']));
1802
1803         // sign it
1804
1805         if($like)
1806                 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
1807         else
1808                 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
1809
1810         $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1811
1812         $msg = replace_macros($tpl,array(
1813                 '$guid' => xmlify($item['guid']),
1814                 '$parent_guid' => xmlify($parent_guid),
1815                 '$target_type' =>xmlify($target_type),
1816                 '$authorsig' => xmlify($authorsig),
1817                 '$body' => xmlify($text),
1818                 '$positive' => xmlify($positive),
1819                 '$handle' => xmlify($myaddr)
1820         ));
1821
1822         logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
1823
1824         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1825
1826         return(diaspora_transmit($owner,$contact,$slap,$public_batch));
1827 }
1828
1829
1830 function diaspora_send_relay($item,$owner,$contact,$public_batch = false) {
1831
1832
1833         $a = get_app();
1834         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1835         $theiraddr = $contact['addr'];
1836
1837
1838         $p = q("select guid from item where parent = %d limit 1",
1839                 $item['parent']
1840         );
1841         if(count($p))
1842                 $parent_guid = $p[0]['guid'];
1843         else
1844                 return;
1845
1846         if($item['verb'] === ACTIVITY_LIKE) {
1847                 $tpl = get_markup_template('diaspora_like_relay.tpl');
1848                 $like = true;
1849                 $target_type = 'Post';
1850                 $positive = (($item['deleted']) ? 'false' : 'true');
1851         }
1852         else {
1853                 $tpl = get_markup_template('diaspora_comment_relay.tpl');
1854                 $like = false;
1855         }
1856
1857         $body = $item['body'];
1858
1859         $text = html_entity_decode(bb2diaspora($body));
1860
1861         // fetch the original signature if somebody sent the post to us to relay
1862         // If we are relaying for a reply originating on our own account, there wasn't a 'send to relay'
1863         // action. It wasn't needed. In that case create the original signature and the 
1864         // owner (parent author) signature
1865         // comments from other networks will be relayed under our name, with a brief 
1866         // preamble to describe what's happening and noting the real author
1867
1868         $r = q("select * from sign where iid = %d limit 1",
1869                 intval($item['id'])
1870         );
1871         if(count($r)) { 
1872                 $orig_sign = $r[0];
1873                 $signed_text = $orig_sign['signed_text'];
1874                 $authorsig = $orig_sign['signature'];
1875                 $handle = $orig_sign['signer'];
1876         }
1877         else {
1878
1879                 $itemcontact = q("select * from contact where `id` = %d limit 1",
1880                         intval($item['contact-id'])
1881                 );
1882                 if(count($itemcontact)) {
1883                         if(! $itemcontact[0]['self']) {
1884                                 $prefix = sprintf( t('[Relayed] Comment authored by %s from network %s'),
1885                                         '['. $item['author-name'] . ']' . '(' . $item['author-link'] . ')',  
1886                                         network_to_name($itemcontact['network'])) . "\n";
1887                                 $body = $prefix . $body;
1888                         }
1889                 }
1890                 else {
1891
1892                         if($like)
1893                                 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
1894                         else
1895                                 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
1896
1897                         $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1898
1899                         q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1900                                 intval($item['id']),
1901                                 dbesc($signed_text),
1902                                 dbesc(base64_encode($authorsig)),
1903                                 dbesc($myaddr)
1904                         );
1905                         $handle = $myaddr;
1906                 }
1907         }
1908
1909         // sign it
1910
1911         $parentauthorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1912
1913         $msg = replace_macros($tpl,array(
1914                 '$guid' => xmlify($item['guid']),
1915                 '$parent_guid' => xmlify($parent_guid),
1916                 '$target_type' =>xmlify($target_type),
1917                 '$authorsig' => xmlify($orig_sign['signature']),
1918                 '$parentsig' => xmlify($parentauthorsig),
1919                 '$body' => xmlify($text),
1920                 '$positive' => xmlify($positive),
1921                 '$handle' => xmlify($handle)
1922         ));
1923
1924         logger('diaspora_relay_comment: base message: ' . $msg, LOGGER_DATA);
1925
1926         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1927
1928         return(diaspora_transmit($owner,$contact,$slap,$public_batch));
1929
1930 }
1931
1932
1933
1934 function diaspora_send_retraction($item,$owner,$contact,$public_batch = false) {
1935
1936         $a = get_app();
1937         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1938
1939         $signed_text = $item['guid'] . ';' . 'StatusMessage';
1940
1941         $tpl = get_markup_template('diaspora_signed_retract.tpl');
1942         $msg = replace_macros($tpl, array(
1943                 '$guid'   => $item['guid'],
1944                 '$type'   => 'StatusMessage',
1945                 '$handle' => $myaddr,
1946                 '$signature' => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'))
1947         ));
1948
1949         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1950
1951         return(diaspora_transmit($owner,$contact,$slap,$public_batch));
1952 }
1953
1954 function diaspora_send_mail($item,$owner,$contact) {
1955
1956         $a = get_app();
1957         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1958
1959         $r = q("select * from conv where id = %d and uid = %d limit 1",
1960                 intval($item['convid']),
1961                 intval($item['uid'])
1962         );
1963
1964         if(! count($r)) {
1965                 logger('diaspora_send_mail: conversation not found.');
1966                 return;
1967         }
1968         $cnv = $r[0];
1969
1970         $parent = null;
1971
1972         if($item['parent-uri'] != $item['uri']) {
1973                 $r = q("select * from mail where uri = '%s' and uid = %d limit 1",
1974                         dbesc($item['parent-uri']),
1975                         intval($item['uid'])
1976                 );
1977                 $parent = $r[0];
1978         }
1979
1980         $conv = array(
1981                 'guid' => xmlify($cnv['guid']),
1982                 'subject' => xmlify($cnv['subject']),
1983                 'created_at' => xmlify(datetime_convert('UTC','UTC',$cnv['created'],'Y-m-d H:i:s \U\T\C')),
1984                 'diaspora_handle' => xmlify($cnv['creator']),
1985                 'participant_handles' => xmlify($cnv['recips'])
1986         );
1987
1988         $body = bb2diaspora($item['body']);
1989         $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
1990         $parent_guid = (($item['parent-uri'] == $item['uri']) ? $cnv['guid'] : $parent['guid']);
1991  
1992         $signed_text =  $item['guid'] . ';' . $parent_guid . ';' . $body .  ';' 
1993                 . $created . ';' . $myaddr . ';' . $cnv['guid'];
1994
1995         $sig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1996
1997         $msg = array(
1998                 'guid' => xmlify($item['guid']),
1999                 'parent_guid' => (($item['parent-uri'] == $item['uri']) ? xmlify($cnv['guid']) : xmlify($parent['guid'])),
2000                 'parent_author_signature' => (($item['parent-uri'] == $item['uri']) ? xmlify($sig) : null),
2001                 'author_signature' => xmlify($sig),
2002                 'text' => xmlify($body),
2003                 'created_at' => xmlify($created),
2004                 'diaspora_handle' => xmlify($myaddr),
2005                 'conversation_guid' => xmlify($cnv['guid'])
2006         );
2007
2008         $conv['messages'] = array($msg);
2009
2010         $tpl = get_markup_template('diaspora_conversation.tpl');
2011         $msg = replace_macros($tpl, array('$conv' => $conv));
2012
2013         logger('diaspora_conversation: ' . print_r($msg,true));
2014
2015         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false)));
2016
2017         return(diaspora_transmit($owner,$contact,$slap,false));
2018
2019
2020 }
2021
2022 function diaspora_transmit($owner,$contact,$slap,$public_batch) {
2023
2024         $a = get_app();
2025         $logid = random_string(4);
2026         $dest_url = (($public_batch) ? $contact['batch'] : $contact['notify']);
2027         if(! $dest_url) {
2028                 logger('diaspora_transmit: no url for contact: ' . $contact['id'] . ' batch mode =' . $public_batch);
2029                 return 0;
2030         } 
2031
2032         logger('diaspora_transmit: ' . $logid . ' ' . $dest_url);
2033
2034         post_url($dest_url . '/', $slap);
2035
2036         $return_code = $a->get_curl_code();
2037         logger('diaspora_transmit: ' . $logid . ' returns: ' . $return_code);
2038
2039         if((! $return_code) || (($return_code == 503) && (stristr($a->get_curl_headers(),'retry-after')))) {
2040                 logger('diaspora_transmit: queue message');
2041
2042                 $r = q("SELECT id from queue where cid = %d and network = '%s' and content = '%s' and batch = %d limit 1",
2043                         intval($contact['id']),
2044                         dbesc(NETWORK_DIASPORA),
2045                         dbesc($slap),
2046                         intval($public_batch)
2047                 );
2048                 if(count($r)) {
2049                         logger('diaspora_transmit: add_to_queue ignored - identical item already in queue');
2050                 }
2051                 else {
2052                         // queue message for redelivery
2053                         add_to_queue($contact['id'],NETWORK_DIASPORA,$slap,$public_batch);
2054                 }
2055         }
2056
2057
2058         return(($return_code) ? $return_code : (-1));
2059 }