Use PHP function to override default JSON target with Array - php

We built an API to directly access other social networks APIs using our keys.
I'm trying to build a fuction to access that API.
The default function has been written and is working.
Question
How can I specify a new array to target the json data?
This will override the default setting.
function SocialAPI($handle, $service, $path="") {
$handle = strtolower($handle);
$service = strtolower($service);
$api = file_get_contents("https://api.service.domain.com/v1/Social?handle=$handle&service=$service");
if($api !== false) {
$data = json_decode($api, true);
if($data !== null) {
if($service === "twitter") {
return $data['0']['followers_count'];
}
if($service === "instagram") {
if(!empty($path)) {
while($id = array_shift($path)) {
echo $data[$id];
}
return $data;
} else {
return $data['user']['followed_by']['count'];
}
}
} else {
return false;
}
} else {
return "API call failed.";
}
}
//Test API Function - ** TO BE DELETED **
echo SocialAPI("JohnDoe", "Instagram", "['user']['full_name']");
exit();

function array_deref($data, $keys) {
return empty($keys) ? $data
: array_deref($data[$keys[0]], array_slice($data, 1))
}
function SocialAPI($handle, $service, $path="") {
$handle = strtolower($handle);
$service = strtolower($service);
$api = file_get_contents("https://api.service.domain.com/v1/Social?handle=$handle&service=$service");
if ($api === false) {
return "API call failed.";
}
$data = json_decode($api, true);
if($data !== null) {
return false;
}
if ($service === "twitter") {
if (empty($path)) $path = ['0','followers_count'];
return array_deref($data, $path);
} elseif ($service === "instagram") {
if (empty($path)) $path = ['user','followed_by'];
return array_deref($data, $path);
}
}
//Test API Function - ** TO BE DELETED **
echo SocialAPI("JohnDoe", "Instagram", ['user', 'full_name']);
echo SocialAPI("JohnDoe", "Instagram");
exit();
I added a utility function, array_deref, to walk the arrays recursively (calls itself to handle each level down).

Related

How to generate GraphQL Schema from schema.graphql file in PHP

I have created the schema.graphql file in PHP using the following code:
$data = SchemaPrinter::doPrint($schema);
file_put_contents('/var/cache/Graphql/schema.graphql', $data);
Now I want to create new schema using this file content. How to achieve this?
I have created the schema from schema.graphql using the BuildSchema::build().
By default, such schema is created without any resolvers. So we need to define our custom resolvers as follows:
$contents = file_get_contents($this->projectDir.'/config/schema.graphql');
$typeConfigDecorator = function($typeConfig, $typeDefinitionNode) {
$name = $typeConfig['name'];
if ($name === 'Query') {
$typeConfig['resolveField'] =
function ($source, $args, $context, ResolveInfo $info) {
if ($info->fieldDefinition->name == 'login') {
if ($args['userName'] === 'test' && $args['password'] === '1234') {
return "Valid User.";
} else {
return "Invalid User";
}
} elseif ($info->fieldDefinition->name == 'validateUser') {
if ($args['age'] < 18) {
return ['userId' => $args['userId'], 'category' => 'Not eligible for voting'];
}
}
}
}
;
}
return $typeConfig;
};
$schema = BuildSchema::build($contents, $typeConfigDecorator);

php Hook Error spl_object_hash() expects exactly 1 parameter, 2 given

I want to create anonymous functions and add them to the hook instead of using defined functions in the hooks.
Error:spl_object_hash() expects exactly 1 parameter, 2 given in D:server\www\deneme\sistem\kanca.php on line 313
Error Problem function benzersiz_Filtre_id() spl_object_hash function
Misuse: kanca_cek("panel_main",function(){ return "a";});
Normal use: kanca_cek("panel_main","db_filter");
function kanca_tak($ad,$fonksiyon,$onem=10,$deger=1){
return self::filtre_ekle($ad,$fonksiyon,$onem,$deger);
}
function kanca_sil($ad,$fonksiyon,$onem=10){
return self::filtre_sil($ad,$fonksiyon,$onem);
}
function tum_kancalari_sil($ad,$onem=false){
return self::tum_filtreleri_sil($ad,$onem);
}
function kanca_sor($ad,$fonksiyon_kontrol=false){
return self::filtre_sor($ad,$fonksiyon_kontrol);
}
function kanca_saydir($ad){
if(!isset($this->islemSayaci) || !isset($this->islemSayaci[$ad]))
return 0;
return $this->islemSayaci[$ad];
}
function islemSayaci($ad,$kanca=false){
$kancaSor=($kanca ? "kanca":"filtre");
if(isset($this->islemSayaci[$ad][$kancaSor]))
$this->islemSayaci[$ad][$kancaSor]++;
else
$this->islemSayaci[$ad][$kancaSor]=1;
}
function kanca_cek($ad,$deger=''){
$depo = array();
$uFv=array();
if (isset($this->filtreler['hepsi'])) {
$this->guncelFiltre[] = $ad;
$depo = func_get_args();
$this->tum_kancalari_cagir($depo);
}
if (!isset($this->filtreler[$ad])) {
if (isset($this->filtreler['hepsi']))
array_pop($this->guncelFiltre);
return;
}
if (!isset($this->filtreler['hepsi']))
$this->guncelFiltre[] = $ad;
if (is_array($deger) && 1 == count($deger) && isset($deger[0]) && is_object($deger[0])) // array(&$this)
$depo[] =& $deger[0];
elseif(!empty($deger))
$depo[] = $deger;
for ($a = 2; $a < func_num_args(); $a++)
$depo[] = func_get_arg($a);
// Sort
if (!isset($this->topluFiltreler[$ad])) {
ksort($this->filtreler[$ad]);
$this->topluFiltreler[$ad] = true;
}
self::islemSayaci($ad,true);
do {
foreach ((array) current($this->filtreler[$ad]) as $yaz){
/**
*#param $uFv değişkeni call_user_func_array fonksiyonunda kullanıcı tanımlı fonksiyona gönderilecek değerleri içerir
*#param accepted_args varsa ve gelen değer eğer dizeyse $uFv ile $yaz["accepted_args"] birleştirir $uFv değişkenine atar.
* #example call_user_func_array gönderilecek değerleri oluşturur.
*/
$uFv=array_slice($depo, 0, (int) $yaz['accepted_args']);
if(isset($yaz["accepted_args"]) && is_array($yaz["accepted_args"]))
$uFv=array_merge($uFv,$yaz["accepted_args"]);
if (isset($yaz['fonksiyon']) && !is_null($yaz['fonksiyon']))
call_user_func_array($yaz["fonksiyon"], $uFv);
// call_user_func_array($yaz['fonksiyon'], array_slice($depo, 0, (int) $yaz['accepted_args']));
}
} while (next($this->filtreler[$ad]) !== false);
array_pop($this->guncelFiltre);
}
function referans_diziyle_kancala($ad,$deger){
if (isset($this->filtreler['hepsi'])) {
$this->guncelFiltre[] = $ad;
$depo = func_get_args();
$this->tum_kancalari_cagir($depo);
}
if (!isset($this->filtreler[$ad])) {
if (isset($this->filtreler['hepsi']))
array_pop($this->guncelFiltre);
return;
}
if (!isset($this->filtreler['hepsi']))
$this->guncelFiltre[] = $tag;
// Sort
if (!isset($this->topluFiltreler[$ad])) {
ksort($this->filtreler[$ad]);
$this->topluFiltreler[$ad] = true;
}
reset($this->filtreler[$tag]);
do {
foreach ((array) current($this->filtreler[$ad]) as $yaz)
if (isset($yaz['fonksiyon']) && !is_null($yaz['fonksiyon']))
call_user_func_array($yaz['fonksiyon'], array_slice($deger, 0, (int) $yaz['accepted_args']));
} while (next($this->filtreler[$ad]) !== false);
array_pop($this->guncelFiltre);
}
function filtre_ekle($ad,$fonksiyon,$onem,$deger=1,$sadeceKelime=0){
$fk=($sadeceKelime ? $ad."_".password_hash(rand(0,10000),PASSWORD_DEFAULT):$fonksiyon);
$cId=self::benzersiz_Filtre_id($ad,$fk,$onem);
if($sadeceKelime){
$this->filtreler[$ad][$onem][$cId]=array(
'deger'=>$fonksiyon,
'accepted_args'=>$deger,
'sK'=>$sadeceKelime);
}
else{
$this->filtreler[$ad][$onem][$cId]=array(
'fonksiyon'=>$fonksiyon,
'accepted_args'=>$deger,
'sK'=>$sadeceKelime);
}
unset($this->topluFiltreler[$ad]);
}
function filtre_sil($ad,$fonksiyon,$onem=10){
$fSil = self::benzersiz_Filtre_id($ad, $fonksiyon, $onem);
$varMi = isset($this->filtreler[$ad][$onem][$fSil]);
if (true === $varMi) {
unset($this->filtreler[$ad][$onem][$fSil]);
if (empty($this->filtreler[$ad][$onem]))
unset($this->filtreler[$ad][$onem]);
unset($this->topluFiltreler[$ad]);
}
return $varMi;
}
function tum_filtreleri_sil($ad,$onem=false){
if (isset($this->filtreler[$ad])) {
if (false !== $onem && isset($this->filtreler[$ad][$onem]))
unset($this->filtreler[$ad][$onem]);
else
unset($this->filtreler[$ad]);
}
if (isset($this->topluFiltreler[$ad]))
unset($this->topluFiltreler[$ad]);
return true;
}
function filtre_sor($ad,$fonksiyon_kontrol=false){
$sor=!empty($this->filtreler[$ad]);
if($fonksiyon_kontrol===false || $sor==false)
return $sor;
if(!$idSor=self::benzersiz_Filtre_id($ad,$fonksiyon_kontrol,false))
return false;
foreach ((array) array_keys($this->filtreler[$ad]) as $onem) {
if (isset($this->filtreler[$ad][$onem][$idSor]))
return $onem;
}
return false;
}
function guncel_filtre(){
return end($this->guncelFiltre);
}
public function filtrele($ad, $deger)
{
$depo = array();
$dondur=null;
$uFv=array();//call_user_func_array gönderilen Dizisi
// Do 'all' actions first
if(isset($this->filtreler["all"]))
{
$this->guncelFiltre=$ad;
$depo=func_get_arg();
$this->tum_kancalari_cagir($depo);
}
if(!isset($this->filtreler[$ad]))
{
if(isset($this->filtreler["all"]))
array_pop($this->guncelFiltre);
return $deger;
}
if (!isset($this->filtreler['hepsi']))
$this->guncelFiltre[] = $ad;
// Sort
if (!isset($this->topluFiltreler[$ad])) {
ksort($this->filtreler[$ad]);
$this->topluFiltreler[$ad] = true;
}
if (empty($depo))
$depo = func_get_args();
$keySifirla = array_map('array_values', $this->filtreler[$ad]);
do {
$conDizi=(is_array($keySifirla) ? $keySifirla:(array) $KXC);
foreach (current($conDizi) as $kx=>$yaz){
if (isset($yaz['fonksiyon']) && !is_null($yaz['fonksiyon'])) {
$depo[1] = $deger;
}
if(isset($yaz["deger"])){
if(is_array($yaz["deger"])){
foreach($yaz["deger"] as $yK)
$deger[]=$yK;
}else{
$deger=$yaz["deger"];
}
}else{
if(is_callable($yaz["fonksiyon"]) && $yaz["fonksiyon"] instanceof Closure) {
$yaz["fonksiyon"]();
}
elseif(function_exists($yaz["fonksiyon"])){
/**
*#param $uFv değişkeni call_user_func_array fonksiyonunda kullanıcı tanımlı fonksiyona gönderilecek değerleri içerir
*#param accepted_args varsa ve gelen değer eğer dizeyse $uFv ile $yaz["accepted_args"] birleştirir $uFv değişkenine atar.
* #example call_user_func_array gönderilecek değerleri oluşturur.
*/
$uFv=array_slice($depo, 1, (int) $yaz['accepted_args']);
if(isset($yaz["accepted_args"]) && is_array($yaz["accepted_args"]))
$uFv=array_merge($uFv,$yaz["accepted_args"]);
$deger = call_user_func_array($yaz["fonksiyon"], $uFv);
}
else{
hata_ekle($yaz["fonksiyon"]." fonksiyonu bulunamadı.","hata");
return false;
}
}
}
} while (next($keySifirla) !== false);
array_pop($this->guncelFiltre);
self::islemSayaci($ad);
return $deger;
}
function referans_diziyle_filtrele($ad,$deger){
// Do 'all' actions first
if (isset($this->filtrele['all'])) {
$this->guncelFiltre[] = $ad;
$depo = func_get_args();
$this->tum_kancalari_cagir($depo);
}
if (!isset($this->filtrele[$ad])) {
if (isset($this->filtrele['all']))
array_pop($this->guncelFiltre);
return $deger[0];
}
if (!isset($this->filtrele['all']))
$this->guncelFiltre[] = $ad;
// Sort
if (!isset($this->topluFiltreler[$ad])) {
ksort($this->filtrele[$ad]);
$this->topluFiltreler[$ad] = true;
}
reset($this->filtrele[$ad]);
do {
foreach ((array) current($this->filtrele[$ad]) as $yaz)
if (isset($yaz['fonksiyon']) && !is_null($yaz['fonksiyon']))
$deger[0] = call_user_func_array($yaz['fonksiyon'], array_slice($deger, 0, (int) $deger['accepted_args']));
} while (next($this->filtrele[$ad]) !== false);
array_pop($this->guncelFiltre);
return $depo[0];
}
public function tum_kancalari_cagir($deger)
{
reset($this->filtreler['hepsi']);
do {
foreach ((array) current($this->filtreler['hepsi']) as $yaz)
if (isset($yaz['fonksiyon']) && !is_null($yaz['fonksiyon']))
call_user_func_array($yaz['fonksiyon'], $depo);
} while (next($this->filtreler['hepsi']) !== false);
}
function dumps(){
echo "<pre>";
print_r($this);
echo "</pre>";
}
function benzersiz_Filtre_id($ad,$fonksiyon,$onem){
static $idSaydir=0;
if(is_string($fonksiyon))
return $fonksiyon;
if(is_object($fonksiyon))
$fonksiyon=array($fonksiyon,'');
else
$fonksiyon=(array) $fonksiyon;
if(is_object($fonksiyon[0]))
{
if(function_exists('spl_object_hash')){
return spl_object_hash($fonksiyon[0],$fonksiyon[1]);
}else{
$nesneId=get_class($fonksiyon[0]).$fonksiyon[1];
if (!isset($fonksiyon[0]->filter_id)) {
if (false === $onem)
return false;
$nesneId .= isset($this->filtreler[$ad][$onem]) ? count((array) $$this->filtreler[$ad][$onem]) : $idSaydir;
$fonksiyon[0]->filter_id = $idSaydir;
++$idSaydir;
} else {
$nesneId .= $fonksiyon[0]->filter_id;
}
return $nesneId;
}
} else if (is_string($fonksiyon[0])) {
if(count($fonksiyon)>=2)
return $fonksiyon[0] . $fonksiyon[1];
else
return $fonksiyon[0];
}
}
}
Problem Function 313 line code
if(function_exists('spl_object_hash')){
return spl_object_hash($fonksiyon[0],$fonksiyon[1]);
}else{
$nesneId=get_class($fonksiyon[0]).$fonksiyon[1];
the function from which the error was received
function benzersiz_Filtre_id($ad,$fonksiyon,$onem){
static $idSaydir=0;
if(is_string($fonksiyon))
return $fonksiyon;
if(is_object($fonksiyon))
$fonksiyon=array($fonksiyon,'');
else
$fonksiyon=(array) $fonksiyon;
if(is_object($fonksiyon[0]))
{
if(function_exists('spl_object_hash')){
return spl_object_hash($fonksiyon[0],$fonksiyon[1]);
}else{
$nesneId=get_class($fonksiyon[0]).$fonksiyon[1];
if (!isset($fonksiyon[0]->filter_id)) {
if (false === $onem)
return false;
$nesneId .= isset($this->filtreler[$ad][$onem]) ? count((array) $$this->filtreler[$ad][$onem]) : $idSaydir;
$fonksiyon[0]->filter_id = $idSaydir;
++$idSaydir;
} else {
$nesneId .= $fonksiyon[0]->filter_id;
}
return $nesneId;
}
} else if (is_string($fonksiyon[0])) {
if(count($fonksiyon)>=2)
return $fonksiyon[0] . $fonksiyon[1];
else
return $fonksiyon[0];
}
}
As documented spl_object_hash requires only one argument.
So the part you are using is wrong
if(function_exists('spl_object_hash')){
return spl_object_hash($fonksiyon[0],$fonksiyon[1]);
}else{
$nesneId=get_class($fonksiyon[0]).$fonksiyon[1];
}
As you want the ID (hash) of one object, I suppose you mean
return spl_object_hash($fonksiyon);
// or
return spl_object_hash($fonksiyon[0]);
You can remove the function_exists part, because SPL is part of PHP since 5.0.

PHP get link from txtfile, unset this link inside the array and get random array value

I'm trying to load a website url from a textfile, then unset this string from an array and pick a random website from the array.
But once I try to access the array from my function the array would return NULL, does someone know where my mistake is located at?
My current code looks like the following:
<?php
$activeFile = 'activeSite.txt';
$sites = array(
'http://wwww.google.com',
'http://www.ebay.com',
'http://www.icloud.com',
'http://www.hackforums.net',
'http://www.randomsite.com'
);
function getActiveSite($file)
{
$activeSite = file_get_contents($file, true);
return $activeSite;
}
function unsetActiveSite($activeSite)
{
if(($key = array_search($activeSite, $sites)) !== false)
{
unset($sites[$key]);
return true;
}
else
{
return false;
}
}
function updateActiveSite($activeFile)
{
$activeWebsite = getActiveSite($activeFile);
if(!empty($activeWebsite))
{
$unsetActive = unsetActiveSite($activeWebsite);
if($unsetActive == true)
{
$randomSite = $sites[array_rand($sites)];
return $randomSite;
}
else
{
echo 'Could not unset the active website.';
}
}
else
{
echo $activeWebsite . ' did not contain any active website.';
}
}
$result = updateActiveSite($activeFile);
echo $result;
?>
$sites is not avaliable in unsetActiveSite function you need to create a function called "getSites" which return the $sites array and use it in unsetActiveSite
function getSites(){
$sites = [
'http://wwww.google.com',
'http://www.ebay.com',
'http://www.icloud.com',
'http://www.hackforums.net',
'http://www.randomsite.com'
];
return $sites;
}
function unsetActiveSite($activeSite)
{
$sites = getSites();
if(($key = array_search($activeSite, $sites)) !== false)
{
unset($sites[$key]);
return true;
}
else
{
return false;
}
}

Array to string conversion Error in Laravel 4.2

I was working in one Laravel Project using 92Five App. when access user List. its goto Something Went Wrong Page. Its Display Array to string conversion Error in Error Log.
In User Controller Following Functions are Defined.
Error :
[2016-08-09 13:13:12] log.ERROR: Something Went Wrong in User
Repository - getAllUsersData():Array to string conversion [] []
My Code :
public function getAllUsersData()
{
try{
$users = array();
$tempUsers = \User::all()->toArray();
$users = $this->getGroupBaseRole($tempUsers);
return $users;
}
catch (\Exception $e)
{
\Log::error('Something Went Wrong in User Repository - getAllUsersData():'. $e->getMessage());
throw new SomeThingWentWrongException();
}
}
public function getGroupBaseRole($groupMembersInfo) {
$data = [];
if(!empty($groupMembersInfo) && isset($groupMembersInfo)) {
foreach($groupMembersInfo as $user)
{
$banned = false;
$suspended = false;
$loginAttempt = 0;
$usersThrottle = \Throttle::where('user_id',$user['id'])->get()->toArray();
// print_r($usersThrottle); exit;
if(sizeof($usersThrottle) != 0)
{
foreach($usersThrottle as $userThrottle)
{
if($userThrottle['banned'] == true)
{
$banned = true;
}
if($userThrottle['suspended'] == true)
{
$suspended = true;
}
$loginAttempt = $loginAttempt + $userThrottle['attempts'];
}
$user['banned'] = $banned;
$user['suspended'] = $suspended;
$user['loginAttempt'] = $loginAttempt;
}
else
{
$user['banned'] = false;
$user['suspended'] = false;
$user['loginAttempt'] = 0;
}
$groupUser = \Sentry::findUserById($user['id']);
$groups = $groupUser->getGroups()->toArray();
if(sizeof($groups)!=0)
{
$user['role'] =$groups[0]['name'];
}
else
{
$user['role'] = '';
}
$data[] = $user;
}
}
return $data;
}
It seeems getGroupBaseRole() method accepts string, but you're trying to pass an array $tempUsers as first argument.

Check if admin has logged in

If there's someone logged in, this code checks the sessions and I can successfully view the page, but now I'd like to check if the user is admin. I tried checking in the model by Below is what I have tried and its not working.
method that checks session and if its an admin
public function index()
{
$this->load->library('authlib');
$loggedin = $this->authlib->is_loggedin();
///$admin = $this->auth->admin();
if ($loggedin === false) {
$this->load->helper('url');
redirect('/auth/login');
}
if ($this->auth->admin() === false) {
$message ['msg'] = "You are not an admin!";
$this->load->view('homeview', $message);
}
else
{
$this->load->view('add_view');
}
}
Auth Controller
public function authenticate()
{
$username = $this->input->post('uname');
$password = $this->input->post('pword');
$user = $this->authlib->login($username,$password);
**>> $this->admin($username,$password); << passes the posted in values**
if ($user !== false) {
$this->load->view('homeview',array('name' => $user['name']));
}
else {
$data['errmsg'] = 'Unable to login - please try again';
$this->load->view('login_view',$data);
}
}
public function admin($username,$password){
//$this->load-model('usermodel');
$admin = $this->authlib->adminlib($username,$password);
if ($admin == false){
return false;
//if ($res->num_rows() != 1){
//return false;
}
}
library authlib
public function adminlib($user,$pwd)
{
return $this->ci->usermodel->chkadmn($user,$pwd);
}
the model
function chkadmn($username,$password)
{
$this->db-where(array('username' => $username,'password' => sha1($password)));
$res = $this->db->get('users',array('type'));
if ($res->num_rows() != 1) {
return false;
}
}
Made some changes and now I get "Call to undefined function where() in C:\xampp\htdocs\ecwm604\application\models\usermodel.php on line 54"
personally i will replace all your if statments and i would test it as shown:
public function index()
{
$this->load->library('authlib');
$loggedin = $this->authlib->is_loggedin();
///$admin = $this->auth->admin();
if (!$loggedin) {
$this->load->helper('url');
redirect('/auth/login');
}
if (!$this->auth->admin()) {
$message ['msg'] = "You are not an admin!";
$this->load->view('homeview', $message);
}
else
{
$this->load->view('add_view');
}
}
public function admin(){
$this->load-model('usermodel');
$admin = $this->usermodel->chkadmn($username,$password);
if (!$admin){
return false;
//if ($res->num_rows() !== 1){
//return false;
}
}
function chkadmn($username,$password)
{
$this->db-where(array('username' => $username,'password' => sha1($password)));
$res = $this->db->get('users',array('type'));
if ($res->num_rows() !== 1) {
return false;
}
}

Categories