Fatal Error: call to a member function uploadFile() on a non-object
Getting this error of upload file function on Uploading File to dropbox using PHP API On live Server. Same Code Working fine on localhost and doing it in codeigniter. start of code is**
<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
error_reporting(1);
require_once(APPPATH . 'libraries/dropbox/vendor/autoload.php');
use \Dropbox as dbx;
class Knowledge extends CI_Controller
{
public $appInfoFile;
public $requestPath; **
public function __construct()
{
parent::__construct();
$this->load->library('session');
$this->load->helper('form');
$this->load->helper('url');
$this->load->database();
$this->load->library('form_validation');
//load the models
$this->load->model('knowledge_model');
//$this->load->helper('messages');
//$this->load->model('messages_model');
$this->load->model('messages_model', 'send_messages');
// custom library in codeigniter
$this->appInfoFile = APPPATH.'libraries/dropbox/app-info.json';
$redirect_uri ='https://www.domainname.com/knowledge/add/';
$requestPath = $this->init();
session_start();
validate_user();
}
public function index($msg = NULL)
{
$session_data = $this->session->all_userdata();
$data['msg'] = $msg;
if (isset($session_data["validated"]) && $session_data["validated"] == '1') {
$data['title'] = 'Knowledge Center';
$data['records'] = $this->knowledge_model->get_all_rec();
// echo "<pre>".print_r($data['records'],true)."</pre>";exit;
$this->load->view('includes/header', $data);
$this->load->view('includes/sidebar', $data);
$this->load->view('knowledge', $data);
$this->load->view('includes/footer');
} else {
redirect(base_url());
}
}
public function tag($msg = NULL)
{
$tagname = $this->uri->segment("3");
$tagnamehits = $this->uri->segment("4");
$session_data = $this->session->all_userdata();
$data['msg'] = $msg;
if (isset($session_data["validated"]) && $session_data["validated"] == '1') {
$data['title'] = 'Knowledge Center';
$data['update_rec'] = $this->knowledge_model->update_hits($tagnamehits);
$data['records'] = $this->knowledge_model->get_notifyrec_bytags($tagname);
//echo "<pre>".print_r($data['records'],true)."</pre>";exit;
$this->load->view('includes/header', $data);
$this->load->view('includes/sidebar', $data);
$this->load->view('knowledge', $data);
$this->load->view('includes/footer');
} else {
redirect(base_url());
}
}
public function add()
{
//validate form input
$this->form_validation->set_rules('subject', 'subject', 'required');
$this->data['message'] = (validation_errors() ? validation_errors() : $this->session->flashdata('message'));
$seralizedtags = serialize($this->input->post('tagsar'));
//echo "<pre>".print_r($seralizedArray,true)."</pre>";exit;
// drop box upload filess
if (isset($_FILES['attached_file']['name']) && !empty($_FILES['attached_file']['name'])) {
$file_name= $_FILES['attached_file']['name'];
$return_result=$this->upload_to_dropbox($file_name);
$rev=$return_result['rev'];
$mime_type=$return_result['mime_type'];
$path=$return_result['path'];
$size=$return_result['size'];
$revision=$return_result['revision'];
}
if ($this->form_validation->run() == true) {
$session_data = $this->session->all_userdata();
$user_id = $session_data["userid"];
$data = array(
'user_id' => $user_id,
'edit_by_userid' => $user_id,
'subject' => $this->input->post('subject'),
'tags' => $seralizedtags,
'description' => $this->input->post('description'),
'dropbox_rev'=>$rev,
'dropbox_mim_type'=>$mime_type,
'dropbox_path'=>$path,
'dropbox_filesize'=>$size,
'dropbox_revision'=>$revision,
);
$message=$this->input->post('subject');
//for slack call
if(isset($message)){
$message=$message;
$messageType = "Knowledge_center";
$this->send_messages->send_message_on_slack($messageType);
}
//echo "<pre>" . print_r($data, true) . "</pre>";
$insert_res = $this->knowledge_model->insert_rec($data);
if ($insert_res != "conf") {
if ($insert_res == "subject") {
$this->session->set_flashdata('message', "<p>Subject Name already exist.Please change Subject</p>");
} else {
$this->session->set_flashdata('message', "<p>Error in Insertion.</p>");
}
echo '<script>window.location.href = "' . base_url() . 'knowledge/add";</script>';
} else {
$this->session->set_flashdata('message', "<p>Record added successfully.</p>");
echo '<script>window.location.href = "' . base_url() . 'knowledge";</script>';
}
} else {
//set the flash data error message if there is one
$this->data['message'] = (validation_errors() ? validation_errors() : $this->session->flashdata('message'));
$this->data['subject'] = array(
'name' => 'subject',
'class' => 'form-control round-input',
'id' => 'subject',
'placeholder' => 'Subject',
'type' => 'text',
'autofocus' => 'true',
'data-required' => '1',
'value' => $this->form_validation->set_value('subject'),
);
$this->data['tagdata'] = array(
'name' => 'tagsar',
'class' => 'form-control tags tags-input',
'id' => 'tagsar',
'type' => 'text',
'autofocus' => 'true',
'data-type' => 'tags',
'value' => $this->form_validation->set_value('tagsar'),
);
$data['desc'] = $this->form_validation->set_value('description');
// $data['dropbox']=$this->dropbox->dp();
$msg = "";
$data['title'] = 'Knowledge Center';
$data['msg'] = $msg;
$this->load->view('includes/header', $data);
$this->load->view('includes/sidebar', $data);
$this->load->view('add_knowledge', $this->data);
$this->load->view('includes/footer');
}
}
public function view($id)
{
$update_rec = $this->knowledge_model->get_rec_byid($id);
$data['dropbox_detail']=array(
"dropbox_rev"=> $update_rec[0]->dropbox_rev,
"dropbox_mim_type"=> $update_rec[0]->dropbox_mim_type,
"dropbox_path"=> $update_rec[0]->dropbox_path,
"dropbox_filesize"=> $update_rec[0]->dropbox_filesize,
"dropbox_revision"=> $update_rec[0]->dropbox_revision,
);
$data['subject_data'] = $update_rec[0]->subject;
$data['tags_data'] = unserialize($update_rec[0]->tags);
$data['desc'] = $update_rec[0]->description;
$data['title'] = 'Knowledge Center';
$this->load->view('includes/header', $data);
$this->load->view('includes/sidebar', $data);
$this->load->view('view_knowledge', $this->data);
$this->load->view('includes/footer');
}
public function manage_notify()
{
$notifyid = $_POST["elid"];
$notifytext = $_POST["notifytext"];
$notify_rec = $this->knowledge_model->get_notifyrec_byid($notifytext);
$ret_res = "<ul>";
foreach ($notify_rec as $notify_record) {
$ret_res .= "<li>" . $notify_record->subject . "</li>";
}
$ret_res .= "</ul>";
echo $ret_res;
exit;
}
public function update($id)
{
//validate form input
$this->form_validation->set_rules('subject', 'subject', 'required');
$this->data['message'] = (validation_errors() ? validation_errors() : $this->session->flashdata('message'));
$update_rec = $this->knowledge_model->get_rec_byid($id);
//echo "<pre>".print_r($update_rec[0],true)."</pre>";exit;
$seralizedtags = serialize($this->input->post('tagsar'));
if ($this->form_validation->run() == true) {
$session_data = $this->session->all_userdata();
$user_id = $session_data["userid"];
$data = array(
'edit_by_userid' => $user_id,
'subject' => $this->input->post('subject'),
'tags' => $seralizedtags,
'description' => $this->input->post('description')
);
$recid = $this->input->post('recid');
// echo "<pre>".print_r($data,true)."</pre>";exit;
$update_res = $this->knowledge_model->update_rec($recid, $data);
if ($update_res > 0) {
$this->session->set_flashdata('message', "<p>Record Updated successfully.</p>");
echo '<script>window.location.href = "' . base_url() . 'knowledge";</script>';
} else {
$this->session->set_flashdata('message', "<p>Error in Updation.</p>");
echo '<script>window.location.href = "' . base_url() . 'knowledge/update/' . $recid . '";</script>';
}
} else {
//set the flash data error message if there is one
$this->data['message'] = (validation_errors() ? validation_errors() : $this->session->flashdata('message'));
if (isset($update_rec)) {
$this->data['recid'] = array(
'name' => 'recid',
'class' => 'form-control',
'id' => 'recid',
'type' => 'hidden',
'autofocus' => 'true',
'data-required' => '1',
'value' => $update_rec[0]->id,
);
$this->data['subject'] = array(
'name' => 'subject',
'class' => 'form-control round-input',
'id' => 'subject',
'placeholder' => 'Subject',
'type' => 'text',
'autofocus' => 'true',
'data-required' => '1',
'value' => $update_rec[0]->subject,
);
$tags_data = unserialize($update_rec[0]->tags);
$this->data['tagdata'] = array(
'name' => 'tagsar',
'class' => 'form-control tags tags-input',
'id' => 'tagsar',
'type' => 'text',
'autofocus' => 'true',
'data-type' => 'tags',
'value' => $tags_data,
);
$data['desc'] = $update_rec[0]->description;
} else {
$this->session->set_flashdata('message', "<p>Update Record not found.</p>");
echo '<script>window.location.href = "' . base_url() . 'knowledge";</script>';
}
$msg = "";
$data['title'] = 'Knowledge Center';
$data['msg'] = $msg;
$this->load->view('includes/header', $data);
$this->load->view('includes/sidebar', $data);
$this->load->view('edit_knowledge', $this->data);
$this->load->view('includes/footer');
}
}
public function download_dbx_file(){
$file_path = $_POST['dropbox_path'];
$mime_type = $_POST['dropbox_mim_type'];
$this->download_file($file_path,$mime_type);
}
public function del($id)
{
$this->knowledge_model->del_rec($id);
$this->session->set_flashdata('message', "<p>Record Deleted successfully.</p>");
redirect(base_url() . 'knowledge');
}
// for upload to dropbox //
function getAppConfig()
{
global $appInfoFile;
try {
$appInfo = dbx\AppInfo::loadFromJsonFile($this->appInfoFile);
}
catch (dbx\AppInfoLoadException $ex) {
throw new Exception("Unable to load \"$this->appInfoFile\": " . $ex->getMessage());
}
$clientIdentifier = "examples-web-file-browser";
$userLocale = null;
return array($appInfo, $clientIdentifier, $userLocale);
}
function getClient()
{
if (!isset($_SESSION['access-token'])) {
return false;
}
list($appInfo, $clientIdentifier, $userLocale) = $this->getAppConfig();
$accessToken = $_SESSION['access-token'];
return new dbx\Client($accessToken, $clientIdentifier, $userLocale,$appInfo->getHost());
}
function getWebAuth()
{
list($appInfo, $clientIdentifier, $userLocale) = $this->getAppConfig();
$redirectUri = getUrl("dropbox-auth-finish");
$csrfTokenStore = new dbx\ArrayEntryStore($_SESSION, 'dropbox-auth-csrf-token');
return new dbx\WebAuth($appInfo, $clientIdentifier, $redirectUri, $csrfTokenStore, $userLocale);
}
function respondWithError($code, $title, $body = "")
{
$proto = $_SERVER['SERVER_PROTOCOL'];
header("$proto $code $title", true, $code);
echo renderHtmlPage($title, $body);
}
function getUrl($relative_path)
{
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') {
$scheme = "https";
} else {
$scheme = "http";
}
$host = $_SERVER['HTTP_HOST'];
$path = getPath($relative_path);
return $scheme."://".$host.$path;
}
function getPath($relative_path)
{
if (PHP_SAPI === 'cli-server') {
return "/".$relative_path;
} else {
return $_SERVER["SCRIPT_NAME"]."/".$relative_path;
}
}
function init()
{
global $argv;
// If we were run as a command-line script, launch the PHP built-in web server.
if (PHP_SAPI === 'cli') {
launchBuiltInWebServer($argv);
assert(false);
}
if (PHP_SAPI === 'cli-server') {
// For when we're running under PHP's built-in web server, do the routing here.
return $_SERVER['SCRIPT_NAME'];
}
else {
// For when we're running under CGI or mod_php.
if (isset($_SERVER['PATH_INFO'])) {
return $_SERVER['PATH_INFO'];
} else {
return "/";
}
}
}
function launchBuiltInWebServer($argv)
{
// The built-in web server is only available in PHP 5.4+.
if (version_compare(PHP_VERSION, '5.4.0', '<')) {
fprintf(STDERR,
"Unable to run example. The version of PHP you used to run this script (".PHP_VERSION.")\n".
"doesn't have a built-in web server. You need PHP 5.4 or newer.\n".
"\n".
"You can still run this example if you have a web server that supports PHP 5.3.\n".
"Copy the Dropbox PHP SDK into your web server's document path and access it there.\n");
exit(2);
}
$php_file = $argv[0];
if (count($argv) === 1) {
$port = 5000;
} else if (count($argv) === 2) {
$port = intval($argv[1]);
} else {
fprintf(STDERR,
"Too many arguments.\n".
"Usage: php $argv[0] [server-port]\n");
exit(1);
}
$host = "localhost:$port";
$cmd = escapeshellarg(PHP_BINARY)." -S ".$host." ".escapeshellarg($php_file);
$descriptors = array(
0 => array("pipe", "r"), // Process' stdin. We'll just close this right away.
1 => STDOUT, // Relay process' stdout to ours.
2 => STDERR, // Relay process' stderr to ours.
);
$proc = proc_open($cmd, $descriptors, $pipes);
if ($proc === false) {
fprintf(STDERR,
"Unable to launch PHP's built-in web server. Used command:\n".
" $cmd\n");
exit(2);
}
fclose($pipes[0]); // Close the process' stdin.
$exitCode = proc_close($proc); // Wait for process to exit.
exit($exitCode);
}
public function upload_to_dropbox($filename){
if($filename != ''){
try {
$dbxClient = $this->getClient();
$remoteDir = "/";
if (isset($_POST['folder'])) $remoteDir = $_POST['folder'];
$remotePath = rtrim($remoteDir, "/")."/".$filename;
$fp = fopen($_FILES['attached_file']['tmp_name'], "rb");
$result = $dbxClient->uploadFile($remotePath, dbx\WriteMode::add(), $fp);
fclose($fp);
//$str = print_r($result, true);
return $result;
} catch (Exception $e) {
echo $e->getMessage();
exit;
}
}
else{
echo "File does not exists";
exit;
}
}
public function download_file($file_path,$file_mime_type){
if($file_path != '' && $file_mime_type != '' ) {
try {
$dbxClient = $this->getClient();
$path = $file_path;
$fd = tmpfile();
$metadata = $dbxClient->getFile($path, $fd);
header("Content-Type: $metadata[mime_type]");
fseek($fd, 0);
fpassthru($fd);
fclose($fd);
} catch (Exception $e) {
echo $e->getMessage();
exit;
}
}
else{
echo "Invalid Request";
exit;
}
}
}
Related
i want to write a API for updating data in sql. I am using CI for it.I am new to this field.while i have written it is not working in localhost itself .Can anyone help me? I am attaching my controller and model here.it is showing an error like this page is not working
function editprofile($id,$data) {
$this->db->where(array('user_id' => $id));
$this->db->update('registrationdetails', $data);
if(!empty($id))
{
$result = true;
} else {
$result = false;
}
return $result;
}
public function updateuser()
{
$adminId = 1;
$AUTHENTIC_KEY = "4u0IOxa1YTwNo38QjArD9ysW6PgVnbX7vtlJ";
$user_id=2;
$firstname ="aiswarya";
$lastname ="mathew";
$email ="aiswarya#gmail.com";
$password ="aiswarya";
$confirmpassword ="aiswarya";
$contactnumber ="999999999";
$gender ="female";
$address ="canada";
$department ="cse";
$designation ="swe";
$Admindetails = $this->common->CheckValidAdmin($adminId,$AUTHENTIC_KEY);
if($Admindetails != false)
{
$validAdmin = array('authentication_key' => $Admindetails->authentication_key,
'admin_id' => $Admindetails->id
);
$data = array();
$data = array('firstname'=>$firstname,'lastname'=>$lastname,'email'=>$email,'password'=>$password,'confirmpassword'=>$confirmpassword,'contactnumber'=>$contactnumber,'gender'=>$gender,'address'=>$address,'department'=>$department,'designation'=>$designation);
$status = $this->user->editprofile($user_id,$data);
if($status == true)
{
$response = array('status' => 200,
'message' => 'updated successfully',
'admin_details' => $validAdmin
);
} else {
$response = array('status' => 404,
'message' => 'unable to add, please try again',
'admin_details' => $validAdmin);
}
} else {
$response = array('status' => 404,
'message' => 'Authentication Failed');
}
echo json_encode($response);
}
function editprofile($data) {
if(!empty($data['user_id']))
{
$this->db->where(array('user_id' => $data['user_id']));
$this->db->update('registrationdetails', $data);
$result = true;
} else {
$result = false;
}
return $result;
}
public function updateuser()
{
$data['adminId'] = 1;
$data['AUTHENTIC_KEY'] = "4u0IOxa1YTwNo38QjArD9ysW6PgVnbX7vtlJ";
$data['user_id']=2;
$data['firstname'] ="aiswarya";
$data['lastname'] ="mathew";
$data['email'] ="aiswarya#gmail.com";
$data['password'] ="aiswarya";
$data['confirmpassword'] ="aiswarya";
$data['contactnumber'] ="999999999";
$data['gender'] ="female";
$data['address'] ="canada";
$data['department'] ="cse";
$data['designation'] ="swe";
$Admindetails = $this->common->CheckValidAdmin($data['adminId'],$data['AUTHENTIC_KEY']);
if($Admindetails != false)
{
$validAdmin = array('authentication_key' => $Admindetails->authentication_key,
'admin_id' => $Admindetails->id);
$status = $this->user->editprofile($data);
if($status == true)
{
$response = array('status' => 200,
'message' => 'updated successfully',
'admin_details' => $validAdmin
);
} else {
$response = array('status' => 404,
'message' => 'unable to add, please try again',
'admin_details' => $validAdmin);
}
} else {
$response = array('status' => 404,
'message' => 'Authentication Failed');
}
echo json_encode($response);
}
I'm a total newbie to Wordpress and having a hard time figuring things out.
I'm using plugin called "WP-Pro-Quiz", a quiz plugin, and within the plugin there's an option to show "Leaderboard" of all users who completed the quiz. In the leaderboard on the frontend, there's user id, time, points and user's Display Name, etc for each user..
What I want to achieve is to make Display name clickable (and then to go to author's profile once clicked). That is, to connect Display Name with author profile who took the quiz, to create hyperlink from Display Name.
This is from controller WpProQuiz_Controller_Toplist.php :
<?php
class WpProQuiz_Controller_Toplist extends WpProQuiz_Controller_Controller
{
public function route()
{
$quizId = $_GET['id'];
$action = isset($_GET['action']) ? $_GET['action'] : 'show';
switch ($action) {
default:
$this->showAdminToplist($quizId);
break;
}
}
private function showAdminToplist($quizId)
{
if (!current_user_can('wpProQuiz_toplist_edit')) {
wp_die(__('You do not have sufficient permissions to access this page.'));
}
$view = new WpProQuiz_View_AdminToplist();
$quizMapper = new WpProQuiz_Model_QuizMapper();
$quiz = $quizMapper->fetch($quizId);
$view->quiz = $quiz;
$view->show();
}
public function getAddToplist(WpProQuiz_Model_Quiz $quiz)
{
$userId = get_current_user_id();
if (!$quiz->isToplistActivated()) {
return null;
}
$data = array(
'userId' => $userId,
'token' => wp_create_nonce('wpProQuiz_toplist'),
'canAdd' => $this->preCheck($quiz->getToplistDataAddPermissions(), $userId),
);
if ($quiz->isToplistDataCaptcha() && $userId == 0) {
$captcha = WpProQuiz_Helper_Captcha::getInstance();
if ($captcha->isSupported()) {
$data['captcha']['img'] = WPPROQUIZ_CAPTCHA_URL . '/' . $captcha->createImage();
$data['captcha']['code'] = $captcha->getPrefix();
}
}
return $data;
}
private function handleAddInToplist(WpProQuiz_Model_Quiz $quiz)
{
if (!wp_verify_nonce($this->_post['token'], 'wpProQuiz_toplist')) {
return array('text' => __('An error has occurred.', 'wp-pro-quiz'), 'clear' => true);
}
if (!isset($this->_post['points']) || !isset($this->_post['totalPoints'])) {
return array('text' => __('An error has occurred.', 'wp-pro-quiz'), 'clear' => true);
}
$quizId = $quiz->getId();
$userId = get_current_user_id();
$points = (int)$this->_post['points'];
$totalPoints = (int)$this->_post['totalPoints'];
$name = !empty($this->_post['name']) ? trim($this->_post['name']) : '';
$email = !empty($this->_post['email']) ? trim($this->_post['email']) : '';
$ip = filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP);
$captchaAnswer = !empty($this->_post['captcha']) ? trim($this->_post['captcha']) : '';
$prefix = !empty($this->_post['prefix']) ? trim($this->_post['prefix']) : '';
$quizMapper = new WpProQuiz_Model_QuizMapper();
$toplistMapper = new WpProQuiz_Model_ToplistMapper();
if ($quiz == null || $quiz->getId() == 0 || !$quiz->isToplistActivated()) {
return array('text' => __('An error has occurred.', 'wp-pro-quiz'), 'clear' => true);
}
if (!$this->preCheck($quiz->getToplistDataAddPermissions(), $userId)) {
return array('text' => __('An error has occurred.', 'wp-pro-quiz'), 'clear' => true);
}
$numPoints = $quizMapper->sumQuestionPoints($quizId);
if ($totalPoints > $numPoints || $points > $numPoints) {
return array('text' => __('An error has occurred.', 'wp-pro-quiz'), 'clear' => true);
}
$clearTime = null;
if ($quiz->isToplistDataAddMultiple()) {
$clearTime = $quiz->getToplistDataAddBlock() * 60;
}
if ($userId > 0) {
if ($toplistMapper->countUser($quizId, $userId, $clearTime)) {
return array('text' => __('You can not enter again.', 'wp-pro-quiz'), 'clear' => true);
}
$user = wp_get_current_user();
$email = $user->user_email;
$name = $user->display_name;
} else {
if ($toplistMapper->countFree($quizId, $name, $email, $ip, $clearTime)) {
return array('text' => __('You can not enter again.', 'wp-pro-quiz'), 'clear' => true);
}
if (empty($name) || empty($email) || filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
return array('text' => __('No name or e-mail entered.', 'wp-pro-quiz'), 'clear' => false);
}
if (strlen($name) > 15) {
return array('text' => __('Your name can not exceed 15 characters.', 'wp-pro-quiz'), 'clear' => false);
}
if ($quiz->isToplistDataCaptcha()) {
$captcha = WpProQuiz_Helper_Captcha::getInstance();
if ($captcha->isSupported()) {
if (!$captcha->check($prefix, $captchaAnswer)) {
return array('text' => __('You entered wrong captcha code.', 'wp-pro-quiz'), 'clear' => false);
}
}
}
}
$toplist = new WpProQuiz_Model_Toplist();
$toplist->setQuizId($quizId)
->setUserId($userId)
->setDate(time())
->setName($name)
->setEmail($email)
->setPoints($points)
->setResult(round($points / $totalPoints * 100, 2))
->setIp($ip);
$toplistMapper->save($toplist);
return true;
}
private function preCheck($type, $userId)
{
switch ($type) {
case WpProQuiz_Model_Quiz::QUIZ_TOPLIST_TYPE_ALL:
return true;
case WpProQuiz_Model_Quiz::QUIZ_TOPLIST_TYPE_ONLY_ANONYM:
return $userId == 0;
case WpProQuiz_Model_Quiz::QUIZ_TOPLIST_TYPE_ONLY_USER:
return $userId > 0;
}
return false;
}
public static function ajaxAdminToplist($data)
{
if (!current_user_can('wpProQuiz_toplist_edit')) {
return json_encode(array());
}
$toplistMapper = new WpProQuiz_Model_ToplistMapper();
$j = array('data' => array());
$limit = (int)$data['limit'];
$start = $limit * ($data['page'] - 1);
$isNav = isset($data['nav']);
$quizId = $data['quizId'];
if (isset($data['a'])) {
switch ($data['a']) {
case 'deleteAll':
$toplistMapper->delete($quizId);
break;
case 'delete':
if (!empty($data['toplistIds'])) {
$toplistMapper->delete($quizId, $data['toplistIds']);
}
break;
}
$start = 0;
$isNav = true;
}
$toplist = $toplistMapper->fetch($quizId, $limit, $data['sort'], $start);
foreach ($toplist as $tp) {
$j['data'][] = array(
'id' => $tp->getToplistId(),
'name' => $tp->getName(),
'email' => $tp->getEmail(),
'type' => $tp->getUserId() ? 'R' : 'UR',
'date' => WpProQuiz_Helper_Until::convertTime($tp->getDate(),
get_option('wpProQuiz_toplistDataFormat', 'Y/m/d g:i A')),
'points' => $tp->getPoints(),
'result' => $tp->getResult()
);
}
if ($isNav) {
$count = $toplistMapper->count($quizId);
$pages = ceil($count / $limit);
$j['nav'] = array(
'count' => $count,
'pages' => $pages ? $pages : 1
);
}
return json_encode($j);
}
public static function ajaxAddInToplist($data)
{
// workaround ...
$_POST = $_POST['data'];
$ctn = new WpProQuiz_Controller_Toplist();
$quizId = isset($data['quizId']) ? $data['quizId'] : 0;
$prefix = !empty($data['prefix']) ? trim($data['prefix']) : '';
$quizMapper = new WpProQuiz_Model_QuizMapper();
$quiz = $quizMapper->fetch($quizId);
$r = $ctn->handleAddInToplist($quiz);
if ($quiz->isToplistActivated() && $quiz->isToplistDataCaptcha() && get_current_user_id() == 0) {
$captcha = WpProQuiz_Helper_Captcha::getInstance();
if ($captcha->isSupported()) {
$captcha->remove($prefix);
$captcha->cleanup();
if ($r !== true) {
$r['captcha']['img'] = WPPROQUIZ_CAPTCHA_URL . '/' . $captcha->createImage();
$r['captcha']['code'] = $captcha->getPrefix();
}
}
}
if ($r === true) {
$r = array('text' => __('You signed up successfully.', 'wp-pro-quiz'), 'clear' => true);
}
return json_encode($r);
}
public static function ajaxShowFrontToplist($data)
{
// workaround ...
$_POST = $_POST['data'];
$quizIds = empty($data['quizIds']) ? array() : array_unique((array)$data['quizIds']);
$toplistMapper = new WpProQuiz_Model_ToplistMapper();
$quizMapper = new WpProQuiz_Model_QuizMapper();
$j = array();
foreach ($quizIds as $quizId) {
$quiz = $quizMapper->fetch($quizId);
if ($quiz == null || $quiz->getId() == 0) {
continue;
}
$toplist = $toplistMapper->fetch($quizId, $quiz->getToplistDataShowLimit(), $quiz->getToplistDataSort());
foreach ($toplist as $tp) {
$j[$quizId][] = array(
'name' => $tp->getName(),
'date' => WpProQuiz_Helper_Until::convertTime($tp->getDate(),
get_option('wpProQuiz_toplistDataFormat', 'Y/m/d g:i A')),
'points' => $tp->getPoints(),
'result' => $tp->getResult()
);
}
}
return json_encode($j);
}
}
and from model WpProQuiz_Model_Toplist.php:
<?php
class WpProQuiz_Model_Toplist extends WpProQuiz_Model_Model
{
protected $_toplistId;
protected $_quizId;
protected $_userId;
protected $_date;
protected $_name;
protected $_email;
protected $_points;
protected $_result;
protected $_ip;
public function setToplistId($_toplistId)
{
$this->_toplistId = (int)$_toplistId;
return $this;
}
public function getToplistId()
{
return $this->_toplistId;
}
public function setQuizId($_quizId)
{
$this->_quizId = (int)$_quizId;
return $this;
}
public function getQuizId()
{
return $this->_quizId;
}
public function setUserId($_userId)
{
$this->_userId = (int)$_userId;
return $this;
}
public function getUserId()
{
return $this->_userId;
}
public function setDate($_date)
{
$this->_date = (int)$_date;
return $this;
}
public function getDate()
{
return $this->_date;
}
public function setName($_name)
{
$this->_name = (string)$_name;
return $this;
}
public function getName()
{
return $this->_name;
}
public function setEmail($_email)
{
$this->_email = (string)$_email;
return $this;
}
public function getEmail()
{
return $this->_email;
}
public function setPoints($_points)
{
$this->_points = (int)$_points;
return $this;
}
public function getPoints()
{
return $this->_points;
}
public function setResult($_result)
{
$this->_result = (float)$_result;
return $this;
}
public function getResult()
{
return $this->_result;
}
public function setIp($_ip)
{
$this->_ip = (string)$_ip;
return $this;
}
public function getIp()
{
return $this->_ip;
}
}
I have this code:
public function getJccLineItem($id,$action)
{
$res = array();
$q = 'SELECT * FROM jcc_line_items jli,ipo_line_item ili ,line_items li
WHERE jli.line_item_id= ili.id and li.id = jli.line_item_id
and ili.dn_number_id in ( Select dn_number from ipo where project_id= '.$id.')';
$res = $this->db->query($q);
echo $this->db->last_query();
$jccLineItemArray = array();
echo $id;
print_r($res->result());
if($action == 'array')
{
foreach ( $res->result() as $key => $value) // The error comes in this line
{
$jccLineItemArray[ $value->id ] = $value->item_description;
}
$res = $jccLineItemArray;
}
else
{
$res = $res->result();
}
return $res;
}
The error is in the foreach loop. I have printed the result and it shows the result in object array but when it goes to foreach loop. It show this error
"Call to a member function result() on a non-object "
But when I set db['default']['db_debug']=true , it shows that the $id is missing from the query whereas when it was false it was showing result in object array and giving error at loop. Any Help would be appreciated.Thanks
Controller Code
public function createInvoice( $id = "" )
{
if (empty($id))
{
$id = $this->input->post('dataid');
}
echo $id;
$data['jcc_line_list'] = $this->product_model->getJccLineItem($id,'array');
$data['jcc_line_lists'] = $this->product_model->getJccLineItem($id,'');
$data['items'] = $this->product_model->getAllSubInvoice($id);
$data['single_project'] = $this->product_model->getSingleProject($id);
$data['site'] = $this->product_model->getAllSiteArray();
$data['job_types'] = $this->product_model->getAllJobTypeArray();
$data['title'] = 'Invoice';
$data['operation'] = 'Create';
$data['buttonText'] = 'Save';
$data['id'] = $id;
$this->load->helper(array('form', 'url'));
$this->load->helper('security');
$this->form_validation->set_rules('line_item_id', 'Line Item', 'required|xss_clean|max_length[50]');
$this->form_validation->set_rules('job_type_id', 'Job Type', 'required|xss_clean|max_length[50]');
$this->form_validation->set_rules('site_id', 'Site', 'required|xss_clean|max_length[50]');
$this->form_validation->set_rules('milestone', 'Milestone', 'required|xss_clean|max_length[50]');
$this->form_validation->set_error_delimiters('<span class="error">', '</span>');
if ($this->form_validation->run() == FALSE) {
$this->session->set_flashdata('error_message', validation_errors());
$this->load->view('admin/viewinvoicesub', $data);
} else if ($this->form_validation->run() == TRUE) {
$formData = array(
'invoice_id' => $id,
'line_item_id' => $this->form_validation->set_value('line_item_id'),
'job_type_id' => $this->form_validation->set_value('job_type_id'),
'site_id' => $this->form_validation->set_value('site_id'),
'milestone' => $this->form_validation->set_value('milestone'),
);
$this->product_model->insertInvoiceSub($formData);
$this->session->set_flashdata('sucess_message', "Data successfully save !");
redirect('Products/createInvoice', "refresh");
} else {
$this->load->view('admin/viewinvoicesub', $data);
}
}
Try this and let me know if that helps
public function getJccLineItem($id = '' ,$action = '')
{
if($id != '')
{
$res = array();
$q = 'SELECT * FROM jcc_line_items jli,ipo_line_item ili ,line_items li
WHERE jli.line_item_id= ili.id and li.id = jli.line_item_id
and ili.dn_number_id in ( Select dn_number from ipo where project_id= '.$id.')';
$res = $this->db->query($q)->result();
$jccLineItemArray = array();
if($action == 'array')
{
foreach($res as $key => $value) // The error comes in this line
{
$jccLineItemArray[ $value->id ] = $value->item_description;
}
$res = $jccLineItemArray;
}
return $res;
}
else
{
echo "id is null"; die();
}
}
And your Controller code should be
public function createInvoice( $id = "" )
{
$this->load->helper(array('form', 'url'));
$this->load->helper('security');
if ($id = "")
{
$id = (isset($this->input->post('dataid')))?$this->input->post('dataid'):3;// i am sure your error is from here
}
$data['jcc_line_list'] = $this->product_model->getJccLineItem($id,'array');
$data['jcc_line_lists'] = $this->product_model->getJccLineItem($id,'');
$data['items'] = $this->product_model->getAllSubInvoice($id);
$data['single_project'] = $this->product_model->getSingleProject($id);
$data['site'] = $this->product_model->getAllSiteArray();
$data['job_types'] = $this->product_model->getAllJobTypeArray();
$data['title'] = 'Invoice';
$data['operation'] = 'Create';
$data['buttonText'] = 'Save';
$data['id'] = $id;
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$this->form_validation->set_rules('line_item_id', 'Line Item', 'required|xss_clean|max_length[50]');
$this->form_validation->set_rules('job_type_id', 'Job Type', 'required|xss_clean|max_length[50]');
$this->form_validation->set_rules('site_id', 'Site', 'required|xss_clean|max_length[50]');
$this->form_validation->set_rules('milestone', 'Milestone', 'required|xss_clean|max_length[50]');
$this->form_validation->set_error_delimiters('<span class="error">', '</span>');
if ($this->form_validation->run() === FALSE)
{
$this->session->set_flashdata('error_message', validation_errors());
$this->load->view('admin/viewinvoicesub', $data);
}
else
{
$formData = array(
'invoice_id' => $id,
'line_item_id' => $this->form_validation->set_value('line_item_id'),
'job_type_id' => $this->form_validation->set_value('job_type_id'),
'site_id' => $this->form_validation->set_value('site_id'),
'milestone' => $this->form_validation->set_value('milestone'),
);
$this->product_model->insertInvoiceSub($formData);
$this->session->set_flashdata('sucess_message', "Data successfully save !");
redirect('Products/createInvoice/'.$id, "refresh");
}
}
else
{
$this->load->view('admin/viewinvoicesub', $data);
}
}
I am using codeigniter form validation lib and for some reason form is not updating this particular row. And there for not redirecting when form Submitted.
On my controller I use function like this
$this->load->model('admin/setting/model_setting');
$config_meta_title = $this->model_setting->edit_meta_title($this->input->post('config_meta_title'));
if (!empty($config_meta_title)) {
$data['config_meta_title'] = $this->input->post('config_meta_title');
} else {
$data['config_meta_title'] = $this->configs->get('config_meta_title');
}
But not updating database.
Model
<?php
class Model_setting extends CI_Model {
public function edit_meta_title() {
$data = array(
'group' => "config",
'key' => "config_meta_title",
'value' => $this->input->post('config_meta_title')
);
$this->db->where('setting_id', "2");
$this->db->update('setting', $data);
}
}
Controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Setting extends MY_Controller {
public function __construct() {
parent::__construct();
$this->lang->load('admin/setting/setting', 'english');
$this->lang->load('admin/english', 'english');
if ($this->session->userdata('user_id') == true) {
return true;
} else {
redirect('admin');
}
}
public function index() {
$this->load->library('form_validation');
$data['text_yes'] = $this->lang->line('text_yes');
$data['text_no'] = $this->lang->line('text_no');
$data['entry_meta_title'] = $this->lang->line('entry_meta_title');
$data['entry_maintenance'] = $this->lang->line('entry_maintenance');
$data['button_save'] = $this->lang->line('button_save');
$data['button_cancel'] = $this->lang->line('button_cancel');
$data['tab_store'] = $this->lang->line('tab_store');
$data['action'] = site_url('admin/setting');
$data['logout'] = site_url('admin/logout');
$data['cancel'] = site_url('admin/dashboard');
$this->load->model('admin/setting/model_setting');
$config_meta_title = $this->model_setting->edit_meta_title($this->input->post('config_meta_title'));
if (!empty($config_meta_title)) {
$data['config_meta_title'] = $this->input->post('config_meta_title');
} else {
$data['config_meta_title'] = $this->configs->get('config_meta_title');
}
if ($this->form_validation->run() == FALSE) {
return $this->load->view('setting/settings', $data);
} else {
redirect('admin/dashboard');
}
}
}
In your model, kindly try to pass it as a parameter:
public function edit_meta_title($config_meta_title) {
$data = array(
'group' => "config",
'key' => "config_meta_title",
'value' => $config_meta_title,
);
$this->db->where('setting_id', "2");
$this->db->update('setting', $data);
return $this->db->affected_rows();
}
I have fixed my issues now All working perfect
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Setting extends MY_Controller {
public function __construct() {
parent::__construct();
$this->lang->load('admin/setting/setting', 'english');
$this->lang->load('admin/english', 'english');
if ($this->session->userdata('user_id') == true) {
return true;
} else {
redirect('admin');
}
}
public function index() {
$data = array();
$data['text_yes'] = $this->lang->line('text_yes');
$data['text_no'] = $this->lang->line('text_no');
$data['entry_meta_title'] = $this->lang->line('entry_meta_title');
$data['entry_template'] = $this->lang->line('entry_template');
$data['entry_maintenance'] = $this->lang->line('entry_maintenance');
$data['button_save'] = $this->lang->line('button_save');
$data['button_cancel'] = $this->lang->line('button_cancel');
$data['tab_store'] = $this->lang->line('tab_store');
$data['action'] = site_url('admin/setting');
$data['logout'] = site_url('admin/logout');
$data['cancel'] = site_url('admin/dashboard');
$this->load->model('admin/setting/model_setting');
if (empty($config_meta_title)) {
$data['config_meta_title'] = $this->configs->get('config_meta_title');
}
if (empty($config_template)) {
$data['config_template'] = $this->configs->get('config_template');
}
$data['templates'] = array();
$directories = glob(APPPATH . 'modules/catalog/views/theme/*', GLOB_ONLYDIR);
foreach ($directories as $directory) {
$data['templates'][] = basename($directory);
}
if (empty($config_maintenance)) {
$data['config_maintenance'] = $this->configs->get('config_maintenance');
}
$this->load->library('form_validation');
$this->form_validation->set_rules('config_meta_title', 'Meta Title');
$this->form_validation->set_rules('config_template', 'Template');
$this->form_validation->set_rules('config_maintenance', 'Maintenance');
if ($this->form_validation->run() == FALSE) {
return $this->load->view('setting/settings', $data);
} else {
$config_meta_title = $this->model_setting->edit_meta_title($this->input->post('config_meta_title'));
$config_template = $this->model_setting->edit_template($this->input->post('config_template'));
$config_maintenance = $this->model_setting->edit_maintenance($this->input->post('config_maintenance'));
redirect('admin/dashboard');
}
}
}
Model
<?php
class Model_setting extends CI_Model {
public function edit_maintenance($config_maintenance) {
$data = array(
'group' => "config",
'key' => "config_maintenance",
'value' => $config_maintenance,
);
$this->db->where('setting_id', "1");
$this->db->update('setting', $data);
}
public function edit_meta_title($config_meta_title) {
$data = array(
'group' => "config",
'key' => "config_meta_title",
'value' => $config_meta_title,
);
$this->db->where('setting_id', "2");
$this->db->update('setting', $data);
}
public function edit_template($config_template) {
$data = array(
'group' => "config",
'key' => "config_template",
'value' => $config_template,
);
$this->db->where('setting_id', "3");
$this->db->update('setting', $data);
}
}
I am trying to post on behalf of user. I have used tutorial given on this page: http://25labs.com/updated-post-to-multiple-facebook-pages-or-groups-efficiently-v2-0/ .
I could successfully perform authentication but could not post on behalf.
Here is the source code : https://github.com/karimkhanp/fbPostOnBehalf
Testing can be done here: http://ec2-54-186-110-98.us-west-2.compute.amazonaws.com/fb/
Does any one experienced this?
I'm not familiar with the batch process that the tutorial is using but below is a code sample that posts to a Facebook group
<?php
# same this file as
# test.php
include_once "src/facebook.php";
$config = array(
'appId' => "YOURAPPID",
'secret' => "YOURAPPSECRET",
'allowSignedRequest' => false, // optional, but should be set to false for non-canvas apps
);
class PostToFacebook
{
private $facebook;
private $pages;
public function initialise($config){
$this->name = "Facebook";
// current necessary configs to set
// $config = array(
// 'appId' => FB_APP_ID,
// 'secret' => FB_APP_SECRET,
// 'allowSignedRequest' => false, // optional, but should be set to false for non-canvas apps
// );
$this->facebook = new Facebook($config);
try{
// if user removes app authorization
$this->hasAccess = $this->has_permissions();
if($this->hasAccess){
$this->groups = $this->getGroupData();
}
}
catch(Exception $err){
}
}
public function postMessageToGroup($message, $groupid){
$messageResponse = array(
'STATUS' => 0
);
$fbMessageObj = array(
"message" => strip_tags($message),
);
try
{
$user_page_post = $this->facebook->api("/$groupid/feed", 'POST', $fbMessageObj);
if($user_page_post && !empty($user_page_post['id'])){
$messageResponse['STATUS'] = 200;
$messageData = array(
'id' => $user_page_post['id'],
'link' => 'http://facebook.com/' . $user_page_post['id'],
);
$messageResponse['data'] = $messageData;
}
else{
$messageResponse['STATUS'] = 302;
}
}
catch(Exception $err){
$messageResponse['STATUS'] = 500;
$messageResponse['data'] = array($err);
}
return $messageResponse;
}
// TODO: should read a template somewhere
function show_login() {
$login_url = $this->facebook->getLoginUrl( array( 'scope' => implode(",",$this->permissions()) ));
return 'Login to Facebook and Grant Necessary Permissions';
}
// TODO: should read a template somewhere
public function toString()
{
if($this->hasAccess){
if($this->groups){
$msg = "";
$msg .= '<select name="group_id"><option value=""></option>';
foreach($this->groups as $group) {
$msg .= '<option value="' .
'' . urlencode($group['id']) .
'">' .
$group['name'] .
'</option>' .
'';
}
$msg .= '</select>';
return $msg;
}
else
return "No Groups";
}
else{
return $this->show_login();
}
}
function getGroupData(){
$raw = $this->facebook->api('/me/groups', 'GET');
$data = array();
if (null != $raw && array_key_exists('data', $raw))
return $raw['data'];
return null;
}
// check if current instance has access to facebook
function has_permissions() {
$user_id = #$this->facebook->getUser();
#print_r($user_id);
if($user_id == null) return false;
$permissions = $this->facebook->api("/me/permissions");
foreach($this->permissions() as $perm){
if( !array_key_exists($perm, $permissions['data'][0]) ) {
return false;
}
}
return true;
}
// permissins needed to post
function permissions(){
return array('manage_pages', 'user_groups');
}
}
$fb = new PostToFacebook();
$fb->initialise($config);
if(!$fb->has_permissions())
{
echo $fb->show_login();
}
else{
?>
<form method="post" action="test.php">
<textarea name='message'></textarea>
<?php echo $fb->toString(); ?>
<input type='submit'>
</form>
<?php
}
if(!empty($_POST)){
$response = $fb->postMessageToGroup($_POST['message'], $_POST['group_id']);
if($response['STATUS'] == 200)
print_r("<a href='" . $response['data']['link'] . "'>" . $response['data']['id'] ."</a>");
else
{
echo "ERROR!";
print_r($response);
}
}
?>