Using TwitterOauth within a function - php

I am trying to create a small php script that pulls down a list of all user id's of people that are following/friends with a handle on twitter, for this I am using https://twitteroauth.com
I can get the id's to a file itself when I use either "friends" or "followers" individually, but when I am trying to move this script to a function I get "Fatal error: Call to a member function get() on null" (line 19)
the error is triggered because this line
" $tweets = $twitteroauth->get($type . '/ids', array ( 'screen_name' => $term, 'cursor' => $next_cursor, 'count' => 50));
"
is being used inside a function...
I used composer and tried and got it to work outside a function.. the 2 main files are
index.php
#!/usr/bin/php
<?php
require __DIR__ . '/vendor/autoload.php';
use Abraham\TwitterOAuth\TwitterOAuth;
require_once 'config.php';
// Pass in arguments
if (PHP_SAPI === 'cli') {
$type = $argv[1];
$term = $argv[2];
}
else {
$type = $_GET['type'];
$term = $_GET['term'];
}
switch ($type){
case 'timeline':
include 'timeline.php';
break;
case 'followers':
case 'friends':
include 'f.php';
break;
case 'ratelimit':
include 'ratelimit.php';
break;
case 'users_followers':
case 'users_friends':
include 'users.php';
break;
case 'all':
// include 'timeline.php';
include 'f.php';
break;
}
?>
And f.php
<?php
function getFrindsFollowers($term, $type){
// create file to print follwer/friends id's to file
$file = "files/" . $term . '_' . $type . '.csv';
// set empty content to file
$content = null;
// set previous cursor
$previous_cursor = 0;
$next_cursor = -1;
$loop_num = 0;
// While statment for followers or friends calls.
while($next_cursor != $previous_cursor && $loop_num < 15 && $next_cursor != 0){
//use Abraham\TwitterOAuth\TwitterOAuth;
//$twitteroauth = new TwitterOAuth(consumer_key, consumer_secret, oauth_access_token, oauth_access_token_secret);
$tweets = $twitteroauth->get($type . '/ids', array ( 'screen_name' => $term, 'cursor' => $next_cursor, 'count' => 50));
// Pause the loop for 16 min after every 15th request
if ($loop_num % 15 == 0 && $loop_num > 15) {
echo "sleep mode";
sleep(960);
echo "sleep mode done";
}
// set cursors
$previous_cursor = $next_cursor;
//echo 'Previous cursor is ' . $previous_cursor;
//echo '\n Next cursor is ' . $next_cursor;
foreach($tweets as $key => $val) {
if($key == "ids"){
//echo $val[0];
foreach($val as $value){
$value . "\n";
$content .= ",\n" . $value;
}
}
if($key == "next_cursor"){
//echo "\n \n";
$next_cursor = $val;
}
}
$loop_num ++;
echo "Type is now " . $type . "\n";
echo "Loop is " . $loop_num . " for " . $type . "\n";
file_put_contents($file, $content);
}
}
getFrindsFollowers($term, $type);
?>
Is most likely a easy fix but would appreciate any guidance on how to use a get request inside a function.

You are having trouble with scope (http://php.net/manual/en/language.variables.scope.php)
If you already have the twitteroauth variable defined outside the function, add this line at the start of it
global $twitteroauth;
This will give you access to the variable inside the function.

Related

Php Elastica - how to resolve - No enabled connection error - in long cycle

I have a php console script which processes long array in foreach cycle and send Elasticsearch bulks to database. I need to solve case if bulk insert fails on connection error like: No enabled connection. I would like to catch it and try it again. But my solution does not work. Still no enabled connection error. Here is the code:
/** #var Elastica\Client $elastic */
$elastic = new Elastica\Client(['servers' => [['host' => 'xxx.xxx.x.xx', 'port' => 9200]]]);
/** #var \Elastica\Index $searchCz */
$searchCz = $elastic->getIndex('search_cz');
$bulkLimit = 500;
$scrollIcos = [About 2mil items...];
$continue = TRUE;
while ( $continue && $bulkIcos = array_splice( $scrollIcos, 0, $bulkLimit ) )
{
try
{
$elasticBulk = [];
$icos = array_values($bulkIcos);
foreach ($bulkIcos as $ico) // Numeric key does not work with array_splice()
{
$offset++;
$companyData = [];
$companyData['ico'] = $ico;
$companyData['xxx'] = 'yyy';
...
$elasticBulk[] = new \Elastica\Document((string)$ico, $companyData);
}
if( $elasticBulk )
{
echo 'Bulk send start ' . PHP_EOL;
$searchCz->getType('doc')->addDocuments($elasticBulk);
echo '----- offset ' . $offset . ' OK' . PHP_EOL;
}
}
catch( \Exception $e )
{
echo '------------------------' . PHP_EOL;
echo 'Error while bulk insert. ' . $e->getMessage() . PHP_EOL . PHP_EOL;
setIcosBackToScrollIcos($bulkIcos, $scrollIcos);
sleep(30);
}
}

Laravel Undefined Property Error with Google Pagespeed API

I'm a beginner in using laravel. For my webapp I want to use the Google API PageSpeed. When visiting /pagespeed, it gives me this error: ErrorException (E_NOTICE)
Undefined property: stdClass::$ruleScore
Also I'm not sure if i made a correct return. I just want to show the meassured data on the /pagespeed page.
Couldn't really find an answer for my problem, I hope you can help.
I used the pagespeed.php code from https://gist.github.com/typhonius/6259822/revisions and put this in my PagespeedController:
public function pageSpeed(){
$url = 'https://www.facebook.com';
$key = 'my API key';
// View https://developers.google.com/speed/docs/insights/v1/getting_started#before_starting to get a key
$data = json_decode(file_get_contents("https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url=$url&key=$key"));
$dat = $data->formattedResults->ruleResults;
foreach($dat as $d) {
$name = $d->localizedRuleName;
$score = $d->ruleScore;
print "\nTest: " . $name . "\n";
print "Score: " . $score . "\n";
if ($score != 100) {
if (isset($d->urlBlocks[0]->header->args)) {
$advice_header = replace_placeholders($d->urlBlocks[0]->header->format, $d->urlBlocks[0]->header->args);
}
else {
$advice_header = $d->urlBlocks[0]->header->format;
}
print "Advice: " . $advice_header . "\n";
foreach ($d->urlBlocks[0]->urls as $url) {
$advice = replace_placeholders($url->result->format, $url->result->args);
print $advice . "\n";
}
}
};
function replace_placeholders($format, $args) {
$i = 1;
foreach ($args as $arg) {
$format = str_replace("\$" . $i, "$arg->value", $format);
$i++;
}
return view('pagespeed')->with('format');
}
This is in my views folder: pagespeed.blade.php:
#extends('layouts.app')
#section('content')
<h1>Page Speed</h1>
#endsection
This is my Route in web.php:
Route::get('/pagespeed', 'PagespeedController#pageSpeed');
Change this
$score = $d->ruleScore;
to
$score = $d->score;

Load codeigniter language variables into an array

I am using codeigniter. I need to get all variables from a language file to an array.Is it possible?
Is there any method available like as follows?
$a = $this->load->language('editor');
print_r($a);
I was tried $this->lang->language; But,This will return labels from another language files loaded.
$CI = & get_instance();
$arr = $CI->lang->language;
Or Use following library
Class My_language {
var $language = array();
/**
* List of loaded language files
*
* #var array
*/
var $is_loaded = array();
function __construct() {
log_message('debug', "Language Class Initialized");
}
function load($langfile = '', $idiom = '', $return = FALSE, $add_suffix = TRUE, $alt_path = '') {
$langfile = str_replace('.php', '', $langfile);
if ($add_suffix == TRUE) {
$langfile = str_replace('_lang.', '', $langfile) . '_lang';
}
$langfile .= '.php';
if (in_array($langfile, $this->is_loaded, TRUE)) {
return;
}
$config = & get_config();
if ($idiom == '') {
$deft_lang = (!isset($config['language'])) ? 'english' : $config['language'];
$idiom = ($deft_lang == '') ? 'english' : $deft_lang;
}
// Determine where the language file is and load it
if ($alt_path != '' && file_exists($alt_path . 'language/' . $idiom . '/' . $langfile)) {
include($alt_path . 'language/' . $idiom . '/' . $langfile);
} else {
$found = FALSE;
foreach (get_instance()->load->get_package_paths(TRUE) as $package_path) {
if (file_exists($package_path . 'language/' . $idiom . '/' . $langfile)) {
include($package_path . 'language/' . $idiom . '/' . $langfile);
$found = TRUE;
break;
}
}
if ($found !== TRUE) {
show_error('Unable to load the requested language file: language/' . $idiom . '/' . $langfile);
}
}
if (!isset($lang)) {
log_message('error', 'Language file contains no data: language/' . $idiom . '/' . $langfile);
return;
}
if ($return == TRUE) {
return $lang;
}
$this->is_loaded[] = $langfile;
$this->language = array();
$this->language = $lang;
return $this->language;
unset($lang);
log_message('debug', 'Language file loaded: language/' . $idiom . '/' . $langfile);
return TRUE;
}
}
Call like this
$this->load->library('my_language');
$arr = $this->my_language->load('demo');
print_r($arr);
I know this is quite an old question, but I just want to give my solution for this problem since no answers has done the trick for this problem. (tested on codeigniter 3)
$this->load->helper('language');
$foo = $this->lang->load('lang_file', 'english', true);
print_r($foo);
notice that the third parameter for load method determines whether to return the loaded array of translations. source: codeigniter 3 docs.
hope this helps
Yeah ofcourse its possible. You can do like this :
//load helper for language
$this->load->helper('language');
//test is the language file in english folder
$this->lang->load('test','english');
//fetch all the data in $var variable
$var=$this->lang->language;
//print $var
print_r($var);
$var will return the array. :)
If you want to return language file data in Array than you need to pass the third parameter in load function.
$this->lang->load('header','hindi',true) // filename,language,true

Switch Case issue with default value

I am running with some weird situation with Switch Case statement in PHP, where it is somehow ignoring the case and throwing default value. However this is not limited to the Switch Case only and happening with if else as well. So might be something wrong I am doing apart from conditional check.
I am using codeingiter and below I am posting all my code and helpers. I hope this would be enough information but let me know if you need any more information.
Helpers
// get employees
function get_employees(array $array = array())
{
$CI = get_instance();
return $CI->db->get_where('employees', $array)->result();
}
// get employee status from the `employment_status`
function get_employee_status($id)
{
$result = get_employees(array('id' => $id));
foreach ($result as $employee)
{
$status = $employee->employment_status;
}
return ($status !== '') ? $status : 'none';
}
// get employee status icon (based on status)
function get_employee_status_icon($id, $tooltip = TRUE)
{
$status = get_employee_status($id);
$get_icon = ($tooltip) ? 'rel="tooltip" title="' . ucwords(str_replace('_', ' ', $status)) . '"' : NULL;
switch ($status)
{
case 'active':
$status_icon = '<span class="glyphicon glyphicon-ok" ' . $get_icon . '></span>';
break;
case 'at_risK':
$status_icon = '<span class="glyphicon glyphicon-warning-sign" ' . $get_icon . '></span>';
break;
case 'attrition':
$status_icon = '<span class="glyphicon glyphicon-ban-circle" ' . $get_icon . '></span>';
break;
default:
$status_icon = '<span class="glyphicon glyphicon-exclamation-sign" ' . $get_icon . '></span>';
break;
}
return $status_icon;
}
Controller
public function employees()
{
$this->data['title'] = '<i class="fa fa-users"></i> ' . lang('emp_all');
$base_url = base_url() . 'admin/hr/employees';
$numbs = $this->employees_model->filter_count();
$total_rows = $numbs['count'];
$limit = get_option('per_page');
$page = ($this->uri->segment(4) !== FALSE) ? (int) $this->uri->segment(4) : 0;
get_pagination($base_url, $total_rows, $limit, 4, 2, TRUE);
$this->data['results'] = $this->employees_model->fetch_rows($limit, $page);
$this->data['links'] = $this->pagination->create_links();
$this->load->view('hr/employees/index', $this->data);
}
View file
// view file
foreach ($results as $employee):
do_print(get_employee_status($employee->id) . ' - ' .get_employee_status_icon($employee->id));
echo '<tr>';
...
echo '<td class="status-' . get_employee_status($employee->id) . '">' . get_employee_status_icon($employee->id) . '</td>';
...
echo '</tr>';
endforeach;
To clear things again: the code outputs the default value (icon) for the last case. It is ignoring the last case just only for the ICON and not for the tooltip or even th class
So how can I fix this where I can get output same as the case everywhere?
EDIT: --- Added output images and var_dump image
Please see the second last var_dump and output result to match the at_risk icon. Which is wrong
HTML Output
var_dump()
First of all you should correct your this function by properly initializing $status variable;
// get employee status from the `employment_status`
function get_employee_status($id)
{
$result = get_employees(array('id' => $id));
$status = '';
foreach ($result as $employee)
{
$status = $employee->employment_status;
}
return ($status !== '') ? $status : 'none';
}
Now, you should do var_dump of $status and see what you find in status variable value.

Executing a PHP script from within nested batch scripts

I'm trying to rewrite our Windows FTP server configuration script that was created for IIS and now we're trying to get something similar working for Filezilla Server.
The structure goes like this, we have a batch file which is a for loop of another batch file, so we can batch configure our FTP websites. This batch file I'm currently trying to get working contains a line of code to execute a PHP script to set up the FTP username and password in Filezilla as well as doing a few other neat things.
Now, running CreateIIStmp.bat var1 var2 works just fine. But executing the BatchCreateIIS.bat seems to skip the execution of the php script, or the php script fails. (I'm just looking into how I put in some error handling into the PHP script to catch any error and display it, but I'm not a (PHP) developer/coder so I'll be updating this when I figure it out.)
Here's a stripped down version of what I'm talking about:
The initial batch file BatchCreateIIS.bat:
#Echo off
for /f %%X in (NewWebsiteEntries.txt) do start cmd.exe /c "CreateIIStmp.bat %%X %%X"
echo ...
echo *** BATCH PROCESS HAS BEEN COMPLETED ***
pause
The CreateIIStmp.bat:
# echo off
C:\php5\php-win.exe -f filezilla-user-script.php -- %1 %2
pause
#echo on
The NewWebsiteEntries.txt:
somedomain.com ftpuname
somedomain2.net ftpuname2
The filezilla-user-script.php:
<?php
$xmlfolder = 'C:/Program Files (x86)/FileZilla Server/';
$xmlfilename = 'FileZilla Server.xml';
$ftpRoot = 'C:/inetpub/wwwroot/';
$ftpDocumentation = 'C:/Documentation ftp server/';
$xmlfile = $xmlfolder . $xmlfilename;
$xmlbackupfile = $xmlfolder . #date("Y-m-d-H-i-s") . '_FileZilla_Server.xml';
// Copy Config for backup
createXMLbackup($xmlfile,$xmlbackupfile);
//Load XML file
$xml = simplexml_load_file($xmlfile);
$msg = "Allowed usernames: 20 characters out of a...z A...Z 0...9 _ \n\nPlease input username (Ctrl+C to quit)";
// Copy Config for backup before each change, too.
createXMLbackup($xmlfile,$xmlbackupfile);
echo "\n\n";
$input = ($argv[2]);
echo "\n";
//echo 'Userinput: ' . $input . "\n";
$isvalid = isUserID($input);
//var_dump($isvalid);
if($isvalid)
{
$ftpUserFolder = $ftpRoot . ($argv[1]);
if ((file_exists($ftpUserFolder) && is_dir($ftpUserFolder)))
{
echo "The directory $ftpUserFolder exists.\nPlease select another user name.\n";
}
else
{
//echo "The directory $ftpUserFolder does not exist\n";
if(!check_user_exists($xml,$input))
{
echo "Adding user $input...\n";
if (!mkdir($ftpUserFolder))
{
die("Could not create directory $ftpUserFolder \n");
}
else
{
echo "Directory $ftpUserFolder created.\n";
}
$password = generatePassword();
//echo 'Password: ' . $password . "\n";
$user = $xml->Users->addChild('User');
$user->addAttribute('Name', $input);
$option = $user->addChild('Option', md5($password));
$option->addAttribute('Name', 'Pass');
$option = $user->addChild('Option');
$option->addAttribute('Name', 'Group');
$option = $user->addChild('Option', '0');
$option->addAttribute('Name', 'Bypass server userlimit');
$option = $user->addChild('Option', '0');
$option->addAttribute('Name', 'User Limit');
$option = $user->addChild('Option', '0');
$option->addAttribute('Name', 'IP Limit');
$option = $user->addChild('Option', '1');
$option->addAttribute('Name', 'Enabled');
$option = $user->addChild('Option', 'none');
$option->addAttribute('Name', 'Comments');
$option = $user->addChild('Option', '0');
$option->addAttribute('Name', 'ForceSsl');
$filter = $user->addChild('IpFilter');
$filter->addChild('Disallowed');
$filter->addChild('Allowed');
$permissions = $user->addChild('Permissions');
$permission = $permissions->addChild('Permission');
$permission->addAttribute('Dir', str_replace("/","\\",$ftpUserFolder));
$option = $permission->addChild('Option', '1');
$option->addAttribute('Name', 'FileRead');
$option = $permission->addChild('Option', '1');
$option->addAttribute('Name', 'FileWrite');
$option = $permission->addChild('Option', '0');
$option->addAttribute('Name', 'FileDelete');
$option = $permission->addChild('Option', '1');
$option->addAttribute('Name', 'FileAppend');
$option = $permission->addChild('Option', '1');
$option->addAttribute('Name', 'DirCreate');
$option = $permission->addChild('Option', '0');
$option->addAttribute('Name', 'DirDelete');
$option = $permission->addChild('Option', '1');
$option->addAttribute('Name', 'DirList');
$option = $permission->addChild('Option', '1');
$option->addAttribute('Name', 'DirSubdirs');
$option = $permission->addChild('Option', '1');
$option->addAttribute('Name', 'IsHome');
$option = $permission->addChild('Option', '0');
$option->addAttribute('Name', 'AutoCreate');
$speed = $user->addChild('SpeedLimits');
$speed->addAttribute('DlType', '1');
$speed->addAttribute('DlLimit', '10');
$speed->addAttribute('ServerDlLimitBypass', '0');
$speed->addAttribute('UlType', '1');
$speed->addAttribute('UlLimit', '10');
$speed->addAttribute('ServerUlLimitBypass', '0');
$speed->addChild('Download');
$speed->addChild('Upload');
$rv = $xml->asXML($xmlfile);
//echo $rv . "\n";
if(!$rv)
{
die('SimpleXML could not write file');
}
//$newentry = $xml->addChild('element', iconv('ISO-8859-1', 'UTF-8', $write));
//The DOM extension uses UTF-8 encoding. Use utf8_encode() and utf8_decode()
//to work with texts in ISO-8859-1 encoding or Iconv for other encodings.
//make human readable, parse using DOM function
//otherwise everything will be printed on one line
if( !file_exists($xmlfile) ) die('Missing file: ' . $xmlfile);
else
{
$dom = new DOMDocument("1.0","ISO-8859-1");
//Setze die Flags direkt nach dem Initialisieren des Objektes:
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
//$dl = #$dom->load($xmlfile); // remove error control operator (#) to print any error message generated while loading.
$dl = $dom->load($xmlfile); // remove error control operator (#) to print any error message generated while loading.
if ( !$dl ) die('Error while parsing the document: ' . $xmlfile);
//echo $dom->save($xmlfile) . "\n";
if(!$dom->save($xmlfile))
{
die('DOMDocument could not write file');
}
}
//Create documentation
$docuFile = $ftpDocumentation . $input . '.txt';
//echo $docuFile . "\n";
$docuString = "Username: " . $input . "\n";
$docuString = $docuString . "Password: " . $password . "\n";
$docuString = $docuString . "Folder: " . str_replace("/","\\",$ftpUserFolder) . "\n";
$docuString = $docuString . "Date: " . #date("d.m.Y") . "\n";
// $docuString = $docuString . "\n";
// $docuString = $docuString . "Direct link:\n";
// $docuString = $docuString . "ftp://" . $input . ":" . $password . "#ftp.yourcompany.com";
$handleDocuFile = fopen($docuFile, "wt");
if(!$handleDocuFile)
{
die('Could not fopen docu file');
}
$rv = fwrite($handleDocuFile, $docuString);
if(!$rv)
{
die('Could not fwrite docu file');
}
// Close xml file
$rv = fclose($handleDocuFile);
if(!$rv)
{
die('Could not fclose docu file');
}
echo "Documentary file written.\n";
$ftpExecutable = "\"C:\\Program Files (x86)\\FileZilla Server\\FileZilla server.exe\" /reload-config";
$command = $ftpExecutable;
$last_line = system($command, $retval);
echo ("Filezilla reloaded, user active.\n");
echo ("Close Notepad to add another user or quit.\n");
$command = "C:\\Windows\\System32\\notepad.exe $docuFile";
$last_line = system($command, $retval);
}
else
{
echo "Username $input already exists...\n";
}
}
}
else
{
echo "Username $input is invalid\n";
}
function check_user_exists($xml,$username)
{
$children=$xml->Users->children();
foreach($children as $child)
{
if ($child->getName()=='User')
{
foreach($child->attributes() as $attributes )
{
if(trim($attributes) == trim($username))
{
echo "Username $username already exists... \n";
return true;
}
}
}
}
return false;
}
function isUserID($username)
{
//return preg_match('/^\w{2,20}$/', $username);
return preg_match('/^[A-Za-z0-9][A-Za-z0-9]*(?:_[A-Za-z0-9]+)*$/', $username);
}
function isValid($str)
{
//return !preg_match('/[^A-Za-z0-9.#\\-$]/', $str);
return !preg_match('/[^A-Za-z0-9\_\-]/', $str);
}
function getInput($msg)
{
fwrite(STDOUT, "$msg: ");
$varin = trim(fgets(STDIN,20));
return $varin;
//$input = fgets($fr,128); // read a maximum of 128 characters
}
function createXMLbackup($xmlfile,$xmlbackupfile)
{
// Copy Config for backup
$rv = copy($xmlfile,$xmlbackupfile);
if(!$rv)
{
die('Problem creating xml backup file');
}
echo "\nBackup file created\n";
}
function generatePassword ($length = 15)
{
// start with a blank password
$password = "";
$possible = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
// we refer to the length of $possible a few times, so let's grab it now
$maxlength = strlen($possible);
// check for length overflow and truncate if necessary
if ($length > $maxlength)
{
$length = $maxlength;
}
// set up a counter for how many characters are in the password so far
$i = 0;
// add random characters to $password until $length is reached
while ($i < $length)
{
// pick a random character from the possible ones
$char = substr($possible, mt_rand(0, $maxlength-1), 1);
// have we already used this character in $password?
if (!strstr($password, $char))
{
// no, so it's OK to add it onto the end of whatever we've already got...
$password .= $char;
// ... and increase the counter by one
$i++;
}
}
// done!
return $password;
}
?>
I've looked around and there are some places that suggest using # in front of calling in PHP so: #C:\php5\php-win.exe -f filezilla-user-script.php -- %1 %2 but that doesn't work, and I can see that my script does work, just not in this nested form.
Maybe there's an approach to this problem that I'm missing? Or something that I don't know about executing scripts in nested batch scripts?
In your BatchCreateIIS.bat, when you use this:
start cmd.exe /c "CreateIIStmp.bat %%X %%X"
the parent cmd.exe will not wait for each instance of CreateIIStmp.bat (and child processes) to finish. Since you seem to be writing to the same XML file, it is likely that the DOM that get written last persists. Instead try this:
call "CreateIIStmp.bat %%X %%X"

Categories