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