<?php
$sumfingIncl=true;
require '../config.thing.php';
// Get options
$set = get_adm_opts();
include 'translate.php';
require '../fb/facebook.php';

if(!isset($_POST['uid']) || empty($_POST['uid'])) die(_("Bad request"));
$admin = $_POST['uid'];

if((trim($_POST['title']) == '') || (trim($_POST['msg']) == '')) die(_("Attention! Title and message must be filled in!"));

// Check for admin
$checkuser = is_user_fakeid($admin);
if($checkuser->isadmin != 1) die(_("Access denied"));
unset($checkuser);

// Get image for post
$postimage = explode("/",$_POST['img']);
$postimage = $postimage[2];
if($postimage == '') die(_("Not posted! Please change the picture on right"));
// Init the Facebook SDK
$facebook = new Facebook(array(
	'appId'  => FB_APPID,
    'secret' => FB_SECRET,
	'cookie' => true,
));

$url = urldecode($_POST['url']);
$tokens = get_users_token($admin,$_POST['amnt']);

// Loop and post
$i = 1;
if(is_array($tokens)) {
foreach($tokens as $usertoken) {
	$msg =  array(
				'link'    => MY_APP_URL,
				'picture' => $url.'uploads/'.$postimage,
				'name'    => $_POST['title'],
				'description' => $_POST['msg'],
				'access_token' => $usertoken
			);
						
						
	try {
		$facebook->api('/me/feed', 'POST', $msg);
		$i++;
	} 
	catch(FacebookApiException $e) {
		$i--;
		error_log('Can not post to timeline. Not valid token.' . $e);
	}
}
echo $i . _(" messages were posted successfully");
} else {
	error_log('Posting failed: Admin to timelines!');	
}
?>