How can I reset the cron task with elysia cron? - cron

I can't reset the cron task.
I did force run than ran the cron and nothing. mymodule_queue_function - doesn't execute and the $count always increases.
I was trying reset count in maintenance settings (reset statistics) but it doesn't work.
How can I fix it?
mymodule_cronapi($op, $job = NULL) {
$items['functions_cron_month_prepare'] = array(
'description' => 'users pay for services',
'rule' => '4 0 24 * *',
'arguments' => array(5),
'callback' => 'mymodule_select_month_prepare',
);
return $items;
}
// /** * Implementation of hook_cron_queue_info() */
function tariffing_cron_queue_info() {
$queues['mymodule_queue_main'] = array(
'worker callback' => 'mymodule_queue_function',
'time' => 3600,
);
return $queues;
}
function mymodule_select_month_prepare() {
if($users) {
foreach ($users as $usr) {
$usr_s[$usr['uid']][] = $usr['service_name'];
}
$n = round(count($usr_s)/4);
$items = count($usr_s) > 4 ? array_chunk($usr_s, $n, true) : array(0 => $usr_s);
$queue = DrupalQueue::get('mymodule_queue_main');
foreach ($items as $item) {
$count = $queue->numberOfItems();
$queue->createItem($item);
}
}
}
function mymodule_queue_function($data) {
watchdog('$data_users', print_r($data,true));
}

The problem was resolved by replacing the name of the function. But appeared another problem:
The time of my cron task is (4 0 1 * *) but now 25th day, and the job task was executed. Why?? What did I wrong?
Could did it happen case I deleted all cron execution statistics?

Related

Laratrust 6x- problems with db:seed

I need help about php artisan db:seed.
I installed Laratrust 5.2 for Laravel 7 and than i make upgrade from 5.2 to 6.
I follow this steps: https://laratrust.santigarcor.me/docs/6.x/upgrade.html;
This is how it works, everything is ok.
Later, I ran the command: php artisan migrate:fresh to get the new tables but I have a problem:
sviluppo#Mac-mini-di-sviluppo prova % php artisan migrate:fresh
Dropped all tables successfully.
Migration table created successfully.
Migrating: 2014_10_12_000000_create_users_table
Migrated: 2014_10_12_000000_create_users_table (0.04 seconds)
Migrating: 2014_10_12_100000_create_password_resets_table
Migrated: 2014_10_12_100000_create_password_resets_table (0.04 seconds)
Migrating: 2019_08_19_000000_create_failed_jobs_table
Migrated: 2019_08_19_000000_create_failed_jobs_table (0.02 seconds)
Migrating: 2022_09_26_102236_laratrust_setup_tables
Migrated: 2022_09_26_102236_laratrust_setup_tables (0.39 seconds)
Migrating: 2022_09_26_102709_create_roles_table
Illuminate\Database\QueryException
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'roles' already exists (SQL: create table `roles` (`id` bigint unsigned not null auto_increment primary key, `created_at` timestamp null, `updated_at` timestamp null) default character set utf8mb4 collate 'utf8mb4_unicode_ci')
at vendor/laravel/framework/src/Illuminate/Database/Connection.php:671
667| // If an exception occurs when attempting to run a query, we'll format the error
668| // message to include the bindings with SQL, which will make this exception a
669| // lot more helpful to the developer instead of just the database's errors.
670| catch (Exception $e) {
> 671| throw new QueryException(
672| $query, $this->prepareBindings($bindings), $e
673| );
674| }
675|
+9 vendor frames
10 database/migrations/2022_09_26_102709_create_roles_table.php:19
Illuminate\Support\Facades\Facade::__callStatic("create")
+32 vendor frames
43 artisan:37
Illuminate\Foundation\Console\Kernel::handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
sviluppo#Mac-mini-di-sviluppo visan-day-app %
And if i run:
sviluppo#Mac-mini-di-sviluppo prova % php artisan db:seed
Seeding: LaratrustSeeder
Truncating User, Role and Permission tables
The configuration has not been published. Did you run `php artisan vendor:publish --tag="laratrust-seeder"`
Seeded: LaratrustSeeder (0.03 seconds)
Database seeding completed successfully.
Info:
My file in laratrust.php e laratrust_seeder.php are config;
There are tables in the database/migrations;
It is present within database/seed/DatabaseSeeder.php => $this->call(LaratrustSeeder::class);
My file laratrustSeeder.php:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Config;
class LaratrustSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
$this->truncateLaratrustTables();
$config = Config::get('laratrust_seeder.roles_structure');
if ($config === null) {
$this->command->error("The configuration has not been published. Did you run `php artisan vendor:publish --tag=\"laratrust-seeder\"`");
$this->command->line('');
return false;
}
$mapPermission = collect(config('laratrust_seeder.permissions_map'));
foreach ($config as $key => $modules) {
// Create a new role
$role = \App\Role::firstOrCreate([
'name' => $key,
'display_name' => ucwords(str_replace('_', ' ', $key)),
'description' => ucwords(str_replace('_', ' ', $key))
]);
$permissions = [];
$this->command->info('Creating Role '. strtoupper($key));
// Reading role permission modules
foreach ($modules as $module => $value) {
foreach (explode(',', $value) as $p => $perm) {
$permissionValue = $mapPermission->get($perm);
$permissions[] = \App\Permission::firstOrCreate([
'name' => $module . '-' . $permissionValue,
'display_name' => ucfirst($permissionValue) . ' ' . ucfirst($module),
'description' => ucfirst($permissionValue) . ' ' . ucfirst($module),
])->id;
$this->command->info('Creating Permission to '.$permissionValue.' for '. $module);
}
}
// Attach all permissions to the role
$role->permissions()->sync($permissions);
if (Config::get('laratrust_seeder.create_users')) {
$this->command->info("Creating '{$key}' user");
// Create default user for each role
$user = \App\User::create([
'name' => ucwords(str_replace('_', ' ', $key)),
'email' => $key.'#app.com',
'password' => bcrypt('password')
]);
$user->attachRole($role);
}
}
}
/**
* Truncates all the laratrust tables and the users table
*
* #return void
*/
public function truncateLaratrustTables()
{
$this->command->info('Truncating User, Role and Permission tables');
Schema::disableForeignKeyConstraints();
DB::table('permission_role')->truncate();
DB::table('permission_user')->truncate();
DB::table('role_user')->truncate();
if (Config::get('laratrust_seeder.truncate_tables')) {
DB::table('roles')->truncate();
DB::table('permissions')->truncate();
if (Config::get('laratrust_seeder.create_users')) {
$usersTable = (new \App\User)->getTable();
DB::table($usersTable)->truncate();
}
}
Schema::enableForeignKeyConstraints();
}
}
Thanks!

Codeigniter 4 Query Builder loses SELECT and WHERE condition while executing once more

I am using Codeigniter 4 Query Builder.
Following is code to retrieve data from the database
public function get_data()
{
$where = [
'username' => 'admin'
];
$this->_builder = $this->_db->table('pf_user_master s');
$this->_builder->join('pf_role_master r', 'r.role_id = s.role_id');
$this->_builder->select('username, first_name, last_name, mobile, email, r.role_name, s.status');
if (is_array($where) && !empty($where)) {
$this->_builder->where($where);
}
$first= $this->_builder->get()->getResultArray();
print_r($first);
$second= $this->_builder->get()->getResultArray();
print_r($second);
exit;
}
I am getting the following output:
In variable $first I am getting output as expected
Array
(
[0] => Array
(
[username] => admin
[first_name] => Fisrt
[last_name] => Last
[mobile] =>
[email] => first.last#gmail.com
[role_name] => Admin
[status] => 1
)
)
But in variable $second it Query Builder loses SELECT, WHERE condition and also JOIN.
And prints the output as follows:
Array
(
[0] => Array
(
[user_id] => 1
[username] => admin
[password] => 21232f297a57a5a743894a0e4a801fc3
[first_name] => First
[last_name] => Last
[mobile] =>
[email] => first.last#gmail.com
[role_id] => 1
[status] => 1
[created_by] =>
[created_date] => 2020-09-08 19:30:52
[updated_by] =>
[updated_date] => 2020-09-08 19:32:42
)
[1] => Array
(
[user_id] => 2
[username] => superadmin
[password] => 21232f297a57a5a743894a0e4a801fc3
[first_name] => NewFirst
[last_name] => NewLast
[mobile] =>
[email] => new.new#gmail.com
[role_id] => 1
[status] => 1
[created_by] =>
[created_date] => 2020-09-08 21:51:42
[updated_by] =>
[updated_date] =>
)
)
I've not tested this and it comes from reading the documentation only.
In the CodeIgniter documentation get() has the following parameters
get([$limit = NULL[, $offset = NULL[, $reset = TRUE]]]])
Reference: https://codeigniter.com/user_guide/database/query_builder.html#get
If you were to use
$first= $this->_builder->get(NULL,NULL,FALSE)->getResultArray();
Then your code would become:
public function get_data()
{
$where = [
'username' => 'admin'
];
$this->_builder = $this->_db->table('pf_user_master s');
$this->_builder->join('pf_role_master r', 'r.role_id = s.role_id');
$this->_builder->select('username, first_name, last_name, mobile, email, r.role_name, s.status');
if (is_array($where) && !empty($where)) {
$this->_builder->where($where);
}
$first= $this->_builder->get(NULL,NULL,FALSE)->getResultArray();
print_r($first);
$second= $this->_builder->get()->getResultArray();
print_r($second);
exit;
}
Of course if you were to perform this a 3rd time, the 2nd instance should cause a reset.
The Code is the Documentation ( in most cases ) so we have
In CodeIgniter 4.04 - /system/Database/BaseBuilder.php - Line 1824
The code is
/**
* Get
*
* Compiles the select statement based on the other functions called
* and runs the query
*
* #param integer $limit The limit clause
* #param integer $offset The offset clause
* #param boolean $reset Are we want to clear query builder values?
*
* #return ResultInterface
*/
public function get(int $limit = null, int $offset = 0, bool $reset = true)
{
if (! is_null($limit))
{
$this->limit($limit, $offset);
}
$result = $this->testMode
? $this->getCompiledSelect($reset)
: $this->db->query($this->compileSelect(), $this->binds, false);
if ($reset === true)
{
$this->resetSelect();
// Clear our binds so we don't eat up memory
$this->binds = [];
}
return $result;
}
So the default for $reset, will "clear" what you have observed.
As mentioned by TimBrownlaw
I changed
$first= $this->_builder->get()->getResultArray();
to
$first= $this->_builder->get(NULL, 0 , false)->getResultArray();
and it worked for me as it didn't reset the query as third parameter of get() is for resetting the query

Import excel data given in each repeated 5 rows to one row in database. Laravel 5.8

I've an excel file with following data. The below is the data of 2 users. Each user have 5 rows of details. I need to import the following to 2 rows in database.
The below is my table structure
What I need is, I need to import the excel in such a way, in the table there should be only 2 rows like below.
How can I do this in Laravel 5.8.
Here is my controller code
public function importMovementFile (Request $request){
$this->validate($request, [
'mcafile' => 'required|mimes:xls,xlsx,ods'
]);
$path = $request->file('mcafile')->getRealPath();
$data = \Excel::import(new UsersImport,$path);
return back()->with('success', 'Excel Data Imported successfully.');
}
UserImports
use Maatwebsite\Excel\Row;
use Maatwebsite\Excel\Concerns\OnEachRow;
class UsersImport implements OnEachRow
{
public function onRow(Row $row)
{
$rowIndex = $row->getIndex();
$row = $row->toArray();
UploadMovAnalysisDataFiles::create([
'member_name' => $row[0][$rowIndex],
]);
}
}
Okay I found the solution to this,
We can do this by checking the name inside a for loop. First of all, check whether the name is empty or not, if empty place the first name in name variable and loop throughout. Store each scores of the corresponding name in an object. When another name comes insert the first details and loop through the next and so on.
public function insertExcel
{
$obj= new UploadMovAnalysisDataFiles();
$name ='';
for($i=1;$i<$rows->count();$i++){
if($name==''){
$name = $rows[$i][0];
$id = $rows[$i][1];
$date = date('Y-m-d h:i:s', strtotime($rows[$i][2]));
$visit_date = $date;
//function call
score($rows[$i][3],$rows[$i][4];
}elseif($name==$rows[$i][0]){
//function call
score($rows[$i][3],$rows[$i][4];
}else{
UploadMovAnalysisDataFiles::create([
'member_name' => $name,
'mov_analysis_tag_id' => $id ,
'visit_date' => $date,
'fitness_score' => $obj->fscore,
'knee_score' => $obj->kscore,
'hip_score' => $obj->hscore,
'core_score' => $obj->cscore,
'shoulder_score' => $obj->sscore,
]);
$name = $rows[$i][0];
$id = $rows[$i][1];
$date = date('Y-m-d h:i:s', strtotime($rows[$i][2]));
$visit_date = $date;
//function call
score($rows[$i][3],$rows[$i][4]);
}
}
UploadMovAnalysisDataFiles::create([
'member_name' => $name,
'mov_analysis_tag_id' => $id ,
'visit_date' => $date,
'fitness_score' => $obj->fscore,
'knee_score' => $obj->kscore,
'hip_score' => $obj->hscore,
'core_score' => $obj->cscore,
'shoulder_score' => $obj->sscore,
]);
}
Function to keep each score in an object.
function score($rows[$i][3],$rows[$i][4){
if($rows[$i][3]== 'VSFitness_Score'){
$obj->fscore = $rows[$i][4];
}if($rows[$i][3]== 'knee_Score'){
$obj->kscore = $rows[$i][4];
}if($rows[$i][3]== 'Hip_Score'){
$obj->hscore = $rows[$i][4];
}if($rows[$i][3]== 'Core_Score'){
$obj->cscore = $rows[$i][4];
}if($rows[$i][3]== 'Shoulder_Score'){
$obj->sscore = $rows[$i][4];
}
}

assign users to group modx

How can i assign newly created user to the particular group in modx Programmaticaly ? Below is my code
if(isset($_POST) && count($_POST)){
$oUser = $modx->newObject('modUser');
$oUser->set('username', "test");
//$oUser->set('password', "test");
$oProfile = $modx->newObject('modUserProfile');
$oProfile->set('fullname', $_POST['fname']);
$oProfile->set('email', $_POST['email']);
$oUser->addOne($oProfile);
if($oUser->save()===false){
echo "Error";
}else
echo "Done";
}
I googled but all i find is graphical tutorial how to create groups and edit user and then assign roles, If you know any tutorial then also its fine.
Here is how I have been doing it, this is a posthook snippet that fires after a user registers [and the user is created]
<?php
$specialty = $hook->getValue('specialty');
$country = strtolower($hook->getValue('excountry'));
$username = $hook->getValue('username');
$staff = $hook->getValue('staff-or-resident'); //Staff | Resident
$joingroup = '';
$joinrole = '';
$blockuser = 'false';
switch ($specialty){
case 'Other' :
$joingroup = 15; // Other
$joinrole = 1; //member
$blockuser = 'true';
break;
// there are about 15 different groups and roles here...
default :
$joingroup = '0'; // none
$joinrole = '0'; // none
break;
}
if($joingroup > 0 && $joinrole > 0){
$user = $modx->getObject('modUser', array('username'=>$username));
$internalkey = $user->get('id');
$profile = $user->getOne('Profile',array('internalKey'=>$internalkey));
$user->joinGroup($joingroup, $joinrole);
if($blockuser == 'true'){ //block user if they belong to the "other" group
$profile->set('blocked',1);
}
if(!$user->save()){
return false;
};
}
return true;
The key is the: $user->joinGroup($joingroup, $joinrole); where joingroup is the group id ~ or name and the joinrole is the role id ~ or name. It's documented here: http://api.modx.com/revolution/2.1/_model_modx_moduser.class.html#%5CmodUser::joinGroup()
The best way to create/edit something in revo >2.2 this is use "Class-based Processors" - https://www.markhamstra.com/modx-blog/2012/2/getting-started-with-class-based-processors-2.2/ to add user to group use this processor https://github.com/modxcms/revolution/blob/develop/core/model/modx/processors/security/user/update.class.php with this -
http://rtfm.modx.com/display/revolution20/Using+runProcessor
$param = array(
'id' => 1, // user id
'groups' => array(
array(
"usergroup" => 1,
"name" => "Administrator",
"member" => 1,
"role" => 2,
"rolename" => "Super User",
"primary_group" => true,
"rank" => 0,
"menu" => null
),
array( .... )
)
);
$response = $modx->runProcessor('security/user/update',$param );
if ($response->isError()) {
return $response->getMessage();
}

Extending Drupal 7 search

I want to extend default Drupal 7 node search with one additional field.
I alter search form with the following new field:
function mymodule_form_search_form_alter(&$form, &$form_state, $form_id) {
$form['basic']['site'] = array(
'#type' => 'select',
'#options' => array(
'KEY1' => 'TITLE1',
'KEY2' => 'TITLE2',
'KEY3' => 'TITLE3'
)
);
}
I have a field called field_data_field_site.field_site_value which i need to use as a filter in this search.
I've tried to read about hook_search_* functions but didn't get the idea.
My question is the following. How can I extend search form? Anyone have live examples?
The following is the best way I solve this problem.
First of all I need to alter Drupal's search block and search form with my field and define new submit function.
/**
* Implements hook_form_FORM_ID_alter().
*/
function mymodule_form_search_block_form_alter(&$form, &$form_state, $form_id) {
$form['#submit'][] = 'search_form_alter_submit';
$form['site'] = array(
'#type' => 'select',
'#options' => _options(),
'#default_value' => (($_GET['site']) ? $_GET['site'] : '')
);
}
/**
* Implements hook_form_FORM_ID_alter().
*/
function mymodule_form_search_form_alter(&$form, &$form_state, $form_id) {
$form['#submit'][] = 'search_form_alter_submit';
$form['basic']['site'] = array(
'#type' => 'select',
'#options' => _options(),
'#default_value' => (($_GET['site']) ? $_GET['site'] : '')
);
}
function _options() {
return array(
'' => 'Select site',
'site-1' => 'Site 1',
'site-2' => 'Site 2'
);
}
Submit function will forward us to default search/node page but with our query. Page would look like search/node/Our-query-string?site=Our-option-selected.
function search_form_alter_submit($form, &$form_state) {
$path = $form_state['redirect'];
$options = array(
'query' => array(
'site' => $form_state['values']['site']
)
);
drupal_goto($path, $options);
}
Next step is to use hook_search_info (Don't forget to turn it on and set as default on admin/config/search/settings page).
/**
* Implements hook_search_info().
*/
function mymodule_search_info() {
return array(
'title' => 'Content',
'path' => 'node',
'conditions_callback' => '_conditions_callback',
);
}
Conditions callback function defined in hook_search_info. We need to provide additional queries to our search.
function _conditions_callback($keys) {
$conditions = array();
if (!empty($_REQUEST['site'])) {
$conditions['site'] = $_REQUEST['site'];
}
return $conditions;
}
Finally, hook_search_execute will filter our content by our query. I used default code from this hook with modifications I need.
/**
* Implements hook_search_execute().
*/
function mymodule_search_execute($keys = NULL, $conditions = NULL) {
// Build matching conditions
$query = db_select('search_index', 'i', array('target' => 'slave'))
->extend('SearchQuery')
->extend('PagerDefault');
$query->join('node', 'n', 'n.nid = i.sid');
// Here goes my filter where I joined another table and
// filter by required field
$site = (isset($conditions['site'])) ? $conditions['site'] : NULL;
if ($site) {
$query->leftJoin('field_data_field_site', 's', 's.entity_id = i.sid');
$query->condition('s.field_site_value', $site);
}
// End of my filter
$query
->condition('n.status', 1)
->addTag('node_access')
->searchExpression($keys, 'node');
// Insert special keywords.
$query->setOption('type', 'n.type');
$query->setOption('language', 'n.language');
if ($query->setOption('term', 'ti.tid')) {
$query->join('taxonomy_index', 'ti', 'n.nid = ti.nid');
}
// Only continue if the first pass query matches.
if (!$query->executeFirstPass()) {
return array();
}
// Add the ranking expressions.
_node_rankings($query);
// Load results.
$find = $query
->limit(10)
->execute();
$results = array();
foreach ($find as $item) {
// Build the node body.
$node = node_load($item->sid);
node_build_content($node, 'search_result');
$node->body = drupal_render($node->content);
// Fetch comments for snippet.
$node->rendered .= ' ' . module_invoke('comment', 'node_update_index', $node);
// Fetch terms for snippet.
$node->rendered .= ' ' . module_invoke('taxonomy', 'node_update_index', $node);
$extra = module_invoke_all('node_search_result', $node);
$results[] = array(
'link' => url("node/{$item->sid}", array('absolute' => TRUE)),
'type' => check_plain(node_type_get_name($node)),
'title' => $node->title,
'user' => theme('username', array('account' => $node)),
'date' => $node->changed,
'node' => $node,
'extra' => $extra,
'score' => $item->calculated_score,
'snippet' => search_excerpt($keys, $node->body)
);
}
return $results;
}
I'd be happy if anyone would give me a better answer.

Resources