I have a Laravel 5.4 project. There is a route issue that i can't solve second day.
I have two routes like:
Route::get('/', 'HomeController#index')->name('index');
public function index(CookieJar $cookieJar, Request $request)
{
// Берем город из куков
$city_from_cookie = Cookie::get('city');
// Если города нет в куках
if (!$city_from_cookie) {
$client = new Client();
$ip = $request->ip() == '127.0.0.1' ? '95.85.70.7' : $request->ip();
$json = $client->request('GET', 'http://freegeoip.net/json/' . $ip . '');
$city = json_decode($json->getBody()->getContents());
if ($city->city === null) {
$cookie = cookie('city', config('custom.city.default_slug'), 21600, null, null, false, true);
$cookieJar->queue($cookie);
$city = config('custom.city.default_slug');
} else {
$city = strtolower($city->city);
try {
$city = City::findBySlugOrFail($city);
$city = $city->slug;
} catch (ModelNotFoundException $ex) {
$city = 'moskva';
}
$cookie = cookie('city', $city, 21600, null, null, false, false);
$cookieJar->queue($cookie);
}
} else {
$city = $city_from_cookie;
}
return redirect(route('city', [$city]), 301);
}
AND
Route::get('{city}', 'HomeController#getCityCategories')->name('city');
public function getCityCategories(City $city, CookieJar $cookieJar)
{
// Cache::flush();
// dd(request()->getRequestUri());
$cookie = cookie('city', $city->slug, 21600, null, null, false, false);
$cookieJar->queue($cookie);
$categories = Category::whereNull('parent_id')->with('subcategories')->get();
if ($city->weather_id) {
$weather = $this->getWeather($city->weather_id);
} else {
$weather = [
'city' => '',
'temp_min' => '',
'temp_max' => '',
'day' => '',
'symbol' => '',
'symbol_desc' => ''
];
}
return view('pages.categories', compact('categories', 'city', 'weather'));
}
The problem is that if you go to the '/' root first time method will do it's work but when you're getting the city like /moskva and if you change your city with another for example /abakan and then go the root '/' you will be redirected to the /moskva. I tried almost everything, turned off any cahing, cleared cache with artisan commands but it does not helped. Here is domain for testing this issue: okololo.ru
Related
I have a problem, I am currently doing a search by date range of maximum 10 days and the issue is that if there are more than 10 messages or there is a total of 38 messages it takes 4 to 5 minutes to load the data, so I wanted to know if there is a way to bring it paginated directly when doing the query in Horde.
public function connect($username, $password, $hostname, $port, $ssl, $folder, $debug = 0, $cache = 0)
{
$opt = [
'username' => $username,
'password' => $password,
'hostspec' => $hostname,
'port' => $port,
'secure' => $ssl,
];
if ($debug) $opt['debug'] = Log::debug("message");
if ($cache) $opt['cache'] = array(
'backend' => new \Horde_Imap_Client_Cache_Backend_Cache(array(
'cacheob' => new Horde_Cache(new Horde_Cache_Storage_File(array(
'dir' => '/tmp/hordecache'
)))
))
);
static::$folder = 'INBOX';
try {
return static::$client = new \Horde_Imap_Client_Socket($opt);
} catch (\Horde_Imap_Client_Exception $e) {
// Any errors will cause an Exception.
dd('Error');
}
}
public function searchSince($date_string)
{
try {
$query = new Horde_Imap_Client_Search_Query();
$query->dateSearch(
new Horde_Imap_Client_DateTime($date_string), Horde_Imap_Client_Search_Query::DATE_SINCE
);
$results = static::$client->search(static::$folder,$query);
} catch (\Exception $th) {
dd('Since Mail');
}
if ($results) {
static::$var = $results['match']->ids;
return true;
}
return false;
}
//I get the header data of each message (subject, date, uid, from, client name)
public function next(){
if ($var = next(static::$var)) {
static::$id = $var;
$headers = HordeImap::fetchHeaders(static::$id);
static::$clientName = $headers->getHeader('From')->getAddressList(true)->first()->__get('personal');
static::$fromEmail = $headers->getHeader('From')->getAddressList(true)->first()->__get('bare_address');
static::$subject = $headers->getHeader('subject')->__get('value');
$emailDate = $headers->getHeader('Date')->__get('value');
$unixTimestamp = strtotime($emailDate);
static::$emailDate = date('Y-m-d H:i:s',$unixTimestamp);
return true;
}
return false;
}
Controller
$mailb = new HordeImap();
$mailb->connect($userMail->client,$userMail->secret_token,$userMail->server,$userMail->port,'ssl','INDEX',1);
$msgs = $mailb->searchSince(date('d F Y', strtotime(date("Y-m-d", time()) . " -10 days")));
static::$mailbox = [];
if($msgs) while($mailb->next()){
static::$mailbox[] = [
'uid' => $mailb::$id,
'from' => $mailb::$fromEmail,
'client'=> $mailb::$clientName,
'date' => $mailb::$emailDate,
'subject'=> $mailb::$subject,
];
}
// I page the array once I have obtained all the contents.
$page = null;
$page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
$items = static::$mailbox instanceof Collection ? static::$mailbox : Collection::make(static::$mailbox);
dd(new LengthAwarePaginator($items->forPage($page, 5), $items->count(), 5, null, []));
I have this php script:
<?php
class Curl_Class {
private $endpointUrl;
private $userName;
private $userKey;
public $token;
public $errorMsg = '';
private $defaults = array(
CURLOPT_HEADER => 0,
CURLOPT_HTTPHEADER => array('Expect:'),
// CURLOPT_FRESH_CONNECT => 1,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_TIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_SSL_VERIFYHOST => 0
);
//constructor saves the values
function __construct($url, $name, $key) {
$this->endpointUrl=$url;
$this->userName=$name;
$this->userKey=$key;
$this->token=$key;
}
private function getChallenge() {
$curl_handler = curl_init();
$params = array("operation" => "getchallenge", "username" => $this->userName);
$options = array(CURLOPT_URL => $this->endpointUrl."?".http_build_query($params));
curl_setopt_array($curl_handler, ($this->defaults + $options));
$result = curl_exec($curl_handler);
if (!$result) {
$this->errorMsg = curl_error($curl_handler);
return false;
}
$jsonResponse = json_decode($result, true);
if($jsonResponse["success"]==false) {
$this->errorMsg = "getChallenge failed: ".$jsonResponse["error"]["message"]."<br>";
return false;
}
$challengeToken = $jsonResponse["result"]["token"];
return $challengeToken;
}
function login() {
$curl_handler = curl_init();
$token = $this->getChallenge();
//create md5 string containing user access key from my preference menu
//and the challenge token obtained from get challenge result
$generatedKey = md5($token.$this->userKey);
$params = array("operation" => "login", "username" => $this->userName, "accessKey" => $generatedKey);
$options = array(CURLOPT_URL => $this->endpointUrl, CURLOPT_POST => 1, CURLOPT_POSTFIELDS => http_build_query($params));
curl_setopt_array($curl_handler, ($this->defaults + $options));
$result = curl_exec($curl_handler);
if (!$result) {
$this->errorMsg = curl_error($curl_handler);
return false;
}
$jsonResponse = json_decode($result, true);
if($jsonResponse["success"]==false) {
$this->errorMsg = "Login failed: ".$jsonResponse["error"]["message"]."<br>";
return false;
}
$sessionId = $jsonResponse["result"]["sessionName"];
//save session id
$this->token=$sessionId;
return true;
}
private function handleReturn($result, $name, $curl_handler) {
if (!$result) {
$this->errorMsg = curl_error($curl_handler);
return false;
}
$jsonResponse = json_decode($result, true);
if (!$jsonResponse) {
$this->errorMsg = "$name failed: ".$result."<br>";
return false;
}
if($jsonResponse["success"]==false) {
$this->errorMsg = "$name failed: ".$jsonResponse["error"]["message"]."<br>";
return false;
}
return $jsonResponse["result"];
}
public function operation($name, $params, $type = "GET", $filepath = '') {
$params = array_merge(array("operation" => $name, "sessionName" => $this->token), $params);
if (strtolower($type) == "post") {
$options = array(CURLOPT_URL => $this->endpointUrl, CURLOPT_POST => 1, CURLOPT_POSTFIELDS => http_build_query($params));
}
else {
$options = array(CURLOPT_URL => $this->endpointUrl."?".http_build_query($params));
}
if ($filepath != '' && strtolower($type) == "post") {
$element = $params['element'];
if (!empty($element)) {
$element = json_decode($element, true);
}
if (isset($element['filename'])) {
$filename = $element['filename'];
}
else {
$filename = pathinfo($filepath, PATHINFO_BASENAME);
}
$size = filesize($filepath);
$add_options = array(CURLOPT_HTTPHEADER => array("Content-Type: multipart/form-data"), CURLOPT_INFILESIZE => $size);
if (function_exists("mime_content_type")) {
$type = mime_content_type($filepath);
}
elseif (isset($element['filetype'])) {
$type = $element['filetype'];
}
else {
$type = '';
}
if (!function_exists('curl_file_create')) {
$add_params = array("filename" => "#$filepath;type=$type;filename=$filename");
}
else {
$cfile = curl_file_create($filepath, $type, $filename);
$add_params = array('filename' => $cfile);
}
$options += $add_options;
$options[CURLOPT_POSTFIELDS] = $params + $add_params;
}
$curl_handler = curl_init();
curl_setopt_array($curl_handler, ($this->defaults + $options));
$result = curl_exec($curl_handler);
return $this->handleReturn($result, $name, $curl_handler);
}
}
?>
I'm learning programming so i'm in no way good at this.. I need to execute the function login() of this class from a url, giving in input the parameters (private $endpointUrl,private $userName,private $userKey) and receiving in output the $sessionId.
So, for example, i'll write in the url
https://webserver.com/Login.php? endpointUrl=1&username=2&userKey=3
and receiving in output the $sessionId.
Is it possible? How? Thanks!
Here's some example;
if(isset($_GET["endpointUrl"], $_GET["username"], $_GET["userKey"])){
$x = new Curl_Class($_GET["endpointUrl"], $_GET["username"], $_GET["userKey"]);
if($x->login()){
echo $x->token;
}
}
Better if serialize the GET input for security purposes. But in this example, just a simple call of login.
Since the login() method returning boolean, so from there we can know if the token created or not.
I am currently doing an internship and I tried to make an activity module to show playlist, from video given by a filemanager. I succeed to send the video to the database but when I want to edit my module, it doesn't show any videos in the filemanager.
I read the moodle documentation about file API and I decided to use the following code (Load existing files into draft area)
:
if (empty($entry->id)) {
$entry = new stdClass;
$entry->id = null;
}
$draftitemid = file_get_submitted_draft_itemid('attachments');
file_prepare_draft_area($draftitemid, $context->id, 'mod_glossary','attachment', $entry->id,array('subdirs' => 0, 'maxbytes' => $maxbytes, 'maxfiles' => 50));
$entry->attachments = $draftitemid;
$mform->set_data($entry);
So I put the following lines in my mod_form.php :
$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);
if (empty($entry->id)) {
$entry = new stdClass;
$entry->id = null;
}
$draftitemid = file_get_submitted_draft_itemid('mymanager');
file_prepare_draft_area($draftitemid, $this->context->id, 'mod_playlist', 'content', 0,
array('subdirs'=>true));
$entry->attachments = $draftitemid;
$mform->set_data($entry);
The problem is that the file manager is still empty, and the line "$mform->set_data($entry); " makes the page to crash(blank).
Here is a template for uploading files.
In local/myplugin/upload.php
require_once(dirname(dirname(dirname(__FILE__))) . '/config.php');
require_once(dirname(__FILE__) . '/upload_form.php');
require_login();
$context = context_system::instance();
require_capability('local/myplugin:upload', $context);
$pageurl = new moodle_url('/local/myplugin/upload.php');
$heading = get_string('myupload', 'local_myplugin');
$PAGE->set_context($context);
$PAGE->set_heading(format_string($heading));
$PAGE->set_title(format_string($heading));
$PAGE->set_url('/local/myplugin/upload.php');
echo $OUTPUT->header();
echo $OUTPUT->heading($heading);
$fileoptions = array(
'maxbytes' => 0,
'maxfiles' => '1',
'subdirs' => 0,
'context' => context_system::instance()
);
$data = new stdClass();
$data = file_prepare_standard_filemanager($data, 'myfiles',
$fileoptions, context_system::instance(), 'local_myplugin', 'myfiles', 0); // 0 is the item id.
$mform = new upload_form(
null,
array(
'fileoptions' => $fileoptions,
)
);
if ($formdata = $mform->get_data()) {
// Save the file.
$data = file_postupdate_standard_filemanager($data, 'myfiles',
$fileoptions, context_system::instance(), 'local_myplugin', 'myfiles', 0);
} else {
// Display the form.
$mform->set_data($data);
$mform->display();
}
echo $OUTPUT->footer();
Then in local/myplugin/upload_form.php
defined('MOODLE_INTERNAL') || die;
require_once($CFG->libdir . '/formslib.php');
class upload_form extends moodleform {
public function definition() {
$mform =& $this->_form;
$fileoptions = $this->_customdata['fileoptions'];
$mform->addElement('filemanager', 'myfiles_filemanager',
get_string('myfiles', 'local_myplugin'), null, $fileoptions);
$this->add_action_buttons(false, get_string('save', 'local_myplugin'));
}
}
You will also need this in /local/myplugin/lib.php
function local_myplugin_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options = array()) {
if ($context->contextlevel != CONTEXT_SYSTEM) {
send_file_not_found();
}
$fs = get_file_storage();
$file = $fs->get_file($context->id, 'local_myplugin', $filearea, $args[0], '/', $args[1]);
send_stored_file($file);
}
I'm currently implementing smartrecruiter api in my project. I'm using two endpoints namely /jobs-list and /job-details. The problem is that every time I'm extracting the details in the second endpoint which is the /job-details, the execution time is so slow.
Here's what I've done so far:
function getContext()
{
$opts = array(
'http'=> array(
'method' => 'GET',
'header' => 'X-SmartToken: xxxxxxxxxxxxxxxxx'
)
);
return $context = stream_context_create($opts);
}
function getSmartRecruitmentJob($city, $department)
{
$tmp = array();
$results= array();
$limit = 100; //max limit for smartrecruiter api is 100
// Open the file using the HTTP headers set above
$file = file_get_contents('https://api.smartrecruiters.com/jobs?limit='.$limit.'&city='.$city.'&department='.$department, false, $this->getContext());
$lists= json_decode($file, true);
foreach($lists['content'] as $key => $list)
{
if ($list['status'] == 'SOURCING' || $list['status'] == 'INTERVIEW' || $list['status'] == 'OFFER')
{
$results['id'] = $list['id'];
$tmp[] = $this->getSmartRecruitmentJobDetails($results['id']);
}
}
return $tmp;
}
function getSmartRecruitmentJobDetails($id)
{
$results = array();
$file = file_get_contents('https://api.smartrecruiters.com/jobs/'.$id, false, $this->getContext());
$lists= json_decode($file, true);
$results['title'] = isset($lists['title']) ? $lists['title'] : null;
$results['department_label'] = isset($lists['department']['label']) ? $lists['department']['label'] : null;
$results['country_code'] = isset($lists['location']['countryCode']) ? $lists['location']['countryCode'] : null;
$results['city'] = isset($lists['location']['city']) ? $lists['location']['city'] : null;
$results['url'] = isset($lists['actions']['applyOnWeb']['url']) ? $lists['actions']['applyOnWeb']['url'] : null;
return $results;
}
Solved it by caching the function for extracting the data:
function getCache()
{
if ($this->cache === null)
{
$cache = \Zend\Cache\StorageFactory::factory(
array(
'adapter' => array(
'name' => 'filesystem',
'options' => array(
'ttl' => 3600 * 7, // 7 hours
'namespace' => 'some-namespace',
'cache_dir' => 'your/cache/directory'
),
),
'plugins' => array(
'clear_expired_by_factor' => array('clearing_factor' => 10),
),
)
);
$this->cache = $cache;
}
return $this->cache;
}
function getSmartRecruitmentJobDetails($id)
{
$cache = $this->getCache();
$key = md5('https://api.smartrecruiters.com/jobs/'.$id);
$lists = unserialize($cache->getItem($key, $success));
$results = array();
if($success && $lists)
{
header('Debug-cache-recruit: true');
}
else
{
header('Debug-cache-recruit: false');
// Open the file using the HTTP headers set above
$file = file_get_contents('https://api.smartrecruiters.com/jobs/'.$id, false, $this->getContext());
$lists= json_decode($file, true);
$cache->addItem($key, serialize($lists));
}
$results['title'] = isset($lists['title']) ? $lists['title'] : null;
$results['department_label'] = isset($lists['department']['label']) ? $lists['department']['label'] : null;
$results['country'] = isset($lists['location']['country']) ? $lists['location']['country'] : null;
$results['country_code'] = isset($lists['location']['countryCode']) ? $lists['location']['countryCode'] : null;
$results['city'] = isset($lists['location']['city']) ? $lists['location']['city'] : null;
$results['url'] = isset($lists['actions']['applyOnWeb']['url']) ? $lists['actions']['applyOnWeb']['url'] : null;
return $results;
}
What my problem is that I can not send array to solr machine in order to update. I am using codeigniter as a framework and here is my code:
$solrData = array();
$solrData['id'] = $this->data['profil_data']['id'];
$solrData['site'] = $this->data['profil_data']['site'];
$solrData['url_Domain'] = $this->data['profil_data']['url_Domain'];
$solrData['url_Page'] = $this->data['profil_data']['url_Page'];
$solrData['url_Profil'] = $this->data['profil_data']['url_Profil'];
$solrData['scr_Kobi_Rank'] = $this->data['profil_data']['scr_Kobi_Rank'];
$solrData['scr_A'] = $this->data['profil_data']['scr_A'];
$solrData['scr_B'] = $this->data['profil_data']['scr_B'];
$solrData['scr_C'] = $this->data['profil_data']['scr_C'];
$solrData['scr_D'] = $this->data['profil_data']['scr_D'];
$solrData['loc_City'] = $this->input->post('plakano');
$solrData['loc_Lat_Lon'] = $this->input->post('loc_Lat_Lon');
$solrData['com_Category'] = explode(',', $this->input->post('category'));
$urunData = $this->input->post('urun_list');
foreach($urunData as $row)
{
$ontoData = $this->m_onto->getOntoDataByOntoDataId($row);
$solrData['com_Products'][] = $ontoData['baslik'];
}
$hizmetData = $this->input->post('hizmet_list');
foreach($hizmetData as $row)
{
$ontoData = $this->m_onto->getOntoDataByOntoDataId($row);
$solrData['com_Services'][] = $ontoData['baslik'];
}
$solrData['com_Type'] = $this->input->post('sirketturu');
$solrData['com_Description'] = $this->input->post('description');
$solrData['com_Title_Selected'] = $this->input->post('title');
$solrData['com_Title_Long'] = $this->data['profil_data']['com_Title_Long'];
$solrData['crm_Tel'] = $this->input->post('tel');
$solrData['crm_Fax'] = $this->input->post('fax');
$solrData['crm_Email'] = $this->input->post('email');
$this->solr->updateSolrProfilData($solrData);
And solr process:
public function updateSolrProfilData($arrData)
{
if(count($arrData) == 0)
return FALSE;
$solrClientOptions = $this->solrClientOptionsYazProfil;
$solrClientOptionsCommit = $this->solrClientOptionsYazProfilCommit;
$solrClient = new SolrClient($solrClientOptions);
$solrDoc = new SolrInputDocument();
foreach($arrData as $firmaField => $firmaValue)
{
if(! is_array($firmaValue))
{
$solrDoc->addField($firmaField, $firmaValue);
}
else
{
foreach($firmaValue as $firmaField2 => $firmaValue2)
{
if($firmaValue2 != '')
{
$solrDoc->addField($firmaField, $firmaValue2);
}
}
}
}
try {
$this->_solrCommit($solrClientOptionsCommit);
} catch (Exception $e) {
echo $e->getMessage();
}
}
Solr Commit function:
private function _solrCommit($solrArr)
{
$urlCommit = 'http://' . $solrArr['hostname'] . ":" . $solrArr['port'] . '/' . $solrArr['path'] . "/update?stream.body=%3Ccommit/%3E&wt=json";
$output = file_get_contents($urlCommit);
$outputArr = json_decode($output, TRUE);
if ($outputArr['responseHeader']['status'] === 0)
return TRUE;
else
return FALSE;
}
And that is the options:
private $solrClientOptionsYazProfilCommit = array(
'hostname' => SOLR_HOST_YAZ,
'login' => '',
'password' => '',
'port' => SOLR_PORT,
'path' => 'solr/collection1'
);
Altough try-catch returns no error, the data can not be updated. Moreover, code sends solr commit succesfully. I checked the url but it is in correct form. What is wrong in here?
Dont use PHP/Pecl solr libs. If you can access solr via a URL then you should just use PHP and CURL:
static function doCurl($url, $username = null, $password = null) {
if (!function_exists('curl_init')) {
// throw error
}
$ch = curl_init();
$opts = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_TIMEOUT => 120,
CURLOPT_FAILONERROR => 1,
CURLOPT_HTTPAUTH => CURLAUTH_ANY
);
if ($password != null && $username != null) {
$opts[CURLOPT_USERPWD] = "$username:$password";
}
curl_setopt_array($ch, $opts);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
usage is:
doCurl("http://hostNameHere:8983/solr/select/?q=solr&start=0&rows=10&indent=on", "user", "pass");
Your issue is that you are never issuing a command to Solr to add the document that you have built to your index. You are only issuing the commit command, which is executing successfully.
Since you are using PHP, I would recommend using the PHP SolrClient. This will save you from having to manually write all of the functions (add, delete, commit, etc.) yourself. In this case, you would need to call the addDocument function.