]> git.mxchange.org Git - friendica-addons.git/blob - appnet/appnet.php
App.net: New connector that will be expanded to a bidirectional connector in the...
[friendica-addons.git] / appnet / appnet.php
1 <?php
2
3 /**
4  * Name: App.net Connector
5  * Description: Post to app.net
6  * Version: 0.1
7  * Author: Michael Vogel <https://pirati.ca/profile/heluecht>
8  */
9
10 function appnet_install() {
11         register_hook('post_local',           'addon/appnet/appnet.php', 'appnet_post_local');
12         register_hook('notifier_normal',      'addon/appnet/appnet.php', 'appnet_send');
13         register_hook('jot_networks',         'addon/appnet/appnet.php', 'appnet_jot_nets');
14         register_hook('connector_settings',      'addon/appnet/appnet.php', 'appnet_settings');
15         register_hook('connector_settings_post', 'addon/appnet/appnet.php', 'appnet_settings_post');
16 }
17
18
19 function appnet_uninstall() {
20         unregister_hook('post_local',       'addon/appnet/appnet.php', 'appnet_post_local');
21         unregister_hook('notifier_normal',  'addon/appnet/appnet.php', 'appnet_send');
22         unregister_hook('jot_networks',     'addon/appnet/appnet.php', 'appnet_jot_nets');
23         unregister_hook('connector_settings',      'addon/appnet/appnet.php', 'appnet_settings');
24         unregister_hook('connector_settings_post', 'addon/appnet/appnet.php', 'appnet_settings_post');
25 }
26
27 function appnet_module() {}
28
29 function appnet_content(&$a) {
30         if(! local_user()) {
31                 notice( t('Permission denied.') . EOL);
32                 return '';
33         }
34
35         require_once("mod/settings.php");
36         settings_init($a);
37
38         if (isset($a->argv[1]))
39                 switch ($a->argv[1]) {
40                         case "connect":
41                                 $o = appnet_connect($a);
42                                 break;
43                         default:
44                                 $o = print_r($a->argv, true);
45                                 break;
46                 }
47         else
48                 $o = appnet_connect($a);
49
50         return $o;
51 }
52
53 function appnet_connect(&$a) {
54         require_once 'addon/appnet/AppDotNet.php';
55
56         $clientId     = get_pconfig(local_user(),'appnet','clientid');
57         $clientSecret = get_pconfig(local_user(),'appnet','clientsecret');
58
59         $app = new AppDotNet($clientId, $clientSecret);
60
61         try {
62                 $token = $app->getAccessToken($a->get_baseurl().'/appnet/connect');
63
64                 logger("appnet_connect: authenticated");
65                 $o .= t("You are now authenticated to app.net. ");
66                 set_pconfig(local_user(),'appnet','token', $token);
67         }
68         catch (AppDotNetException $e) {
69                 $o .= t("<p>Error fetching token. Please try again.</p>");
70         }
71
72         $o .= '<br /><a href="'.$a->get_baseurl().'/settings/connectors">'.t("return to the connector page").'</a>';
73
74         return($o);
75 }
76
77 function appnet_jot_nets(&$a,&$b) {
78         if(! local_user())
79                 return;
80
81         $post = get_pconfig(local_user(),'appnet','post');
82         if(intval($post) == 1) {
83                 $defpost = get_pconfig(local_user(),'appnet','post_by_default');
84                 $selected = ((intval($defpost) == 1) ? ' checked="checked" ' : '');
85                 $b .= '<div class="profile-jot-net"><input type="checkbox" name="appnet_enable"' . $selected . ' value="1" /> '
86                         . t('Post to app.net') . '</div>';
87     }
88 }
89
90 function appnet_settings(&$a,&$s) {
91         require_once 'addon/appnet/AppDotNet.php';
92
93         if(! local_user())
94                 return;
95
96         $token = get_pconfig(local_user(),'appnet','token');
97         $app_clientId     = get_pconfig(local_user(),'appnet','clientid');
98         $app_clientSecret = get_pconfig(local_user(),'appnet','clientsecret');
99
100         /* Add our stylesheet to the page so we can make our settings look nice */
101         $a->page['htmlhead'] .= '<link rel="stylesheet"  type="text/css" href="' . $a->get_baseurl() . '/addon/appnet/appnet.css' . '" media="all" />' . "\r\n";
102
103         $enabled = get_pconfig(local_user(),'appnet','post');
104         $checked = (($enabled) ? ' checked="checked" ' : '');
105
106         $css = (($enabled) ? '' : '-disabled');
107
108         $def_enabled = get_pconfig(local_user(),'appnet','post_by_default');
109         $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
110
111         $s .= '<span id="settings_appnet_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_appnet_expanded\'); openClose(\'settings_appnet_inflated\');">';
112         $s .= '<img class="connector'.$css.'" src="images/appnet.png" /><h3 class="connector">'. t('App.net Export').'</h3>';
113         $s .= '</span>';
114         $s .= '<div id="settings_appnet_expanded" class="settings-block" style="display: none;">';
115         $s .= '<span class="fakelink" onclick="openClose(\'settings_appnet_expanded\'); openClose(\'settings_appnet_inflated\');">';
116         $s .= '<img class="connector'.$css.'" src="images/appnet.png" /><h3 class="connector">'. t('App.net Export').'</h3>';
117         $s .= '</span>';
118
119         if ($token != "") {
120                 $app = new AppDotNet($app_clientId, $app_clientSecret);
121                 $app->setAccessToken($token);
122
123                 try {
124                         $userdata = $app->getUser();
125
126                         $s .= '<div id="appnet-info" ><img id="appnet-avatar" src="'.$userdata["avatar_image"]["url"].'" /><p id="appnet-info-block">'. t('Currently connected to: ') .'<a href="'.$userdata["canonical_url"].'" target="_appnet">'.$userdata["username"].'</a><br /><em>'.$userdata["description"]["text"].'</em></p></div>';
127                         $s .= '<div id="appnet-enable-wrapper">';
128                         $s .= '<label id="appnet-enable-label" for="appnet-checkbox">' . t('Enable App.net Post Plugin') . '</label>';
129                         $s .= '<input id="appnet-checkbox" type="checkbox" name="appnet" value="1" ' . $checked . '/>';
130                         $s .= '</div><div class="clear"></div>';
131
132                         $s .= '<div id="appnet-bydefault-wrapper">';
133                         $s .= '<label id="appnet-bydefault-label" for="appnet-bydefault">' . t('Post to App.net by default') . '</label>';
134                         $s .= '<input id="appnet-bydefault" type="checkbox" name="appnet_bydefault" value="1" ' . $def_checked . '/>';
135                         $s .= '</div><div class="clear"></div>';
136                 }
137                 catch (AppDotNetException $e) {
138                         $s .= t("<p>Error fetching user profile. Please clear the configuration and try again.</p>");
139                 }
140                 //$s .= print_r($userdata, true);
141
142         } elseif (($app_clientId == '') OR ($app_clientSecret == '')) {
143                 $s .= t("<p>You have two ways to connect to App.net.</p>");
144                 $s .= "<hr />";
145                 $s .= t('<p>First way: Register an application at <a href="https://account.app.net/developer/apps/">https://account.app.net/developer/apps/</a> and enter Client ID and Client Secret. ');
146                 $s .= sprintf(t("Use '%s' as Redirect URI<p>"), $a->get_baseurl().'/appnet/connect');
147                 $s .= '<div id="appnet-clientid-wrapper">';
148                 $s .= '<label id="appnet-clientid-label" for="appnet-clientid">' . t('Client ID') . '</label>';
149                 $s .= '<input id="appnet-clientid" type="text" name="clientid" value="'.$app_clientId.'" />';
150                 $s .= '</div><div class="clear"></div>';
151                 $s .= '<div id="appnet-clientsecret-wrapper">';
152                 $s .= '<label id="appnet-clientsecret-label" for="appnet-clientsecret">' . t('Client Secret') . '</label>';
153                 $s .= '<input id="appnet-clientsecret" type="text" name="clientsecret" value="'.$app_clientSecret.'" />';
154                 $s .= '</div><div class="clear"></div>';
155                 $s .= "<hr />";
156                 $s .= t('<p>Second way: fetch a token at <a href="http://dev-lite.jonathonduerig.com/">http://dev-lite.jonathonduerig.com/</a>. ');
157                 $s .= t("Set these scopes: 'Basic', 'Stream', 'Write Post', 'Public Messages', 'Messages'.</p>");
158                 $s .= '<div id="appnet-token-wrapper">';
159                 $s .= '<label id="appnet-token-label" for="appnet-token">' . t('Token') . '</label>';
160                 $s .= '<input id="appnet-token" type="text" name="token" value="'.$token.'" />';
161                 $s .= '</div><div class="clear"></div>';
162
163         } else {
164                 $app = new AppDotNet($app_clientId, $app_clientSecret);
165
166                 $scope =  array('basic', 'stream', 'write_post',
167                                 'public_messages', 'messages');
168
169                 $url = $app->getAuthUrl($a->get_baseurl().'/appnet/connect', $scope);
170                 $s .= '<div class="clear"></div>';
171                 $s .= '<a href="'.$url.'">'.t("Sign in using App.net").'</a>';
172         }
173
174         if (($app_clientId != '') OR ($app_clientSecret != '') OR ($token !='')) {
175                 $s .= '<div id="appnet-disconnect-wrapper">';
176                 $s .= '<label id="appnet-disconnect-label" for="appnet-disconnect">'. t('Clear OAuth configuration') .'</label>';
177
178                 $s .= '<input id="appnet-disconnect" type="checkbox" name="appnet-disconnect" value="1" />';
179                 $s .= '</div><div class="clear"></div>';
180         }
181
182         /* provide a submit button */
183         $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="appnet-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>';
184
185         $s .= '</div>';
186 }
187
188 function appnet_settings_post(&$a,&$b) {
189
190         if(x($_POST,'appnet-submit')) {
191
192                 if (isset($_POST['appnet-disconnect'])) {
193                         del_pconfig(local_user(), 'appnet', 'clientsecret');
194                         del_pconfig(local_user(), 'appnet', 'clientid');
195                         del_pconfig(local_user(), 'appnet', 'token');
196                 }
197
198                 if (isset($_POST["clientsecret"]))
199                         set_pconfig(local_user(),'appnet','clientsecret', $_POST['clientsecret']);
200
201                 if (isset($_POST["clientid"]))
202                         set_pconfig(local_user(),'appnet','clientid', $_POST['clientid']);
203
204                 if (isset($_POST["token"]) AND ($_POST["token"] != ""))
205                         set_pconfig(local_user(),'appnet','token', $_POST['token']);
206
207                 set_pconfig(local_user(),'appnet','post',intval($_POST['appnet']));
208                 set_pconfig(local_user(),'appnet','post_by_default',intval($_POST['appnet_bydefault']));
209         }
210 }
211
212 function appnet_post_local(&$a,&$b) {
213
214         if($b['edit'])
215                 return;
216
217         if((! local_user()) || (local_user() != $b['uid']))
218                 return;
219
220         if($b['private'] || $b['parent'])
221                 return;
222
223         $post   = intval(get_pconfig(local_user(),'appnet','post'));
224
225         $enable = (($post && x($_REQUEST,'appnet_enable')) ? intval($_REQUEST['appnet_enable']) : 0);
226
227         if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'appnet','post_by_default')))
228                 $enable = 1;
229
230         if(!$enable)
231                 return;
232
233         if(strlen($b['postopts']))
234                 $b['postopts'] .= ',';
235
236         $b['postopts'] .= 'appnet';
237 }
238
239 function appnet_send(&$a,&$b) {
240
241         logger('appnet_send: invoked for post '.$b['id']." ".$b['app']);
242
243         if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
244                 return;
245
246         if(! strstr($b['postopts'],'appnet'))
247                 return;
248
249         if($b['parent'] != $b['id'])
250                 return;
251
252         $token = get_pconfig($b['uid'],'appnet','token');
253
254         if($token) {
255                 require_once 'addon/appnet/AppDotNet.php';
256
257                 $clientId     = get_pconfig(local_user(),'appnet','clientid');
258                 $clientSecret = get_pconfig(local_user(),'appnet','clientsecret');
259
260                 $app = new AppDotNet($clientId, $clientSecret);
261                 $app->setAccessToken($token);
262
263                 $data = array();
264
265                 require_once("include/plaintext.php");
266                 require_once("include/network.php");
267
268                 $post = plaintext($a, $b, 256, false);
269                 logger("appnet_send: converted message ".$b["id"]." result: ".print_r($post, true), LOGGER_DEBUG);
270
271                 if (isset($post["image"])) {
272                         $img_str = fetch_url($post['image'],true, $redirects, 10);
273                         $tempfile = tempnam(get_config("system","temppath"), "cache");
274                         file_put_contents($tempfile, $img_str);
275
276                         try {
277                                 $photoFile = $app->createFile($tempfile, array(type => "com.github.jdolitsky.appdotnetphp.photo"));
278
279                                 $data["annotations"][] = array(
280                                                                 "type" => "net.app.core.oembed",
281                                                                 "value" => array(
282                                                                         "+net.app.core.file" => array(
283                                                                                 "file_id" => $photoFile["id"],
284                                                                                 "file_token" => $photoFile["file_token"],
285                                                                                 "format" => "oembed")
286                                                                         )
287                                                                 );
288                         }
289                         catch (AppDotNetException $e) {
290                                 logger("appnet_send: Error creating file");
291                         }
292
293                         unlink($tempfile);
294                 }
295
296                 // To-Do
297                 // Alle Links verkürzen
298
299                 if (isset($post["url"]) AND !isset($post["title"])) {
300                         $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $post["url"]);
301                         $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
302
303                         if (strlen($display_url) > 26)
304                                 $display_url = substr($display_url, 0, 25)."…";
305
306                         $post["title"] = $display_url;
307                 }
308
309                 if (isset($post["url"]) AND isset($post["title"])) {
310                         $post["title"] = shortenmsg($post["title"], 90);
311                         $post["text"] = shortenmsg($post["text"], 256 - strlen($post["title"]));
312                         $post["text"] .= "\n[".$post["title"]."](".$post["url"].")";
313                 } elseif (isset($post["url"])) {
314                         $post["url"] = short_link($post["url"]);
315                         $post["text"] = shortenmsg($post["text"], 240);
316                         $post["text"] .= " ".$post["url"];
317                 }
318
319                 //print_r($post);
320                 $data["entities"]["parse_links"] = true;
321                 $data["entities"]["parse_markdown_links"] = true;
322
323                 try {
324                         $ret = $app->createPost($post["text"], $data);
325                         logger("appnet_send: send message ".$b["id"]." result: ".print_r($ret, true), LOGGER_DEBUG);
326                 }
327                 catch (AppDotNetException $e) {
328                         logger("appnet_send: Error sending message ".$b["id"]);
329                 }
330         }
331 }