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