]> git.mxchange.org Git - friendica-addons.git/blob - diaspora/diaspora.php
34d84c8ff11b746ff815bbfd7259882cb56b67a1
[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\Addon;
13 use Friendica\Core\PConfig;
14 use Friendica\Database\DBM;
15 use Friendica\Model\Queue;
16
17 function diaspora_install() {
18         Addon::registerHook('post_local',           'addon/diaspora/diaspora.php', 'diaspora_post_local');
19         Addon::registerHook('notifier_normal',      'addon/diaspora/diaspora.php', 'diaspora_send');
20         Addon::registerHook('jot_networks',         'addon/diaspora/diaspora.php', 'diaspora_jot_nets');
21         Addon::registerHook('connector_settings',      'addon/diaspora/diaspora.php', 'diaspora_settings');
22         Addon::registerHook('connector_settings_post', 'addon/diaspora/diaspora.php', 'diaspora_settings_post');
23         Addon::registerHook('queue_predeliver', 'addon/diaspora/diaspora.php', 'diaspora_queue_hook');
24 }
25 function diaspora_uninstall() {
26         Addon::unregisterHook('post_local',       'addon/diaspora/diaspora.php', 'diaspora_post_local');
27         Addon::unregisterHook('notifier_normal',  'addon/diaspora/diaspora.php', 'diaspora_send');
28         Addon::unregisterHook('jot_networks',     'addon/diaspora/diaspora.php', 'diaspora_jot_nets');
29         Addon::unregisterHook('connector_settings',      'addon/diaspora/diaspora.php', 'diaspora_settings');
30         Addon::unregisterHook('connector_settings_post', 'addon/diaspora/diaspora.php', 'diaspora_settings_post');
31         Addon::unregisterHook('queue_predeliver', 'addon/diaspora/diaspora.php', 'diaspora_queue_hook');
32 }
33
34
35 function diaspora_jot_nets(&$a,&$b) {
36     if(! local_user())
37         return;
38
39     $diaspora_post = PConfig::get(local_user(),'diaspora','post');
40     if(intval($diaspora_post) == 1) {
41         $diaspora_defpost = PConfig::get(local_user(),'diaspora','post_by_default');
42         $selected = ((intval($diaspora_defpost) == 1) ? ' checked="checked" ' : '');
43         $b .= '<div class="profile-jot-net"><input type="checkbox" name="diaspora_enable"' . $selected . ' value="1" /> '
44             . t('Post to Diaspora') . '</div>';
45     }
46 }
47
48 function diaspora_queue_hook(&$a,&$b) {
49         $hostname = $a->get_hostname();
50
51         $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
52                 dbesc(NETWORK_DIASPORA2)
53         );
54         if(! count($qi))
55                 return;
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                                 Queue::removeItem($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
108                 if (!$success) {
109                         logger('diaspora_queue: delayed');
110                         Queue::updateTime($x['id']);
111                 }
112         }
113 }
114
115 function diaspora_settings(&$a,&$s) {
116
117         if(! local_user())
118                 return;
119
120         /* Add our stylesheet to the page so we can make our settings look nice */
121
122         $a->page['htmlhead'] .= '<link rel="stylesheet"  type="text/css" href="' . $a->get_baseurl() . '/addon/diaspora/diaspora.css' . '" media="all" />' . "\r\n";
123
124         /* Get the current state of our config variables */
125
126         $enabled = PConfig::get(local_user(),'diaspora','post');
127         $checked = (($enabled) ? ' checked="checked" ' : '');
128         $css = (($enabled) ? '' : '-disabled');
129
130         $def_enabled = PConfig::get(local_user(),'diaspora','post_by_default');
131
132         $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
133
134         $handle = PConfig::get(local_user(), 'diaspora', 'handle');
135         $password = PConfig::get(local_user(), 'diaspora', 'password');
136         $aspect = PConfig::get(local_user(),'diaspora','aspect');
137
138         $status = "";
139
140         $r = q("SELECT `addr` FROM `contact` WHERE `self` AND `uid` = %d", intval(local_user()));
141         if (DBM::is_result($r)) {
142                 $status = sprintf(t("Please remember: You can always be reached from Diaspora with your Friendica handle %s. "), $r[0]['addr']);
143                 $status .= t('This connector is only meant if you still want to use your old Diaspora account for some time. ');
144                 $status .= sprintf(t('However, it is preferred that you tell your Diaspora contacts the new handle %s instead.'), $r[0]['addr']);
145         }
146
147         $aspects = false;
148
149         if ($handle && $password) {
150                 $conn = new Diaspora_Connection($handle, $password);
151                 $conn->logIn();
152                 $aspects = $conn->getAspects();
153                 if (!$aspects) {
154                         $status = t("Can't login to your Diaspora account. Please check handle (in the format user@domain.tld) and password.");
155                 }
156         }
157
158         /* Add some HTML to the existing form */
159
160         $s .= '<span id="settings_diaspora_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_diaspora_expanded\'); openClose(\'settings_diaspora_inflated\');">';
161         $s .= '<img class="connector'.$css.'" src="images/diaspora-logo.png" /><h3 class="connector">'. t('Diaspora Export').'</h3>';
162         $s .= '</span>';
163         $s .= '<div id="settings_diaspora_expanded" class="settings-block" style="display: none;">';
164         $s .= '<span class="fakelink" onclick="openClose(\'settings_diaspora_expanded\'); openClose(\'settings_diaspora_inflated\');">';
165         $s .= '<img class="connector'.$css.'" src="images/diaspora-logo.png" /><h3 class="connector">'. t('Diaspora Export').'</h3>';
166         $s .= '</span>';
167
168         if ($status) {
169                 $s .= '<div id="diaspora-status-wrapper"><strong>';
170                 $s .= $status;
171                 $s .= '</strong></div><div class="clear"></div>';
172         }
173
174         $s .= '<div id="diaspora-enable-wrapper">';
175         $s .= '<label id="diaspora-enable-label" for="diaspora-checkbox">' . t('Enable Diaspora Post Addon') . '</label>';
176         $s .= '<input id="diaspora-checkbox" type="checkbox" name="diaspora" value="1" ' . $checked . '/>';
177         $s .= '</div><div class="clear"></div>';
178
179         $s .= '<div id="diaspora-username-wrapper">';
180         $s .= '<label id="diaspora-username-label" for="diaspora-username">' . t('Diaspora handle') . '</label>';
181         $s .= '<input id="diaspora-username" type="text" name="handle" value="' . $handle . '" />';
182         $s .= '</div><div class="clear"></div>';
183
184         $s .= '<div id="diaspora-password-wrapper">';
185         $s .= '<label id="diaspora-password-label" for="diaspora-password">' . t('Diaspora password') . '</label>';
186         $s .= '<input id="diaspora-password" type="password" name="password" value="' . $password . '" />';
187         $s .= '</div><div class="clear"></div>';
188
189         if ($aspects) {
190                 $single_aspect =  new stdClass();
191                 $single_aspect->id = 'all_aspects';
192                 $single_aspect->name = t('All aspects');
193                 $aspects[] = $single_aspect;
194
195                 $single_aspect =  new stdClass();
196                 $single_aspect->id = 'public';
197                 $single_aspect->name = t('Public');
198                 $aspects[] = $single_aspect;
199
200                 $s .= '<label id="diaspora-aspect-label" for="diaspora-aspect">' . t('Post to aspect:') . '</label>';
201                 $s .= '<select name="aspect" id="diaspora-aspect">';
202                 foreach($aspects as $single_aspect) {
203                         if ($single_aspect->id == $aspect)
204                                 $s .= "<option value='".$single_aspect->id."' selected>".$single_aspect->name."</option>";
205                         else
206                                 $s .= "<option value='".$single_aspect->id."'>".$single_aspect->name."</option>";
207                 }
208
209                 $s .= "</select>";
210                 $s .= '<div class="clear"></div>';
211         }
212
213         $s .= '<div id="diaspora-bydefault-wrapper">';
214         $s .= '<label id="diaspora-bydefault-label" for="diaspora-bydefault">' . t('Post to Diaspora by default') . '</label>';
215         $s .= '<input id="diaspora-bydefault" type="checkbox" name="diaspora_bydefault" value="1" ' . $def_checked . '/>';
216         $s .= '</div><div class="clear"></div>';
217
218         /* provide a submit button */
219
220         $s .= '<div class="settings-submit-wrapper" ><input type="submit" id="diaspora-submit" name="diaspora-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div></div>';
221
222 }
223
224
225 function diaspora_settings_post(&$a,&$b) {
226
227         if(x($_POST,'diaspora-submit')) {
228
229                 PConfig::set(local_user(),'diaspora','post',intval($_POST['diaspora']));
230                 PConfig::set(local_user(),'diaspora','post_by_default',intval($_POST['diaspora_bydefault']));
231                 PConfig::set(local_user(),'diaspora','handle',trim($_POST['handle']));
232                 PConfig::set(local_user(),'diaspora','password',trim($_POST['password']));
233                 PConfig::set(local_user(),'diaspora','aspect',trim($_POST['aspect']));
234         }
235
236 }
237
238 function diaspora_post_local(&$a,&$b) {
239
240         if ($b['edit']) {
241                 return;
242         }
243
244         if (!local_user() || (local_user() != $b['uid'])) {
245                 return;
246         }
247
248         if ($b['private'] || $b['parent']) {
249                 return;
250         }
251
252         $diaspora_post   = intval(PConfig::get(local_user(),'diaspora','post'));
253
254         $diaspora_enable = (($diaspora_post && x($_REQUEST,'diaspora_enable')) ? intval($_REQUEST['diaspora_enable']) : 0);
255
256         if ($b['api_source'] && intval(PConfig::get(local_user(),'diaspora','post_by_default'))) {
257                 $diaspora_enable = 1;
258         }
259
260         if (!$diaspora_enable) {
261                 return;
262         }
263
264         if (strlen($b['postopts'])) {
265                 $b['postopts'] .= ',';
266         }
267
268         $b['postopts'] .= 'diaspora';
269 }
270
271
272
273
274 function diaspora_send(&$a,&$b) {
275         $hostname = $a->get_hostname();
276
277         logger('diaspora_send: invoked');
278
279         if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited'])) {
280                 return;
281         }
282
283         if(! strstr($b['postopts'],'diaspora')) {
284                 return;
285         }
286
287         if($b['parent'] != $b['id']) {
288                 return;
289         }
290
291         // Dont't post if the post doesn't belong to us.
292         // This is a check for forum postings
293         $self = dba::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
294         if ($b['contact-id'] != $self['id']) {
295                 return;
296         }
297
298         logger('diaspora_send: prepare posting', LOGGER_DEBUG);
299
300         $handle = PConfig::get($b['uid'],'diaspora','handle');
301         $password = PConfig::get($b['uid'],'diaspora','password');
302         $aspect = PConfig::get($b['uid'],'diaspora','aspect');
303
304         if ($handle && $password) {
305
306                 logger('diaspora_send: all values seem to be okay', LOGGER_DEBUG);
307
308                 require_once('include/bb2diaspora.php');
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 = bb2diaspora($body, false, true);
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(t('Diaspora post failed. Queued for retry.').EOL);
372                 }
373         }
374 }