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