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