Run frontend web controller method in console controller method for cronjob yii2 - yii2-advanced-app

I have a index method in frontend/controllers/FollowupcandidteclientController
where i am returning some values after running this controller method.
below is my code(just for reference)
class FollowupcandidteclientController extends \yii\web\Controller
{
public function actionIndex()
{
$a=2;
$b=3;
$c=$a + $b;
return $c;
}
}
I have set cronjob with the controller name CronjobController in console/controllers/CronjobController.
In this I have a method called runcron().
I want to run the followupcandidateclient/index in this cronjob controller runcron method
Below is my code for cronjob
namespace console\controllers;
use Yii;
use yii\console\Controller;
Class CronjobController extends Controller
{
public function actionRuncron(){
here this action should run index.php?r=followupcandidateclient/index when the cronjob is executed
}
}
?>
It would be great and very thankfull if any body helps me on this issue.
Thanks in advance.

I think the shortest way for you is just curl it.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "yourdomain/index.php?r=followupcandidateclient/index");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
// use $output if needed
If you can't access it in cron via internet, then you can start PHP server like this (with appropriate port number):
$ cd /path/to/your/index.php/
$ PHP -S localhost:8002
Then in curl request you can use localhost:8002 instead of yourdomain

Related

Get Email state using codeigniter & sendgrid Webhook

I have integrated sendgrid for send mail. I also want to track whether a user has opened the mail and click the link inside the mail or not.
that's why I used sendgrid.
using it I can send mail, but can't track mail states(mail is opened or not, the link is clicked or not).
I tried the below code for sending mail.
function sendMail($toMails, $body, $subject, $ccMails = array(), $bccMails = array()) {
$ci = &get_instance();
if (empty($toName)) {
$toName = $toMails;
}
$sendMail = $ci->config->item('sendMail');
$email = new \SendGrid\Mail\Mail();
$email->setFrom($ci->config->item('from'), "From User name");
$email->setSubject($subject);
$email->addTos($toMails); //for multiple user pass array with emails and names
$email->addCcs($ccMails);
$email->addBccs($bccMails);
$email->addContent("text/html", $body);
$email->setFooter(false, "", "<strong>If you don't want to receive this type of email in the future, please <a href='http://w3schools.com'>Unsubscribe</a>.</strong>");
//$email->setSpamCheck(true, 1, "http://localhost:8081/");
// Tracking Settings
$email->setClickTracking(true, true);
//$email->setOpenTracking(true, true);
$sendgrid = new \SendGrid($ci->config->item('key'));
try {
$response = $sendgrid->send($email);
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
if ($sendMail) :
if (!$response->statusCode()) :
_pre($response->headers());
return false;
else :
return true;
endif;
endif;
}
which is working fine, except it is going in the spam.
now below code, I am using to get details as per email id.
$sendgrid = new \SendGrid($this->config->item('key'));
$query_params = json_decode('{"start_date": "2019-10-07","end_date": "2019-10-07","to_email": "cadmin1#getnada.com","subject":"This is a subject test"}');
$response = $sendgrid->client->stats()->get(null, $query_params);
_pre($response->body());
exit;
above code only gives me date wise data, but I also want email id wise.
but in spite of adding a parameter for that, still, I am not getting desired output.
https://sendgrid.com/docs/for-developers/sending-email/getting-started-email-activity-api/#filter-by-recipient-email
I have used the above demo, in that demo, they have used curl but I am using CodeIgniter's way.
I am not sure about sendgrid version that's why I added both version tag, I used API one.
anyone having a proper solution regarding it?
I have implemented webhooks to archive my desire output.
for that need to follow steps as per documentation shows
after that need to create a page from where we can get mails status.
on executing that page it returns data as per activity.
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: *');
$data = file_get_contents("php://input");
$events = json_encode($data, true);
$requestData = array('response' => $events);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "<url which we earlier set for webhook as per documentation>");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
curl_close($ch);
?>
i have used Curl for getting desire output.

How to access to Slim container from other classess?

Suppose that in my dependencies.php file I setup this container:
<?php
$container = $app->getContainer();
$container['db'] = function($config)
{
$db = $config['settings']['db'];
$pdo = new PDO("mysql:host=" . $db['host'] . ";port=" . $db['port'] .
";dbname=" . $db['dbname'] . ";charset=" . $db['charset'], $db['user'], $db['pass']);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
return $pdo;
};
I can use this container inside my route, called for example table.php:
<?php
use Slim\Http\Request;
use Slim\Http\Response;
$app->get('/table/get_table', function (Request $request, Response $response, array $args)
{
$sql = $this->db->prepare("SELECT * FROM some_table");
$sql->execute();
$result = $sql->fetchAll();
return $response->withJson($result);
});
this is basically the default usage, right? Said that, how can I instead use the db container from other classes? Supposes I have created a class called TableUtility and imported inside the table.php:
class TableUtility
{
function GetTableFromDb()
{
$sql = $this->db->prepare("SELECT * FROM some_table");
$sql->execute();
$result = $sql->fetchAll();
return $response->withJson($result);
}
}
as you can see I moved the logic of PDO inside GetTableFromDb of TableUtility, how can I access to db container from this class?
The usage in table.php will be:
<?php
use Slim\Http\Request;
use Slim\Http\Response;
$app->get('/table/get_table', function (Request $request, Response $response, array $args)
{
$tableUtility = new TableUtility();
return $response->withJson($tableUtility->GetTableFromDb());
});
actually I get in TableUtility:
Call to a member function prepare() on null
The full name for what you refer to as container is Dependency Injection Container. It is supposed to contain dependencies for objects. Passing this container to objects is considered bad practice. Instead you should pass only required dependencies for that object, which in your case is to pass db to $tableUtility. This is usually used by passing dependencies when constructing the object, or using setter methods. In your case you can refactor your code like this:
class TableUtility
{
function __construct($db) {
$this->db = $db;
}
}
Now in any method of TableUtility class, you have access to db object using $this->db but you'll need to pass db to class constructor whenever you create a new object. So you also need to do this:
$app->get('/table/get_table', function (Request $request, Response $response, array $args)
{
$tableUtility = new TableUtility($this->db);
// rest of the code
});

How to detect wrong URL using Joomla! System Plugin?

I have developed a Joomla! system plugin.
I would like to detect wrong URL when that plugin is executed.
For example:
If I enter a URL "http://localhost/wrong-url", I want to catch that error in the system plugin.
How do I know that the system will display the error page (404)?
You can do this using the following technique
Check URL Function
function checkURL($URL){
$ch = curl_init($URL);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpcode != 200) {
return false;
}else{
return true;
}
}
Use Of the CheckURL Function
/*URL May be a Joomla OR Non Joomla Site*/
if(checkURL("http://adidac.github.com/jmm/index.html")){
echo "URL Exist";
}else{
echo "URL NOT Exist";
//JError::raiseWarning(500,$URL. " is not exists");
}
if(checkURL("http://adidac.github.com/jmm/indexsdadssdasaasdaas.html")){
echo "URL Exist";
}else{
echo "URL NOT Exist";
//JError::raiseWarning(500,$URL. " is not exists");
}
NOTE: Check you have PHP curl lib installed
In a system plugin to trap the 404 you would have to add a function from your plugin as a callback to JError error handler array.
I would have a look at the way com_redirect does it, with it's system plugin. e.g.
function __construct(&$subject, $config)
{
parent::__construct($subject, $config);
// Set the error handler for E_ERROR to be the class handleError method.
JError::setErrorHandling(E_ERROR, 'callback', array('plgSystemRedirect', 'handleError'));
}
static function handleError(&$error)
{
// Get the application object.
$app = JFactory::getApplication();
// Make sure we are not in the administrator and it's a 404.
if (!$app->isAdmin() and ($error->getCode() == 404))
{
// Do cool stuff here
}
}
The only problem is JError is depreciated so I'm not sure going forward when this would break e.g. it should be fine in 3.0, 3.1, 3.2 and 3.5 but after that who knows?
I know this is an old question, but I needed a solution today and found this question, so leaving my solution below to help anyone else searching in the future.
In the plugin file:
/**
* The global exception handler registered before the plugin was instantiated
*
* #var callable
* #since 3.6
*/
private static $previousExceptionHandler;
/**
* Constructor.
*
* #param object &$subject The object to observe
* #param array $config An optional associative array of configuration settings.
*
* #since 1.6
*/
public function __construct(&$subject, $config) {
parent::__construct($subject, $config);
// Register the previously defined exception handler so we can forward errors to it
self::$previousExceptionHandler = set_exception_handler(array('PlgSystemVmsreporting', 'handleException'));
}
public static function handleException($exception) {
// Wrap in try/catch to prevent any further exceptions being raised
try {
// Do whatever you need with the error
} catch (Exception $e) {
//Don't make a fuss - fail silently
}
// Proxy to the previous exception handler if available, otherwise use the default Joomla handler
if (self::$previousExceptionHandler) {
call_user_func_array(self::$previousExceptionHandler, array($exception));
} else {
ExceptionHandler::render($exception);
}
}

How to get all work logs for a period of time from the Jira REST API?

I'm writing an application using PHP and the Jira REST API which is required to generate a report for a particular period of time with the accumulation of hours spent by a person on a particular project.
For this I will need a call which will give something like this.
e.g: For the period 01/01/2012 - 31/01/2012 give me the worklogs for project X.
The method I found so far, was to get the updated issues after the start date and filter the worklogs for each issue by the period again.
Is there a better alternative?
As many have said, there's no direct way. However, if you narrow down the search space efficiently, it's not so bad. The following PHP code runs quite fast on my setup, but of course, your mileage may vary:
<?php
$server = 'jira.myserver.com';
$fromDate = '2012-01-01';
$toDate = '2012-01-31';
$project = 'X';
$assignee = 'bob';
$username = 'my_name';
$password = 'my_password';
$curl = curl_init();
curl_setopt($curl, CURLOPT_USERPWD, "$username:$password");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
# Give me up to 1000 search results with the Key, where
# assignee = $assignee AND project = $project
# AND created < $toDate AND updated > $fromDate
# AND timespent > 0
curl_setopt($curl, CURLOPT_URL,
"https://$server/rest/api/2/search?startIndex=0&jql=".
"assignee+%3D+$assignee+and+project+%3D+$project+".
"and+created+%3C+$toDate+and+updated+%3E+$fromDate+".
"and+timespent+%3E+0&fields=key&maxResults=1000");
$issues = json_decode(curl_exec($curl), true);
foreach ($issues['issues'] as $issue) {
$key = $issue['key'];
# for each issue in result, give me the full worklog for that issue
curl_setopt($curl, CURLOPT_URL,
"https://$server/rest/api/2/issue/$key/worklog");
$worklog = json_decode(curl_exec($curl), true);
foreach ($worklog['worklogs'] as $entry) {
$shortDate = substr($entry['started'], 0, 10);
# keep a worklog entry on $key item,
# iff within the search time period
if ($shortDate >= $fromDate && $shortDate <= $toDate)
$periodLog[$key][] = $entry;
}
}
# Show Result:
# echo json_encode($periodLog);
# var_dump($periodLog);
?>
If you can't find the an out-of-the-box function that does what you've asked for, I can think of three other solutions other than yours:
Query the DB directly so you could get the work logs using one query. Be sure not to insert/delete/update the DB directly, but only to query it.
Use something like Jira Scripting Suite or Behaviours Plugin to add scripts that will write the work-logs somewhere on the disk. Then use another app to read the written information from the disk and display it to the users.
Use the Tempo plugin
It is worth pointing out that Jira queries have an expand option which allows you to specify which fields you want attached to your search:
// Javascript
$jql = 'project = MyProject and updated > 2016-02-01 and updated < 2016-03-01';
// note this definition
$fields = 'key,summary,worklog';
$query = "https://{server}/rest/api/2/search?maxResults=100&fields={fields}&jql={jql}"
.replace(/{server}/g,$server)
.replace(/{jql}/g,encodeURIComponent($jql))
.replace(/{fields}/g,$fields)
;
The returned JSON object returned will be a list of tickets, and each ticket will have a collection of work items attached (potentially zero length).
Javascript rather than PHP, but the same idea holds:
function getJql(params){
$.ajax({
url: getJiraUrl()
+ "/rest/api/2/search?startIndex=0&fields=worklog,assignee,status,key,summary&maxResults=1000&jql="
+ encodeURI(params.jql),
success: function (resp) {
resp.issues.forEach(function(issue) {
issue.fields.worklog.worklogs.forEach(function(work){
alert(JSON.stringify(work));
db.AddWork(work);
});
});
}
});
}
posted on GitLab: https://gitlab.com/jefferey-cave/ProductivityBlockers/blob/5c4cb33276e8403443d4d766fc94ab2f92292da6/plugin-data-jira.js
The approach I've personally used for the same kind of an application is to get ALL records from JIRA on a weekly basis and then generate reports from the database they're stored in.
This way you will also have the data available if a major JIRA crash occurs. Our company went through such a problem with a OnDemand instance when a RAID Array burned and most of the data was unrecoverable.

Getting 404 Error from Facebook Graph API

So I am getting this error and I have no clue why. When I run it on the server it's on, I get a 404 error with a simple request like this.
$json = file_get_contents('https://graph.facebook.com/me?access_token='.LONGSTRING);
The error is:
function.file-get-contents: failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found
However, I can paste the URL that I am using with file_get_contents directly in the browser at the same time and it comes up. So it seems as if Facebook is blocking my server.
Also it works half the time.
Any ideas?
Try cURL, not sure why file_get_contents is unreliable but I have seen the same issue in the past. I use this geturl function to cURL a URL and pass the parameters in as a PHP array
function geturl($url, $params) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params, null, '&'));
$ret = curl_exec($ch);
curl_close($ch);
return $ret;
}
Which can then be called like so
$url = 'https://www.graph.facebook.com/me';
$params = array('access_token' => '*********************');
$graph_ret = geturl($url, $params);
$json = #file_get_contents('https://graph.facebook.com/me?access_token='.$access_token) or die("ERROR");
use this will help you alot