PageRenderTime 57ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/fbpost/fbpost.php

https://github.com/chiefdome/friendica-addons
PHP | 1194 lines | 728 code | 272 blank | 194 comment | 243 complexity | f32a0ff0965cb935a553d243307ed0ba MD5 | raw file
Possible License(s): BSD-3-Clause, AGPL-3.0, GPL-2.0
  1. <?php
  2. /**
  3. * Name: Facebook Post Connector
  4. * Version: 1.3
  5. * Author: Mike Macgirvin <http://macgirvin.com/profile/mike>
  6. * Author: Tobias Hößl <https://github.com/CatoTH/>
  7. *
  8. */
  9. /**
  10. * Installing the Friendica/Facebook connector
  11. *
  12. * Detailed instructions how to use this plugin can be found at
  13. * https://github.com/friendica/friendica/wiki/How-to:-Friendica%E2%80%99s-Facebook-connector
  14. *
  15. * Vidoes and embeds will not be posted if there is no other content. Links
  16. * and images will be converted to a format suitable for the Facebook API and
  17. * long posts truncated - with a link to view the full post.
  18. *
  19. * Facebook contacts will not be able to view private photos, as they are not able to
  20. * authenticate to your site to establish identity. We will address this
  21. * in a future release.
  22. */
  23. define('FACEBOOK_DEFAULT_POLL_INTERVAL', 5); // given in minutes
  24. require_once('include/security.php');
  25. function fbpost_install() {
  26. register_hook('post_local', 'addon/fbpost/fbpost.php', 'fbpost_post_local');
  27. register_hook('notifier_normal', 'addon/fbpost/fbpost.php', 'fbpost_post_hook');
  28. register_hook('jot_networks', 'addon/fbpost/fbpost.php', 'fbpost_jot_nets');
  29. register_hook('connector_settings', 'addon/fbpost/fbpost.php', 'fbpost_plugin_settings');
  30. register_hook('enotify', 'addon/fbpost/fbpost.php', 'fbpost_enotify');
  31. register_hook('queue_predeliver', 'addon/fbpost/fbpost.php', 'fbpost_queue_hook');
  32. register_hook('cron', 'addon/fbpost/fbpost.php', 'fbpost_cron');
  33. }
  34. function fbpost_uninstall() {
  35. unregister_hook('post_local', 'addon/fbpost/fbpost.php', 'fbpost_post_local');
  36. unregister_hook('notifier_normal', 'addon/fbpost/fbpost.php', 'fbpost_post_hook');
  37. unregister_hook('jot_networks', 'addon/fbpost/fbpost.php', 'fbpost_jot_nets');
  38. unregister_hook('connector_settings', 'addon/fbpost/fbpost.php', 'fbpost_plugin_settings');
  39. unregister_hook('enotify', 'addon/fbpost/fbpost.php', 'fbpost_enotify');
  40. unregister_hook('queue_predeliver', 'addon/fbpost/fbpost.php', 'fbpost_queue_hook');
  41. unregister_hook('cron', 'addon/fbpost/fbpost.php', 'fbpost_cron');
  42. }
  43. /* declare the fbpost_module function so that /fbpost url requests will land here */
  44. function fbpost_module() {}
  45. // If a->argv[1] is a nickname, this is a callback from Facebook oauth requests.
  46. // If $_REQUEST["realtime_cb"] is set, this is a callback from the Real-Time Updates API
  47. /**
  48. * @param App $a
  49. */
  50. function fbpost_init(&$a) {
  51. if($a->argc != 2)
  52. return;
  53. $nick = $a->argv[1];
  54. if(strlen($nick))
  55. $r = q("SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1",
  56. dbesc($nick)
  57. );
  58. if(!(isset($r) && count($r)))
  59. return;
  60. $uid = $r[0]['uid'];
  61. $auth_code = (x($_GET, 'code') ? $_GET['code'] : '');
  62. $error = (x($_GET, 'error_description') ? $_GET['error_description'] : '');
  63. if($error)
  64. logger('fbpost_init: Error: ' . $error);
  65. if($auth_code && $uid) {
  66. $appid = get_config('facebook','appid');
  67. $appsecret = get_config('facebook', 'appsecret');
  68. $x = fetch_url('https://graph.facebook.com/oauth/access_token?client_id='
  69. . $appid . '&client_secret=' . $appsecret . '&redirect_uri='
  70. . urlencode($a->get_baseurl() . '/fbpost/' . $nick)
  71. . '&code=' . $auth_code);
  72. logger('fbpost_init: returned access token: ' . $x, LOGGER_DATA);
  73. if(strpos($x,'access_token=') !== false) {
  74. $token = str_replace('access_token=', '', $x);
  75. if(strpos($token,'&') !== false)
  76. $token = substr($token,0,strpos($token,'&'));
  77. set_pconfig($uid,'facebook','access_token',$token);
  78. set_pconfig($uid,'facebook','post','1');
  79. fbpost_get_self($uid);
  80. }
  81. }
  82. }
  83. /**
  84. * @param int $uid
  85. */
  86. function fbpost_get_self($uid) {
  87. $access_token = get_pconfig($uid,'facebook','access_token');
  88. if(! $access_token)
  89. return;
  90. $s = fetch_url('https://graph.facebook.com/me/?access_token=' . $access_token);
  91. if($s) {
  92. $j = json_decode($s);
  93. set_pconfig($uid,'facebook','self_id',(string) $j->id);
  94. }
  95. }
  96. // This is the POST method to the facebook settings page
  97. // Content is posted to Facebook in the function facebook_post_hook()
  98. /**
  99. * @param App $a
  100. */
  101. function fbpost_post(&$a) {
  102. $uid = local_user();
  103. if($uid){
  104. $fb_limited = get_config('facebook','crestrict');
  105. $value = ((x($_POST,'post_by_default')) ? intval($_POST['post_by_default']) : 0);
  106. set_pconfig($uid,'facebook','post_by_default', $value);
  107. $value = ((x($_POST,'mirror_posts')) ? intval($_POST['mirror_posts']) : 0);
  108. set_pconfig($uid,'facebook','mirror_posts', $value);
  109. $value = ((x($_POST,'suppress_view_on_friendica')) ? intval($_POST['suppress_view_on_friendica']) : 0);
  110. set_pconfig($uid,'facebook','suppress_view_on_friendica', $value);
  111. $value = ((x($_POST,'post_to_page')) ? $_POST['post_to_page'] : "0-0");
  112. $values = explode("-", $value);
  113. set_pconfig($uid,'facebook','post_to_page', $values[0]);
  114. set_pconfig($uid,'facebook','page_access_token', $values[1]);
  115. info( t('Settings updated.') . EOL);
  116. }
  117. return;
  118. }
  119. // Facebook settings form
  120. /**
  121. * @param App $a
  122. * @return string
  123. */
  124. function fbpost_content(&$a) {
  125. if(! local_user()) {
  126. notice( t('Permission denied.') . EOL);
  127. return '';
  128. }
  129. if(! service_class_allows(local_user(),'facebook_connect')) {
  130. notice( t('Permission denied.') . EOL);
  131. return upgrade_bool_message();
  132. }
  133. if($a->argc > 1 && $a->argv[1] === 'remove') {
  134. del_pconfig(local_user(),'facebook','post');
  135. info( t('Facebook Post disabled') . EOL);
  136. }
  137. $o = '';
  138. $fb_installed = false;
  139. if (get_pconfig(local_user(),'facebook','post')) {
  140. $access_token = get_pconfig(local_user(),'facebook','access_token');
  141. if ($access_token) {
  142. $s = fetch_url('https://graph.facebook.com/me/feed?access_token=' . $access_token);
  143. if($s) {
  144. $j = json_decode($s);
  145. if (isset($j->data)) $fb_installed = true;
  146. }
  147. }
  148. }
  149. $appid = get_config('facebook','appid');
  150. if(! $appid) {
  151. notice( t('Facebook API key is missing.') . EOL);
  152. return '';
  153. }
  154. $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="'
  155. . $a->get_baseurl() . '/addon/fbpost/fbpost.css' . '" media="all" />' . "\r\n";
  156. $o .= '<h3>' . t('Facebook Post') . '</h3>';
  157. if(! $fb_installed) {
  158. $o .= '<div id="fbpost-enable-wrapper">';
  159. $o .= '<a href="https://www.facebook.com/dialog/oauth?client_id=' . $appid . '&redirect_uri='
  160. . $a->get_baseurl() . '/fbpost/' . $a->user['nickname'] . '&scope=read_stream,publish_stream,manage_pages,photo_upload,user_groups,offline_access">' . t('Install Facebook Post connector for this account.') . '</a>';
  161. $o .= '</div>';
  162. }
  163. if($fb_installed) {
  164. $o .= '<div id="fbpost-disable-wrapper">';
  165. $o .= '<a href="' . $a->get_baseurl() . '/fbpost/remove' . '">' . t('Remove Facebook Post connector') . '</a></div>';
  166. $o .= '<div id="fbpost-enable-wrapper">';
  167. $o .= '<a href="https://www.facebook.com/dialog/oauth?client_id=' . $appid . '&redirect_uri='
  168. . $a->get_baseurl() . '/fbpost/' . $a->user['nickname'] . '&scope=read_stream,publish_stream,manage_pages,photo_upload,user_groups,offline_access">' . t('Re-authenticate [This is necessary whenever your Facebook password is changed.]') . '</a>';
  169. $o .= '</div>';
  170. $o .= '<div id="fbpost-post-default-form">';
  171. $o .= '<form action="fbpost" method="post" >';
  172. $post_by_default = get_pconfig(local_user(),'facebook','post_by_default');
  173. $checked = (($post_by_default) ? ' checked="checked" ' : '');
  174. $o .= '<input type="checkbox" name="post_by_default" value="1"' . $checked . '/>' . ' ' . t('Post to Facebook by default') . EOL;
  175. $suppress_view_on_friendica = get_pconfig(local_user(),'facebook','suppress_view_on_friendica');
  176. $checked = (($suppress_view_on_friendica) ? ' checked="checked" ' : '');
  177. $o .= '<input type="checkbox" name="suppress_view_on_friendica" value="1"' . $checked . '/>' . ' ' . t('Suppress "View on friendica"') . EOL;
  178. $mirror_posts = get_pconfig(local_user(),'facebook','mirror_posts');
  179. $checked = (($mirror_posts) ? ' checked="checked" ' : '');
  180. $o .= '<input type="checkbox" name="mirror_posts" value="1"' . $checked . '/>' . ' ' . t('Mirror wall posts from facebook to friendica.') . EOL;
  181. // List all pages
  182. $post_to_page = get_pconfig(local_user(),'facebook','post_to_page');
  183. $page_access_token = get_pconfig(local_user(),'facebook','page_access_token');
  184. $fb_token = get_pconfig($a->user['uid'],'facebook','access_token');
  185. $url = 'https://graph.facebook.com/me/accounts';
  186. $x = fetch_url($url."?access_token=".$fb_token);
  187. $accounts = json_decode($x);
  188. $o .= t("Post to page/group:")."<select name='post_to_page'>";
  189. if (intval($post_to_page) == 0)
  190. $o .= "<option value='0-0' selected>".t('None')."</option>";
  191. else
  192. $o .= "<option value='0-0'>".t('None')."</option>";
  193. foreach($accounts->data as $account) {
  194. if (is_array($account->perms))
  195. if ($post_to_page == $account->id)
  196. $o .= "<option value='".$account->id."-".$account->access_token."' selected>".$account->name."</option>";
  197. else
  198. $o .= "<option value='".$account->id."-".$account->access_token."'>".$account->name."</option>";
  199. }
  200. $url = 'https://graph.facebook.com/me/groups';
  201. $x = fetch_url($url."?access_token=".$fb_token);
  202. $groups = json_decode($x);
  203. foreach($groups->data as $group) {
  204. if ($post_to_page == $group->id)
  205. $o .= "<option value='".$group->id."-0' selected>".$group->name."</option>";
  206. else
  207. $o .= "<option value='".$group->id."-0'>".$group->name."</option>";
  208. }
  209. $o .= "</select>";
  210. $o .= '<p><input type="submit" name="submit" value="' . t('Submit') . '" /></form></div>';
  211. }
  212. return $o;
  213. }
  214. /**
  215. * @param App $a
  216. * @param null|object $b
  217. */
  218. function fbpost_plugin_settings(&$a,&$b) {
  219. $b .= '<div class="settings-block">';
  220. $b .= '<h3>' . t('Facebook') . '</h3>';
  221. $b .= '<a href="fbpost">' . t('Facebook Post Settings') . '</a><br />';
  222. $b .= '</div>';
  223. }
  224. /**
  225. * @param App $a
  226. * @param null|object $o
  227. */
  228. function fbpost_plugin_admin(&$a, &$o){
  229. $o = '<input type="hidden" name="form_security_token" value="' . get_form_security_token("fbsave") . '">';
  230. $o .= '<h4>' . t('Facebook API Key') . '</h4>';
  231. $appid = get_config('facebook', 'appid' );
  232. $appsecret = get_config('facebook', 'appsecret' );
  233. $ret1 = q("SELECT `v` FROM `config` WHERE `cat` = 'facebook' AND `k` = 'appid' LIMIT 1");
  234. $ret2 = q("SELECT `v` FROM `config` WHERE `cat` = 'facebook' AND `k` = 'appsecret' LIMIT 1");
  235. if ((count($ret1) > 0 && $ret1[0]['v'] != $appid) || (count($ret2) > 0 && $ret2[0]['v'] != $appsecret)) $o .= t('Error: it appears that you have specified the App-ID and -Secret in your .htconfig.php file. As long as they are specified there, they cannot be set using this form.<br><br>');
  236. $o .= '<label for="fb_appid">' . t('App-ID / API-Key') . '</label><input id="fb_appid" name="appid" type="text" value="' . escape_tags($appid ? $appid : "") . '"><br style="clear: both;">';
  237. $o .= '<label for="fb_appsecret">' . t('Application secret') . '</label><input id="fb_appsecret" name="appsecret" type="text" value="' . escape_tags($appsecret ? $appsecret : "") . '"><br style="clear: both;">';
  238. $o .= '<input type="submit" name="fb_save_keys" value="' . t('Save') . '">';
  239. }
  240. /**
  241. * @param App $a
  242. */
  243. function fbpost_plugin_admin_post(&$a){
  244. check_form_security_token_redirectOnErr('/admin/plugins/fbpost', 'fbsave');
  245. if (x($_REQUEST,'fb_save_keys')) {
  246. set_config('facebook', 'appid', $_REQUEST['appid']);
  247. set_config('facebook', 'appsecret', $_REQUEST['appsecret']);
  248. info(t('The new values have been saved.'));
  249. }
  250. }
  251. /**
  252. * @param App $a
  253. * @param object $b
  254. * @return mixed
  255. */
  256. function fbpost_jot_nets(&$a,&$b) {
  257. if(! local_user())
  258. return;
  259. $fb_post = get_pconfig(local_user(),'facebook','post');
  260. if(intval($fb_post) == 1) {
  261. $fb_defpost = get_pconfig(local_user(),'facebook','post_by_default');
  262. $selected = ((intval($fb_defpost) == 1) ? ' checked="checked" ' : '');
  263. $b .= '<div class="profile-jot-net"><input type="checkbox" name="facebook_enable"' . $selected . ' value="1" /> '
  264. . t('Post to Facebook') . '</div>';
  265. }
  266. }
  267. function fbpost_ShareAttributes($match) {
  268. $attributes = $match[1];
  269. $author = "";
  270. preg_match("/author='(.*?)'/ism", $attributes, $matches);
  271. if ($matches[1] != "")
  272. $author = $matches[1];
  273. preg_match('/author="(.*?)"/ism', $attributes, $matches);
  274. if ($matches[1] != "")
  275. $author = $matches[1];
  276. $headline = '<div class="shared_header">';
  277. $headline .= sprintf(t('%s:'), $author);
  278. $headline .= "</div>";
  279. //$text = "<br />".$headline."</strong><blockquote>".$match[2]."</blockquote>";
  280. $text = "\n\t".$match[2].":\t";
  281. return($text);
  282. }
  283. /**
  284. * @param App $a
  285. * @param object $b
  286. * @return mixed
  287. */
  288. function fbpost_post_hook(&$a,&$b) {
  289. if($b['deleted'] || ($b['created'] !== $b['edited']))
  290. return;
  291. // Don't transmit answers (have to be cleaned up in the following code)
  292. if($b['parent'] != $b['id'])
  293. return;
  294. // if post comes from facebook don't send it back
  295. if($b['app'] == "Facebook")
  296. return;
  297. /**
  298. * Post to Facebook stream
  299. */
  300. require_once('include/group.php');
  301. require_once('include/html2plain.php');
  302. logger('Facebook post');
  303. $reply = false;
  304. $likes = false;
  305. $deny_arr = array();
  306. $allow_arr = array();
  307. $toplevel = (($b['id'] == $b['parent']) ? true : false);
  308. $linking = ((get_pconfig($b['uid'],'facebook','no_linking')) ? 0 : 1);
  309. if((! $toplevel) && ($linking)) {
  310. $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
  311. intval($b['parent']),
  312. intval($b['uid'])
  313. );
  314. if(count($r) && substr($r[0]['uri'],0,4) === 'fb::')
  315. $reply = substr($r[0]['uri'],4);
  316. elseif(count($r) && substr($r[0]['extid'],0,4) === 'fb::')
  317. $reply = substr($r[0]['extid'],4);
  318. else
  319. return;
  320. $u = q("SELECT * FROM user where uid = %d limit 1",
  321. intval($b['uid'])
  322. );
  323. if(! count($u))
  324. return;
  325. // only accept comments from the item owner. Other contacts are unknown to FB.
  326. if(! link_compare($b['author-link'], $a->get_baseurl() . '/profile/' . $u[0]['nickname']))
  327. return;
  328. logger('facebook reply id=' . $reply);
  329. }
  330. if(strstr($b['postopts'],'facebook') || ($b['private']) || ($reply)) {
  331. if($b['private'] && $reply === false) {
  332. $allow_people = expand_acl($b['allow_cid']);
  333. $allow_groups = expand_groups(expand_acl($b['allow_gid']));
  334. $deny_people = expand_acl($b['deny_cid']);
  335. $deny_groups = expand_groups(expand_acl($b['deny_gid']));
  336. $recipients = array_unique(array_merge($allow_people,$allow_groups));
  337. $deny = array_unique(array_merge($deny_people,$deny_groups));
  338. $allow_str = dbesc(implode(', ',$recipients));
  339. if($allow_str) {
  340. $r = q("SELECT `notify` FROM `contact` WHERE `id` IN ( $allow_str ) AND `network` = 'face'");
  341. if(count($r))
  342. foreach($r as $rr)
  343. $allow_arr[] = $rr['notify'];
  344. }
  345. $deny_str = dbesc(implode(', ',$deny));
  346. if($deny_str) {
  347. $r = q("SELECT `notify` FROM `contact` WHERE `id` IN ( $deny_str ) AND `network` = 'face'");
  348. if(count($r))
  349. foreach($r as $rr)
  350. $deny_arr[] = $rr['notify'];
  351. }
  352. if(count($deny_arr) && (! count($allow_arr))) {
  353. // One or more FB folks were denied access but nobody on FB was specifically allowed access.
  354. // This might cause the post to be open to public on Facebook, but only to selected members
  355. // on another network. Since this could potentially leak a post to somebody who was denied,
  356. // we will skip posting it to Facebook with a slightly vague but relevant message that will
  357. // hopefully lead somebody to this code comment for a better explanation of what went wrong.
  358. notice( t('Post to Facebook cancelled because of multi-network access permission conflict.') . EOL);
  359. return;
  360. }
  361. // if it's a private message but no Facebook members are allowed or denied, skip Facebook post
  362. if((! count($allow_arr)) && (! count($deny_arr)))
  363. return;
  364. }
  365. if($b['verb'] == ACTIVITY_LIKE)
  366. $likes = true;
  367. $appid = get_config('facebook', 'appid' );
  368. $secret = get_config('facebook', 'appsecret' );
  369. if($appid && $secret) {
  370. logger('facebook: have appid+secret');
  371. $fb_token = get_pconfig($b['uid'],'facebook','access_token');
  372. // post to facebook if it's a public post and we've ticked the 'post to Facebook' box,
  373. // or it's a private message with facebook participants
  374. // or it's a reply or likes action to an existing facebook post
  375. if($fb_token && ($toplevel || $b['private'] || $reply)) {
  376. logger('facebook: able to post');
  377. require_once('library/facebook.php');
  378. require_once('include/bbcode.php');
  379. $msg = $b['body'];
  380. logger('Facebook post: original msg=' . $msg, LOGGER_DATA);
  381. // make links readable before we strip the code
  382. // unless it's a dislike - just send the text as a comment
  383. // if($b['verb'] == ACTIVITY_DISLIKE)
  384. // $msg = trim(strip_tags(bbcode($msg)));
  385. // Old code
  386. /*$search_str = $a->get_baseurl() . '/search';
  387. if(preg_match("/\[url=(.*?)\](.*?)\[\/url\]/is",$msg,$matches)) {
  388. // don't use hashtags for message link
  389. if(strpos($matches[2],$search_str) === false) {
  390. $link = $matches[1];
  391. if(substr($matches[2],0,5) != '[img]')
  392. $linkname = $matches[2];
  393. }
  394. }
  395. // strip tag links to avoid link clutter, this really should be
  396. // configurable because we're losing information
  397. $msg = preg_replace("/\#\[url=(.*?)\](.*?)\[\/url\]/is",'#$2',$msg);
  398. // provide the link separately for normal links
  399. $msg = preg_replace("/\[url=(.*?)\](.*?)\[\/url\]/is",'$2 $1',$msg);
  400. if(preg_match("/\[img\](.*?)\[\/img\]/is",$msg,$matches))
  401. $image = $matches[1];
  402. $msg = preg_replace("/\[img\](.*?)\[\/img\]/is", t('Image: ') . '$1', $msg);
  403. if((strpos($link,z_root()) !== false) && (! $image))
  404. $image = $a->get_baseurl() . '/images/friendica-64.jpg';
  405. $msg = trim(strip_tags(bbcode($msg)));*/
  406. // New code
  407. // Looking for the first image
  408. $image = '';
  409. if(preg_match("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/is",$b['body'],$matches))
  410. $image = $matches[3];
  411. if ($image == '')
  412. if(preg_match("/\[img\](.*?)\[\/img\]/is",$b['body'],$matches))
  413. $image = $matches[1];
  414. // When saved into the database the content is sent through htmlspecialchars
  415. // That means that we have to decode all image-urls
  416. $image = htmlspecialchars_decode($image);
  417. // Checking for a bookmark element
  418. $body = $b['body'];
  419. if (strpos($body, "[bookmark") !== false) {
  420. // splitting the text in two parts:
  421. // before and after the bookmark
  422. $pos = strpos($body, "[bookmark");
  423. $body1 = substr($body, 0, $pos);
  424. $body2 = substr($body, $pos);
  425. // Removing the bookmark and all quotes after the bookmark
  426. // they are mostly only the content after the bookmark.
  427. $body2 = preg_replace("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",'',$body2);
  428. $body2 = preg_replace("/\[quote\=([^\]]*)\](.*?)\[\/quote\]/ism",'',$body2);
  429. $body2 = preg_replace("/\[quote\](.*?)\[\/quote\]/ism",'',$body2);
  430. $body = $body1.$body2;
  431. }
  432. // Convert recycle signs
  433. $body = str_replace("\t", " ", $body);
  434. // recycle 1
  435. $recycle = html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8');
  436. $body = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', "\n\t$2:\t", $body);
  437. // recycle 2 (Test)
  438. $recycle = html_entity_decode("&#x25CC; ", ENT_QUOTES, 'UTF-8');
  439. $body = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', "\n\t$2:\t", $body);
  440. // share element
  441. $body = preg_replace_callback("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]/ism","fbpost_ShareAttributes", $body);
  442. $bodyparts = explode("\t", $body);
  443. // Doesn't help with multiple repeats - the problem has to be solved later
  444. if (sizeof($bodyparts) == 3) {
  445. $html = bbcode($bodyparts[2], false, false);
  446. $test = trim(html2plain($html, 0, true));
  447. if (trim($bodyparts[0]) == "")
  448. $body = trim($bodyparts[2]);
  449. else if (trim($test) == "")
  450. $body = trim($bodyparts[0]);
  451. else
  452. $body = trim($bodyparts[0])."\n\n".trim($bodyparts[1])."[quote]".trim($bodyparts[2])."[/quote]";
  453. } else
  454. $body = str_replace("\t", "", $body);
  455. // At first convert the text to html
  456. $html = bbcode($body, false, false);
  457. // Then convert it to plain text
  458. $msg = trim($b['title']." \n\n".html2plain($html, 0, true));
  459. // Removing useless spaces
  460. if (substr($msg, -2) == "«")
  461. $msg = trim(substr($msg, 0, -2))."«";
  462. $msg = html_entity_decode($msg,ENT_QUOTES,'UTF-8');
  463. // Removing multiple newlines
  464. while (strpos($msg, "\n\n\n") !== false)
  465. $msg = str_replace("\n\n\n", "\n\n", $msg);
  466. // add any attachments as text urls
  467. $arr = explode(',',$b['attach']);
  468. if(count($arr)) {
  469. $msg .= "\n";
  470. foreach($arr as $r) {
  471. $matches = false;
  472. $cnt = preg_match('|\[attach\]href=\"(.*?)\" size=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches);
  473. if($cnt) {
  474. $msg .= "\n".$matches[1];
  475. }
  476. }
  477. }
  478. $link = '';
  479. $linkname = '';
  480. // look for bookmark-bbcode and handle it with priority
  481. if(preg_match("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/is",$b['body'],$matches)) {
  482. $link = $matches[1];
  483. $linkname = $matches[2];
  484. }
  485. // If there is no bookmark element then take the first link
  486. if ($link == '') {
  487. $links = collecturls($html);
  488. if (sizeof($links) > 0) {
  489. reset($links);
  490. $link = current($links);
  491. }
  492. }
  493. // Remove trailing and leading spaces
  494. $msg = trim($msg);
  495. // Fallback - if message is empty
  496. if(!strlen($msg))
  497. $msg = $linkname;
  498. if(!strlen($msg))
  499. $msg = $link;
  500. if(!strlen($msg))
  501. $msg = $image;
  502. // If there is nothing to post then exit
  503. if(!strlen($msg))
  504. return;
  505. logger('Facebook post: msg=' . $msg, LOGGER_DATA);
  506. $video = "";
  507. if($likes) {
  508. $postvars = array('access_token' => $fb_token);
  509. } else {
  510. // message, picture, link, name, caption, description, source, place, tags
  511. if(trim($link) != "")
  512. if (@exif_imagetype($link) != 0) {
  513. $image = $link;
  514. $link = "";
  515. }
  516. $postvars = array(
  517. 'access_token' => $fb_token,
  518. 'message' => $msg
  519. );
  520. if(trim($image) != "")
  521. $postvars['picture'] = $image;
  522. if(trim($link) != "") {
  523. $postvars['link'] = $link;
  524. if ((stristr($link,'youtube')) || (stristr($link,'youtu.be')) || (stristr($link,'vimeo'))) {
  525. $video = $link;
  526. }
  527. }
  528. if(trim($linkname) != "")
  529. $postvars['name'] = $linkname;
  530. }
  531. if(($b['private']) && ($toplevel)) {
  532. $postvars['privacy'] = '{"value": "CUSTOM", "friends": "SOME_FRIENDS"';
  533. if(count($allow_arr))
  534. $postvars['privacy'] .= ',"allow": "' . implode(',',$allow_arr) . '"';
  535. if(count($deny_arr))
  536. $postvars['privacy'] .= ',"deny": "' . implode(',',$deny_arr) . '"';
  537. $postvars['privacy'] .= '}';
  538. }
  539. $post_to_page = get_pconfig($b['uid'],'facebook','post_to_page');
  540. $page_access_token = get_pconfig($b['uid'],'facebook','page_access_token');
  541. if ((intval($post_to_page) != 0) and ($page_access_token != ""))
  542. $target = $post_to_page;
  543. else
  544. $target = "me";
  545. if($reply) {
  546. $url = 'https://graph.facebook.com/' . $reply . '/' . (($likes) ? 'likes' : 'comments');
  547. } else if (($video != "") or (($image == "") and ($link != ""))) {
  548. // If it is a link to a video or a link without a preview picture then post it as a link
  549. if ($video != "")
  550. $link = $video;
  551. $postvars = array(
  552. 'access_token' => $fb_token,
  553. 'link' => $link,
  554. );
  555. if ($msg != $video)
  556. $postvars['message'] = $msg;
  557. $url = 'https://graph.facebook.com/'.$target.'/links';
  558. } else if (($link == "") and ($image != "")) {
  559. // If it is only an image without a page link then post this image as a photo
  560. $postvars = array(
  561. 'access_token' => $fb_token,
  562. 'url' => $image,
  563. );
  564. if ($msg != $image)
  565. $postvars['message'] = $msg;
  566. $url = 'https://graph.facebook.com/'.$target.'/photos';
  567. } else if (($link != "") or ($image != "") or ($b['title'] == '') or (strlen($msg) < 500)) {
  568. $url = 'https://graph.facebook.com/'.$target.'/feed';
  569. if (!get_pconfig($b['uid'],'facebook','suppress_view_on_friendica') and $b['plink'])
  570. $postvars['actions'] = '{"name": "' . t('View on Friendica') . '", "link": "' . $b['plink'] . '"}';
  571. } else {
  572. // if its only a message and a subject and the message is larger than 500 characters then post it as note
  573. $postvars = array(
  574. 'access_token' => $fb_token,
  575. 'message' => bbcode($b['body'], false, false),
  576. 'subject' => $b['title'],
  577. );
  578. $url = 'https://graph.facebook.com/'.$target.'/notes';
  579. }
  580. // Post to page?
  581. if (!$reply and ($target != "me") and $page_access_token)
  582. $postvars['access_token'] = $page_access_token;
  583. logger('facebook: post to ' . $url);
  584. logger('facebook: postvars: ' . print_r($postvars,true));
  585. // "test_mode" prevents anything from actually being posted.
  586. // Otherwise, let's do it.
  587. if(! get_config('facebook','test_mode')) {
  588. $x = post_url($url, $postvars);
  589. logger('Facebook post returns: ' . $x, LOGGER_DEBUG);
  590. $retj = json_decode($x);
  591. if($retj->id) {
  592. q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d LIMIT 1",
  593. dbesc('fb::' . $retj->id),
  594. intval($b['id'])
  595. );
  596. }
  597. else {
  598. if(! $likes) {
  599. $s = serialize(array('url' => $url, 'item' => $b['id'], 'post' => $postvars));
  600. require_once('include/queue_fn.php');
  601. add_to_queue($a->contact,NETWORK_FACEBOOK,$s);
  602. notice( t('Facebook post failed. Queued for retry.') . EOL);
  603. }
  604. if (isset($retj->error) && $retj->error->type == "OAuthException" && $retj->error->code == 190) {
  605. logger('Facebook session has expired due to changed password.', LOGGER_DEBUG);
  606. $last_notification = get_pconfig($b['uid'], 'facebook', 'session_expired_mailsent');
  607. if (!$last_notification || $last_notification < (time() - FACEBOOK_SESSION_ERR_NOTIFICATION_INTERVAL)) {
  608. require_once('include/enotify.php');
  609. $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($b['uid']) );
  610. notification(array(
  611. 'uid' => $b['uid'],
  612. 'type' => NOTIFY_SYSTEM,
  613. 'system_type' => 'facebook_connection_invalid',
  614. 'language' => $r[0]['language'],
  615. 'to_name' => $r[0]['username'],
  616. 'to_email' => $r[0]['email'],
  617. 'source_name' => t('Administrator'),
  618. 'source_link' => $a->config["system"]["url"],
  619. 'source_photo' => $a->config["system"]["url"] . '/images/person-80.jpg',
  620. ));
  621. set_pconfig($b['uid'], 'facebook', 'session_expired_mailsent', time());
  622. } else logger('Facebook: No notification, as the last one was sent on ' . $last_notification, LOGGER_DEBUG);
  623. }
  624. }
  625. }
  626. }
  627. }
  628. }
  629. }
  630. /**
  631. * @param App $app
  632. * @param object $data
  633. */
  634. function fbpost_enotify(&$app, &$data) {
  635. if (x($data, 'params') && $data['params']['type'] == NOTIFY_SYSTEM && x($data['params'], 'system_type') && $data['params']['system_type'] == 'facebook_connection_invalid') {
  636. $data['itemlink'] = '/facebook';
  637. $data['epreamble'] = $data['preamble'] = t('Your Facebook connection became invalid. Please Re-authenticate.');
  638. $data['subject'] = t('Facebook connection became invalid');
  639. $data['body'] = sprintf( t("Hi %1\$s,\n\nThe connection between your accounts on %2\$s and Facebook became invalid. This usually happens after you change your Facebook-password. To enable the connection again, you have to %3\$sre-authenticate the Facebook-connector%4\$s."), $data['params']['to_name'], "[url=" . $app->config["system"]["url"] . "]" . $app->config["sitename"] . "[/url]", "[url=" . $app->config["system"]["url"] . "/facebook]", "[/url]");
  640. }
  641. }
  642. /**
  643. * @param App $a
  644. * @param object $b
  645. */
  646. function fbpost_post_local(&$a,&$b) {
  647. // Figure out if Facebook posting is enabled for this post and file it in 'postopts'
  648. // where we will discover it during background delivery.
  649. // This can only be triggered by a local user posting to their own wall.
  650. if((local_user()) && (local_user() == $b['uid'])) {
  651. $fb_post = intval(get_pconfig(local_user(),'facebook','post'));
  652. $fb_enable = (($fb_post && x($_REQUEST,'facebook_enable')) ? intval($_REQUEST['facebook_enable']) : 0);
  653. // if API is used, default to the chosen settings
  654. // but allow a specific override
  655. if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'facebook','post_by_default'))) {
  656. if(! x($_REQUEST,'facebook_enable'))
  657. $fb_enable = 1;
  658. }
  659. if(! $fb_enable)
  660. return;
  661. if(strlen($b['postopts']))
  662. $b['postopts'] .= ',';
  663. $b['postopts'] .= 'facebook';
  664. }
  665. }
  666. /**
  667. * @param App $a
  668. * @param object $b
  669. */
  670. function fbpost_queue_hook(&$a,&$b) {
  671. $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
  672. dbesc(NETWORK_FACEBOOK)
  673. );
  674. if(! count($qi))
  675. return;
  676. require_once('include/queue_fn.php');
  677. foreach($qi as $x) {
  678. if($x['network'] !== NETWORK_FACEBOOK)
  679. continue;
  680. logger('facebook_queue: run');
  681. $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` on `contact`.`uid` = `user`.`uid`
  682. WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
  683. intval($x['cid'])
  684. );
  685. if(! count($r))
  686. continue;
  687. $user = $r[0];
  688. $appid = get_config('facebook', 'appid' );
  689. $secret = get_config('facebook', 'appsecret' );
  690. if($appid && $secret) {
  691. $fb_post = intval(get_pconfig($user['uid'],'facebook','post'));
  692. $fb_token = get_pconfig($user['uid'],'facebook','access_token');
  693. if($fb_post && $fb_token) {
  694. logger('facebook_queue: able to post');
  695. require_once('library/facebook.php');
  696. $z = unserialize($x['content']);
  697. $item = $z['item'];
  698. $j = post_url($z['url'],$z['post']);
  699. $retj = json_decode($j);
  700. if($retj->id) {
  701. q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d LIMIT 1",
  702. dbesc('fb::' . $retj->id),
  703. intval($item)
  704. );
  705. logger('facebook_queue: success: ' . $j);
  706. remove_queue_item($x['id']);
  707. }
  708. else {
  709. logger('facebook_queue: failed: ' . $j);
  710. update_queue_time($x['id']);
  711. }
  712. }
  713. }
  714. }
  715. }
  716. /**
  717. * @return bool|string
  718. */
  719. function fbpost_get_app_access_token() {
  720. $acc_token = get_config('facebook','app_access_token');
  721. if ($acc_token !== false) return $acc_token;
  722. $appid = get_config('facebook','appid');
  723. $appsecret = get_config('facebook', 'appsecret');
  724. if ($appid === false || $appsecret === false) {
  725. logger('fb_get_app_access_token: appid and/or appsecret not set', LOGGER_DEBUG);
  726. return false;
  727. }
  728. logger('https://graph.facebook.com/oauth/access_token?client_id=' . $appid . '&client_secret=' . $appsecret . '&grant_type=client_credentials', LOGGER_DATA);
  729. $x = fetch_url('https://graph.facebook.com/oauth/access_token?client_id=' . $appid . '&client_secret=' . $appsecret . '&grant_type=client_credentials');
  730. if(strpos($x,'access_token=') !== false) {
  731. logger('fb_get_app_access_token: returned access token: ' . $x, LOGGER_DATA);
  732. $token = str_replace('access_token=', '', $x);
  733. if(strpos($token,'&') !== false)
  734. $token = substr($token,0,strpos($token,'&'));
  735. if ($token == "") {
  736. logger('fb_get_app_access_token: empty token: ' . $x, LOGGER_DEBUG);
  737. return false;
  738. }
  739. set_config('facebook','app_access_token',$token);
  740. return $token;
  741. } else {
  742. logger('fb_get_app_access_token: response did not contain an access_token: ' . $x, LOGGER_DATA);
  743. return false;
  744. }
  745. }
  746. function fbpost_cron($a,$b) {
  747. $last = get_config('facebook','last_poll');
  748. $poll_interval = intval(get_config('facebook','poll_interval'));
  749. if(! $poll_interval)
  750. $poll_interval = FACEBOOK_DEFAULT_POLL_INTERVAL;
  751. if($last) {
  752. $next = $last + ($poll_interval * 60);
  753. if($next > time()) {
  754. logger('facebook: poll intervall not reached');
  755. return;
  756. }
  757. }
  758. logger('facebook: cron_start');
  759. $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'facebook' AND `k` = 'mirror_posts' AND `v` = '1' ORDER BY RAND() ");
  760. if(count($r)) {
  761. foreach($r as $rr) {
  762. logger('facebook: fetching for user '.$rr['uid']);
  763. fbpost_fetchwall($a, $rr['uid']);
  764. }
  765. }
  766. logger('facebook: cron_end');
  767. set_config('facebook','last_poll', time());
  768. }
  769. function fbpost_fetchwall($a, $uid) {
  770. $access_token = get_pconfig($uid,'facebook','access_token');
  771. $post_to_page = get_pconfig($uid,'facebook','post_to_page');
  772. $lastcreated = get_pconfig($uid,'facebook','last_created');
  773. if ((int)$post_to_page == 0)
  774. $post_to_page = "me";
  775. $url = "https://graph.facebook.com/".$post_to_page."/feed?access_token=".$access_token;
  776. $first_time = ($lastcreated == "");
  777. if ($lastcreated != "")
  778. $url .= "&since=".urlencode($lastcreated);
  779. $feed = fetch_url($url);
  780. $data = json_decode($feed);
  781. $items = array_reverse($data->data);
  782. foreach ($items as $item) {
  783. if ($item->created_time > $lastcreated)
  784. $lastcreated = $item->created_time;
  785. if ($first_time)
  786. continue;
  787. if ($item->application->id == get_config('facebook','appid'))
  788. continue;
  789. if(isset($item->privacy) && ($item->privacy->value !== 'EVERYONE') && ($item->privacy->value !== ''))
  790. continue;
  791. $_SESSION["authenticated"] = true;
  792. $_SESSION["uid"] = $uid;
  793. $_REQUEST["type"] = "wall";
  794. $_REQUEST["api_source"] = true;
  795. $_REQUEST["profile_uid"] = $uid;
  796. $_REQUEST["source"] = "Facebook";
  797. $_REQUEST["body"] = (isset($item->message) ? escape_tags($item->message) : '');
  798. if(isset($item->name) and isset($item->link))
  799. $_REQUEST["body"] .= "\n\n[bookmark=".$item->link."]".$item->name."[/bookmark]";
  800. elseif (isset($item->name))
  801. $_REQUEST["body"] .= "\n\n[b]" . $item->name."[/b]";
  802. /*if(isset($item->caption)) {
  803. if(!isset($item->name) and isset($item->link))
  804. $_REQUEST["body"] .= "\n\n[bookmark=".$item->link."]".$item->caption."[/bookmark]";
  805. //else
  806. // $_REQUEST["body"] .= "[i]" . $item->caption."[/i]\n";
  807. }
  808. if(!isset($item->caption) and !isset($item->name)) {
  809. if (isset($item->link))
  810. $_REQUEST["body"] .= "\n[url]".$item->link."[/url]\n";
  811. else
  812. $_REQUEST["body"] .= "\n";
  813. }*/
  814. $quote = "";
  815. if(isset($item->description) and ($item->type != "photo"))
  816. $quote = $item->description;
  817. if(isset($item->caption) and ($item->type == "photo"))
  818. $quote = $item->caption;
  819. //if (isset($item->properties))
  820. // foreach ($item->properties as $property)
  821. // $quote .= "\n".$property->name.": [url=".$property->href."]".$property->text."[/url]";
  822. if ($quote)
  823. $_REQUEST["body"] .= "\n[quote]".$quote."[/quote]";
  824. // Only import the picture when the message is no video
  825. // oembed display a picture of the video as well
  826. if ($item->type != "video") {
  827. //if (($item->type != "video") and ($item->type != "photo")) {
  828. if(isset($item->picture) && isset($item->link))
  829. $_REQUEST["body"] .= "\n".'[url='.$item->link.'][img]'.fpost_cleanpicture($item->picture).'[/img][/url]';
  830. else {
  831. if (isset($item->picture))
  832. $_REQUEST["body"] .= "\n".'[img]'.fpost_cleanpicture($item->picture).'[/img]';
  833. // if just a link, it may be a wall photo - check
  834. if(isset($item->link))
  835. $_REQUEST["body"] .= fbpost_get_photo($uid,$item->link);
  836. }
  837. }
  838. /*if (($datarray['app'] == "Events") and isset($item->actions))
  839. foreach ($item->actions as $action)
  840. if ($action->name == "View")
  841. $_REQUEST["body"] .= " [url=".$action->link."]".$item->story."[/url]";
  842. */
  843. if(trim($_REQUEST["body"]) == '') {
  844. logger('facebook: empty body '.$item->id.' '.print_r($item, true));
  845. continue;
  846. }
  847. $_REQUEST["body"] = trim($_REQUEST["body"]);
  848. if (isset($item->place)) {
  849. if ($item->place->name or $item->place->location->street or
  850. $item->place->location->city or $item->place->location->country) {
  851. $_REQUEST["location"] = '';
  852. if ($item->place->name)
  853. $_REQUEST["location"] .= $item->place->name;
  854. if ($item->place->location->street)
  855. $_REQUEST["location"] .= " ".$item->place->location->street;
  856. if ($item->place->location->city)
  857. $_REQUEST["location"] .= " ".$item->place->location->city;
  858. if ($item->place->location->country)
  859. $_REQUEST["location"] .= " ".$item->place->location->country;
  860. $_REQUEST["location"] = trim($_REQUEST["location"]);
  861. }
  862. if ($item->place->location->latitude and $item->place->location->longitude)
  863. $_REQUEST["coord"] = substr($item->place->location->latitude, 0, 8)
  864. .' '.substr($item->place->location->longitude, 0, 8);
  865. }
  866. //print_r($_REQUEST);
  867. logger('facebook: posting for user '.$uid);
  868. require_once('mod/item.php');
  869. item_post($a);
  870. }
  871. set_pconfig($uid,'facebook','last_created', $lastcreated);
  872. }
  873. function fbpost_get_photo($uid,$link) {
  874. $access_token = get_pconfig($uid,'facebook','access_token');
  875. if(! $access_token || (! stristr($link,'facebook.com/photo.php')))
  876. return "";
  877. $ret = preg_match('/fbid=([0-9]*)/',$link,$match);
  878. if($ret)
  879. $photo_id = $match[1];
  880. else
  881. return "";
  882. $x = fetch_url('https://graph.facebook.com/'.$photo_id.'?access_token='.$access_token);
  883. $j = json_decode($x);
  884. if($j->picture)
  885. return "\n\n".'[url='.$link.'][img]'.fpost_cleanpicture($j->picture).'[/img][/url]';
  886. return "";
  887. }
  888. function fpost_cleanpicture($image) {
  889. if (strpos($image, ".fbcdn.net/") and (substr($image, -6) == "_s.jpg"))
  890. $image = substr($image, 0, -6)."_n.jpg";
  891. $queryvar = fbpost_parse_query($image);
  892. if ($queryvar['url'] != "")
  893. $image = urldecode($queryvar['url']);
  894. return $image;
  895. }
  896. function fbpost_parse_query($var) {
  897. /**
  898. * Use this function to parse out the query array element from
  899. * the output of parse_url().
  900. */
  901. $var = parse_url($var, PHP_URL_QUERY);
  902. $var = html_entity_decode($var);
  903. $var = explode('&', $var);
  904. $arr = array();
  905. foreach($var as $val) {
  906. $x = explode('=', $val);
  907. $arr[$x[0]] = $x[1];
  908. }
  909. unset($val, $x, $var);
  910. return $arr;
  911. }