I need to use the functions of this class,I wrote a code but the output was empty,need echo data from all functions.
I correctly entered the connection requirements,script use Json-rpc for request,The port is open on the server
I don't know how to use this class
my class
<?php
require_once("jsonrpc.inc");
class IBSjsonrpcClient {
function IBSjsonrpcClient($server_ip="127.0.0.1", $auth_name="user", $auth_pass="pass", $auth_type="ADMIN", $server_port="1237", $timeout=1800){
$this->client = new jsonrpc_client($server_ip. ':' . $server_port);
$this->auth_name = $auth_name;
$this->auth_pass = $auth_pass;
$this->auth_type = $auth_type;
$this->timeout = $timeout;
}
function sendRequest($server_method, $params_arr){
/*
Send request to $server_method, with parameters $params_arr
$server_method: method to call ex admin.addNewAdmin
$params_arr: an array of parameters
*/
$params_arr["auth_name"] = $this->auth_name;
$params_arr["auth_pass"] = $this->auth_pass;
$params_arr["auth_type"] = $this->auth_type;
$response = $this->client->send($server_method, $params_arr, $this->timeout);
$result = $this->__returnResponse($response);
unset($response);
return $result;
}
function __returnResponse($response){
if ($response == FALSE)
return $this->__returnError("Error occured while connecting to server");
else if ($response->faultCode() != 0)
return $this->__returnError($response->faultString());
else
return $this->__returnSuccess($response->value());
}
function __returnError($err_str){
return array(FALSE, $err_str);
}
function __returnSuccess($value){
return array(TRUE, $value);
}
function getUserInfoByUserID($user_id){
return $this->sendRequest("user.getUserInfo", array("user_id"=>(string)$user_id));
}
function getUserInfoByNormalUserName($normal_username){
return $this->sendRequest("user.getUserInfo", array("normal_username"=>$normal_username));
}
function getBasicUserInfoByNormalUserName($normal_username){### for Zahedan Telecom, ticket 34083
$result = $this->sendRequest("user.getUserInfo", array("normal_username"=>$normal_username));
if(!$result[0]){
return $result;
}
$info = $result[1];
return array(
"user_id" => $info["basic_info"]["user_id"],
"normal_username" => $info["attrs"]["normal_username"],
"remaining_days" => $info["remaining_days"],
"remaining_mega_bytes" => $info["remaining_mega_bytes"],
"credit" => $info["basic_info"]["credit"],
"group_name" => $info["basic_info"]["group_name"]
);
}
function getUserInfoBySerial($serial){
return $this->sendRequest("user.getUserInfo", array("serial"=>$serial));
}
function addNewUser($count, $credit, $isp_name, $group_name, $credit_comment=""){
return $this->sendRequest("user.addNewUsers", array(
"count" => $count,
"credit" => $credit,
"isp_name" => $isp_name,
"group_name" => $group_name,
"credit_comment" => $credit_comment
));
}
function setNormalUserAuth($user_id, $username, $password){
return $this->setUserAttributes($user_id, array(
"normal_user_spec" => array(
"normal_username"=>$username,
"normal_password"=>$password,
)
));
}
}
?>
example code for use function in class but empty array
<?php
require "ibs-jsonrpc-client.php";
$ibs = new IBSjsonrpcClient();
$a = $ibs->getBasicUserInfoByNormalUserName("user1");
print_r($a);
?>
Related
I have a problem, I am currently doing a search by date range of maximum 10 days and the issue is that if there are more than 10 messages or there is a total of 38 messages it takes 4 to 5 minutes to load the data, so I wanted to know if there is a way to bring it paginated directly when doing the query in Horde.
public function connect($username, $password, $hostname, $port, $ssl, $folder, $debug = 0, $cache = 0)
{
$opt = [
'username' => $username,
'password' => $password,
'hostspec' => $hostname,
'port' => $port,
'secure' => $ssl,
];
if ($debug) $opt['debug'] = Log::debug("message");
if ($cache) $opt['cache'] = array(
'backend' => new \Horde_Imap_Client_Cache_Backend_Cache(array(
'cacheob' => new Horde_Cache(new Horde_Cache_Storage_File(array(
'dir' => '/tmp/hordecache'
)))
))
);
static::$folder = 'INBOX';
try {
return static::$client = new \Horde_Imap_Client_Socket($opt);
} catch (\Horde_Imap_Client_Exception $e) {
// Any errors will cause an Exception.
dd('Error');
}
}
public function searchSince($date_string)
{
try {
$query = new Horde_Imap_Client_Search_Query();
$query->dateSearch(
new Horde_Imap_Client_DateTime($date_string), Horde_Imap_Client_Search_Query::DATE_SINCE
);
$results = static::$client->search(static::$folder,$query);
} catch (\Exception $th) {
dd('Since Mail');
}
if ($results) {
static::$var = $results['match']->ids;
return true;
}
return false;
}
//I get the header data of each message (subject, date, uid, from, client name)
public function next(){
if ($var = next(static::$var)) {
static::$id = $var;
$headers = HordeImap::fetchHeaders(static::$id);
static::$clientName = $headers->getHeader('From')->getAddressList(true)->first()->__get('personal');
static::$fromEmail = $headers->getHeader('From')->getAddressList(true)->first()->__get('bare_address');
static::$subject = $headers->getHeader('subject')->__get('value');
$emailDate = $headers->getHeader('Date')->__get('value');
$unixTimestamp = strtotime($emailDate);
static::$emailDate = date('Y-m-d H:i:s',$unixTimestamp);
return true;
}
return false;
}
Controller
$mailb = new HordeImap();
$mailb->connect($userMail->client,$userMail->secret_token,$userMail->server,$userMail->port,'ssl','INDEX',1);
$msgs = $mailb->searchSince(date('d F Y', strtotime(date("Y-m-d", time()) . " -10 days")));
static::$mailbox = [];
if($msgs) while($mailb->next()){
static::$mailbox[] = [
'uid' => $mailb::$id,
'from' => $mailb::$fromEmail,
'client'=> $mailb::$clientName,
'date' => $mailb::$emailDate,
'subject'=> $mailb::$subject,
];
}
// I page the array once I have obtained all the contents.
$page = null;
$page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
$items = static::$mailbox instanceof Collection ? static::$mailbox : Collection::make(static::$mailbox);
dd(new LengthAwarePaginator($items->forPage($page, 5), $items->count(), 5, null, []));
I have this php script:
<?php
class Curl_Class {
private $endpointUrl;
private $userName;
private $userKey;
public $token;
public $errorMsg = '';
private $defaults = array(
CURLOPT_HEADER => 0,
CURLOPT_HTTPHEADER => array('Expect:'),
// CURLOPT_FRESH_CONNECT => 1,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_TIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_SSL_VERIFYHOST => 0
);
//constructor saves the values
function __construct($url, $name, $key) {
$this->endpointUrl=$url;
$this->userName=$name;
$this->userKey=$key;
$this->token=$key;
}
private function getChallenge() {
$curl_handler = curl_init();
$params = array("operation" => "getchallenge", "username" => $this->userName);
$options = array(CURLOPT_URL => $this->endpointUrl."?".http_build_query($params));
curl_setopt_array($curl_handler, ($this->defaults + $options));
$result = curl_exec($curl_handler);
if (!$result) {
$this->errorMsg = curl_error($curl_handler);
return false;
}
$jsonResponse = json_decode($result, true);
if($jsonResponse["success"]==false) {
$this->errorMsg = "getChallenge failed: ".$jsonResponse["error"]["message"]."<br>";
return false;
}
$challengeToken = $jsonResponse["result"]["token"];
return $challengeToken;
}
function login() {
$curl_handler = curl_init();
$token = $this->getChallenge();
//create md5 string containing user access key from my preference menu
//and the challenge token obtained from get challenge result
$generatedKey = md5($token.$this->userKey);
$params = array("operation" => "login", "username" => $this->userName, "accessKey" => $generatedKey);
$options = array(CURLOPT_URL => $this->endpointUrl, CURLOPT_POST => 1, CURLOPT_POSTFIELDS => http_build_query($params));
curl_setopt_array($curl_handler, ($this->defaults + $options));
$result = curl_exec($curl_handler);
if (!$result) {
$this->errorMsg = curl_error($curl_handler);
return false;
}
$jsonResponse = json_decode($result, true);
if($jsonResponse["success"]==false) {
$this->errorMsg = "Login failed: ".$jsonResponse["error"]["message"]."<br>";
return false;
}
$sessionId = $jsonResponse["result"]["sessionName"];
//save session id
$this->token=$sessionId;
return true;
}
private function handleReturn($result, $name, $curl_handler) {
if (!$result) {
$this->errorMsg = curl_error($curl_handler);
return false;
}
$jsonResponse = json_decode($result, true);
if (!$jsonResponse) {
$this->errorMsg = "$name failed: ".$result."<br>";
return false;
}
if($jsonResponse["success"]==false) {
$this->errorMsg = "$name failed: ".$jsonResponse["error"]["message"]."<br>";
return false;
}
return $jsonResponse["result"];
}
public function operation($name, $params, $type = "GET", $filepath = '') {
$params = array_merge(array("operation" => $name, "sessionName" => $this->token), $params);
if (strtolower($type) == "post") {
$options = array(CURLOPT_URL => $this->endpointUrl, CURLOPT_POST => 1, CURLOPT_POSTFIELDS => http_build_query($params));
}
else {
$options = array(CURLOPT_URL => $this->endpointUrl."?".http_build_query($params));
}
if ($filepath != '' && strtolower($type) == "post") {
$element = $params['element'];
if (!empty($element)) {
$element = json_decode($element, true);
}
if (isset($element['filename'])) {
$filename = $element['filename'];
}
else {
$filename = pathinfo($filepath, PATHINFO_BASENAME);
}
$size = filesize($filepath);
$add_options = array(CURLOPT_HTTPHEADER => array("Content-Type: multipart/form-data"), CURLOPT_INFILESIZE => $size);
if (function_exists("mime_content_type")) {
$type = mime_content_type($filepath);
}
elseif (isset($element['filetype'])) {
$type = $element['filetype'];
}
else {
$type = '';
}
if (!function_exists('curl_file_create')) {
$add_params = array("filename" => "#$filepath;type=$type;filename=$filename");
}
else {
$cfile = curl_file_create($filepath, $type, $filename);
$add_params = array('filename' => $cfile);
}
$options += $add_options;
$options[CURLOPT_POSTFIELDS] = $params + $add_params;
}
$curl_handler = curl_init();
curl_setopt_array($curl_handler, ($this->defaults + $options));
$result = curl_exec($curl_handler);
return $this->handleReturn($result, $name, $curl_handler);
}
}
?>
I'm learning programming so i'm in no way good at this.. I need to execute the function login() of this class from a url, giving in input the parameters (private $endpointUrl,private $userName,private $userKey) and receiving in output the $sessionId.
So, for example, i'll write in the url
https://webserver.com/Login.php? endpointUrl=1&username=2&userKey=3
and receiving in output the $sessionId.
Is it possible? How? Thanks!
Here's some example;
if(isset($_GET["endpointUrl"], $_GET["username"], $_GET["userKey"])){
$x = new Curl_Class($_GET["endpointUrl"], $_GET["username"], $_GET["userKey"]);
if($x->login()){
echo $x->token;
}
}
Better if serialize the GET input for security purposes. But in this example, just a simple call of login.
Since the login() method returning boolean, so from there we can know if the token created or not.
Recently I try to create an API with PHP. all thing goes alright till suddenly I face unexpected 'a' error when trying to parse a JSON from the request throw Postman. I found something related to my issue but there is no solution in my case here : link
I send
{
"teacher_code":"sas"
}
JSON to teachers.php file to assign a student to the teacher
here is the teacher.php file content :
require_once ("classes/Rest.php");
require_once ("classes/api.php");
$api = new Api();
if($api->getHttpmethod() === 'POST'){
$api->validateParameter('teacher_code' ,$teacher_code = $api->getParam('teacher_code') , STRING , true);
$api->checkUserAccessablity();
$api->teacherCodeinRange($teacher_code);
$query = "INSERT INTO `group_users` (`user_id`,`group_id` )
VALUES (:user_id , (SELECT group_id FROM `groups` WHERE group_name = 'all' AND user_id =
(SELECT user_id FROM `teachers` WHERE t_code = :teacher_code)) )";
$keyValue = [
"user_id" => $api->getUserid() ,
"teacher_code" => $teacher_code
];
$result = $api->queryExecute($query , $keyValue );
$api->returnResponse(SUCCESS , SUCCESS_MESSAGE);
}
and api.php file :
require_once ("dbConnect.php");
require_once ("JWT.php");
class Api extends Rest
{
public $dbConn;
private $userId;
public function __construct()
{
parent::__construct();
$db = new dbConnect();
$this->dbConn = $db->connect();
}
public function setUserid($id){
$this->userId = $id;
}
public function getUserid(){
return $this->userId;
}
public function checkUserAccessablity(){
$payload = $this->deCodetoken();
$this->setUserid($payload->user_id);
$this->validateUser();
}
public function validateUser(){
$query = "SELECT * FROM `users` WHERE user_id = :id";
$keyValue = [
"id" => $this->getUserid()
];
$result = $this->queryExecute($query , $keyValue,true );
if(!$result){
$this->throwError(SYSTEM_ERROR , SYSTEM_ERROR_MESSAGE );
}
if(!is_array($result)){
$this->throwError(USER_NOT_FOUND_CODE , USER_NOT_FOUND_MESSAGE . $this->getUserid());
}
//TODO CHECK USER ACTIVE
return true;
}
public function teacherCodeinRange($tCode){
$query = "SELECT * FROM `teachers` INNER JOIN `licenses` ON (licenses.user_id = teachers.user_id)
WHERE teachers.t_code = :tcode LIMIT 1";
$keyValue = [
"tcode" => $tCode
];
$this->queryExecute($query , $keyValue,true );
return true;
}
public function teacherCodeinStudentrange($teacherID){
//TODO SELECT TEACHER STUDENT RANGE
$query = "SELECT DISTICT user_id FROM `teachers` INNER JOIN `groups` ON (groups.user_id = teachers.user_id)
INNER JOIN `group_users` ON (group_users.group_id = groups.group_id)
WHERE teachers.user_id = :teacherID AND groups.group_name = 'all' AND group_users.user_id = :userID ";
$keyValue = [
"userID" => $this->getUserid(),
"teacherID" => $teacherID,
];
$result = $this->queryExecute($query , $keyValue,true );
if(!is_array($result)){
$this->throwError(TEACHER_NOT_FOUND , TEACHER_NOT_FOUND_MESSAGE);
}
return true;
}
public function getHttpmethod(){
return $this->HttpMethod;
}
public function getParam($key){
return $this->arrayFinddeep($this->data , $key);
}
public function queryExecute($query , $keyArray , $isSelect = false){
$queryExec = $this->dbConn->prepare($query);
if(is_array($keyArray) || !empty($keyArray)) {
foreach ($keyArray as $key => &$value) {
$queryExec->bindParam(':' . $key, $value);
}
}
if($isSelect) {
$queryExec->execute();
$result = $queryExec->fetch(PDO::FETCH_ASSOC);
}else {
$result = $queryExec->execute();
}
return $result;
}
public function getLastuserId(){
return $this->dbConn->lastInsertId();
}
public function generateToken($payload , $secretKey){
try{
return \Firebase\JWT\JWT::encode($payload , $secretKey);
}catch (Exception $exception){
$this->throwError(JWT_PROCESSING_ERROR , $exception->getMessage());
}
}
public function deCodetoken(){
try{
$token = $this->getBearerToken();
$payload = \Firebase\JWT\JWT::decode($token , SECURITY_KEY , ['HS256']);
return $payload;
}catch (Exception $exception){
$this->throwError(ACCESS_TOKEN_ERROR , $exception->getMessage());
}
}
}
and the last class is Rest.php :
require_once ("Constans.php");
class Rest
{
protected $HttpMethod;
protected $request;
protected $data;
public function __construct(){
$this->HttpMethod = $_SERVER['REQUEST_METHOD'];
if($this->checkValidhttpMethod()) {
try{
$handler = fopen('php://input', 'r');
$this->request = stream_get_contents($handler);
}catch (Exception $exception){
//TODO HANDLE EXEPTION
}
$this->validateRequest();
}
}
public function checkValidhttpMethod(){
if(empty($this->HttpMethod) or !in_array($this->HttpMethod,ACCEPTABLE_HTTP_METHOD)){
$this->throwError(NOT_VALID_HTTP_METHOD,NOT_VALID_HTTP_METHOD_Message);
}
return true;
}
public function setJsonheader(){
header("content-type: application/json");
}
public function validateRequest(){
if($_SERVER['CONTENT_TYPE'] !== 'application/json'){
$this->throwError(REQUEST_CONTENT_NOT_VALID , REQUEST_CONTENT_NOT_VALID_MESSAGE);
}
try{
$this->data = json_decode($this->request , true);
}catch (Exception $exception){
//TODO HANDLE EXEPTION
}
}
public function processAPI(){
}
public function throwError($code , $message){
$this->setJsonheader();
echo json_encode(['error' => ['status' => $code , 'message' => $message]]);
exit;
}
public function returnResponse($code , $data){
$this->setJsonheader();
echo json_encode(['response' => ['status' => $code , 'result' => $data ]]);
exit;
}
//TODO SQL injection Validate
public function validateParameter($fieldName , $value , $dataType , $required = true){
if($required && empty($value)){
$this->throwError(PARAMETR_REQUIRED,PARAMETR_REQUIRED_MESSAGE . $fieldName);
}
//TODO SQL injection
//TODO CHECK The All Data Type
switch ($dataType){
case BOOLEAN :
if(!is_bool($value)){
$this->throwError(PARAMETR_DATA_TYPE_NOT_VALID , PARAMETR_DATA_TYPE_NOT_VALID_MESSAGE . $fieldName);
}
break;
case INTEGER :
if(!is_numeric($value)){
$this->throwError(PARAMETR_DATA_TYPE_NOT_VALID , PARAMETR_DATA_TYPE_NOT_VALID_MESSAGE . $fieldName);
}
break;
case STRING :
if(!is_string($value)){
$this->throwError(PARAMETR_DATA_TYPE_NOT_VALID , PARAMETR_DATA_TYPE_NOT_VALID_MESSAGE . $fieldName);
}
break;
case DONT_CARE :
break;
default:
break;
}
return $value;
}
public function arrayFinddeep($array, $search)
{
foreach($array as $key => $value) {
if (is_array($value)) {
$sub = $this->arrayFinddeep($value, $search);
if (count($sub)) {
return $sub;
}
} elseif ($key === $search) {
return $value;
}
}
return array();
}
/**
* Get hearder Authorization
* */
function getAuthorizationHeader(){
$headers = null;
if (isset($_SERVER['Authorization'])) {
$headers = trim($_SERVER["Authorization"]);
}
else if (isset($_SERVER['HTTP_AUTHORIZATION'])) { //Nginx or fast CGI
$headers = trim($_SERVER["HTTP_AUTHORIZATION"]);
} elseif (function_exists('apache_request_headers')) {
$requestHeaders = apache_request_headers();
// Server-side fix for bug in old Android versions (a nice side-effect of this fix means we don't care about capitalization for Authorization)
$requestHeaders = array_combine(array_map('ucwords', array_keys($requestHeaders)), array_values($requestHeaders));
//print_r($requestHeaders);
if (isset($requestHeaders['Authorization'])) {
$headers = trim($requestHeaders['Authorization']);
}
}
return $headers;
}
/**
* get access token from header
* */
function getBearerToken() {
$headers = $this->getAuthorizationHeader();
// HEADER: Get the access token from the header
if (!empty($headers)) {
if (preg_match('/Bearer\s(\S+)/', $headers, $matches)) {
return $matches[1];
}
}
$this->throwError(AUTHORIZATION_HEADER_NOT_FOUND , AUTHORIZATION_HEADER_NOT_FOUND_MESSAGE);
}
}
all queries go along queryExecute function in api.php class and recently I got that the bindParam function is not going to work fine too.
I really don't have any idea where the problem is, as In the reference said its somehow related to DB queries result. I try to use mysqli also but it did not work.
any help will be appreciated :-)
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;
}
}
Can someone please help me, I get this fatal error message when I try to run the code in a browser. I have searched through various topics and couldn't find the answer. I have two very similar functions and only one of them is reporting an error. Function getById is working just fine, but function get reports an error. Here's my db.php file:
class DB {
private $db;
public $limit = 5;
public function __construct($config){
$this->connect($config);
}
private function connect($config){
try{
if ( !class_exists('Mongo')){
echo ("The MongoDB PECL extension has not been installed or enabled");
return false;
}
$connection= new MongoClient($config['connection_string'],array('username'=>$config['username'],'password'=>$config['password']));
return $this->db = $connection->selectDB($config['dbname']);
}catch(Exception $e) {
return false;
}
}
public function create($collection,$article){
$table = $this->db->selectCollection($collection);
return $result = $table->insert($article);
}
public function get($page,$collection){
$currentPage = $page;
$articlesPerPage = $this->limit;
//number of article to skip from beginning
$skip = ($currentPage - 1) * $articlesPerPage;
$table = $this->db->selectCollection($collection); **//here reports an error**
$cursor = $table->find();
//total number of articles in database
$totalArticles = $cursor->count();
//total number of pages to display
$totalPages = (int) ceil($totalArticles / $articlesPerPage);
$cursor->sort(array('saved_at' => -1))->skip($skip)->limit($articlesPerPage);
//$cursor = iterator_to_array($cursor);
$data=array($currentPage,$totalPages,$cursor);
return $data;
}
public function getById($id,$collection){
// Convert strings of right length to MongoID
if (strlen($id) == 24){
$id = new MongoId($id);
}
$table = $this->db->selectCollection($collection);
$cursor = $table->find(array('_id' => $id));
$article = $cursor->getNext();
if (!$article ){
return false ;
}
return $article;
}
public function delete($id,$collection){
// Convert strings of right length to MongoID
if (strlen($id) == 24){
$id = new \MongoId($id);
}
$table = $this->db->selectCollection($collection);
$result = $table->remove(array('_id'=>$id));
if (!$id){
return false;
}
return $result;
}
public function update($id,$collection,$article){
// Convert strings of right length to MongoID
if (strlen($id) == 24){
$id = new \MongoId($id);
}
$table = $this->db->selectCollection($collection);
$result = $table->update(
array('_id' => new \MongoId($id)),
array('$set' => $article)
);
if (!$id){
return false;
}
return $result;
}
public function commentId($id,$collection,$comment){
$postCollection = $this->db->selectCollection($collection);
$post = $postCollection->findOne(array('_id' => new \MongoId($id)));
if (isset($post['comments'])) {
$comments = $post['comments'];
}else{
$comments = array();
}
array_push($comments, $comment);
return $postCollection->update(
array('_id' => new \MongoId($id)),
array('$set' => array('comments' => $comments))
);
}
}