laravel Trying to get property 'id' of non-object error - php

I was working on another person's code and when I deployed the laravel app the login page works but when I input the testing credentials it spits out this error
Trying to get property 'id' of non-object
in helpers.php line 159
at HandleExceptions->handleError(8, 'Trying to get property \'id\' of non-object', '/var/www/html/first-project/app/Helpers/helpers.php', 159, array('fields' => object(Collection), 'fieldsValues' => object(Collection), 'htmlFields' => array(), 'startSeparator' => '<div style="flex: 50%;max-width: 50%;padding: 0 4px;" class="column">', 'endSeparator' => '</div>', 'field' => object(CustomField), 'dynamicVars' => array('$RANDOM_VARIABLE$' => 'var15931958241638660037ble', '$FIELD_NAME$' => 'phone', '$DISABLED$' => '', '$REQUIRED$' => '"required" => "required",', '$MODEL_NAME_SNAKE$' => 'user', '$FIELD_VALUE$' => '\'+136 226 5660\'', '$INPUT_ARR_SELECTED$' => '+136 226 5660'), 'gf' => object(GeneratorField), 'value' => object(CustomFieldValue)))
in helpers.php line 159
The actual function referred to is the following
function generateCustomField($fields, $fieldsValues = null)
{
$htmlFields = [];
$startSeparator = '<div style="flex: 50%;max-width: 50%;padding: 0 4px;" class="column">';
$endSeparator = '</div>';
foreach ($fields as $field) {
$dynamicVars = [
'$RANDOM_VARIABLE$' => 'var' . time() . rand() . 'ble',
'$FIELD_NAME$' => $field->name,
'$DISABLED$' => $field->disabled === true ? '"disabled" => "disabled",' : '',
'$REQUIRED$' => $field->required === true ? '"required" => "required",' : '',
'$MODEL_NAME_SNAKE$' => getOnlyClassName($field->custom_field_model),
'$FIELD_VALUE$' => 'null',
'$INPUT_ARR_SELECTED$' => '[]',
];
$gf = new GeneratorField();
if ($fieldsValues) {
foreach ($fieldsValues as $value) {
if ($field->id === $value->customField->id) {
$dynamicVars['$INPUT_ARR_SELECTED$'] = $value->value ? $value->value : '[]';
$dynamicVars['$FIELD_VALUE$'] = '\'' . addslashes($value->value) . '\'';
$gf->validations[] = $value->value;
continue;
}
}
}
// dd($gf->validations);
$gf->htmlType = $field['type'];
$gf->htmlValues = $field['values'];
$gf->dbInput = '';
if ($field['type'] === 'selects') {
$gf->htmlType = 'select';
$gf->dbInput = 'hidden,mtm';
}
$fieldTemplate = HTMLFieldGenerator::generateCustomFieldHTML($gf, config('infyom.laravel_generator.templates', 'adminlte-templates'));
if (!empty($fieldTemplate)) {
foreach ($dynamicVars as $variable => $value) {
$fieldTemplate = str_replace($variable, $value, $fieldTemplate);
}
$htmlFields[] = $fieldTemplate;
}
// dd($fieldTemplate);
}
foreach ($htmlFields as $index => $field) {
if (round(count($htmlFields) / 2) == $index + 1) {
$htmlFields[$index] = $htmlFields[$index] . "\n" . $endSeparator . "\n" . $startSeparator;
}
}
$htmlFieldsString = implode("\n\n", $htmlFields);
$htmlFieldsString = $startSeparator . "\n" . $htmlFieldsString . "\n" . $endSeparator;
// dd($htmlFieldsString);
$renderedHtml = "";
try {
$renderedHtml = render(Blade::compileString($htmlFieldsString));
// dd($renderedHtml);
} catch (FatalThrowableError $e) {
}
return $renderedHtml;
}
its usage is as follows in the controllers. It is used many times in almost all controllers for example in the UserController.php file I think this is the calling method. I am not that well versed in laravel sorry for any noob mistakes in advance.
public function profile()
{
$user = $this->userRepository->findWithoutFail(auth()->id());
unset($user->password);
$customFields = false;
$role = $this->roleRepository->pluck('name', 'name');
$rolesSelected = $user->getRoleNames()->toArray();
$customFieldsValues = $user->customFieldsValues()->with('customField')->get();
$hasCustomField = in_array($this->userRepository->model(), setting('custom_field_models', []));
if ($hasCustomField) {
$customFields = $this->customFieldRepository->findByField('custom_field_model', $this->userRepository->model());
$customFields = generateCustomField($customFields, $customFieldsValues);
}
return view('settings.users.profile', compact(['user', 'role', 'rolesSelected', 'customFields', 'customFieldsValues']));
}

You have to change this line
From
$user = $this->userRepository->findWithoutFail(auth()->id());
To
$user = $this->userRepository->findWithoutFail(auth()->user()->id());

My first guess, change this $user = $this->userRepository->findWithoutFail(auth()->id()); to $user = $this->userRepository->findWithoutFail(auth()->user()->id);
Added auth()->user()->id;

Related

Problem of Curly Brackets in my controller Php Symfony

I want to call my function but when I call it I have a problem with curly Brackets at the end of my code and i have this error Error SYMFONY ( {} ) in my Controller.
I have no idea where to put them for my code to work. I have this problem when I add my function that allows me to retrieve the
history of the action. The mentioned function goes as this:
$this->logHistory->addHistoryConnection($project->getId(), $user->getId(), 'Delete Local Suf', $sf_code);
Function Supp Suf
/**
* #Route("/creation/suf/supp", name="suf_supp")
*/
public function suf(
Request $request,
ShapesRepository $shapesRepository
) {
$params = $this->requestStack->getSession();
$projet = $params->get('projet');
$modules = $params->get('modules');
$fonctionnalites = $params->get('fonctionnalites');
$user = $this->getUser()->getUserEntity();
$manager = $this->graceManager;
$mapManager = $this->mapManager;
$countElements = $mapManager->getCount();
$shapes = $shapesRepository->findBy(array('projet' => $projet->getId()));
$adresseWeb = $this->getParameter('adresse_web');
$carto = $params->get('paramCarto');
$centrage = $params->get('centrage');
$cableColor = $params->get('cableColor');
$sf_code = '';
if ($request->get('suf') != '') {
$sf_code = $request->get('suf');
}
$suf = $manager->getSuf($sf_code);
$success = '';
$error = '';
$warning = '';
if ($request->query->get('success')) {
$success = $request->query->get('success');
} elseif ($request->query->get('error')) {
$error = $request->query->get('error');
} elseif ($request->query->get('warning')) {
$warning = $request->query->get('warning');
}
if ($request->isMethod('POST')) {
if ($request->request->get('sf_code') != '') {
$sf_code = $request->request->get('sf_code');
}
if ($request->get('val') != '') {
$val = $request->get('val');
}
$dir = $this->getparameter('client_directory');
$dossier = str_replace(' ', '_', $projet->getProjet());
$dir = $dir . $dossier . '/documents/';
$cable = $val[0];
$chem = $val[1];
$t_suf = $this->graceCreator->supprimeSuf($sf_code, $cable, $chem);
if ($t_suf[0][0] == '00000') {
$this->logHistorique->addHistoryConnection($projet->getId(), $user->getId(), 'Suppression Suf Local', $sf_code);
// $creator->delDirObjet( $st_code, $dir );
$data = new JsonResponse(array("success" => "create!"));
return $data;
} else {
$data = new JsonResponse(array("error" => "Error : " . $t_suf));
return $data;
}
return $this->render('Modifications/supSuf.html.twig', array(
'user' => $user,
'paramCarto' => $carto,
'cableColor' => $cableColor,
'suf' => $suf,
'adresseWeb' => $adresseWeb,
'centrage' => $centrage,
'shapes' => $shapes,
'projet' => $projet,
'modules' => $modules,
'fonctionnalites' => $fonctionnalites,
'countElements' => $countElements
));
}
}
Your only return statement is inside of an if condition. If the code does not pass the condition, it has nothing to return. The code must return something in all possible cases. If you are not still used to these practices, an IDE might guide you until it becomes a routine. PHPStorm is my personal preference.
BTW, I recommend you to switch from the array() syntax to the more globally accepted [] although you must be in PHP 5.4 or higher.

Insert limit in local WAMP or XAMPP server

I'm trying to import an excel file with 15,000 record in a local php and mysql system, but it's always stop inserting in after 3000 records and ignoring the rest of records.
Even in the hosted copy of the system it's insert only 3027 record.
Can I get some help please?
Import csv php script
if ($this->form_validation->run() == true) {
if (isset($_FILES['userfile'])) {
$this->load->library('upload');
$config['upload_path'] = $this->digital_upload_path;
$config['allowed_types'] = 'csv';
$config['max_size'] = $this->allowed_file_size;
$config['overwrite'] = true;
$config['encrypt_name'] = true;
$config['max_filename'] = 25;
$this->upload->initialize($config);
if (!$this->upload->do_upload()) {
$error = $this->upload->display_errors();
$this->session->set_flashdata('error', $error);
admin_redirect('products/import_csv');
}
$csv = $this->upload->file_name;
$arrResult = [];
$handle = fopen($this->digital_upload_path . $csv, 'r');
if ($handle) {
while (($row = fgetcsv($handle, 15000, ',')) !== false) {
$arrResult[] = $row;
}
fclose($handle);
}
$titles = array_shift($arrResult);
$updated = 0;
$items = [];
foreach ($arrResult as $key => $value) {
$supplier_name = isset($value[24]) ? trim($value[24]) : '';
$supplier = $supplier_name ? $this->products_model->getSupplierByName($supplier_name) : false;
$item = [
'name' => isset($value[0]) ? trim($value[0]) : '',
'code' => isset($value[1]) ? trim($value[1]) : '',
'barcode_symbology' => isset($value[2]) ? mb_strtolower(trim($value[2]), 'UTF-8') : '',
'brand' => isset($value[3]) ? trim($value[3]) : '',
'category_code' => isset($value[4]) ? trim($value[4]) : '',
'unit' => isset($value[5]) ? trim($value[5]) : '',
'sale_unit' => isset($value[6]) ? trim($value[6]) : '',
'purchase_unit' => isset($value[7]) ? trim($value[7]) : '',
'cost' => isset($value[8]) ? trim($value[8]) : '',
'price' => isset($value[9]) ? trim($value[9]) : '',
'alert_quantity' => isset($value[10]) ? trim($value[10]) : '',
'tax_rate' => isset($value[11]) ? trim($value[11]) : '',
'tax_method' => isset($value[12]) ? (trim($value[12]) == 'exclusive' ? 1 : 0) : '',
'image' => isset($value[13]) ? trim($value[13]) : '',
'subcategory_code' => isset($value[14]) ? trim($value[14]) : '',
'variants' => isset($value[15]) ? trim($value[15]) : '',
'cf1' => isset($value[16]) ? trim($value[16]) : '',
'cf2' => isset($value[17]) ? trim($value[17]) : '',
'cf3' => isset($value[18]) ? trim($value[18]) : '',
'cf4' => isset($value[19]) ? trim($value[19]) : '',
'cf5' => isset($value[20]) ? trim($value[20]) : '',
'cf6' => isset($value[21]) ? trim($value[21]) : '',
'hsn_code' => isset($value[22]) ? trim($value[22]) : '',
'second_name' => isset($value[23]) ? trim($value[23]) : '',
'supplier1' => $supplier ? $supplier->id : null,
'supplier1_part_no' => isset($value[25]) ? trim($value[25]) : '',
'supplier1price' => isset($value[26]) ? trim($value[26]) : '',
'slug' => $this->sma->slug($value[0]),
];
if ($catd = $this->products_model->getCategoryByCode($item['category_code'])) {
$tax_details = $this->products_model->getTaxRateByName($item['tax_rate']);
$prsubcat = $this->products_model->getCategoryByCode($item['subcategory_code']);
$brand = $this->products_model->getBrandByName($item['brand']);
$unit = $this->products_model->getUnitByCode($item['unit']);
$base_unit = $unit ? $unit->id : null;
$sale_unit = $base_unit;
$purcahse_unit = $base_unit;
if ($base_unit) {
$units = $this->site->getUnitsByBUID($base_unit);
foreach ($units as $u) {
if ($u->code == $item['sale_unit']) {
$sale_unit = $u->id;
}
if ($u->code == $item['purchase_unit']) {
$purcahse_unit = $u->id;
}
}
} else {
$this->session->set_flashdata('error', lang('check_unit') . ' (' . $item['unit'] . '). ' . lang('unit_code_x_exist') . ' ' . lang('line_no') . ' ' . ($key + 1));
admin_redirect('products/import_csv');
}
unset($item['category_code'], $item['subcategory_code']);
$item['unit'] = $base_unit;
$item['sale_unit'] = $sale_unit;
$item['category_id'] = $catd->id;
$item['purchase_unit'] = $purcahse_unit;
$item['brand'] = $brand ? $brand->id : null;
$item['tax_rate'] = $tax_details ? $tax_details->id : null;
$item['subcategory_id'] = $prsubcat ? $prsubcat->id : null;
if ($product = $this->products_model->getProductByCode($item['code'])) {
if ($product->type == 'standard') {
if ($item['variants']) {
$vs = explode('|', $item['variants']);
foreach ($vs as $v) {
if (!empty(trim($v))) {
$variants[] = ['product_id' => $product->id, 'name' => trim($v)];
}
}
}
unset($item['variants']);
if ($this->products_model->updateProduct($product->id, $item, null, null, null, null, $variants)) {
$updated++;
}
}
$item = false;
}
} else {
$this->session->set_flashdata('error', lang('check_category_code') . ' (' . $item['category_code'] . '). ' . lang('category_code_x_exist') . ' ' . lang('line_no') . ' ' . ($key + 1));
admin_redirect('products/import_csv');
}
if ($item) {
$items[] = $item;
}
}
}
// $this->sma->print_arrays($items);
}
Insert script
public function add_products($products = [])
{
if (!empty($products)) {
foreach ($products as $product) {
$variants = explode('|', $product['variants']);
unset($product['variants']);
if ($this->db->insert('products', $product)) {
$product_id = $this->db->insert_id();
foreach ($variants as $variant) {
if ($variant && trim($variant) != '') {
$vat = ['product_id' => $product_id, 'name' => trim($variant)];
$this->db->insert('product_variants', $vat);
}
}
}
}
return true;
}
return false;
}
I think you're using codeigniter, so i recommend you to use yield (generator in php) and insert_bulk to handle some big data or some huge records to optimize your code and keep your cpu/memory not to leaks or timeout.
Here's some logic :
Import your csv and store it in generator.
Process your titles, key values from csv in one process,DO NOT store it in array variable except your titles only.
Convert the generator to array, and do your another process.
Do your logic to insert the data and Store your inserted data to generator.
Convert the generator to array and insert it using insert_batch function from codeigniter.
Actually you can combine poin 4 to the poin 2 so you have one process do all the logic and the result is the data you want to insert to the database.
Here's my simple code how you implement the logic :
<?php
// I think you're using codeigniter as your framework here, so i recommend you using yield and insert_bulk to insert the data
$filename = "testdata.csv";
$titles = [];
$readcsv = function($filename)use(&$titles){
$keys = ['name','code','barcode_symbology','brand','category_code','unit','sale_unit','purchase_unit','cost','price','alert_quantity','tax_rate','tax_method','image','subcategory_code','variants','cf1','cf2','cf3','cf4','cf5','cf6','hsn_code','second_name','supplier1','supplier1_part_no','supplier1price','slug'];
$handle = fopen($filename,"r");
$first = true;
while (($data = fgetcsv($handle, 15000, ",")) !== FALSE) {
if($first){
$titles = $data;
$first = false;
}else{
if(count($keys) == count($data)){
yield array_combine($keys,$data);
}
}
}
fclose($handle);
};
// Your csv data will be in this variable and your $titles now have value
$yourdata = iterator_to_array($readcsv($filename));
// This function store your inserted data to the yield (generator in php) if the conditions true
$list_insert_data = function($yourdata){
// Loop your csv data and do your logic here...
$break = false;
$cnt = 1;
foreach($yourdata as $v){
if(!empty($v) && !$break){
yield $v;
}
// Just simple logic to store 3 records from the csv
if($cnt == 3){
$break = true;
}else if($break){
break;
}
$cnt++;
}
};
// This variable contains 3 array from the csv data
$inserted = iterator_to_array($list_insert_data($yourdata));
// Then insert the data to the database.
$this->db->insert_batch('product_variants', $inserted);
UPDATED:
If you're using mysql, you need to check your max_allowed_packet and check it in your mysql SHOW VARIABLES WHERE Variable_name LIKE '%max_allowed_packet%' and increase or double the value.
Change in the my.ini file by including the single line under [mysqld] or [client] section in your file:
max_allowed_packet=1024M
then restart the MySQL service and you are done. Hope this simple logic help you out of trouble.
You need to change the max_execution_time on php.ini
max_execution_time = 5000
Or on top of your script, add the following line.
ini_set('max_execution_time', 5000);

Laravel validator 'in' issue for numbers in input

I need help in fixing an issue in which I am using laravel 'in' validator to match a given input against multiple comma separated string of values. Now the issue is when there is a number in the input and it does not matches with any of the comma separated values then it gives an exception:
preg_match() expects parameter 2 to be string, array given
However it should simply give error message in validator object that input field does not match. instead it gives above mentioned exception. Following is my code:
if (!empty($program)) {
$institution_id = $program->InstitutionId;
$roster_users = $program->usersRosters()->where('ProfileType', 'Student')->get();
if (!empty($roster_users)) {
$rostered_users_ids = implode(',', $roster_users->lists('id'));
}
if (!empty($roster_users)) {
$rostered_users_usernames = implode(',', $roster_users->lists('UserName'));
}
$teacher_roster_users = $program->usersRosters()->where('ProfileType', 'External Staff')->get();
if (!empty($teacher_roster_users)) {
$teacher_rostered_users_usernames = implode(',', $teacher_roster_users->lists('UserName'));
}
if (!empty($teacher_roster_users)) {
$teacher_rostered_users_data = $teacher_roster_users->lists('id', 'UserName');
}
}
$rules = [
'aasectionname.required' => '501 – AA section does not exist',
'aaid' => 'numeric|exists:users,id|in:' . $rostered_users_ids . '|aaidinstitutionmismatch:' . $institution_id,
'institutionid' => 'numeric|in:' . $institution_id,
'username' => 'exists:users,UserName|in:' . $rostered_users_usernames . '|usernameinstitutionmismatch:' . $institution_id,
'schoolid' => 'numeric',
'groupowner' => 'in:'.$teacher_rostered_users_usernames,
'remove' => 'in:0,1'
];
$messages = [
// InstitutionId
'institutionid.numeric' => '101 – Invalid Institution ID',
'institutionid.in' => '102 – Institution ID does not match Program',
// Usernames
'username.exists' => '201 – UserName does not exist',
'username.in' => '202 – UserName is not rostered to this program',
'username.usernameinstitutionmismatch' => '203 – User/Institution Mismatch - UserName is not assigned to this Institution',
// AAId
'aaid.numeric' => '301 – AA ID does not exist',
'aaid.exists' => '301 – AA ID does not exist',
'aaid.in' => '302 – AA ID is not rostered to this program',
'aaid.aaidinstitutionmismatch' => '303 – AA ID/Institution Mismatch – AAID is not assigned to this Institution',
// Mismatch
'bothmismatch' => '401 – AAID/UserName/SchoolID do not match (This is a combination of at least 2 of these items)',
// Teacher
'groupowner.in' => '501 – GroupOwner does not exist',
// Remove
'remove' => '601 – No Student record match to remove',
];
Excel::load($file, function($excel) use($program, $rules, $messages, $errors, &$errors_data, $teacher_rostered_users_data) {
global $totalmismatch;
$results = $excel->get();
$program_group_model = new ProgramGroup;
$option_model = new Option;
$group_default_status_id = key($option_model->getProgramsStatus(['Active']));
$groupVisibilityStatusId = $group_type = $option_model->getVisibilityOptions('Question Visibility','Private');
$data = [];
$lastSecId = null;
$groupSectionPreviousName = null;
$groupname = null;
$data['status'] = $group_default_status_id;
$data['program_id'] = $program->Id;
$groupname_lists = $program_group_model->with(['programs' => function ($query) use ($program){
$query->where('ProgramId','=',$program->Id);
}])->get()->lists('Name','Id');
foreach ($results as $key => $row) {
$inputs = $row->toArray();
$groupname = trim($inputs['usergroup']);
$errors = [];
// Stop reading the excel when aasectionname is empty
if (empty($groupname) || $groupname == null) {
$errors['remove'] = $messages['aasectionname.required'];
}
$validator = Validator::make($inputs, $rules, $messages);
if ($validator->fails()) {
$errors = $validator->messages()->toArray();
foreach ($errors as $error) {
foreach ($error as $e) {
$errors_data[] = [$key + 2, $e];
}
}
} else {
$aaid = intval($inputs['aaid']);
$groupowner_name = $inputs['groupowner'];
if (!empty($teacher_rostered_users_data[$groupowner_name])) {
$groupowner_id = $teacher_rostered_users_data[$groupowner_name];
$data['owner'] = $groupowner_id;
}
$remove = intval($inputs['remove']);
// Remove existing Student Roster
if (!empty($remove)) {
$removed = false;
$user_ids = is_array($aaid) ? $aaid : [$aaid];
$program_group = $program->programGroups()->where('Name', $groupname);
if (!empty($program_group)) {
$program_group = $program_group->first();
}
if (!empty($program_group)) {
$program_group = $program_group->users();
}
if (!empty($program_group) && !empty($user_ids)) {
$removed = $program_group->detach($user_ids);
}
if (!$removed) {
$errors['remove'] = $messages['remove'];
}
} else {
if (!in_array($groupname, $groupname_lists) || $groupSectionPreviousName != $groupname) {
$data['name'] = $groupname;
$data['group_id'] = array_search($groupname, $groupname_lists);
$data['group_type'] = $groupVisibilityStatusId;
$sectionId = $program_group_model->saveProgramGroup($data);
$data[$sectionId]['selected'][] = $aaid;
$groupname_lists[$sectionId] = $groupname;
} else {
$temp = array_flip($groupname_lists);
$data[$temp[$groupname]]['selected'][] = $aaid;
}
}
if ($totalmismatch === 2) {
$errors['bothmismatch'] = $messages['bothmismatch'];
}
foreach ($errors as $error) {
$errors_data[] = [$key + 2, $error];
}
}
$groupSectionPreviousName = $groupname;
}
$programAASectionModelForSectionUsers = new ProgramSectionUser();
$programAASectionModelForSectionUsers->saveProgramGroupUsers($data);
});
$rules
array:7 [
"aasectionname.required" => "501 – AA section does not exist"
"aaid" => "numeric|exists:users,id|in:28,29,32,33,25,24,27|aaidinstitutionmismatch:42"
"institutionid" => "numeric|in:42"
"username" => "exists:users,UserName|in:Kabeer,Ayaz,fddesaaweqq,fdawerascvdfc,haseeb,kamran,shahid|usernameinstitutionmismatch:42"
"schoolid" => "numeric"
"groupowner" => "in:externalstaff,rahat,uzma,sahar,haseebahmad,saimariaz,fredrick"
"remove" => "in:0,1"
]

How could I fix this Auto Increment?

So, here is my problem on login through steam id it creates an account on my website but it also decides on next login to skip an Auto Increment causing the next registered member to gain a ton of Auto Incremented member id's
<?php
require ("common.php");
class SteamSignIn
{
const STEAM_LOGIN = 'https://steamcommunity.com/openid/login';
public static function genUrl($returnTo = false, $useAmp = true)
{
$returnTo = (!$returnTo) ? (!empty($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'] : $returnTo;
$params = array(
'openid.ns' => 'http://specs.openid.net/auth/2.0',
'openid.mode' => 'checkid_setup',
'openid.return_to' => $returnTo,
'openid.realm' => (!empty($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'],
'openid.identity' => 'http://specs.openid.net/auth/2.0/identifier_select',
'openid.claimed_id' => 'http://specs.openid.net/auth/2.0/identifier_select',
);
$sep = ($useAmp) ? '&' : '&';
return self::STEAM_LOGIN . '?' . http_build_query($params, '', $sep);
}
public static function validate()
{
$params = array(
'openid.assoc_handle' => $_GET['openid_assoc_handle'],
'openid.signed' => $_GET['openid_signed'],
'openid.sig' => $_GET['openid_sig'],
'openid.ns' => 'http://specs.openid.net/auth/2.0',
);
$signed = explode(',', $_GET['openid_signed']);
foreach($signed as $item)
{
$val = $_GET['openid_' . str_replace('.', '_', $item)];
$params['openid.' . $item] = get_magic_quotes_gpc() ? stripslashes($val) : $val;
}
$params['openid.mode'] = 'check_authentication';
$data = http_build_query($params);
$context = stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' =>
"Accept-language: en\r\n".
"Content-type: application/x-www-form-urlencoded\r\n" .
"Content-Length: " . strlen($data) . "\r\n",
'content' => $data,
),
));
$result = file_get_contents(self::STEAM_LOGIN, false, $context);
preg_match("#^http://steamcommunity.com/openid/id/([0-9]{17,25})#", $_GET['openid_claimed_id'], $matches);
$steamID64 = is_numeric($matches[1]) ? $matches[1] : 0;
return preg_match("#is_valid\s*:\s*true#i", $result) == 1 ? $steamID64 : '';
}
}
$steam_login_verify = SteamSignIn::validate();
if(!empty($steam_login_verify))
{
// Grab Data From Steam API
$json = file_get_contents('http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=' . $sapik . '&steamids='. $steam_login_verify .'&format=json');
//Decode Data From Steam API
$data = json_decode($json);
foreach($data->response->players as $player)
{
$query = "INSERT INTO steam (steamid, personaname, profileurl, avatar, avatarmedium, avatarfull ) VALUES ( :steamid, :personaname, :profileurl, :avatar, :avatarmedium, :avatarfull) ";
$query_params = array(
':steamid' => $player->steamid,
':personaname' => $player->personaname,
':profileurl' => $player->profileurl,
':avatar' => $player->avatar,
':avatarmedium' => $player->avatarmedium,
':avatarfull' => $player->avatarfull,
);
}
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
switch( $ex->errorInfo[1] )
{
case 1062:
$ps = $db->prepare("SELECT * FROM `steam` WHERE steamid = :sid");
$ps->bindParam(':sid', $steam_login_verify);
$ps->execute();
$ps->setFetchMode(PDO::FETCH_ASSOC);
foreach ($ps as $row)
{
$_SESSION['sid'] = $row['steamid'];
}
header('Location:'.$basedir);
die('redirecting to'.$basedir);
;
}
}
$ps = $db->prepare("SELECT * FROM `steam` WHERE steamid = :sid");
$ps->bindParam(':sid', $steam_login_verify);
$ps->execute();
$ps->setFetchMode(PDO::FETCH_ASSOC);
foreach ($ps as $row)
{
$_SESSION['sid'] = $row['steamid'];
}
header('Location:'.$basedir);
die('redirecting to'.$basedir);
} else {
$steam_sign_in_url = SteamSignIn::genUrl();
}

T_PAAMAYIM_NEKUDOTAYIM Error after override CButtonColumn

I overrode CButtonColumn class and code worked in perfect way on localhost(windows) , but when I uploaded it to linux server I had this error :
Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM in /home/xxx/public_html/protected/components/GridView/XCButtonColumn.php on line 65
I read about what mean "T_PAAMAYIM_NEKUDOTAYIM" , it's mean "::"
link here
,but I didn't understood what i can do to fix problem .
line 65:
if (is_array($modelClass::model()->primaryKey))
This is my code :
<?php
class XCButtonColumn extends CButtonColumn
{
public $htmlOptions = array('class' => 'center vcenter');
public $viewButtonOptions = array('class' => 'btn btn-default tip view');
public $viewButtonImageUrl = '';
public $viewButtonHtml;
public $updateButtonOptions = array('class' => 'btn btn-default tip update');
public $updateButtonImageUrl = '';
public $updateButtonHtml;
public $deleteButtonOptions = array('class' => 'btn btn-default tip delete');
public $deleteButtonImageUrl = '';
public $deleteButtonHtml;
public $showImage = false;
public $showHtml = true;
protected function renderButton($id, $button, $row, $data)
{
if (isset($button['visible']) && !$this->evaluateExpression($button['visible'], array('row' => $row, 'data' => $data))) return;
$label = isset($button['label']) ? $button['label'] : $id;
$url = isset($button['url']) ? $this->evaluateExpression($button['url'], array('data' => $data, 'row' => $row)) : '#';
$options = isset($button['options']) ? $button['options'] : array();
if (!isset($options['title'])) $options['title'] = $label;
if ($this->showImage) {
if (isset($button['imageUrl']) && is_string($button['imageUrl'])) {
echo CHtml::link(CHtml::image($button['imageUrl'], $label), $url, $options);
} else {
echo CHtml::link($label, $url, $options);
}
} else {
if (isset($button['html']) && is_string($button['html'])) {
echo CHtml::link($button['html'], $url, $options);
} else {
echo CHtml::link($button['html'], $url, $options);
}
}
}
protected function initDefaultButtons()
{
if ($this->viewButtonLabel === null) $this->viewButtonLabel = Yii::t('zii', 'View');
if ($this->updateButtonLabel === null)
$this->updateButtonLabel = Yii::t('zii', 'Update');
if ($this->deleteButtonLabel === null)
$this->deleteButtonLabel = Yii::t('zii', 'Delete');
if ($this->viewButtonImageUrl === null)
$this->viewButtonImageUrl = $this->grid->baseScriptUrl .
'/view.png';
if ($this->updateButtonImageUrl === null)
$this->updateButtonImageUrl = $this->grid->baseScriptUrl
. '/update.png';
if ($this->deleteButtonImageUrl === null)
$this->deleteButtonImageUrl = $this->grid->baseScriptUrl
. '/delete.png';
if ($this->viewButtonHtml === null)
$this->viewButtonHtml = '<i class="icon-zoom-in iconwhite"></i>';
if ($this->updateButtonHtml === null)
$this->updateButtonHtml = '<i class="icon-edit iconwhite"></i>';
if ($this->deleteButtonHtml === null)
$this->deleteButtonHtml = '<i class="icon-trash iconwhite"></i>';
if ($this->deleteConfirmation === null)
$this->deleteConfirmation = Yii::t('zii', 'Are you sure you want to delete this item?');
$modelClass = $this->grid->dataProvider->modelClass;
$controller = strtolower($modelClass);
if (is_array($modelClass::model()->primaryKey))
$paramExpression = '",$data->primaryKey)';
else
$paramExpression = '",array("id"=>$data->primaryKey))';
foreach (array('view', 'update', 'delete') as $id) {
$button = array(
'label' => $this->{$id . 'ButtonLabel'},
'url' => 'Yii::app()->urlManager->createUrl("' . "$controller/$id$paramExpression",
'imageUrl' => $this->{$id . 'ButtonImageUrl'},
'html' => $this->{$id . 'ButtonHtml'},
'options' => $this->{$id . 'ButtonOptions'},
);
if (isset($this->buttons[$id]))
$this->buttons[$id] = array_merge($button, $this->buttons[$id]);
else
$this->buttons[$id] = $button;
}
if (!isset($this->buttons['delete']['click'])) {
if (is_string($this->deleteConfirmation))
$confirmation = "if(!confirm(" .
CJavaScript::encode($this->deleteConfirmation) . ")) return false;";
else
$confirmation = '';
if (Yii::app()->request->enableCsrfValidation) {
$csrfTokenName = Yii::app()->request->csrfTokenName;
$csrfToken = Yii::app()->request->csrfToken;
$csrf = "\n\t\tdata:{ '$csrfTokenName':'$csrfToken'
},";
} else
$csrf = '';
if ($this->afterDelete === null)
$this->afterDelete = 'function(){}';
$this->buttons['delete']['click'] = <<<EOD
function() {
$confirmation
var th = this,
afterDelete = $this->afterDelete;
jQuery('#{$this->grid->id}').yiiGridView('update', {
type: 'POST',
url: jQuery(this).attr('href'),$csrf
success: function(data) {
jQuery('#{$this->grid->id}').yiiGridView('update');
afterDelete(th, true, data);
},
error: function(XHR) {
return afterDelete(th, false, XHR);
}
});
return false;
}
EOD;
}
}
}
Thanks in advance
First thanks to benka to help , the problem is in php version and php 5.2 not support
this line :
if (is_array($modelClass::model()->primaryKey))
So to be work on php 5.2 I changed it to be :
if (is_array(CActiveRecord::model($modelClass)->primaryKey))
References :
Link 1
Link 2
should be -> instead of ::
if (is_array($modelClass->model()->primaryKey))

Categories