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