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