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