Yii2 : set current IP address dynamically in console scriptUrl - yii2

I want to get current IP address from OS. Required to remove dependancy of hardcoding url path in 'scripUrl' for 'UrlManager' component in console.php so that cron controller can send emails with proper hyperlinks

The yii Request component is unavailable in console-app
You'll need to rely on php built in functions
From CLI
PHP < 5.3.0
$myIp= getHostByName(php_uname('n'));
echo $myIp;
PHP >= 5.3.0
$myIp = getHostByName(getHostName());
echo $myIp;
see this answer

Related

Iron Python get triggered in initial load for Spotfire Client but not for Spotfire Web player

My script is to hide some pages for the some login User. My script get trigger well in Client not in Webplayer.
To trigger this script i created the Data function property with Input and output parameter.
Input parameter as sysdate
output assigned to document property where below script is present.
import Spotfire.Dxp
from Spotfire.Dxp.Data import *
table=Document.Data.Tables["RestrictedSSO"]
minCol=table.Columns['GROUPNAME']
minCursor=DataValueCursor.Create(minCol)
for row in table.GetRows(minCursor):
Document.Properties["UserGroup"]= minCursor.CurrentValue;
if Document.Properties["UserGroup"]=="Restricted":
for Page in Document.Pages:
if Page.Title == "ABCD":
Document.Pages.Remove(Page)
if Page.Title == "EFGH":
Document.Pages.Remove(Page)
First check if there is a URL specified for the TERR Engine. A default setting might work in the client and not in the webplayer, so specifying the URL can ensure it works in both Client and Webplayer.
If that still does not help you can choose to initiate the python script via Javascript instead of the TERR sysdate output : https://community.tibco.com/wiki/how-trigger-python-script-report-load-javascript-tibco-spotfire
When using TERR Check whether you have have checked refresh automatically and unchecked allow cache from script in data function.
Run terr on server rather than run locally.
Go to file-> Document properties -> uncheck Remember personalized view for each web client user.
Even after doing the above steps if it didn't worked , then you can also go with java script.

Use google api client in cakephp 3

I have been trying to use the google api client in cakekphp 3, but not successful on adding the service account json file to my project.
The below line is mentioned in:
https://github.com/googleapis/google-api-php-client
putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json');
But that doesn't work on cakephp 3. I know I can add it to the .env.default file, but it is not recommended for production.
How to use it then?
This function defines a default credentials setting path to be used, but note that you have not called it yet.
You must "tell" your application to use its default credentials settings.
// app.php
putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json');
// In the file you want to use Google Client
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
CakePHP also can read an specific file for env variables:
// config/.env
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/service-account.json"
// Uncomment this part of your bootstrap.php
if (!env('APP_NAME') && file_exists(CONFIG . '.env')) {
$dotenv = new \josegonzalez\Dotenv\Loader([CONFIG . '.env']);
$dotenv->parse()
->putenv()
->toEnv()
->toServer();
}
Keeping your setup on .env files make it easier maintaining all your settings up to date.

Fatfree routing with PHP built-in web server

I'm learning fatfree's route and found it behaves unexpected.
Here is my code in index.php:
$f3 = require_once(dirname(dirname(__FILE__)). '/lib/base.php');
$f3 = \Base::instance();
echo 'received uri: '.$_SERVER['REQUEST_URI'].'<br>';
$f3->route('GET /brew/#count',
function($f3,$params) {
echo $params['count'].' bottles of beer on the wall.';
}
);
$f3->run();
and here is the URL which I access: http://xx.xx.xx.xx:8090/brew/12
I get a 404 error:
received uri: /brew/12
Not Found
HTTP 404 (GET /12)
the strange thing is that the URI in F3 is now "/12" instead of "/brew/12" and I guess this is the issue.
When I check the base.php (3.6.5), $this->hive['BASE'] = "/brew" and $this->hive['PATH'] = "/12".
But if F3 only uses $this->hive['PATH'] to match the predefined route, it won't be able to match them.
If I change the route to:
$f3->route('GET /brew',
and use the URL: http://xx.xx.xx.xx:8090/brew, then the route matches without issue.
In this case, $this->hive['BASE'] = "" and $this->hive['PATH'] = "/brew". If F3 compares the $this->hive['PATH'] with predefined route, they match each other.
BTW, I'm using PHP's built-in web server and since $_SERVER['REQUEST_URI'] (which is used by base.php) returns the correct URI, I don't think there is anything wrong with the URL rewrite in my .htrouter.php.
Any idea? What did I miss here?
add the content of .htrouter.php here
<?php
#get the relative URL
$uri = urldecode(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
#if request to a real file (such as a html, image, js, css) then leave it as it is
if ($uri !== '/' && file_exists(__DIR__ . $uri)) {
return false;
}
#if request virtual URL then pass it to the bootstrap file - index.php
$_GET['_url'] = $_SERVER['REQUEST_URI'];
require_once __DIR__ . './public/index.php';
Your issue is directly related to the way you're using the PHP built-in web server.
As stated in the PHP docs, here's how the server handles requests:
URI requests are served from the current working directory where PHP was started, unless the -t option is used to specify an explicit document root. If a URI request does not specify a file, then either index.php or index.html in the given directory are returned. If neither file exists, the lookup for index.php and index.html will be continued in the parent directory and so on until one is found or the document root has been reached. If an index.php or index.html is found, it is returned and $_SERVER['PATH_INFO'] is set to the trailing part of the URI. Otherwise a 404 response code is returned.
If a PHP file is given on the command line when the web server is started it is treated as a "router" script. The script is run at the start of each HTTP request. If this script returns FALSE, then the requested resource is returned as-is. Otherwise the script's output is returned to the browser.
That means that, by default (without a router script), the web server is doing a pretty good job for routing unexisting URIs to your document root index.php file.
In other words, provided your file structure is like:
lib/
base.php
template.php
etc.
public/
index.php
The following command is enough to start your server and dispatch the requests properly to the framework:
php -S 0.0.0.0:8090 -t public/
Or if you're running the command directly from the public/ folder:
cd public
php -S 0.0.0.0:8090
Beware that the working directory of your application depends on the folder from which you call the command. In order to leverage this value, I strongly advise you to add chdir(__DIR__); at the top of your public/index.php file. This way, all subsequent require calls will be relative to your public/ folder. For ex: $f3 = require('../lib/base.php');
Routing file-style URIs
The built-in server, by default, won't pass unexisting file URIs to your index.php, as stated in:
If a URI request does not specify a file, then either index.php or index.html in the given directory are returned
So if you plan to define some routes with dots, such as:
$f3->route('GET /brew.json','Brew->json');
$f3->route('GET /brew.html','Brew->html');
Then it won't work because PHP won't pass the request to index.php.
In that case, you need to call a custom router, such as the .htrouter.php you were trying to use. The only thing is that your .htrouter.php has obviously been designed for a different framework (F3 doesn't care about $_GET['url'] but cares about $_SERVER['SCRIPT_NAME'].
Here's an exemple of .htrouter.php that should work with F3:
// public directory definition
$public_dir=__DIR__.'/public';
// serve existing files as-is
if (file_exists($public_dir.$_SERVER['REQUEST_URI']))
return FALSE;
// patch SCRIPT_NAME and pass the request to index.php
$_SERVER['SCRIPT_NAME']='index.php';
require($public_dir.'/index.php');
NB: the $public_dir variable should be set accordingly to the location of the .htrouter.php file.
For example if you call:
php -S 0.0.0.0:8090 -t public/ .htrouter.php
it should be $public_dir=__DIR__.'/public'.
But if you call:
cd public
php -S 0.0.0.0:8090 .htrouter.php
it should be $public_dir=__DIR__.
OK, I checked the base.php and found out when f3 calculates the base URI, it uses $_SERVER['SCRIPT_NAME'].
$base='';
if (!$cli)
$base=rtrim($this->fixslashes(
dirname($_SERVER['SCRIPT_NAME'])),'/');
if we have web server directly forward all requests to index.php, then
_SERVER['SCRIPT_NAME'] = /index.php, and in this this case, base is ''.
if we use URL rewriting via .htrouter.php to index.php, then
_SERVER['SCRIPT_NAME'] = /brew/12, and in this this case, base is '/brew' which causes the issue.
Since I'm going to use the URL rewrite, I have to comment out the if statement and make sure base =''.
Thanks xfra35 for providing the clue.
Apache like php router here:
It can url rewrite.
https://github.com/kyesil/QPHP/blob/master/router.php
Usage:
php -S localhost:8081 router.php

How to send email automatically in Yii2?

How to send email automatically?
My current scenario is I want to trigger mail sending automatically after 15 days.
First step would be to create a command line that can be called to send the mail.
Yii2 supports commands. I would recommend you to make a simple command like this (place in /command app dir). You will need to update config/console.php if using db etc
namespace app\commands;
use yii\console\Controller;
class mailController extends Controller {
public function actionSend() {
//code here to send the mail
}
}
The code sample to send mail can be obtained here
Now you can run this command from shell / command prompt in the yii root dir as below
yii mail/send
Next step is to run this command every 15 days.
Running scheduled jobs require you to have an external trigger on your set interval.
On unix systems, this trigger is provided by cron jobs , an example here
You can configure the cron job as below
0 0 1,16 * * /path/to/yiiroot/yii mail/send

How can I let users register my product online?

I've a MySql database hosted in my web site, with a table named UsrLic
Where any one wants to buy my software must register and enter his/her Generated Machine Key (+ username, email ...etc).
So my question is:
I want to automate this process from my software, how this Process will be?
Should I connect and update my database directly from my software ( and this means I must save all my database connection parameters in it * my database username , password , server * and then use ADO or MyDac to connect to this database ? and if yes how secure is this process ?
or any other suggestions .
I recommend creating an API on your web site in PHP and calling the API from Delphi.
That way, the database is only available to your web server and not to the client application, ever. In fact, you should run your database on localhost or with a private IP so that only machines on the same physical network can reach it.
I have implemented this and am implementing it again as we speak.
PHP
Create a new file named register_config.php. In this file, setup your MySQL connection information.
Create a file named register.php. In this file, put your registration functions. From this file, include 'register_config.php'. You will pass parameters to the functions you create here, and they will do the reading and writing to your database.
Create a file named register_api.php. From this file, include 'register.php'. Here, you will process POST or GET variables that are sent from your client application, call functions in register.php, and return results back to the client, all via HTTP.
You will have to research connecting to and querying a MySQL database. The W3Schools tutorials will have you doing this very quickly.
For example:
Your Delphi program calls https://mysite/register_api.php with Post() and sends the following values:
name=Marcus
email=marcus#gmail.com
Here's how the beginning of register_api.php might look:
// Our actual database and registration functions are in this library
include 'register.php';
// These are the name value pairs sent via POST from the client
$name = $_POST['name'];
$email = $_POST['email'];
// Sanitize and validate the input here...
// Register them in the DB by calling my function in register.php
if registerBuyer($name, $email) {
// Let them know we succeeded
echo "OK";
} else {
// Let them know we failed
echo "ERROR";
}
Delphi
Use Indy's TIdHTTP component and its Post() or Get() method to post data to register_api.php on the website.
You will get the response back in text from your API.
Keep it simple.
Security
All validation should be done on the server (API). The server must be the gatekeeper.
Sanitize all input to the API from the user (the client) before you call any functions, especially queries.
If you are using shared web hosting, make sure that register.php and register_config.php are not world readable.
If you are passing sensitive information, and it sounds like you are, you should call the registration API function from Delphi over HTTPS. HTTPS provides end to end protection so that nobody can sniff the data being sent off the wire.
Simply hookup a TIdSSLIOHandlerSocketOpenSSL component to your TIdHTTP component, and you're good to go, minus any certificate verification.
Use the SSL component's OnVerifyPeer event to write your own certificate verification method. This is important. If you don't verify the server side certificate, other sites can impersonate you with DNS poisoning and collect the data from your users instead of you. Though this is important, don't let this hold you up since it requires a bit more understanding. Add this in a future version.
Why don't you use e.g. share*it? They also handle the buying process (i don't see how you would do this for yourself..) and let you create a reg key through a delphi app.