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