3c4a30d2f7f5c77d9db6a8b5f51041175a08dfbf
[friendica-addons.git] / diaspora / diaspora.php
1 <?php
2
3 /**
4  * Name: Diaspora Post Connector
5  * Description: Post to Diaspora
6  * Version: 0.2
7  * Author: Michael Vogel <heluecht@pirati.ca>
8  */
9
10 require_once("addon/diaspora/Diaspora_Connection.php");
11
12 use Friendica\Core\PConfig;
13 use Friendica\Database\DBM;
14
15 function diaspora_install() {
16         register_hook('post_local',           'addon/diaspora/diaspora.php', 'diaspora_post_local');
17         register_hook('notifier_normal',      'addon/diaspora/diaspora.php', 'diaspora_send');
18         register_hook('jot_networks',         'addon/diaspora/diaspora.php', 'diaspora_jot_nets');
19         register_hook('connector_settings',      'addon/diaspora/diaspora.php', 'diaspora_settings');
20         register_hook('connector_settings_post', 'addon/diaspora/diaspora.php', 'diaspora_settings_post');
21         register_hook('queue_predeliver', 'addon/diaspora/diaspora.php', 'diaspora_queue_hook');
22 }
23 function diaspora_uninstall() {
24         unregister_hook('post_local',       'addon/diaspora/diaspora.php', 'diaspora_post_local');
25         unregister_hook('notifier_normal',  'addon/diaspora/diaspora.php', 'diaspora_send');
26         unregister_hook('jot_networks',     'addon/diaspora/diaspora.php', 'diaspora_jot_nets');
27         unregister_hook('connector_settings',      'addon/diaspora/diaspora.php', 'diaspora_settings');
28         unregister_hook('connector_settings_post', 'addon/diaspora/diaspora.php', 'diaspora_settings_post');
29         unregister_hook('queue_predeliver', 'addon/diaspora/diaspora.php', 'diaspora_queue_hook');
30 }
31
32
33 function diaspora_jot_nets(&$a,&$b) {
34     if(! local_user())
35         return;
36
37     $diaspora_post = PConfig::get(local_user(),'diaspora','post');
38     if(intval($diaspora_post) == 1) {
39         $diaspora_defpost = PConfig::get(local_user(),'diaspora','post_by_default');
40         $selected = ((intval($diaspora_defpost) == 1) ? ' checked="checked" ' : '');
41         $b .= '<div class="profile-jot-net"><input type="checkbox" name="diaspora_enable"' . $selected . ' value="1" /> '
42             . t('Post to Diaspora') . '</div>';
43     }
44 }
45
46 function diaspora_queue_hook(&$a,&$b) {
47         $hostname = $a->get_hostname();
48
49         $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
50                 dbesc(NETWORK_DIASPORA2)
51         );
52         if(! count($qi))
53                 return;
54
55         require_once('include/queue_fn.php');
56
57         foreach($qi as $x) {
58                 if($x['network'] !== NETWORK_DIASPORA2)
59                         continue;
60
61                 logger('diaspora_queue: run');
62
63                 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` on `contact`.`uid` = `user`.`uid`
64                         WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
65                         intval($x['cid'])
66                 );
67                 if(! count($r))
68                         continue;
69
70                 $userdata = $r[0];
71
72                 $handle = PConfig::get($userdata['uid'],'diaspora','handle');
73                 $password = PConfig::get($userdata['uid'],'diaspora','password');
74                 $aspect = PConfig::get($userdata['uid'],'diaspora','aspect');
75
76                 $success = false;
77
78                 if ($handle && $password) {
79                         logger('diaspora_queue: able to post for user '.$handle);
80
81                         $z = unserialize($x['content']);
82
83                         $post = $z['post'];
84
85                         logger('diaspora_queue: post: '.$post, LOGGER_DATA);
86
87                         try {
88                                 logger('diaspora_queue: prepare', LOGGER_DEBUG);
89                                 $conn = new Diaspora_Connection($handle, $password);
90                                 logger('diaspora_queue: try to log in '.$handle, LOGGER_DEBUG);
91                                 $conn->logIn();
92                                 logger('diaspora_queue: try to send '.$body, LOGGER_DEBUG);
93                                 $conn->provider = $hostname;
94                                 $conn->postStatusMessage($post, $aspect);
95
96                                 logger('diaspora_queue: send '.$userdata['uid'].' success', LOGGER_DEBUG);
97
98                                 $success = true;
99
100                                 remove_queue_item($x['id']);
101                         } catch (Exception $e) {
102                                 logger("diaspora_queue: Send ".$userdata['uid']." failed: ".$e->getMessage(), LOGGER_DEBUG);
103                         }
104                 } else
105                         logger('diaspora_queue: send '.$userdata['uid'].' missing username or password', LOGGER_DEBUG);
106
107                 if (!$success) {
108                         logger('diaspora_queue: delayed');
109                         update_queue_time($x['id']);
110                 }
111         }
112 }
113
114 function diaspora_settings(&$a,&$s) {
115
116         if(! local_user())
117                 return;
118
119         /* Add our stylesheet to the page so we can make our settings look nice */
120
121         $a->page['htmlhead'] .= '<link rel="stylesheet"  type="text/css" href="' . $a->get_baseurl() . '/addon/diaspora/diaspora.css' . '" media="all" />' . "\r\n";
122
123         /* Get the current state of our config variables */
124
125         $enabled = PConfig::get(local_user(),'diaspora','post');
126         $checked = (($enabled) ? ' checked="checked" ' : '');
127         $css = (($enabled) ? '' : '-disabled');
128
129         $def_enabled = PConfig::get(local_user(),'diaspora','post_by_default');
130
131         $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
132
133         $handle = PConfig::get(local_user(), 'diaspora', 'handle');
134         $password = PConfig::get(local_user(), 'diaspora', 'password');
135         $aspect = PConfig::get(local_user(),'diaspora','aspect');
136
137         $status = "";
138
139         $r = q("SELECT `addr` FROM `contact` WHERE `self` AND `uid` = %d", intval(local_user()));
140         if (DBM::is_result($r)) {
141                 $status = sprintf(t("Please remember: You can always be reached from Diaspora with your Friendica handle %s. "), $r[0]['addr']);
142                 $status .= t('This connector is only meant if you still want to use your old Diaspora account for some time. ');
143                 $status .= sprintf(t('However, it is preferred that you tell your Diaspora contacts the new handle %s instead.'), $r[0]['addr']);
144         }
145
146         $aspects = false;
147
148         if ($handle && $password) {
149                 $conn = new Diaspora_Connection($handle, $password);
150                 $conn->logIn();
151                 $aspects = $conn->getAspects();
152                 if (!$aspects) {
153                         $status = t("Can't login to your Diaspora account. Please check handle (in the format user@domain.tld) and password.");
154                 }
155         }
156
157         /* Add some HTML to the existing form */
158
159         $s .= '<span id="settings_diaspora_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_diaspora_expanded\'); openClose(\'settings_diaspora_inflated\');">';
160         $s .= '<img class="connector'.$css.'" src="images/diaspora-logo.png" /><h3 class="connector">'. t('Diaspora Export').'</h3>';
161         $s .= '</span>';
162         $s .= '<div id="settings_diaspora_expanded" class="settings-block" style="display: none;">';
163         $s .= '<span class="fakelink" onclick="openClose(\'settings_diaspora_expanded\'); openClose(\'settings_diaspora_inflated\');">';
164         $s .= '<img class="connector'.$css.'" src="images/diaspora-logo.png" /><h3 class="connector">'. t('Diaspora Export').'</h3>';
165         $s .= '</span>';
166
167         if ($status) {
168                 $s .= '<div id="diaspora-status-wrapper"><strong>';
169                 $s .= $status;
170                 $s .= '</strong></div><div class="clear"></div>';
171         }
172
173         $s .= '<div id="diaspora-enable-wrapper">';
174         $s .= '<label id="diaspora-enable-label" for="diaspora-checkbox">' . t('Enable Diaspora Post Plugin') . '</label>';
175         $s .= '<input id="diaspora-checkbox" type="checkbox" name="diaspora" value="1" ' . $checked . '/>';
176         $s .= '</div><div class="clear"></div>';
177
178         $s .= '<div id="diaspora-username-wrapper">';
179         $s .= '<label id="diaspora-username-label" for="diaspora-username">' . t('Diaspora handle') . '</label>';
180         $s .= '<input id="diaspora-username" type="text" name="handle" value="' . $handle . '" />';
181         $s .= '</div><div class="clear"></div>';
182
183         $s .= '<div id="diaspora-password-wrapper">';
184         $s .= '<label id="diaspora-password-label" for="diaspora-password">' . t('Diaspora password') . '</label>';
185         $s .= '<input id="diaspora-password" type="password" name="password" value="' . $password . '" />';
186         $s .= '</div><div class="clear"></div>';
187
188         if ($aspects) {
189                 $single_aspect =  new stdClass();
190                 $single_aspect->id = 'all_aspects';
191                 $single_aspect->name = t('All aspects');
192                 $aspects[] = $single_aspect;
193
194                 $single_aspect =  new stdClass();
195                 $single_aspect->id = 'public';
196                 $single_aspect->name = t('Public');
197                 $aspects[] = $single_aspect;
198
199                 $s .= '<label id="diaspora-aspect-label" for="diaspora-aspect">' . t('Post to aspect:') . '</label>';
200                 $s .= '<select name="aspect" id="diaspora-aspect">';
201                 foreach($aspects as $single_aspect) {
202                         if ($single_aspect->id == $aspect)
203                                 $s .= "<option value='".$single_aspect->id."' selected>".$single_aspect->name."</option>";
204                         else
205                                 $s .= "<option value='".$single_aspect->id."'>".$single_aspect->name."</option>";
206                 }
207
208                 $s .= "</select>";
209                 $s .= '<div class="clear"></div>';
210         }
211
212         $s .= '<div id="diaspora-bydefault-wrapper">';
213         $s .= '<label id="diaspora-bydefault-label" for="diaspora-bydefault">' . t('Post to Diaspora by default') . '</label>';
214         $s .= '<input id="diaspora-bydefault" type="checkbox" name="diaspora_bydefault" value="1" ' . $def_checked . '/>';
215         $s .= '</div><div class="clear"></div>';
216
217         /* provide a submit button */
218
219         $s .= '<div class="settings-submit-wrapper" ><input type="submit" id="diaspora-submit" name="diaspora-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div></div>';
220
221 }
222
223
224 function diaspora_settings_post(&$a,&$b) {
225
226         if(x($_POST,'diaspora-submit')) {
227
228                 PConfig::set(local_user(),'diaspora','post',intval($_POST['diaspora']));
229                 PConfig::set(local_user(),'diaspora','post_by_default',intval($_POST['diaspora_bydefault']));
230                 PConfig::set(local_user(),'diaspora','handle',trim($_POST['handle']));
231                 PConfig::set(local_user(),'diaspora','password',trim($_POST['password']));
232                 PConfig::set(local_user(),'diaspora','aspect',trim($_POST['aspect']));
233         }
234
235 }
236
237 function diaspora_post_local(&$a,&$b) {
238
239         if ($b['edit']) {
240                 return;
241         }
242
243         if (!local_user() || (local_user() != $b['uid'])) {
244                 return;
245         }
246
247         if ($b['private'] || $b['parent']) {
248                 return;
249         }
250
251         $diaspora_post   = intval(PConfig::get(local_user(),'diaspora','post'));
252
253         $diaspora_enable = (($diaspora_post && x($_REQUEST,'diaspora_enable')) ? intval($_REQUEST['diaspora_enable']) : 0);
254
255         if ($b['api_source'] && intval(PConfig::get(local_user(),'diaspora','post_by_default'))) {
256                 $diaspora_enable = 1;
257         }
258
259         if (!$diaspora_enable) {
260                 return;
261         }
262
263         if (strlen($b['postopts'])) {
264                 $b['postopts'] .= ',';
265         }
266
267         $b['postopts'] .= 'diaspora';
268 }
269
270
271
272
273 function diaspora_send(&$a,&$b) {
274         $hostname = $a->get_hostname();
275
276         logger('diaspora_send: invoked');
277
278         if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited'])) {
279                 return;
280         }
281
282         if(! strstr($b['postopts'],'diaspora')) {
283                 return;
284         }
285
286         if($b['parent'] != $b['id']) {
287                 return;
288         }
289
290         // Dont't post if the post doesn't belong to us.
291         // This is a check for forum postings
292         $self = dba::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
293         if ($b['contact-id'] != $self['id']) {
294                 return;
295         }
296
297         logger('diaspora_send: prepare posting', LOGGER_DEBUG);
298
299         $handle = PConfig::get($b['uid'],'diaspora','handle');
300         $password = PConfig::get($b['uid'],'diaspora','password');
301         $aspect = PConfig::get($b['uid'],'diaspora','aspect');
302
303         if ($handle && $password) {
304
305                 logger('diaspora_send: all values seem to be okay', LOGGER_DEBUG);
306
307                 require_once('include/bb2diaspora.php');
308                 $tag_arr = [];
309                 $tags = '';
310                 $x = preg_match_all('/\#\[(.*?)\](.*?)\[/',$b['tag'],$matches,PREG_SET_ORDER);
311
312                 if($x) {
313                         foreach($matches as $mtch) {
314                                 $tag_arr[] = $mtch[2];
315                         }
316                 }
317                 if(count($tag_arr))
318                         $tags = implode(',',$tag_arr);
319
320                 $title = $b['title'];
321                 $body = $b['body'];
322                 // Insert a newline before and after a quote
323                 $body = str_ireplace("[quote", "\n\n[quote", $body);
324                 $body = str_ireplace("[/quote]", "[/quote]\n\n", $body);
325
326                 // Removal of tags and mentions
327                 // #-tags
328                 $body = preg_replace('/#\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', '#$2', $body);
329                 // @-mentions
330                 $body = preg_replace('/@\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', '@$2', $body);
331
332                 // remove multiple newlines
333                 do {
334                         $oldbody = $body;
335                         $body = str_replace("\n\n\n", "\n\n", $body);
336                 } while ($oldbody != $body);
337
338                 // convert to markdown
339                 $body = bb2diaspora($body, false, true);
340
341                 // Adding the title
342                 if(strlen($title))
343                         $body = "## ".html_entity_decode($title)."\n\n".$body;
344
345                 require_once("addon/diaspora/diasphp.php");
346
347                 try {
348                         logger('diaspora_send: prepare', LOGGER_DEBUG);
349                         $conn = new Diaspora_Connection($handle, $password);
350                         logger('diaspora_send: try to log in '.$handle, LOGGER_DEBUG);
351                         $conn->logIn();
352                         logger('diaspora_send: try to send '.$body, LOGGER_DEBUG);
353
354                         $conn->provider = $hostname;
355                         $conn->postStatusMessage($body, $aspect);
356
357                         logger('diaspora_send: success');
358                 } catch (Exception $e) {
359                         logger("diaspora_send: Error submitting the post: " . $e->getMessage());
360
361                         logger('diaspora_send: requeueing '.$b['uid'], LOGGER_DEBUG);
362
363                         $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
364                         if (count($r))
365                                 $a->contact = $r[0]["id"];
366
367                         $s = serialize(['url' => $url, 'item' => $b['id'], 'post' => $body]);
368                         require_once('include/queue_fn.php');
369                         add_to_queue($a->contact,NETWORK_DIASPORA2,$s);
370                         notice(t('Diaspora post failed. Queued for retry.').EOL);
371                 }
372         }
373 }