OS Ticket not load properly - php

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();
}
}
?>

Related

How to integrate msg91 php api with Prestasms or Prestashop?

<?php
error_reporting(E_ALL ^ E_NOTICE);ini_set('error_reporting', E_ALL ^ E_NOTICE);
define('IS_ADMIN_FLAG', false);
include_once(dirname(__FILE__).'/../../config/config.inc.php');
include_once(dirname(__FILE__).'/../../config/setting.inc.php');
include_once('includes/model/smsAdapter.php');
include_once('includes/model/sms.php');
include_once('includes/model/variables.php');
class ControllerSmsApi
{
public function __construct()
{
$this->index();
}
public function index()
{
die("DISABLED");
$to = $this->getVar("to");
$text = $this->getVar("text");
$unicode = $this->getVar("unicode");
$type = $this->getVar("type");
$transaction = $this->getVar("transaction");
if(isset($to) && strlen($to) > 4 && strlen($text) > 0)
{
$sms = new SmsModel(true, SmsModel::TYPE_SIMPLE, $type, ($transaction ? SmsModel::SMS_TRANSACTION : SmsModel::SMS_BULK));
$sms->number($to)->text($text)->unicode($unicode)->send();
if(!$sms->isError())
{
echo "SMSSTATUS:OK";
}
else
{
echo "SMSSTATUS:ERROR";
}
}
else
{
echo "SMSSTATUS:ERROR";
}
}
private function getVar($var)
{
if(filter_input(INPUT_POST, $var))
{
return filter_input(INPUT_POST, $var);
}
elseif(filter_input(INPUT_GET, $var))
{
return filter_input(INPUT_GET, $var);
}
else
{
return null;
}
}
}
new ControllerSmsApi();
?>
I have an ecommers website in which customer placed order and get all updation via email service ,but now i want to make it for sms service also for which i have sms api in msg91 for php. But unfortunately i am unable to integrate it with prestashop via prestasms or any other free module.
Actually making a Module should do the job and adding
various hooks might do the job, you can generate one with nearly all you will need here : https://validator.prestashop.com/
Based on your answer you will certainly need two hooks : actionOrderStatusUpdate and actionValidateOrder. You can also get an updated list here http://www.prestarocket.com/blog/prestashop-1-7-hook-list-liste-des-hooks/.
If you need example of a module well working, you can take a look at modules/dashactivity/ which one of the most compliant to Prestashops guidelines.
Your code might look like this in the end :
<?php
class Msg91SMS extends Module
{
public function __construct()
{
$this->name = 'msg91sms';
$this->tab = 'front_office';
$this->version = '1.0.1';
$this->author = 'YourName';
$this->displayName = $this->l('MSG91SMS');
$this->description = $this->l('Description');
// Hooks you need, setup on install so you might do it again
$this->hooks = array(
'actionValidateOrder',
'actionOrderStatusUpdate',
);
}
public function install() {
if (!parent::install()) {
return false;
} else {
if (isset($this->hooks) && !empty($this->hooks)) {
foreach ($this->hooks as $v) {
if (!$this->registerHook($v)) {
return false;
}
}
}
}
}
public function hookActionValidateOrder($params) {
$order = $params['order'];
// Do your magic here
}
public function hookActionOrderStatusUpdate($params) {
// Same as above, remember to check order state to see if it interests you some ways with $order->id_state and a switch / case
}
}

Moodle: Error on form submission in activity module

Below is a sample of the code that I'm using for the form and then the handling og the file saving. There's something that I'm doing wrong, but I'm not sure what it is. Please assist. I have attached a screenshot showing the error that I'm getting after submitting the form.
error on form submission in moodle inside activity module
class mod_audio_mod_form extends moodleform_mod {
/**
* Defines forms elements
*/
public function definition() {
global $CFG;
$mform = $this->_form;
// Adding the "general" fieldset, where all the common settings are showed.
$mform->addElement('header', 'general', get_string('general', 'form'));
// Adding the standard "name" field.
$mform->addElement('text', 'name', get_string('audioname', 'audio'), array('size' => '64'));
if (!empty($CFG->formatstringstriptags)) {
$mform->setType('name', PARAM_TEXT);
} else {
$mform->setType('name', PARAM_CLEANHTML);
}
$mform->addRule('name', null, 'required', null, 'client');
$mform->addRule('name', get_string('maximumchars', '', 255), 'maxlength', 255, 'client');
$mform->addHelpButton('name', 'audioname', 'audio');
// Adding the standard "intro" and "introformat" fields.
if ($CFG->branch >= 29) {
$this->standard_intro_elements();
} else {
$this->add_intro_editor();
}
// Adding the rest of audio settings, spreading all them into this fieldset
// ... or adding more fieldsets ('header' elements) if needed for better logic.
$mform->addElement('header', 'audiofieldset', get_string('audiofieldset', 'audio'));
$filemanager_options = array();
$filemanager_options['accepted_types'] = '*';
$filemanager_options['maxbytes'] = 0;
$filemanager_options['maxfiles'] = -1;
$filemanager_options['mainfile'] = true;
$mform->addElement('filemanager', 'files', get_string('selectfiles'), null, $filemanager_options);
$mform->addRule('files', null, 'required', null, 'client');
// Add standard grading elements.
$this->standard_grading_coursemodule_elements();
// Add standard elements, common to all modules.
$this->standard_coursemodule_elements();
// Add standard buttons, common to all modules.
$this->add_action_buttons();
}
function data_preprocessing(&$default_values) {
if ($this->current->instance) {
// editing existing instance - copy existing files into draft area
$draftitemid = file_get_submitted_draft_itemid('files');
file_prepare_draft_area($draftitemid, $this->context->id, 'mod_audio', 'content', 0, array('subdirs' => true));
$default_values['files'] = $draftitemid;
}
}
function definition_after_data() {
if ($this->current->instance and $this->current->tobemigrated) {
// resource not migrated yet
return;
}
parent::definition_after_data();
}
function validation($data, $files) {
global $USER;
$errors = parent::validation($data, $files);
$usercontext = context_user::instance($USER->id);
$fs = get_file_storage();
if (!$files = $fs->get_area_files($usercontext->id, 'user', 'draft', $data['files'], 'sortorder, id', false)) {
$errors['files'] = get_string('required');
return $errors;
}
if (count($files) == 1) {
// no need to select main file if only one picked
return $errors;
} else if (count($files) > 1) {
$mainfile = false;
foreach ($files as $file) {
if ($file->get_sortorder() == 1) {
$mainfile = true;
break;
}
}
// set a default main file
if (!$mainfile) {
$file = reset($files);
file_set_sortorder($file->get_contextid(), $file->get_component(), $file->get_filearea(), $file->get_itemid(), $file->get_filepath(), $file->get_filename(), 1);
}
}
return $errors;
}
}
// THE CLASS IN LOCALLIB.PHP
class audio_content_file_info extends file_info_stored {
public function get_parent() {
if ($this->lf->get_filepath() === '/' and $this->lf->get_filename() === '.') {
return $this->browser->get_file_info($this->context);
}
return parent::get_parent();
}
public function get_visible_name() {
if ($this->lf->get_filepath() === '/' and $this->lf->get_filename() === '.') {
return $this->topvisiblename;
}
return parent::get_visible_name();
}
function save_files($data) {
global $DB;
// Storage of files from the filemanager (videos).
$draftitemid = $data->files;
if ($draftitemid) {
file_save_draft_area_files(
$draftitemid, $this->context->id, 'mod_audio', 'files', 0
);
}
}
}
// FUNCTION THAT ADDS THE INSTANCE IN LIB.PHP
function audio_add_instance(stdClass $audio, mod_audio_mod_form $mform = null) {
global $CFG, $DB;
require_once("$CFG->libdir/resourcelib.php");
require_once("$CFG->dirroot/mod/audio/locallib.php");
$cmid = $audio->coursemodule;
$audio->timecreated = time();
$audio->timemodified = time();
resource_set_display_options($audio);
$audio->id = $DB->insert_record('audio', $audio);
$context = context_module::instance($audio->coursemodule);
$audiofile = new audio_content_file_info($context, null, null);
$audiofile->save_files($audio);
// we need to use context now, so we need to make sure all needed info is already in db
$DB->set_field('course_modules', 'instance', $audio->id, array('id' => $cmid));
resource_set_mainfile($audio);
return $audio->id;
}
Please advice on what I could be doing wrong here.

Joomla component router

I'm trying to follow the instructions on this docs page, but I seem to be missing something:
https://docs.joomla.org/Supporting_SEF_URLs_in_your_component
The URI that needs to be corrected is: index.php?com_component&view=legal&page=customermasteragreement
It seems like the routing function should be simple, but the page is just displaying default instead of the sub-view.
Here's my current code:
function ComponentBuildRoute(&$query)
{
$segments = array();
if (isset($query['view'])) {
$segments[] = $query['view'];
unset($query['view']);
}
if (isset($query['page'])) {
$segments[] = $query['page'];
unset($query['page']);
}
return $segments;
}
function ComponentParseRoute($segments)
{
$vars = array();
switch($segments[0])
{
case 'legal':
$vars['view'] = 'legal';
break;
case 'customermasteragreement':
$vars['page'] = 'customermasteragreement';
break;
}
return $vars;
}
Update
This code works to display the subpage, but it gives me a URI like: legal-agreements/legal?page=customermasteragreement
class ComponentRouter extends JComponentRouterBase {
public function build(&$query) {
$segments = array();
$view = null;
if (isset($query['view'])) {
$segments[] = $query['view'];
$view = $query['view'];
unset($query['view']);
}
if (isset($query['id'])) {
if ($view !== null) {
$segments[] = $query['id'];
} else {
$segments[] = $query['id'];
}
unset($query['id']);
}
return $segments;
}
public function parse(&$segments) {
$vars = array();
// View is always the first element of the array
$vars['view'] = array_shift($segments);
return $vars;
}
}
EDIT 2
If it helps, here's my model and views
models/legal.php
// import Joomla modelitem library
jimport('joomla.application.component.modelitem');
class ComponentModelLegal extends JModelItem {
public function __construct($config = array())
{
JLoader::register('ComponentHelper', JPATH_COMPONENT_ADMINISTRATOR . '/helpers/component.php');
parent::__construct($config);
}
/**
*
* #return string
*/
public function getLegal() {
$app = JFactory::getApplication();
$page = $app->input->get('page', '', 'STRING');
if ($page) {
ComponentHelper::add('type', $page); //This is an API request to an external service, returning JSON formatted data
$legal = ComponentHelper::getData('commons/legal-agreements.json', TRUE);
if (isset($legal[0]['status'])) {
JError::raiseError(400, $legal[0]['ERROR']);
return false;
} else {
if (!isset($this->legal)) {
$this->legal = $legal;
}
return $this->legal;
}
}
}
}
views/legal/view.html.php
class ComponentViewLegal extends JViewLegacy {
function display($tpl = null) {
// Assign data to the view
$this->legal = $this->get('legal');
// Check for errors.
if (count($errors = $this->get('Errors'))) {
JLog::add(implode('<br />', $errors), JLog::WARNING, 'jerror');
return false;
}
// Display the view
parent::display($tpl);
}
}
views/legal/tmpl/default.php
$page = JRequest::getVar('page');
$pages = array(
'resellermasteragreement',
'customermasteragreement',
'resellerdomainagreement',
'customerdomainagreement',
'resellerwebserviceagreement',
'customerwebserviceagreement',
'resellerdigicertagreement',
'customerdigicertagreement',
'registraragreement',
'customerhostingproductagreement',
'resellerhostingproductagreement'
);
?>
<div class="col-lg-12">
<?php
echo in_array($page, $pages) ? $this->loadTemplate('legal') : $this->loadTemplate('home');
?>
</div>
views/legal/tmpl/default_legal.php
$page = JRequest::getVar('page');
echo nl2br(htmlspecialchars($this->legal[$page]['defaultagreement'], ENT_NOQUOTES, "UTF-8"));
?>
<a type="button" class="btn btn-primary" href="<?php echo JROUTE::_("index.php?option=com_component&view=legal"); ?>">Back</a>
EDIT 3
This works because I wasn't navigating directly to the page from a menu item. There's a top level menu, then a page a links to the agreements. I have a hidden menu to each item, but that wasn't the link I followed.
$app = JFactory::getApplication()->getMenu();
$customermaster = $app->getItems( 'link', 'index.php?option=com_component&view=legal&page=customermasteragreement', true );
JRoute::_('index.php?Itemid='.$customermaster->id);
You have one view but you're not actually set the page argument correctly when you catch a view argument, but you treat page as some king of another view. Can you please try this and check if it works:
function [componentname]ParseRoute($segments)
{
$vars = array();
switch($segments[0])
{
case 'legal':
$vars['view'] = 'legal';
$vars['page'] = $segments[1];
break;
}
return $vars;
}
Also the functions ComponentBuildRoute, ComponentParseRoute must have your components name instead of Component at the beginning.
EDIT
[componentname]BuildRoute and [componentname]ParseRoute are deprecated, you should stick the the class that extends JComponentRouterBase as you have it in your updated second example. Try this one here and see if it works:
class ComponentRouter extends JComponentRouterBase {
public function build(&$query) {
$segments = array();
$view = null;
if (isset($query['view'])) {
$segments[] = $query['view'];
$view = $query['view'];
unset($query['view']);
}
if (isset($query['page'])) {
$segments[] = $query['page'];
unset($query['page']);
}
return $segments;
}
public function parse(&$segments) {
$vars = array();
// View is always the first element of the array
$vars['view'] = array_shift($segments);
if(count($segments) > 0)
$vars['page'] = array_shift($segments);
return $vars;
}
}
EDIT 2
I have a test Joomla 3 site with a simple component named Ola.
Non SEO component URL: http://j3.dev.lytrax.net/index.php?option=com_ola&page=test_page&view=ola
URL generated by JRoute before Router class added to router.php: http://j3.dev.lytrax.net/index.php/component/ola/?page=test_page&view=ola
SEO URL returned by JRoute::_('index.php?option=com_ola&page=test_page&view=ola'); after creating router.php and used the Router class above: http://j3.dev.lytrax.net/index.php/component/ola/ola/test_page
If you visit the links, you'll see that all are working and you can even see the page, view and JRoute results of the calling component Ola.
Unless I've completely misunderstood Joomla (I've been developing with it for four five years now), there is no "sub-view" concept implemented. Trying to use the idea is what's getting you into trouble I think.
I'm astounded that the idea of using a visual debugger is so unpopular.
Get yourself something like Netbeans (there are others too), set up a local web and database server, and watch the code run. Very (well, relatively very) quickly you'll start to understand how the structure hangs together.
You may put code in your view that picks up the extra params you've set and displays or hides things accordingly, but there is no "sub-view".

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

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.

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.

Categories