How can I get the the number of all logged webuser (or manager, but not all types together). Is it possible with ModX API? Or is it necessary to inspect the DB table modx_session - but how is "data" column to readable?
I want to show a user counter, who is online (like in a forum).
Look at code in https://github.com/modxcms/revolution/blob/master/manager/controllers/default/dashboard/widget.grid-online.php - this is what you want.
I will try to solve it myself. Kind of solution:
Write a plugin that track events and persist it in database or somewhere else: OnWebLogin and OnWebLogout. Then read the count of logged in users.
Created a db table "modx_weblogin_session" (manually) userid, timestamp.
Created a Plugin:
if (isset($modx) && isset($user)) {
$eventName = $modx->event->name;
$isBackend = ($modx->context->key == 'mgr') ? true : false;
$errorMsg = '';
$userId = $user->get('id');
$output = 'WebLoginCountSession-Plugin: ' . $eventName . ' user-id: ' . $userId;
$logout = function ($userId) {
global $modx;
//Custom Mysqli Class
if (MySQLiDB::isConnected()) {
$mysqli = MySQLiDB::getConnection();
if ($mysqli instanceof mysqli) {
try {
$sql = "DELETE FROM `modx_weblogin_session` WHERE userid = ?";
$prep_state = $mysqli->prepare($sql);
$prep_state->bind_param('i', $userId);
$prep_state->execute();
} catch (Exception $e) {
//$modx->log(modX::LOG_LEVEL_ERROR, ...)
}
}
}
};
$login = function ($userId) {
global $modx;
if (MySQLiDB::isConnected()) {
$mysqli = MySQLiDB::getConnection();
if ($mysqli instanceof mysqli) {
try {
$sql = "REPLACE INTO `modx_weblogin_session` (`userid`) VALUES (?)";
$prep_state = $mysqli->prepare($sql);
$prep_state->bind_param('i', $userId);
$prep_state->execute();
} catch (Exception $e) {
//$modx->log(modX::LOG_LEVEL_ERROR, ...)
}
}
}
};
if (!$isBackend && !empty($userId)) {
switch ($eventName) {
case ('OnWebLogin'):
$output .= ' - login';
$login($userId);
break;
case ('OnWebLogout'):
$output .= ' - logout';
$logout($userId);
break;
}
}
if ($debug === true) {
return $output . ' ' . $errorMsg;
}
}
Related
I need your help, delete doesn´t work.
public function postUnregisterPushNotifications()
{
try {
$serial_usr = JWTAuth::getPayload(JWTAuth::getToken())->get('sub');
$device_token = Input::get('device_token');
$topic = null;
$device = Device::where('user_id', $serial_usr)->where('token', $device_token);
$device-> delete();
JWTAuth::setToken(JWTAuth::getToken())->invalidate();
return ws_response(false, 'Unregister Notification success', '', 200);
} catch (Exception $ex) {
return ws_response(true, null, 'ERROR ' . $ex->getCode() . '! ' . $ex->getMessage(), 500);
}
}
The insert to the table works but the delete when I logout does not delete from the table
What you're missing here is the ->get() method which fetches from the database and then ->delete() method works on the selection.
This should be how your code snippet should look like.
public function postUnregisterPushNotifications()
{
try {
$serial_usr = JWTAuth::getPayload(JWTAuth::getToken())->get('sub');
$device_token = Input::get('device_token');
$topic = null;
$device = Device::where('user_id', $serial_usr)->where('token', $device_token)->get();
$device->delete();
JWTAuth::setToken(JWTAuth::getToken())->invalidate();
return ws_response(false, 'Unregister Notification success', '', 200);
} catch (Exception $ex) {
return ws_response(true, null, 'ERROR ' . $ex->getCode() . '! ' . $ex->getMessage(), 500);
}
}
When I deselect my check box in my modify & access permissions it does not unset it from sessions if form is submitted success full.
What I am trying to achieve is on my edit function if any check box is not checked then it will unset from sessions when form is submitted success full. Because the reason need it unset from sessions is because when user logs in the permissions modify and access are set into sessions.
How can I make this work what I am after I have tried it in my edit but not unset when check box is empty
If i use this $this->session->unset_userdata('modify'); it unset all the modify array in sessions I just need it to unset the one that matches the unchecked check box.
public function edit() {
$this->load->model('admin/user/model_user_group');
if ($this->input->server('REQUEST_METHOD') == 'POST') {
$this->model_user_group->editUserGroup($this->uri->segment(4), $this->input->post());
if ($this->session->userdata('user_id') == TRUE) {
if (isset($_POST['permission[access]'])) {
$this->session->unset_userdata('permission[access]');
}
if (isset($_POST['permission[modify]'])) {
$this->session->unset_userdata('permission[modify]');
}
}
redirect('admin/users_group');
}
$this->getForm();
}
public function getForm() {
$data['title'] = "Users Group";
$this->load->model('admin/user/model_user_group');
$user_group_info = $this->model_user_group->getUserGroup($this->uri->segment(4));
if ($this->uri->segment(4) == FALSE) {
$data['name'] = $this->input->post('name');
} else {
$data['name'] = $user_group_info['name'];
}
if ($this->uri->segment(4) == FALSE) {
$data['user_group_id'] = $this->input->post('user_group_id');
} else {
$data['user_group_id'] = $user_group_info['user_group_id'];
}
$ignore = array(
'admin',
'dashboard',
'filemanager',
'login',
'menu',
'register',
'online',
'customer_total',
'user_total',
'chart',
'activity',
'logout',
'footer',
'header',
'permission'
);
$data['permissions'] = array();
$files = glob(FCPATH . 'application/modules/admin/controllers/*/*.php');
foreach ($files as $file) {
$permission = basename(strtolower($file), '.php');
if (!in_array($permission, $ignore)) {
$data['permissions'][] = $permission;
}
}
$permission_access = $this->input->post('permission');
if (isset($permission_access)) {
if (isset($permission_access['access'])) {
$data['access'] = $permission_access['access'];
} elseif (!empty($user_group_info['permission']['access'])) {
$data['access'] = $user_group_info['permission']['access'];
} else {
$data['access'] = array();
}
}
$permission_modify = $this->input->post('permission');
if (isset($permission_modify)) {
if (isset($permission_modify['modify'])) {
$data['modify'] = $permission_modify['modify'];
} elseif (!empty($user_group_info['permission']['modify'])) {
$data['modify'] = $user_group_info['permission']['modify'];
} else {
$data['modify'] = array();
}
}
$this->load->view('template/user/users_group_form.tpl', $data);
}
I have found away to get it working I have got sessions from database then re set the sessions in form, without using unset_sessions();
public function edit() {
$this->load->model('admin/user/model_user_group');
if ($this->input->server('REQUEST_METHOD') == 'POST') {
$this->model_user_group->editUserGroup($this->uri->segment(4), $this->input->post());
$user_group_query = $this->db->query("SELECT permission FROM " . $this->CI->db->dbprefix . "user_group
WHERE user_group_id = '" . (int)$this->session->userdata('user_group_id') . "'");
$permissions = unserialize($user_group_query->row('permission'));
$this->session->set_userdata($permissions);
redirect('admin/users_group');
}
$this->getForm();
}
I need to rename the file on file upload and inserting to the database.
I search for ways but i can't find the right code.
I tried to use callback but it did not work.
Here's my code:
public function home()
{
$crud = new grocery_CRUD();
$crud->set_theme('datatables');
$crud->set_table('blog_post');
$crud->set_field_upload('post_image',UPLOAD_PATH);
$crud->callback_before_upload(array($this,'_before_upload'))
$crud->callback_before_insert(array($this,'rename_img_db'));
$output = $crud->render();
$this->_example_output($output);
}
function rename_img_db($post_array)
{
if (!empty($post_array['post_image'])) {
$ext = end(explode(".",$post_array['post_image']));
$img_name = $post_array['post_image'] = mktime().".".$ext;
$post_array['post_image'] = $img_name;
}
return $post_array;
}
function _before_upload($files_to_upload,$field_info)
{
foreach($files_to_upload as $value) {
$ext = pathinfo($value['name'], PATHINFO_EXTENSION);
$rename = $value['name'];
}
$allowed_formats = array("jpg","gif","png","doc","docx","pdf");
if(in_array($ext,$allowed_formats))
{
return true;
}
else
{
return 'Wrong file format';
}
if ($rename) {
$ext1 = end(explode(".",$rename));
$img_name = $rename = mktime().".".$ext1;
$rename = $img_name;
return $rename;
}
}
I noticed a tipo in your line: $crud->callback_before_upload(array($this,'_before_upload'))
Moreover I had to do something similar and I used the callback_after_insert, then you can get the $primary_key variable and with that update the element, something like this:
$crud->callback_after_insert(array($this, 'rename_img_db'));
public function rename_img_db($post_array,$primary_key)
{
//Here goes the get and set querys with your $primary_key
}
I have create a custom model in Magento which can get to and edit in the admin. I'm having trouble dealing with array's however. When I go to save the model, the text field saves fine, but the multiselect field just saves as 'array' and I'm then unable to go and edit it.
I need to know how to save seperate row in databse not comma seprate .
Can anybody help with this? Any help much appreciated!!!
public function saveAction() {
if ($data = $this->getRequest()->getPost()) {
if(isset($_FILES['image']['name']) && $_FILES['image']['name'] != null) {
try {
/* Starting upload */
$uploader = new Varien_File_Uploader('image');
// Any extention would work
$uploader->setAllowedExtensions(array('jpg','jpeg','gif','png'));
$uploader->setAllowRenameFiles(false);
// Set the file upload mode
// false -> get the file directly in the specified folder
// true -> get the file in the product like folders
// (file.jpg will go in something like /media/f/i/file.jpg)
$uploader->setFilesDispersion(false);
// We set media as the upload dir
$path = Mage::getBaseDir('media') . DS.'magentothem/vendorlist'.DS ;
$uploader->save($path, $_FILES['image']['name'] );
} catch (Exception $e) {
}
//this way the name is saved in DB
$basepath=Mage::getBaseUrl().'media/magentothem/vendorlist/';
$basepath=str_replace("index.php/","",$basepath);
$data['image'] = '<img src="'.$basepath.$_FILES['image']['name'].'" width="150" height="100px" alt="" />';
}
**$data['productid'] = join("," ,$_POST['productid']);**
$model = Mage::getModel('vendorlist/vendorlist');
$model->setData($data)->setId($this->getRequest()->getParam('id'));
try {
if ($model->getCreatedTime == NULL || $model->getUpdateTime() == NULL) {
$model->setCreatedTime(now())
->setUpdateTime(now());
} else {
$model->setUpdateTime(now());
}
$model->save();
Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('vendorlist')->__('Item was successfully saved'));
Mage::getSingleton('adminhtml/session')->setFormData(false);
if ($this->getRequest()->getParam('back')) {
$this->_redirect('*/*/edit', array('id' => $model->getId()));
return;
}
$this->_redirect('*/*/');
return;
} catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
Mage::getSingleton('adminhtml/session')->setFormData($data);
$this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
return;
}
}
Mage::getSingleton('adminhtml/session')->addError(Mage::helper('vendorlist')->__('Unable to find item to save'));
$this->_redirect('*/*/');
}
if you want separate rows in your table, I assume the the id column is not the PK.
In this case you could try:
$model = Mage::getModel('vendorlist/vendorlist');
$productIds = Mage::app()->getRequest()->getParam('productid');
foreach ($productIds as $productId) {
$model->setData($data)->setProductid($productId)->setId($this->getRequest()->getParam('id'));
try {
if ($model->getCreatedTime == NULL || $model->getUpdateTime() == NULL) {
$model->setCreatedTime(now())
->setUpdateTime(now());
} else {
$model->setUpdateTime(now());
}
$model->save();
//remove what is after, put it after the try/catch
} catch (Exception $e) {
//handle exception
}
}
While i run a component i am getting 500 - An error has occurred error reading db in joomla.
My configuration file is perfect.
I don't know what else to change..
Any guidance will be helpful
Thanks in advance...
//No direct acesss
defined('_JEXEC') or die();
jimport('joomla.application.component.model');
class DealsModelDeals extends JModel {
function getDeals(){
$db = $this->getDBO();
$db->setQuery('SELECT * from #__todaysdeal');
$deals = $db->loadObjectList();
if ($deals === null)
JError::raiseError(500, 'Error reading db');
return $deals;
}
function getDeal($id){
$query = ' SELECT * FROM #__todaysdeal '. ' WHERE id = '.$id;
$db = $this->getDBO();
$db->setQuery($query);
$deal = $db->loadObject();
if ($deal === null)
JError::raiseError(500, 'Deal with ID: '.$id.' not found.');
else
return $deal;
}
/**
* Method that returns an empty greeting with id 0
*
* #access public
*/
function getNewDeal(){
$dealTableRow =& $this->getTable('deals');
$dealTableRow->id=0;
$dealTableRow->clientName='';
return $dealTableRow;
}
/**
* Method to store a greeting in the DB
*
* #access public
*/
function saveDeal($deal)
{
//Parameter not necessary because our model is named DealsModelDeals (used to ilustrate that you can specify an alternative name to the JTable extending class)
$dealTableRow =& $this->getTable('deals');
//print_r($dealTableRow);
//print_r($_FILES); exit;
// Bind the form fields to the todaysdeal table
if (!$dealTableRow->bind($deal)) {
JError::raiseError(500, 'Error binding data');
}
// Make sure the deal record is valid
if (!$dealTableRow->check()) {
JError::raiseError(500, 'Invalid data');
}
// Insert/update this record in the db
if (!$dealTableRow->store()) {
$errorMessage = $dealTableRow->getError();
JError::raiseError(500, 'Error binding data: '.$errorMessage);
}
$id = $dealTableRow->id;
if(!empty($_FILES['dealImage']))
{
$file = $_FILES['dealImage'];
$id = $dealTableRow->id;
if ((($_FILES["dealImage"]["type"] == "image/gif") || ($_FILES["dealImage"]["type"] == "image/jpeg") || ($_FILES["dealImage"]["type"] == "image/pjpeg")) && ($_FILES["dealImage"]["size"] < 150000))
{
if ($_FILES["dealImage"]["error"] > 0)
{
echo "Return Code: " . $_FILES["dealImage"]["error"] . "<br />";
}
else
{
if (file_exists("components/com_deals/dealImages/" . $_FILES["dealImage"]["name"])) {
$_FILES["dealImage"]["name"] . " already exists. ";
} else {
move_uploaded_file($_FILES["dealImage"]["tmp_name"], "components/com_deals/dealImages/" .$id."_".$_FILES["dealImage"]["name"]);
echo "Stored in: " . "dealImages/" . $_FILES["dealImage"]["name"];
}
}
}
else
{
}
}
$dealImage = $_FILES['dealImage']['name'];
$dealImage .= (!empty($_FILES['dealImage']['name'])) ? ' ' . $_FILES['dealImage']['name'] : '';
$query = "UPDATE #__todaysdeal SET dealImage='".$id."_".$_FILES['dealImage']['name']."' WHERE id='".$id."'";
$db = $this->getDBO();
$db->setQuery($query);
$db->query();
//If we get here and with no raiseErrors, then everythign went well
}
function deleteDeals($arrayIDs)
{
$query = "DELETE FROM #__todaysdeal WHERE id IN (".implode(',', $arrayIDs).")";
$db = $this->getDBO();
$db->setQuery($query);
if (!$db->query()){
$errorMessage = $this->getDBO()->getErrorMsg();
JError::raiseError(500, 'Error deleting Deals: '.$errorMessage);
}
}
function dealsUploadPhoto($file, $id)
{
//UPLOAD FILE
$config = & JComponentHelper::getParams('com_deals');
$allowed = array('image/pjpeg', 'image/jpeg', 'image/jpg', 'image/png', 'image/x-png', 'image/gif', 'image/ico', 'image/x-icon');
$pwidth = $config->get('pwidth');
$pheight = $config->get('pheight');
$maxsize = $config->get('maxsize');
if($file['size'] > 0 && ($file['size'] / 1024 < $maxsize)){
if(!file_exists(JPATH_SITE . DS. 'images' . DS . 'deals'))
{
if(mkdir(JPATH_SITE . DS . 'images' . DS . 'deals')) {
JPath::setPermissions(JPATH_SITE . DS . 'images' . DS . 'deals', '0777');
if(file_exists(JPATH_SITE . DS . 'images' . DS . 'index.html')) {
copy(JPATH_SITE . DS . 'images' . DS . 'index.html', JPATH_SITE . DS . 'images' . DS . 'deals/index.html');
}
}
}
if($file['error'] != 0){
tpJobsMsgAlert('Upload file photo error.');
exit ();
}
if($file['size'] == 0){
$file = null;
}
if(!in_array($file['type'], $allowed)) {
$file = null;
}
if ($file != null){
$dest = JPATH_SITE.DS.'images'.DS.'deals'.DS.$id.'.jpg';
if(file_exists($dest))
{
$del = unlink($dest);
}
$soure = $file['tmp_name'];
jimport('joomla.filesystem.file');
$uploaded = JFile::upload($soure,$dest);
$fileAtr = getimagesize($dest);
$widthOri = $fileAtr[0];
$heightOri = $fileAtr[1];
$type = $fileAtr['mime'];
$img = false;
switch ($type)
{
case 'image/jpeg':
case 'image/jpg':
case 'image/pjpeg':
$img = imagecreatefromjpeg($dest);
break;
case 'image/ico':
$img = imagecreatefromico($dest);
break;
case 'image/x-png':
case 'image/png':
$img = imagecreatefrompng($dest);
break;
case 'image/gif':
$img = imagecreatefromgif($dest);
break;
}
if(!$img)
{
return false;
}
$curr = #getimagesize($dest);
$perc_w = $pwidth / $widthOri;
$perc_h = $pheight / $heightOri;
if(($widthOri<$pwidth) && ($heightOri<$height))
{
return;
}
if($perc_h > $perc_w)
{
$pwidth = $pwidth;
$pheight = round($heightOri * $perc_w);
}
else
{
$pheight = $pheight;
$pwidth = round($widthOri * $perc_h);
}
$nwimg = imagecreatetruecolor($pwidth, $pheight);
imagecopyresampled($nwimg, $img, 0, 0, 0, 0, $pwidth, $pheight, $widthOri, $heightOri);
imagejpeg($nwimg, $dest, 100);
imagedestroy($nwimg);
imagedestroy($img);
}
}else{
if($file['size'] / 1024 > $maxsize){
dealsMsgAlert('Size of file photo is too big. Maximum size".$maxsize." KB');
exit ();
}
}
}
function dealsMsgAlert($msg)
{
if (!headers_sent())
{
while(#ob_end_clean());
ob_start();
echo "<script> alert('".$msg."'); window.history.go(-1); </script>\n";
$out = ob_get_contents();
ob_end_clean();
echo $out;
exit();
}
echo "<script> alert('".$msg."'); window.history.go(-1); </script>\n";
exit();
}
}
?>
The problem that causes the red screen with 500 Error is happening because you are raising an exception if the requested quote is does not exist. You should not use JError::raiseError().
Use one of the following instead:
// This will set error to the model. You can get the errors from
// the model by your controller $model->getErrors() and output them to the screen.
$this->setError('ERROR MESSAGE GOES HERE');
OR
// This will output errors to the screen right the way
JFactory::getApplication()->enqueueMessage('ERROR MESSAGE GOES HERE', 'message');
Model already has _db property, you do not need to get db into variable. You can access it like this $this->_db. You can read about Joomla Model class here.
Also within your model you are using
$db = $this->getDBO();
$db->setQuery('SELECT * from #__todaysdeal');
$deals = $db->loadObjectList();
Model has simplified method to load list of object, like so
$deals =& $this->_getList('SELECT * from #__todaysdeal');