PHP Behat/mink + selenium2 webdriver unexpectedly start new instance/session - php

I'm trying to help a friend automate some process using behat/mink + selenium2. It's working but somehow in the middle of the process, selenium2 starts new instance/session running in parallel from the original.
Is there a way to prevent this behavior and keep only one instance/session running?
This is my code (laravel controller class):
class testBehat extends Controller
{
protected $session;
public function __construct()
{
set_time_limit(300);
$driver = new Selenium2Driver('firefox');
$capabilities = $driver->getDefaultCapabilities();
$driver->setWebDriver(new WebDriver('http://10.99.0.11:5555/wd/hub'));
$this->session = new Session($driver);
}
public function run()
{
$admin = User::find(0);
$simulator = Simulator::find(0);
$this->session->start();
$this->login($admin->username, $admin->pass);
if ($this->isElementExist('id', 'profilemenu')) {
$this->session->visit('http://dar*******.com/simulator/new/');
}
$this->upload($simulator);
file_put_contents(public_path('screenshoot/' . $admin->user . '-' . $simulator->name . '-success.jpg'), $this->session->getScreenshot());
$this->session->stop();
return 'success';
}
private function login($user, $pass)
{
$this->session->visit('http://dar*******.com/signin');
$this->handlePages('id', 'username', 'text', $user);
$this->handlePages('id', 'password', 'text', $pass);
$this->handlePages('id', 'submit', 'click');
file_put_contents(public_path('screenshoot/' . $user . '-' . '-loggedin.jpg'), $this->session->getScreenshot());
}
private function isElementExist($selector, $locator)
{
if ($selector === 'css')
{
while (!$this->session->getPage()->has($selector, $locator)) {
sleep(1);
file_put_contents(public_path('public/element.jpg'), $this->session->getScreenshot());
}
$return = true;
}
elseif ($selector === 'id' || $selector === 'name')
{
if ($locator === 'tags') {
$selector = 'id_or_name';
}
while (!$this->session->getPage()->has('named', array($selector, $locator))) {
sleep(1);
file_put_contents(public_path('screenshoot/element.jpg'), $this->session->getScreenshot());
}
$return = true;
}
return $return;
}
public function handlePages($selector, $locator, $action, $data = null)
{
$element = $this->elementFinder($selector, $locator);
switch ($action) {
case 'text':
$element->setValue($data);
break;
case 'file':
$element->attachFile($data);
break;
case 'select':
$element->selectOption($data);
break;
case 'click':
$element->click();
break;
case 'load':
break;
case 'upload':
while ($element->getAttribute('style') !== 'width: 100%;') {
sleep(1);
}
break;
default:
echo 'Action not found.';
exit;
}
return $element;
}
public function elementFinder($selector, $locator)
{
if ($this->isElementExist($selector, $locator)) {
if ($selector === 'css') {
return $this->session->getPage()->find('css', $locator);
} else {
if ($locator === 'tags') {
$selector = 'id_or_name';
}
return $this->session->getPage()->find('named', array($selector, $locator));
}
} else {
echo 'Element not Found.';
}
return null;
}
private function upload($simulator)
{
$this->handlePages('id', 'fileupload', 'file', '~/simulator/'. $simulator->name);
sleep(4);
file_put_contents(public_path('screenshoot/' . $simulator->name . '-simulator-file.jpg'), $this->session->getScreenshot());
$this->handlePages('id', 'sim_name', 'text', $simulator->name);
file_put_contents(public_path('screenshoot/' . $simulator->name . '-name-field.jpg'), $this->session->getScreenshot());
$this->handlePages('id', 'sim_category', 'select', $simulator->category);
$this->handlePages('id', 'sim_remark', 'text', $simulator->remark));
$this->handlePages('id', 'save', 'click');
}
}
I'm running selenium server in grid mode, hub and node connected via internal network (LAN). This is the command i use to start the selenium server (i renamed the jar file to selenium-server.jar):
root#10.99.0.10:~/selenium2# java -jar selenium-server.jar -role hub -timeout 12000 -browserTimeout 12000
root#10.99.0.11:~/selenium2# java -jar selenium-server.jar -role node -host 10.99.0.11 -hub http://10.99.0.10:4444/grid/register/ -timeout 12000 -browserTimeout 12000
I'm using laravel 5.1, behat/mink, behat/mink-selenium2-driver and selenium standalone 2.48.2
and this is my problem where the selenium2 unexpectedly start new session while first/original session running.
Original session starting
Unexpectedly started another session while the original running
How to tell the selenium2 server to only start/run 1 session at a time?
Thank you.

Related

Problem with accessing values in Request Session that I put into

I am fairly new to Laravel. This may have an obvious solution but I can't seem to find it so far. Therefore I am asking for help.
Question In Short:
I use Illuminate\Http\Request session ($request->session()) to store some data I get from BigCommerce API. But I can't get them when I need the data.
Context:
I am building a sample app/boilerplate app for BigCommerce platform using Laravel/React. I have built the app using official documentation, semi-official posts released by BigCommerce team and sample codebase provided by them as well.
App works fine with local credentials from a specific store because they are given as environment variables to the app. However I can't read store_hash (which is necessary to fetch data from BigCommerce) and access token. Both I have put in $request->session() object.
I will paste the AppController.php code below, also code is publicly available here:
In the makeBigCommerceAPIRequest method below (as you can see my debugging efforts :)) I can get $this->getAppClientId(), but I can't get anything from $request->session()->get('store_hash') or $request->session()->get('access_token') which returns from $this->getAccessToken($request).
I have tried putting store hash into a global variable, but it didn't work.
From everything I have experienced so far, $request is not working as expected.
Any help appriciated, thanks in advance.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use mysql_xdevapi\Exception;
use Oseintow\Bigcommerce\Bigcommerce;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Bigcommerce\Api\Client as BigcommerceClient;
use Illuminate\Support\Facades\Storage;
use App\Config; //Database Connection
use Bigcommerce\Api\Connection;
class AppController extends Controller
{
protected $bigcommerce;
private $client_id;
private $client_secret;
private $access_token;
private $storehash;
private $redirect_uri;
public function __construct(Bigcommerce $bigcommerce)
{
$this->bigcommerce = $bigcommerce;
$this->client_id = \config('app.clientId');
$this->client_secret = \config('app.clientSecret');
$this->redirect_uri = \config('app.authCallback');
}
public function getAppClientId()
{
if (\config('app.appEnv') === 'local') {
return \config('app.localClientId');
} else {
return \config('app.clientId');
}
}
public function getAppSecret()
{
if (\config('app.appEnv') === 'local') {
return \config('app.localClientSecret');
} else {
return \config('app.clientSecret');
}
}
public function getAccessToken(Request $request)
{
if (\config('app.appEnv') === 'local') {
return \config('app.localAccessToken');
} else {
return $request->session()->get('access_token');
}
}
public function getStoreHash(Request $request)
{
if (\config('app.appEnv') === 'local') {
return \config('app.localStoreHash');
} else {
return $request->session()->get('store_hash');
}
}
public function error(Request $request)
{
$errorMessage = "Internal Application Error";
if ($request->session()->has('error_message')) {
$errorMessage = $request->session()->get('error_message');
}
echo '<h4>An issue has occurred:</h4> <p>' . $errorMessage . '</p> Go back to home';
}
public function load(Request $request)
{
$signedPayload = $request->get('signed_payload');
if (!empty($signedPayload)) {
echo "hello";
$verifiedSignedRequestData = $this->verifySignedRequest($signedPayload);
if ($verifiedSignedRequestData !== null) {
echo "positive return";
$request->session()->put('user_id', $verifiedSignedRequestData['user']['id']);
$request->session()->put('user_email', $verifiedSignedRequestData['user']['email']);
$request->session()->put('owner_id', $verifiedSignedRequestData['owner']['id']);
$request->session()->put('owner_email', $verifiedSignedRequestData['owner']['email']);
$request->session()->put('store_hash', $verifiedSignedRequestData['context']);
echo $request->session()->get('store_hash');
$this->storehash = $verifiedSignedRequestData['context'];
echo ' store hash is at the moment : ' . $this->storehash . ' .....';
} else {
return "The signed request from BigCommerce could not be validated.";
// return redirect()->action([AppController::class, 'error'])->with('error_message', 'The signed request from BigCommerce could not be validated.');
}
} else {
return "The signed request from BigCommerce was empty.";
// return redirect()->action([AppController::class, 'error'])->with('error_message', 'The signed request from BigCommerce was empty.');
}
return redirect(\config('app.appUrl'));
}
public function install(Request $request)
{
// Make sure all required query params have been passed
if (!$request->has('code') || !$request->has('scope') || !$request->has('context')) {
echo 'Not enough information was passed to install this app.';
// return redirect()->action('MainController#error')->with('error_message', 'Not enough information was passed to install this app.');
}
try {
$client = new Client();
$result = $client->request('POST', 'https://login.bigcommerce.com/oauth2/token', [
'json' => [
'client_id' => $this->client_id,
'client_secret' => $this->client_secret,
'redirect_uri' => $this->redirect_uri,
'grant_type' => 'authorization_code',
'code' => $request->input('code'),
'scope' => $request->input('scope'),
'context' => $request->input('context'),
]
]);
$statusCode = $result->getStatusCode();
$data = json_decode($result->getBody(), true);
if ($statusCode == 200) {
$request->session()->put('store_hash', $data['context']);
$request->session()->put('access_token', $data['access_token']);
$request->session()->put('user_id', $data['user']['id']);
$request->session()->put('user_email', $data['user']['email']);
// $configValue = Config::select('*')->where('storehash', $data['context'])->get()->toArray();
// if (count($configValue) != 0) {
// $id = $configValue[0]['id'];
// $configObj = Config::find($id);
// $configObj->access_token = $data['access_token'];
// $configObj->save();
// } else {
// $configObj = new Config;
// $configObj->email = $data['user']['email'];
// $configObj->storehash = $data['context'];
// $configObj->access_token = $data['access_token'];
// $configObj->save();
// }
// If the merchant installed the app via an external link, redirect back to the
// BC installation success page for this app
if ($request->has('external_install')) {
return redirect('https://login.bigcommerce.com/app/' . $this->getAppClientId() . '/install/succeeded');
}
}
return redirect(\config('app.appUrl'));
} catch (RequestException $e) {
$statusCode = $e->getResponse()->getStatusCode();
echo $statusCode;
$errorMessage = "An error occurred.";
if ($e->hasResponse()) {
if ($statusCode != 500) {
echo "some error other than 500";
// $errorMessage = Psr7\str($e->getResponse());
}
}
// If the merchant installed the app via an external link, redirect back to the
// BC installation failure page for this app
if ($request->has('external_install')) {
return redirect('https://login.bigcommerce.com/app/' . $this->getAppClientId() . '/install/failed');
} else {
echo "fail";
// return redirect()->action('MainController#error')->with('error_message', $errorMessage);
}
}
// return view('index');
}
public function verifySignedRequest($signedRequest)
{
list($encodedData, $encodedSignature) = explode('.', $signedRequest, 2);
// decode the data
$signature = base64_decode($encodedSignature);
$jsonStr = base64_decode($encodedData);
echo $jsonStr;
$data = json_decode($jsonStr, true);
// confirm the signature
$expectedSignature = hash_hmac('sha256', $jsonStr, $this->client_secret, $raw = false);
if (!hash_equals($expectedSignature, $signature)) {
error_log('Bad signed request from BigCommerce!');
return null;
}
return $data;
}
public function makeBigCommerceAPIRequest(Request $request, $endpoint)
{
echo ' ...... trying to make an apiRequest now : with storehash : ' . $this->storehash . ' .............';
echo '...........................................';
echo 'other variables at the moment :::: ............... client ID :' . $this->getAppClientId() . '...................... token : ' . $this->getAccessToken($request) . '...............';
$requestConfig = [
'headers' => [
'X-Auth-Client' => $this->getAppClientId(),
'X-Auth-Token' => $this->getAccessToken($request),
'Content-Type' => 'application/json',
]
];
if ($request->method() === 'PUT') {
$requestConfig['body'] = $request->getContent();
}
$client = new Client();
$result = $client->request($request->method(), 'https://api.bigcommerce.com/' . $this->storehash . '/' . $endpoint, $requestConfig);
return $result;
}
public function proxyBigCommerceAPIRequest(Request $request, $endpoint)
{
if (strrpos($endpoint, 'v2') !== false) {
// For v2 endpoints, add a .json to the end of each endpoint, to normalize against the v3 API standards
$endpoint .= '.json';
}
echo ' asadssada ...... trying to make an apiRequest now : with storehash : ' . $this->storehash . ' .............' . $request->session()->get('store_hash') . ' ............ ';
$result = $this->makeBigCommerceAPIRequest($request, $endpoint);
return response($result->getBody(), $result->getStatusCode())->header('Content-Type', 'application/json');
}
}
Thanks for the detailed info. Though it would help to annotate the debug lines with confirmation of what they output, I am making the assumption that you have narrowed the problem down to the session storage and retrieval lines.
$request->session()->put() and get() are the correct ways to access session.
I would therefore suggest investigating Session configuration: https://laravel.com/docs/8.x/session#configuration
If using file-based sessions, confirm that there are no permissions errors, perhaps. Alternatively try and different session storage mechanism.

OS Ticket not load properly

My company just launched a new website with OS Ticket. This OS Ticket was attached to the old WordPress website before we make a switch. Currently, OS Ticket does not load with OS Ticket Content and navigation.
I want to successfully migrate OS ticket database to a new website, but I get these errors:
php error – /support/main.inc.php on line 78
php error – /support/include/class.nav.php on line 321
If it does not load, it means the path not found. I don’t know where to look for it. Any help is greatly appreciated.
[06-Sep-2016 09:09:27 America/Denver] PHP Warning: include(): Failed opening '/support/../wp-blog-header.php' for inclusion (include_path='./:/support/include/:/support/include/pear/') in /support/main.inc.php on line 78
<?php
/*********************************************************************
class.nav.php
Navigation helper classes. Pointless BUT helps keep navigation clean and free from errors.
Peter Rotich <peter#osticket.com>
Copyright (c) 2006-2013 osTicket
http://www.osticket.com
Released under the GNU General Public License WITHOUT ANY WARRANTY.
See LICENSE.TXT for details.
vim: expandtab sw=4 ts=4 sts=4:
**********************************************************************/
require_once(INCLUDE_DIR.'class.app.php');
class StaffNav {
var $activetab;
var $activeMenu;
var $panel;
var $staff;
function StaffNav($staff, $panel='staff'){
$this->staff=$staff;
$this->panel=strtolower($panel);
}
function __get($what) {
// Lazily initialize the tabbing system
switch($what) {
case 'tabs':
$this->tabs=$this->getTabs();
break;
case 'submenus':
$this->submenus=$this->getSubMenus();
break;
default:
throw new Exception($what . ': No such attribute');
}
return $this->{$what};
}
function getPanel(){
return $this->panel;
}
function isAdminPanel(){
return (!strcasecmp($this->getPanel(),'admin'));
}
function isStaffPanel() {
return (!$this->isAdminPanel());
}
function getRegisteredApps() {
return Application::getStaffApps();
}
function setTabActive($tab, $menu=''){
if($this->tabs[$tab]){
$this->tabs[$tab]['active']=true;
if($this->activetab && $this->activetab!=$tab && $this->tabs[$this->activetab])
$this->tabs[$this->activetab]['active']=false;
$this->activetab=$tab;
if($menu) $this->setActiveSubMenu($menu, $tab);
return true;
}
return false;
}
function setActiveTab($tab, $menu=''){
return $this->setTabActive($tab, $menu);
}
function getActiveTab(){
return $this->activetab;
}
function setActiveSubMenu($mid, $tab='') {
if(is_numeric($mid))
$this->activeMenu = $mid;
elseif($mid && $tab && ($subNav=$this->getSubNav($tab))) {
foreach($subNav as $k => $menu) {
if(strcasecmp($mid, $menu['href'])) continue;
$this->activeMenu = $k+1;
break;
}
}
}
function getActiveMenu() {
return $this->activeMenu;
}
function addSubMenu($item,$active=false){
// Triger lazy loading if submenus haven't been initialized
isset($this->submenus[$this->getPanel().'.'.$this->activetab]);
$this->submenus[$this->getPanel().'.'.$this->activetab][]=$item;
if($active)
$this->activeMenu=sizeof($this->submenus[$this->getPanel().'.'.$this->activetab]);
}
function getTabs(){
if(!$this->tabs) {
$this->tabs=array();
$this->tabs['dashboard'] = array('desc'=>__('Dashboard'),'href'=>'dashboard.php','title'=>__('Agent Dashboard'), "class"=>"no-pjax");
$this->tabs['users'] = array('desc' => __('Users'), 'href' => 'users.php', 'title' => __('User Directory'));
$this->tabs['tickets'] = array('desc'=>__('Tickets'),'href'=>'tickets.php','title'=>__('Ticket Queue'));
$this->tabs['kbase'] = array('desc'=>__('Knowledgebase'),'href'=>'kb.php','title'=>__('Knowledgebase'));
if (count($this->getRegisteredApps()))
$this->tabs['apps']=array('desc'=>__('Applications'),'href'=>'apps.php','title'=>__('Applications'));
}
return $this->tabs;
}
function getSubMenus(){ //Private.
global $cfg;
$staff = $this->staff;
$submenus=array();
foreach($this->getTabs() as $k=>$tab){
$subnav=array();
switch(strtolower($k)){
case 'tickets':
$subnav[]=array('desc'=>__('Tickets'),'href'=>'tickets.php','iconclass'=>'Ticket', 'droponly'=>true);
if($staff) {
if(($assigned=$staff->getNumAssignedTickets()))
$subnav[]=array('desc'=>__('My Tickets')." ($assigned)",
'href'=>'tickets.php?status=assigned',
'iconclass'=>'assignedTickets',
'droponly'=>true);
if($staff->canCreateTickets())
$subnav[]=array('desc'=>__('New Ticket'),
'title' => __('Open a New Ticket'),
'href'=>'tickets.php?a=open',
'iconclass'=>'newTicket',
'id' => 'new-ticket',
'droponly'=>true);
}
break;
case 'dashboard':
$subnav[]=array('desc'=>__('Dashboard'),'href'=>'dashboard.php','iconclass'=>'logs');
$subnav[]=array('desc'=>__('Agent Directory'),'href'=>'directory.php','iconclass'=>'teams');
$subnav[]=array('desc'=>__('My Profile'),'href'=>'profile.php','iconclass'=>'users');
break;
case 'users':
$subnav[] = array('desc' => __('User Directory'), 'href' => 'users.php', 'iconclass' => 'teams');
$subnav[] = array('desc' => __('Organizations'), 'href' => 'orgs.php', 'iconclass' => 'departments');
break;
case 'kbase':
$subnav[]=array('desc'=>__('FAQs'),'href'=>'kb.php', 'urls'=>array('faq.php'), 'iconclass'=>'kb');
if($staff) {
if($staff->canManageFAQ())
$subnav[]=array('desc'=>__('Categories'),'href'=>'categories.php','iconclass'=>'faq-categories');
if ($cfg->isCannedResponseEnabled() && $staff->canManageCannedResponses())
$subnav[]=array('desc'=>__('Canned Responses'),'href'=>'canned.php','iconclass'=>'canned');
}
break;
case 'apps':
foreach ($this->getRegisteredApps() as $app)
$subnav[] = $app;
break;
}
if($subnav)
$submenus[$this->getPanel().'.'.strtolower($k)]=$subnav;
}
return $submenus;
}
function getSubMenu($tab=null){
$tab=$tab?$tab:$this->activetab;
return $this->submenus[$this->getPanel().'.'.$tab];
}
function getSubNav($tab=null){
return $this->getSubMenu($tab);
}
}
class AdminNav extends StaffNav{
function AdminNav($staff){
parent::StaffNav($staff, 'admin');
}
function getRegisteredApps() {
return Application::getAdminApps();
}
function getTabs(){
if(!$this->tabs){
$tabs=array();
$tabs['dashboard']=array('desc'=>__('Dashboard'),'href'=>'logs.php','title'=>__('Admin Dashboard'));
$tabs['settings']=array('desc'=>__('Settings'),'href'=>'settings.php','title'=>__('System Settings'));
$tabs['manage']=array('desc'=>__('Manage'),'href'=>'helptopics.php','title'=>__('Manage Options'));
$tabs['emails']=array('desc'=>__('Emails'),'href'=>'emails.php','title'=>__('Email Settings'));
$tabs['staff']=array('desc'=>__('Agents'),'href'=>'staff.php','title'=>__('Manage Agents'));
if (count($this->getRegisteredApps()))
$tabs['apps']=array('desc'=>__('Applications'),'href'=>'apps.php','title'=>__('Applications'));
$this->tabs=$tabs;
}
return $this->tabs;
}
function getSubMenus(){
$submenus=array();
foreach($this->getTabs() as $k=>$tab){
$subnav=array();
switch(strtolower($k)){
case 'dashboard':
$subnav[]=array('desc'=>__('System Logs'),'href'=>'logs.php','iconclass'=>'logs');
$subnav[]=array('desc'=>__('Information'),'href'=>'system.php','iconclass'=>'preferences');
break;
case 'settings':
$subnav[]=array('desc'=>__('Company'),'href'=>'settings.php?t=pages','iconclass'=>'pages');
$subnav[]=array('desc'=>__('System'),'href'=>'settings.php?t=system','iconclass'=>'preferences');
$subnav[]=array('desc'=>__('Tickets'),'href'=>'settings.php?t=tickets','iconclass'=>'ticket-settings');
$subnav[]=array('desc'=>__('Emails'),'href'=>'settings.php?t=emails','iconclass'=>'email-settings');
$subnav[]=array('desc'=>__('Access'),'href'=>'settings.php?t=access','iconclass'=>'users');
$subnav[]=array('desc'=>__('Knowledgebase'),'href'=>'settings.php?t=kb','iconclass'=>'kb-settings');
$subnav[]=array('desc'=>__('Autoresponder'),'href'=>'settings.php?t=autoresp','iconclass'=>'email-autoresponders');
$subnav[]=array('desc'=>__('Alerts and Notices'),'href'=>'settings.php?t=alerts','iconclass'=>'alert-settings');
break;
case 'manage':
$subnav[]=array('desc'=>__('Help Topics'),'href'=>'helptopics.php','iconclass'=>'helpTopics');
$subnav[]=array('desc'=>__('Ticket Filters'),'href'=>'filters.php',
'title'=>__('Ticket Filters'),'iconclass'=>'ticketFilters');
$subnav[]=array('desc'=>__('SLA Plans'),'href'=>'slas.php','iconclass'=>'sla');
$subnav[]=array('desc'=>__('API Keys'),'href'=>'apikeys.php','iconclass'=>'api');
$subnav[]=array('desc'=>__('Pages'), 'href'=>'pages.php','title'=>'Pages','iconclass'=>'pages');
$subnav[]=array('desc'=>__('Forms'),'href'=>'forms.php','iconclass'=>'forms');
$subnav[]=array('desc'=>__('Lists'),'href'=>'lists.php','iconclass'=>'lists');
$subnav[]=array('desc'=>__('Plugins'),'href'=>'plugins.php','iconclass'=>'api');
break;
case 'emails':
$subnav[]=array('desc'=>__('Emails'),'href'=>'emails.php', 'title'=>__('Email Addresses'), 'iconclass'=>'emailSettings');
$subnav[]=array('desc'=>__('Banlist'),'href'=>'banlist.php',
'title'=>__('Banned Emails'),'iconclass'=>'emailDiagnostic');
$subnav[]=array('desc'=>__('Templates'),'href'=>'templates.php','title'=>__('Email Templates'),'iconclass'=>'emailTemplates');
$subnav[]=array('desc'=>__('Diagnostic'),'href'=>'emailtest.php', 'title'=>__('Email Diagnostic'), 'iconclass'=>'emailDiagnostic');
break;
case 'staff':
$subnav[]=array('desc'=>__('Agents'),'href'=>'staff.php','iconclass'=>'users');
$subnav[]=array('desc'=>__('Teams'),'href'=>'teams.php','iconclass'=>'teams');
$subnav[]=array('desc'=>__('Groups'),'href'=>'groups.php','iconclass'=>'groups');
$subnav[]=array('desc'=>__('Departments'),'href'=>'departments.php','iconclass'=>'departments');
break;
case 'apps':
foreach ($this->getRegisteredApps() as $app)
$subnav[] = $app;
break;
}
if($subnav)
$submenus[$this->getPanel().'.'.strtolower($k)]=$subnav;
}
return $submenus;
}
}
class UserNav {
var $navs=array();
var $activenav;
var $user;
function UserNav($user=null, $active=''){
$this->user=$user;
$this->navs=$this->getNavs();
if($active)
$this->setActiveNav($active);
}
function getRegisteredApps() {
return Application::getClientApps();
}
function setActiveNav($nav){
if($nav && $this->navs[$nav]){
$this->navs[$nav]['active']=true;
if($this->activenav && $this->activenav!=$nav && $this->navs[$this->activenav])
$this->navs[$this->activenav]['active']=false;
$this->activenav=$nav;
return true;
}
return false;
}
function getNavLinks(){
global $cfg;
//Paths are based on the root dir.
if(!$this->navs){
$navs = array();
$user = $this->user;
$navs['home']=array('desc'=>__('Support Center Home'),'href'=>'index.php','title'=>'');
if($cfg && $cfg->isKnowledgebaseEnabled())
$navs['kb']=array('desc'=>__('Knowledgebase'),'href'=>'kb/index.php','title'=>'');
// Show the "Open New Ticket" link unless BOTH client
// registration is disabled and client login is required for new
// tickets. In such a case, creating a ticket would not be
// possible for web clients.
if ($cfg->getClientRegistrationMode() != 'disabled'
|| !$cfg->isClientLoginRequired())
$navs['new']=array('desc'=>__('Open a New Ticket'),'href'=>'open.php','title'=>'');
if($user && $user->isValid()) {
if(!$user->isGuest()) {
$navs['tickets']=array('desc'=>sprintf(__('Tickets (%d)'),$user->getNumTickets()),
'href'=>'tickets.php',
'title'=>__('Show all tickets'));
} else {
$navs['tickets']=array('desc'=>__('View Ticket Thread'),
'href'=>sprintf('tickets.php?id=%d',$user->getTicketId()),
'title'=>__('View ticket status'));
}
} else {
$navs['status']=array('desc'=>__('Check Ticket Status'),'href'=>'view.php','title'=>'');
}
$this->navs=$navs;
}
return $this->navs;
}
function getNavs(){
return $this->getNavLinks();
}
}
?>

Logging SOAP envelope in third party library

I am attempting to add logging for the envelope generated by a third party library. I am modifying the updateMetadataField() method below.
I am creating $client like so:
$client = new UpdateClient($UPDATE_END_POINT, $USER_AUTH_ARRAY);
I have tried both $this->client->__getLastRequest() and $this->__getLastRequest() with the same error as a result.
When the SoapClient is instantiated trace is set to true.
Error is
Fatal error: Call to undefined method UpdateClient::__getLastRequest()
So how do I correctly access the __getLastRequest() method?
$USER_AUTH_ARRAY = array(
'login'=>"foo",
'password'=>"bar",
'exceptions'=>0,
'trace'=>true,
'features' => SOAP_SINGLE_ELEMENT_ARRAYS
);
class UpdateClient {
private $client;
public function __construct($endpoint, $auth_array) {
$this->client = new SoapClient($endpoint, $auth_array);
}
public function updateMetadataField($uuid, $key, $value) {
$result = $this->client->updateMetadataField(array(
'assetUuid' => $uuid,
'key' => $key,
'value' => $value)
);
if(is_soap_fault($result)) {
return $result;
}
return $result->return . "\n\n" . $this->client->__getLastRequest();
} // updateMetadataField()
} // UpdateClient
UPDATE - adding calling code This code iterates over an array which maps our data to the remote fields.
What I am hoping to do is begin storing the envelope we send to aid in debugging.
$client = new UpdateClient($UPDATE_END_POINT, $USER_AUTH_ARRAY);
foreach ($widen_to_nool_meta_map as $widen => $nool) { // array defined in widen.php
if ($nool != '') {
// handle exceptions
if ($nool == 'asset_created') { // validate as date - note that Widen pulls exif data so we don't need to pass this
if (!strtotime($sa->$nool)) {
continue;
}
} else if ($nool == 'people_in_photo' || $nool == 'allow_sublicensing' || $nool == 'allowed_use_pr_gallery') {
// we store as 0/1 but GUI at Widen wants Yes/No
$sa->$nool = ($sa->$nool == '1') ? 'Yes' : 'No';
} else if ($nool == 'credit_requirements') {
$sa->$nool = $sa->credit_requirements()->label;
}
$result = $client->updateMetadataField($sa->widen_id, $widen, $sa->$nool);
if(is_soap_fault($result)) {
$sync_result = $sync_result . "\n" . $result->getMessage();
} else {
$sync_result = $sync_result . "\n" . print_r($result, 1);
}
} // nool field set
} // foreach mapped field
If you want to access UpdateClient::__getLastRequest() you have to expose that method on the UpdateClient class since the $client is a private variable. The correct way of calling it is $this->client->__getLastRequest().
Take a look at this working example, as you can see I'm consuming a free web service for testing purposes.
<?php
$USER_AUTH_ARRAY = array(
'exceptions'=>0,
'trace'=>true,
'features' => SOAP_SINGLE_ELEMENT_ARRAYS
);
class TestClient {
private $client;
public function __construct($endpoint, $auth_array) {
$this->client = new SoapClient($endpoint, $auth_array);
}
public function CelsiusToFahrenheit( $celsius ) {
$result = $this->client->CelsiusToFahrenheit(array(
'Celsius' => $celsius
)
);
if(is_soap_fault($result)) {
return $result;
}
return $result;
}
public function __getLastRequest() {
return $this->client->__getLastRequest();
}
}
try
{
$test = new TestClient( "http://www.w3schools.com/webservices/tempconvert.asmx?wsdl", $USER_AUTH_ARRAY);
echo "<pre>";
var_dump($test->CelsiusToFahrenheit( 0 ));
var_dump($test->__getLastRequest());
var_dump($test->CelsiusToFahrenheit( 20 ));
var_dump($test->__getLastRequest());
echo "</pre>";
}
catch (SoapFault $fault)
{
echo $fault->faultcode;
}
?>

save form field in component params joomla

I am using joomla 2.5, I am working on custom component of joomla . I have created the form in backend admin page. what i need is , i want to save the post data of form in params row of that component in database of #_extensions.
Here is my tables/component.php
<?php defined('_JEXEC') or die('Restricted access');
jimport('joomla.database.table');
class componentTablecomponent extends JTable {
function __construct(&$db)
{
parent::__construct('#__extensions', 'extension_id', $db);
}
public function bind($array, $ignore = '')
{
if (isset($array['params']) && is_array($array['params']))
{
// Convert the params field to a string.
$parameter = new JRegistry;
$parameter->loadArray($array['params']);
$array['params'] = (string)$parameter;
}
return parent::bind($array, $ignore);
}
public function load($pk = null, $reset = true)
{
if (parent::load($pk, $reset))
{
// Convert the params field to a registry.
$params = new JRegistry;
$params->loadJSON($this->params);
$this->params = $params;
return true;
}
else
{
return false;
}
} public function store() {
parent::store(null);
}
}
Instead of saving the $data in params row of that component . This code is creating new empty rows in that table(data is saving in those params field).
Here is my save() function in controllers/component.php
public function save()
{
// Check for request forgeries.
JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN'));
// Check if the user is authorized to do this.
if (!JFactory::getUser()->authorise('core.admin'))
{
`JFactory::getApplication()->redirect('index.php',JText::_('JERROR_ALERTNOAUTHOR'));`
return;
}
// Initialise variables.
$app = JFactory::getApplication();
$model = $this->getModel('component');
$form = $model->getForm();
$data = JRequest::getVar('jform', array(), 'post', 'array');
print_r($data);
// Validate the posted data.
$return = $model->validate($form, $data);
// Check for validation errors.
if ($return === false)
{
// Get the validation messages.
$errors = $model->getErrors();
// Push up to three validation messages out to the user.
for ($i = 0, $n = count($errors); $i < $n && $i < 3; $i++) {
if ($errors[$i] instanceof Exception) {
$app->enqueueMessage($errors[$i]->getMessage(), 'warning');
} else {
$app->enqueueMessage($errors[$i], 'warning');
}
}
// Redirect back to the edit screen.
$this->setRedirect(JRoute::_('somelink',false));
return false;
}
// Attempt to save the configuration.
$data = $return;
$return = $model->save($data);
// Check the return value.
if ($return === false)
{
// Save failed, go back to the screen and display a notice.
$message = JText::sprintf('JERROR_SAVE_FAILED', $model->getError());
$this->setRedirect('index.php/somelink','error');
return false;
}
// Set the success message.
$message = JText::_('COM_CONFIG_SAVE_SUCCESS');
// Set the redirect based on the task.
switch ($this->getTask())
{
case 'apply':
$this->setRedirect('somelink',$message);
break;
case 'cancel':
case 'save':
default:
$this->setRedirect('index.php', $message);
break;
}
return true;
}
models/component.php
public function save($data) {
parent::save($data);
return true;
}
I thinks these codes are enough . I can add more codes if you need.
If you want to store params in the extension table, why not just use com_config for it?
See http://docs.joomla.org/J2.5:Developing_a_MVC_Component/Adding_configuration
Then you don't have to do anything besides creating the config.xml and adding a link to the config options in the toolbar.
I have come up with a solution . it works for me . By using this method you can control save () functions i.e. you can run your custom php scripts on save, apply toolbar buttons.
I copied save(),save($data), store($updateNulls = false) functions from com_config component , I have copied the layout from component view . Removed the buttons. Added toolbar buttons in .html.php file.
controllers/mycomponent.php
<?php
defined('_JEXEC') or die;
class componentControllermycomponent extends JControllerLegacy {
function __construct($config = array())
{
parent::__construct($config);
// Map the apply task to the save method.
$this->registerTask('apply', 'save');
}
function save()
{
// Check for request forgeries.
JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN'));
// Set FTP credentials, if given.
JClientHelper::setCredentialsFromRequest('ftp');
// Initialise variables.
$app = JFactory::getApplication();
$model = $this->getModel('mymodel');
$form = $model->getForm();
$data = JRequest::getVar('jform', array(), 'post', 'array');
$id = JRequest::getInt('id');
$option = 'com_mycomponent';
// Check if the user is authorized to do this.
if (!JFactory::getUser()->authorise('core.admin', $option))
{
JFactory::getApplication()->redirect('index.php', JText::_('JERROR_ALERTNOAUTHOR'));
return;
}
// Validate the posted data.
$return = $model->validate($form, $data);
// Check for validation errors.
if ($return === false) {
// Get the validation messages.
$errors = $model->getErrors();
// Push up to three validation messages out to the user.
for ($i = 0, $n = count($errors); $i < $n && $i < 3; $i++) {
if ($errors[$i] instanceof Exception) {
$app->enqueueMessage($errors[$i]->getMessage(), 'warning');
} else {
$app->enqueueMessage($errors[$i], 'warning');
}
}
// Save the data in the session.
$app->setUserState('com_iflychat.config.global.data', $data);
// Redirect back to the edit screen.
$this->setRedirect(JRoute::_('index.php?option=com_mycomponent&view=component&component='.$option.'&tmpl=component', false));
return false;
}
// Attempt to save the configuration.
$data = array(
'params' => $return,
'id' => $id,
'option' => $option
);
// print_r($data);
$return = $model->save($data);
// Check the return value.
if ($return === false)
{
// Save the data in the session.
$app->setUserState('com_config.config.global.data', $data);
// Save failed, go back to the screen and display a notice.
$message = JText::sprintf('JERROR_SAVE_FAILED', $model->getError());
$this->setRedirect('index.php?option=com_mycomponent&view=component&component='.$option.'&tmpl=component', $message, 'error');
return false;
}
// Set the redirect based on the task.
switch ($this->getTask())
{
case 'apply':
$message = JText::_('COM_MYCOMPONENT_SAVE_SUCCESS');
print_r($data);
$this->setRedirect('index.php?option=com_mycomponent&view=myview&layout=edit', $message);
break;
case 'save':
default:
$this->setRedirect('index.php');
break;
}
return true;
}
function cancel()
{
$this->setRedirect('index.php');
}
}
models/mymodel.php
<?php
defined('_JEXEC') or die;
jimport('joomla.application.component.modelform');
class componentModelmymodel extends JModelForm {
protected $event_before_save = 'onConfigurationBeforeSave';
protected $event_after_save = 'onConfigurationAfterSave';
public function getForm($data = array(), $loadData = true){
// Get the form.
$form = $this->loadForm('com_mycomponent.form', 'config',
array('control' => 'jform', 'load_data' => $loadData));
if (empty($form)){
return false;
}
return $form;
}
public function save($data)
{
$dispatcher = JDispatcher::getInstance();
$table = JTable::getInstance('extension');
$isNew = true;
// Save the rules.
if (isset($data['params']) && isset($data['params']['rules']))
{
$rules = new JAccessRules($data['params']['rules']);
$asset = JTable::getInstance('asset');
if (!$asset->loadByName($data['option']))
{
$root = JTable::getInstance('asset');
$root->loadByName('root.1');
$asset->name = $data['option'];
$asset->title = $data['option'];
$asset->setLocation($root->id, 'last-child');
}
$asset->rules = (string) $rules;
if (!$asset->check() || !$asset->store())
{
$this->setError($asset->getError());
return false;
}
// We don't need this anymore
unset($data['option']);
unset($data['params']['rules']);
}
// Load the previous Data
if (!$table->load($data['id']))
{
$this->setError($table->getError());
return false;
}
unset($data['id']);
// Bind the data.
if (!$table->bind($data))
{
$this->setError($table->getError());
return false;
}
// Check the data.
if (!$table->check())
{
$this->setError($table->getError());
return false;
}
// Trigger the oonConfigurationBeforeSave event.
$result = $dispatcher->trigger($this->event_before_save, array($this->option . '.' . $this->name, $table, $isNew));
if (in_array(false, $result, true))
{
$this->setError($table->getError());
return false;
}
// Store the data.
if (!$table->store())
{
$this->setError($table->getError());
return false;
}
// Clean the component cache.
$this->cleanCache('_system');
// Trigger the onConfigurationAfterSave event.
$dispatcher->trigger($this->event_after_save, array($this->option . '.' . $this->name, $table, $isNew));
return true;
}
function getComponent()
{
$result = JComponentHelper::getComponent('com_mycomponent');
return $result;
}
}
tables/mycomponent.php
<?php
// No direct access
defined('_JEXEC') or die('Restricted access');
// import Joomla table library
jimport('joomla.database.table');
/**
* Hello Table class
*/
class componentTableMycomponent extends JTable
{
function __construct(&$db)
{
parent::__construct('#__extensions', 'extension_id', $db);
}
public function bind($array, $ignore = '')
{
if (isset($array['params']) && is_array($array['params']))
{
// Convert the params field to a string.
$parameter = new JRegistry;
$parameter->loadArray($array['params']);
$array['params'] = (string)$parameter;
}
return parent::bind($array, $ignore);
}
public function load($pk = null, $reset = true)
{
if (parent::load($pk, $reset))
{
// Convert the params field to a registry.
$params = new JRegistry;
$params->loadJSON($this->params);
$this->params = $params;
return true;
}
else
{
return false;
}
}
public function store($updateNulls = false)
{
// Transform the params field
if (is_array($this->params)) {
$registry = new JRegistry();
$registry->loadArray($this->params);
$this->params = (string)$registry;
}
$date = JFactory::getDate();
$user = JFactory::getUser();
if ($this->id) {
// Existing item
$this->modified = $date->toSql();
$this->modified_by = $user->get('id');
} else {
// New newsfeed. A feed created and created_by field can be set by the user,
// so we don't touch either of these if they are set.
if (!intval($this->created)) {
$this->created = $date->toSql();
}
if (empty($this->created_by)) {
$this->created_by = $user->get('id');
}
}
// Verify that the alias is unique
$table = JTable::getInstance('Yourinstance', 'mycomponentTable');
if ($table->load(array('alias'=>$this->alias, 'catid'=>$this->catid)) && ($table->id != $this->id || $this->id==0)) {
$this->setError(JText::_('COM_CONTACT_ERROR_UNIQUE_ALIAS'));
return false;
}
// Attempt to store the data.
return parent::store($updateNulls);
}
}
Note : your config.xml file should be in models/forms folder.

PHP OpenID geting nickname & email

For the OpenID authentication I'm using "PHP OpenID Library" (http://www.janrain.com/openid-enabled). How, with the help of this library, ask for additional information (nickname, email)?
I've got some problems with LightOpenID, when I ask email at yandex LightOpenID-> valid returns false(
class Ncw_OpenID extends LightOpenID
{
const OPENID_MODE_CANCEL = 'cancel';
public function __construct()
{
parent::__construct();
$this->required = array('namePerson/friendly', 'contact/email');
$this->optional = array('contact/email');
//$this->returnUrl = 'http://' . SITE_URI . '/users/login';
}
public function getAttributes() {
$attr = parent::getAttributes();
$newAttr = array();
foreach ($attr as $key => $value) {
if (isset(parent::$ax_to_sreg[$key])) $key = parent::$ax_to_sreg[$key];
$newAttr[$key] = $value;
}
return $newAttr;
}
}
class Users_IndexController extends Zend_Controller_Action
{
public function loginAction()
{
$openIDMode = $this->_request->getParam('openid_mode');
$openID = new Ncw_OpenID();
$form = new Users_Form_Login(array('action' => $this->view->url(array(), 'openIDLogin')));
if (null === $openIDMode) {
if ($this->_request->isPost() && $form->isValid($_POST)) {
$openID->identity = $form->getValue('openIDUri');
$this->_redirect($openID->authUrl());
exit();
}
$this->view->content = $form;
} elseif (Ncw_OpenID::OPENID_MODE_CANCEL == $openIDMode) {
$this->view->content = 'Cancel';
} else {
if ($openID->validate()) {
$this->view->content = 'Valid: ' . $openID->identity . ' = ' . var_export($openID->getAttributes(), true);
} else {
$this->view->content = 'Not Valid';
}
$this->view->content .= $form;
}
}
public function logoutAction()
{
// action body
}
}
Here is an incomplete example. It's incomplete in the sense that it's using only SREG, and not every provider supports it (for example, Google supports only AX).
As far as I know, php-openid doesn't offer a simple way to automatically detect what does the server support and accordingly use AX or SREG.
For more information, I'd look at the source code's comments or as the README suggests, generate documentation from them, using phpdoc.
However, if you can switch libraries, I'd recommend LightOpenID. It's easier to use and does most things automatically (contrary to php-openid).

Categories