Cannot redeclare class JSONParserException - php

This is my code,
which always produce error when "new Entity\UserAds($array);" is added
Entities are present in "models\Entity\" folder
use Entity\UserAds;
use Entity\Comment;
class postad extends CI_Controller {
protected $view_data;
public function __construct() {
parent::__construct ();
$this->load->helper ( array (
'form',
'url'
) );
$this->load->library ( 'form_validation' );
// view data
}
public function index() {
if ($this->form_validation->run() == FALSE) {
$this->view_data ['content'] = 'contents/postads';
$this->load->view ( 'templates/layout', $this->view_data );
} else {
$array = $this->input->post ();
try {
$ads = UserAds::createFromPost($array );
$this->em = $this->doctrine->em;
//$repository = $this->em->getRepository ( 'Entity\User' );
$this->em->persist ( $ads );
$this->em->flush ();
$this->session->set_flashdata ( 'err_msg', "" );
$this->log ( "create_post() created new ads." );
$this->view_data['count']=$this->input->post('count');
$this->view_data ['result'] = $ads;
$adid=$ads->getId();
$ads->getImages();
$this->session->set_userdata('id',$adid);
$this->load->model("emailmodel");
$this->emailmodel->send_notification($ads->getEmail(),$adid,$ads->getTitle());
if($this->session->userdata("username")==""){
/*new block added from */
$array = array ();
$name=$array ['name'] = $ads->getName();
$mobile=$array ['mobile'] = $ads->getMobile();
$array ['email'] =$ads->getEmail();
$array ['password'] = '12345';
$array ['dob'] = DateTime::createFromFormat ( "d/m/Y", '');
$array ['everified'] = 0;
$array ['mverified'] = 0;
$array ['devicetype'] = 0;
$array ['usertype'] = 0;
$user = new Entity\User ( $array );
$this->em->persist ( $user );
$this->em->flush (); //till this
$this->load->model ( 'homemodel' );
$randstr = $this->homemodel->rand_string ( $name, $mobile );
$this->load->model ( 'emailmodel' );
$email =$ads->getEmail();
$randstr = $this->emailmodel->getmailcode ( $email );
$this->emailmodel->sendVerificatinEmail ( $email, $randstr );
}
$this->view_data ['content'] = 'contents/adcreated';
$this->load->view ( 'templates/layout', $this->view_data );
} catch ( Exception $e ) {
$this->error ( "createAds(): creation faield." . $e->getMessage () );
$this->session->set_flashdata ( 'err_msg', "Failed to post ad" . $e->getMessage () );
$this->view_data ['content'] = 'contents/postads';
$this->load->view ( 'templates/layout', $this->view_data );
}
}
}
This is my error message:
Cannot redeclare class JSONParserException in C:\wamp\www\rah\application\core\JSONParserException.php on line 12

Related

how to link return in the callback to Codeigniter Model return

can i get model Return Value?
use Web3.php callback in the Codeigniter Model.
I tried it, but it was empty.
how to link return in the callback to CI Model return.
1.Model
use Web3\Web3;
use Web3\Contract;
use Web3\Providers\HttpProvider;
use Web3\RequestManagers\HttpRequestManager;
class Dapps_model extends CI_Model {
public function getItemFromDapps( $item_id ){
$at = "0xMYDAPPSADDRESS";
$json = file_get_contents( APPPATH . "/config/abi.json" , FALSE );
$json = json_decode( $json , TRUE );
$abi = json_encode( $json["abi"] );
$provider = new HttpProvider( new HttpRequestManager('https://ropsten.infura.io/MYAPIKEY') );
$contract = new Contract( $provider , $abi );
$contract->at( $at );
$contract->call( "getItemInfo" , $item_id , function( $err, $item ){
if ( $err !== null ) {
var_dump( $err->getMessage() );
exit;
}
// var_dump( $item ); Data exists.
return $item;
});
}
2.Controller
$item = $this->Dapps_model->getItemFromDapps( 2 );
var_dump( $item ) is Null
Add
I was able to get the Model return value on the Controller.
With Oluwafemi help.
Is this correct use?
$returnData = null;
$contract->call( "getItemInfo" , $item_id , function( $err, $item ) use ( &$returnData ){
if ( $err !== null ) {
var_dump( $err->getMessage() );
exit;
}
// var_dump( $item ); Data exists.
//return $item;
$returnData = $item;
});
return $returnData;

Insert Ads after X paragraph php

Hi im try to use a class to insert adsense blocks after x numbers of paragraph etc.
its works with regular text, but dont works with adsense codes.
the full code is HERE
<?php
namespace keesiemeijer\Insert_Content;
function insert_content( $content, $insert_content = '', $args = array() ) {
$args = array_merge( get_defaults(), (array) $args );
if ( empty( $insert_content ) ) {
return $content;
}
// Validate arguments
$args['parent_element_id'] = trim( (string) $args['parent_element_id'] );
$args['insert_element'] = trim( (string) $args['insert_element'] );
$args['insert_element'] = $args['insert_element'] ? $args['insert_element'] : 'p';
$args['insert_after_p'] = abs( intval( $args['insert_after_p'] ) );
$parent_element = false;
// Content wrapped in the parent HTML element (to be inserted).
$insert_content = "<{$args['insert_element']}>{$insert_content}</{$args['insert_element']}>";
$nodes = new \DOMDocument();
// Load the HTML nodes from the content.
#$nodes->loadHTML( $content );
if ( $args['parent_element_id'] ) {
$parent_element = $nodes->getElementById( $args['parent_element_id'] );
if ( !$parent_element ) {
// Parent element not found.
return $content;
}
// Get all paragraphs from the parent element.
$p = $parent_element->getElementsByTagName( 'p' );
} else {
// Get all paragraphs from the content.
$p = $nodes->getElementsByTagName( 'p' );
}
$insert_nodes = new \DOMDocument();
#$insert_nodes->loadHTML( $insert_content );
$insert_element = $insert_nodes->getElementsByTagName( $args['insert_element'] )->item( 0 );
if ( !$insert_element ) {
return $content;
}
// Get paragraph indexes
$nodelist = get_node_indexes( $p, $args );
// Check if paragraphs are found.
if ( !empty( $nodelist ) ) {
$insert_index = get_item_index( $nodelist, $args );
if ( false === $insert_index ) {
return $content;
}
// Insert content after this (paragraph) node.
$insert_node = $p->item( $insert_index );
// Insert the nodes
insert_content_element( $nodes, $insert_node, $insert_element );
$html = get_HTML( $nodes );
if ( $html ) {
$content = $html;
}
} else {
// No paragraphs found.
if ( (bool) $args['insert_if_no_p'] ) {
if ( $parent_element ) {
// Insert content after parent element.
insert_content_element( $nodes, $parent_element, $insert_element );
$html = get_HTML( $nodes );
if ( $html ) {
$content = $html;
}
} else {
// Add insert content after the content/
$content .= $insert_content;
}
}
}
return $content;
}
/**
* Get default arguments.
*
* #return array Array with default arguments.
*/
function get_defaults() {
return array(
'parent_element_id' => '',
'insert_element' => 'p',
'insert_after_p' => '',
'insert_if_no_p' => true,
'top_level_p_only' => true,
);
}
function get_node_indexes( $nodes, $args ) {
$args = array_merge( get_defaults(), (array) $args );
$nodelist = array();
$length = isset( $nodes->length ) ? $nodes->length : 0;
$parent_id = trim( $args['parent_element_id'] );
for ( $i = 0; $i < $length; ++$i ) {
$nodelist[ $i ] = $i;
$parent = false;
$node = $nodes->item( $i );
if ( $parent_id ) {
if ( $node->parentNode->hasAttribute( 'id' ) ) {
$parent_id_attr = $node->parentNode->getAttribute( 'id' );
$parent = ( $parent_id === $parent_id_attr );
}
} else {
$parent = ( 'body' === $node->parentNode->nodeName );
}
if ( (bool) $args['top_level_p_only'] && !$parent ) {
// Remove nested paragraphs from the list.
unset( $nodelist[ $i ] );
}
}
return array_values( $nodelist );
}
function get_item_index( $nodelist, $args ) {
if ( empty( $nodelist ) ) {
return false;
}
$args = array_merge( get_defaults(), (array) $args );
$count = count( $nodelist );
$insert_index = abs( intval( $args['insert_after_p'] ) );
end( $nodelist );
$last = key( $nodelist );
reset( $nodelist );
if ( !$insert_index ) {
if ( 1 < $count ) {
// More than one paragraph found.
// Get middle position to insert the HTML.
$insert_index = $nodelist[ floor( $count / 2 ) -1 ];
} else {
// One paragraph
$insert_index = $last;
}
} else {
// start counting at 0.
--$insert_index;
--$count;
if ( $insert_index > $count ) {
if ( (bool) $args['insert_if_no_p'] ) {
// insert after last paragraph.
$insert_index = $last;
} else {
return false;
}
}
}
return $nodelist[ $insert_index ];
}
/**
* Insert an element (and it's child elements) in the content.
*
* #param object $nodes DOMNodeList instance containing all nodes.
* #param object $insert_node DOMElement object to insert nodes after
* #param object $insert DOMElement object to insert
* #return void
*/
function insert_content_element( $nodes, $insert_node, $insert_element ) {
$next_sibling = isset( $insert_node->nextSibling ) ? $insert_node->nextSibling : false;
if ( $next_sibling ) {
// get sibling element (exluding text nodes and whitespace).
$next_sibling = nextElementSibling( $insert_node );
}
if ( $next_sibling ) {
// Insert before next sibling.
$next_sibling->parentNode->insertBefore( $nodes->importNode( $insert_element, true ), $next_sibling );
} else {
// Insert as child of parent element.
$insert_node->parentNode->appendChild( $nodes->importNode( $insert_element, true ) );
}
}
function nextElementSibling( $node ) {
while ( $node && ( $node = $node->nextSibling ) ) {
if ( $node instanceof \DOMElement ) {
break;
}
}
return $node;
}
function get_HTML( $nodes ) {
$body_node = $nodes->getElementsByTagName( 'body' )->item( 0 );
if ( $body_node ) {
// Convert nodes from the body element to a string containing HTML.
$content = $nodes->saveHTML( $body_node );
// Remove first body element only.
$replace_count = 1;
return str_replace( array( '<body>', '</body>' ) , array( '', '' ), $content, $replace_count );
}
return '';
}
to call the function
$args = array(
'insert_after_p' => 3, // Insert after the second paragraph
);
echo keesiemeijer\Insert_Content\insert_content($content, $insert_content, $args );

PHP class providing empty object

My index.php page had this code that defaults the user to the homepage.
<?php
require_once ( "config.php" );
$action = isset( $_GET['action'] ) ? $_GET['action'] : "";
switch ( $action ) {
case 'seeAll':
seeAll();
break;
case 'viewResource':
viewResource();
break;
default:
homepage();
}
function homepage() {
$results = array();
$learnData = Resource::getHomePageTiles( 'learn' );
$practiceData = Resource::getHomePageTiles( 'practice' );
$elseData = Resource::getHomePageTiles( 'else' );
$results['learn'] = $learnData;
$results['practice'] = $practiceData;
$results['else'] = $elseData;
$results['pageTitle'] = "Couch To Code";
require_once ( "templates/homepage.php" );
}
Which calls the getHomePageTiles method of my Resource class.
Here is the code for the Resource class and getHomePageTiles method.
class Resource {
public $id = null;
public $title = null;
public $summary= null;
public $url = null;
public $content = null;
public $category = null;
public $is_free = null; //????
public $is_featured = null;
public $is_favorite = null;
public $date_created = null;
public function __construct( $data ) {
if ( isset ( $data['id'] ) ) $this->id = (int) $data['id'];
if ( isset ( $data['title'] ) ) $this->title = $data['title'];
if ( isset ( $data['summary'] ) ) $this->summary = $data['summary'];
if ( isset ( $data['url'] ) ) $this->url = $data['url'];
if ( isset ( $data['content'] ) ) $this->content = $data['content'];
if ( isset ( $data['category'] ) ) $this->category = $data['category'];
if ( isset ( $data['is_free'] ) ) $this->is_free = (int) $data['is_free'];
if ( isset ( $data['is_featured'] ) ) $this->is_featured = (int) $data['is_featured'];
if ( isset ( $data['is_favorite'] ) ) $this->is_favorite = (int) $data['is_favorite'];
if ( isset ( $data['date_created'] ) ) $this->date_created = date("Y-m-d H:i:s");
}
public static function getHomePageTiles( $type ) {
global $DB_HOST;
global $DB_NAME;
global $DB_USERNAME;
global $DB_PASSWORD;
$conn = new mysqli( $DB_HOST, $DB_USERNAME, $DB_PASSWORD, $DB_NAME );
if (mysqli_connect_errno()) {
printf("Connection to the database failed: %s/n", $mysqli -> connect_error);
exit();
}
$sql = "SELECT * FROM resources WHERE category = ? ORDER BY position ASC LIMIT 4;";
if ($st = $conn->prepare( $sql )) {
$st->bind_param( "s", $type );
$st->execute();
$list = array();
while ( $row = $st->fetch() ) {
$resource = new Resource( $row );
$list[] = $resource;
}
$conn = null;
return $list;
} else {
printf("Errormessage: %s\n", $conn->error);
}
}
My Homepage.php file has the following code in it
<?php
foreach ( $results['learn'] as $learnTile ) {
print_r($learnTile);
?>
<div class="col-md-3 col-xs-6 featured">
<a href=".?action=viewResource&resourceId= <?php echo($learnTile->id)?> ">
<img src="#" class="thumbnail img-responsive">
</a>
</div>
<?php } ?>
The code is pulling the correct number of Resource objects, but something is going wring, because my link (in homepage.php) is not pulling in the id from the Resource object.
So, to debug i've printed out ($learnTile) and am getting empty objects/arrays.
Resource Object ( [id] => [title] => [summary] => [url] => [content] => [category] => [is_free] => [is_featured] => [is_favorite] => [date_created] => ) Resource Object ( [id] => [title] => [summary] => [url] => [content] ...
Where am I going wrong? is my constructor not working? Clearly the Resource objects are pulling the null values from the original property definitions to null.
I've been stumped on this one for several days so any help / guidance is appreciated. Thanks!
There is never an array inside the $row. See the manual: php.net/manual/en/mysqli-stmt.fetch.php it returns a boolean only. You should bind your result when using prepare.

Set session in Invision Power Board

After lots of efforts we found something for IPB remote login, but it's not working correctly. We are able to fetch member information but not able to set this member in session.
Please help us to the set session for IPB.
Here is the code:
remote_login.php
<?php
$_SERVER['SCRIPT_FILENAME'] = __FILE__;
$path = '';
require_once $path . 'init.php';
\IPS\Session\Front::i();
$key = md5( md5( \IPS\Settings::i()->sql_user . \IPS\Settings::i()->sql_pass ) . \IPS\Settings::i()->board_start );
$login_type = 'email';
/* uncomment for more security */
// $ip_address = array('127.0.0.1', 'x.x.x.x'); // EDIT THIS LINE!!
// if(in_array($_SERVER['REMOTE_ADDR'], $ip_address) !== TRUE) {
// echo_json(array('status' => 'FAILD', 'msg' => 'BAD_IP_ADDR'));
// }
/* -~-~-~-~-~-~ Stop Editing -~-~-~-~-~-~ */
if( !\IPS\Request::i()->do || !\IPS\Request::i()->id || !\IPS\Request::i()->key || !\IPS\Login::compareHashes( \IPS\Request::i()->key, md5($key . \IPS\Request::i()->id))) {
echo_json(array('status' => 'FAILD', 'msg' => 'BAD_KEY'));
}
$member = \IPS\Member::load( \IPS\Request::i()->id, $login_type );
if( !$member->member_id ) {
echo_json(array('status' => 'FAILD', 'msg' => 'ACCOUNT_NOT_FOUND'));
}
switch(\IPS\Request::i()->do) {
case 'get_salt':
echo_json(array('status' => 'SUCCESS', 'pass_salt' => $member->members_pass_salt));
break;
case 'login':
if( \IPS\Login::compareHashes($member->members_pass_hash, \IPS\Request::i()->password) === TRUE ) {
/* Remove old failed login attempts */
if ( \IPS\Settings::i()->ipb_bruteforce_period and ( \IPS\Settings::i()->ipb_bruteforce_unlock or !isset( $member->failed_logins[ \IPS\Request::i()->ipAddress() ] ) or $member->failed_logins[ \IPS\Request::i()->ipAddress() ] < \IPS\Settings::i()->ipb_bruteforce_attempts ) )
{
$removeLoginsOlderThan = \IPS\DateTime::create()->sub( new \DateInterval( 'PT' . \IPS\Settings::i()->ipb_bruteforce_period . 'M' ) );
$failedLogins = $member->failed_logins;
if ( is_array( $failedLogins ) )
{
foreach ( $failedLogins as $ipAddress => $times )
{
foreach ( $times as $k => $v )
{
if ( $v < $removeLoginsOlderThan->getTimestamp() )
{
unset( $failedLogins[ $ipAddress ][ $k ] );
}
}
}
$member->failed_logins = $failedLogins;
}
else
{
$member->failed_logins = array();
}
$member->save();
}
/* If we're still here, the login was fine, so we can reset the count and process login */
if ( isset( $member->failed_logins[ \IPS\Request::i()->ipAddress() ] ) )
{
$failedLogins = $member->failed_logins;
unset( $failedLogins[ \IPS\Request::i()->ipAddress() ] );
$member->failed_logins = $failedLogins;
}
$member->last_visit = time();
$member->save();
/*==========================try to set session code start================*/
/* Create a unique session key and redirect */
\IPS\Session::i()->setMember( $member );
$expire = new \IPS\DateTime;
$expire->add( new \DateInterval( 'P7D' ) );
\IPS\Request::i()->setCookie( 'member_id', $member->member_id, $expire );
\IPS\Request::i()->setCookie( 'pass_hash', $member->member_login_key, $expire );
if ( $anonymous and !\IPS\Settings::i()->disable_anonymous )
{
\IPS\Request::i()->setCookie( 'anon_login', 1, $expire );
}
\IPS\Session::i()->setMember( $member );
\IPS\Session::i()->init();
\IPS\Request::i()->setCookie( 'ips4_member_id', $member->member_id, $expire );
\IPS\Request::i()->setCookie( 'ips4_pass_hash', $member->member_login_key, $expire );
/*$member->checkLoginKey();
$expire = new \IPS\DateTime;
$expire->add( new \DateInterval( 'P1Y' ) );
\IPS\Request::i()->setCookie( 'ips4_member_id', $member->member_id, $expire );
\IPS\Request::i()->setCookie( 'ips4_pass_hash', $member->member_login_key, $expire );*/
/*==========================try to set session code end================*/
echo_json(
array(
'status' => 'SUCCESS',
'connect_status' => ( $member->members_bitoptions['validating'] ) ? 'VALIDATING' : 'SUCCESS',
'email' => $member->email,
'name' => $member->name,
'connect_id' => $member->member_id,
'member' =>$member
)
);
}
break;
}
function echo_json(array $arr) {
echo json_encode($arr);
exit;
}
login.php
<?php
$ips_connect_key = '3325a51154becfc88fXXXXXXXXX';
$remote_login = 'IPB/remote_login.php';
$email = $_GET['email'];
$password = $_GET['password'];
$key = md5($ips_connect_key . $email);
// fetch salt first
$res = json_decode(file_get_contents($remote_login . "?do=get_salt&id={$email}&key={$key}"), true);
$hash = crypt( $password, '$2a$13$' . $res['pass_salt'] );
$res = json_decode(file_get_contents($remote_login . "?do=login&id={$email}&key={$key}&password={$hash}"), true);
$_COOKIE["ips4_member_id"]=41;
$_COOKIE['ips4_pass_hash']="e195d3939b62342481dfc32fcf360538";
$_COOKIE['ips4_IPSSessionFront']="sn359rogbto4j7jqhcqh10stl5";
print_r($res);
echo "<br/><br/><br/>";
print_r($_COOKIE);
calling login.php
login.php?email=XXXXX#gmail.com&password=XXXXXX!
Here we are able to get member information but not able to set that member as logged in.

Get Inner HTML - PHP

I have the following code:
$data = file_get_contents('http://www.robotevents.com/robot-competitions/vex-robotics-competition?limit=all');
echo "Downloaded";
$dom = new domDocument;
#$dom->loadHTML($data);
$dom->preserveWhiteSpace = false;
$tables = $dom->getElementsByTagName('table');
$rows = $tables->item(2)->getElementsByTagName('tr');
foreach ($rows as $row) {
$cols = $row->getElementsByTagName('td');
for ($i = 0; $i < $cols->length; $i++) {
echo $cols->item($i)->nodeValue . "\n";
}
}
The final field has an Link which I need to store the URL of. Also, The script outputs characters such as "Â". Does anyone know how to do/fix these things?
I would recommend not using DOM to parse HTML, as it has problems with invalid HTML. INstead use regular expression
I use this class:
<?php
/**
* Class to return HTML elements from a HTML document
* #version 0.3.1
*/
class HTMLQuery
{
protected $selfClosingTags = array( 'area', 'base', 'br', 'hr', 'img', 'input', 'link', 'meta', 'param' );
private $html;
function __construct( $html = false )
{
if( $html !== false )
$this->load( $html );
}
/**
* Load a HTML string
*/
public function load( $html )
{
$this->html = $html;
}
/**
* Returns elements from the HTML
*/
public function getElements( $element, $attribute_match = false, $value_match = false )
{
if( in_array( $element, $this->selfClosingTags ) )
preg_match_all( "/<$element *(.*)*\/>/isU", $this->html, $matches );
else
preg_match_all( "/<$element(.*)>(.*)<\/$element>/isU", $this->html, $matches );
if( $matches )
{
#Create an array of matched elements with attributes and content
foreach( $matches[0] as $key => $el )
{
$current_el = array( 'name' => $element );
$attributes = $this->parseAttributes( $matches[1][$key] );
if( $attributes )
$current_el['attributes'] = $attributes;
if( $matches[2][$key] )
$current_el['content'] = $matches[2][$key];
$elements[] = $current_el;
}
#Return only elements with a specific attribute and or value if specified
if( $attribute_match != false && $elements )
{
foreach( $elements as $el_key => $current_el )
{
if( $current_el['attributes'] )
{
foreach( $current_el['attributes'] as $att_name => $att_value )
{
$keep = false;
if( $att_name == $attribute_match )
{
$keep = true;
if( $value_match == false )
break;
}
if( $value_match && ( $att_value == $value_match ) )
{
$keep = true;
break;
}
elseif( $value_match && ( $att_value != $value_match ) )
$keep = false;
}
if( $keep == false )
unset( $elements[$el_key] );
}
else
unset( $elements[$el_key] );
}
}
}
if( $elements )
return array_values( $elements );
else
return array();
}
/**
* Return an associateive array of all the form inputs
*/
public function getFormValues()
{
$inputs = $this->getElements( 'input' );
$textareas = $this->getElements( 'textarea' );
$buttons = $this->getElements( 'button' );
$elements = array_merge( $inputs, $textareas, $buttons );
if( $elements )
{
foreach( $elements as $current_el )
{
$attribute_name = mb_strtolower( $current_el['attributes']['name'] );
if( in_array( $current_el['name'], array( 'input', 'button' ) ) )
{
if( isset( $current_el['attributes']['name'] ) && isset( $current_el['attributes']['value'] ) )
$form_values[$attribute_name] = $current_el['attributes']['value'];
}
else
{
if( isset( $current_el['attributes']['name'] ) && isset( $current_el['content'] ) )
$form_values[$attribute_name] = $current_el['content'];
}
}
}
return $form_values;
}
/**
* Parses attributes into an array
*/
private function parseAttributes( $str )
{
$str = trim( rtrim( trim( $str ), '/' ) );
if( $str )
{
preg_match_all( "/([^ =]+)\s*=\s*[\"'“”]{0,1}([^\"'“”]*)[\"'“”]{0,1}/i", $str, $matches );
if( $matches[1] )
{
foreach( $matches[1] as $key => $att )
{
$attribute_name = mb_strtolower( $att );
$attributes[$attribute_name] = $matches[2][$key];
}
}
}
return $attributes;
}
}
?>
Usage is:
$c = new HTMLQuery();
$x = $c->getElements( 'tr' );
print_r( $x );

Categories