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