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