I'm getting users' profile pictures from another site. I want to create a folder for users who have a URL for the image. Because every user's profile picture must be in its own file. This is what I want to do. I'm running with custom artisan commands.
foreach ($adminUser as $user) {
$a= DB::table('users')->where('email', $user['email'])->first();
if($a) {
echo "\n ", $a->name, " this user already exists. \n";
continue;
} else {
$a = User::create($user);
echo "\n ", $user['name'], " created. \n";
if (isset($user['link']) && strlen($user['link']) > 0) {
$folder_Path = public_path().'/user_images/' . $a->id;
File::makeDirectory($folder_Path, $mode = 0777, true, true);
$contents = file_get_contents($user['link']);
$file_name = basename($user['link']);
Storage::disk('uploads')->put($file_name, $contents);
$this->info(" |--> Profile picture uploaded.");
}
}
Related
I want to get a copy of the logs file using programmability, I just tried to copy the files using this command
$co= Storage::copy('logs/laravel-'.$start.'.log',$filename);
dd($co);
but I have an error which says the file does not exist,
I believe that is because storage looking in the default driver of the config file, how can I tell laravel to look in logs folder when I want to run the copy command, is there any way to do that .
Hi You can get the path of the log file with storage_path() and copy your file anywhere you want with php copy function
I think that is a easy way that you can do it:
<?php
function copyLogFile($logFileName, $destination)
{
$logPathDir = storage_path().'/logs/';
$logFilePath = $logPathDir . $logFileName;
if (file_exists($logFilePath)) {
if( !#copy($logFilePath, $destination) ) {
echo "File can't be copied! \n";
$errors= error_get_last();
echo "COPY ERROR TYPE: ".$errors['type'].PHP_EOL;
echo "COPY ERROR MESSAGE: ".$errors['message'];
}
else {
echo "File has been copied! \n";
}
} else {
echo "The file $logFilePath does not exist";
}
}
// Store the path of destination file
$destination = '/home/azibom/Desktop/backup.log';
// Your log file name
$start = "2020-01-01";
$logFileName = 'laravel-'.$start.'.log';
copyLogFile($logFileName, $destination);
?>
I have a Laravel application working on different urls. example.ch and app.example.net are working will. On the same server like app.example.net i like to run app-stage.example.net.
The application return an error 500 without an error log.
$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);
var_dump($kernel); // returns an object. Everything ok
$response = $kernel->handle(
$request = Illuminate\Http\Request::capture()
);
var_dump($response) //returns error 500
I checked the php version.
I checked the fpm version.
I checked the .env file
I did "sudo chmod -R 777 bootstrap/cache storage"
I restarted the server.
I tried to show the errors.
error_reporting(-1); // reports all errors
ini_set("display_errors", "1"); // shows all errors
ini_set("log_errors", 1);
ini_set("error_log", "/tmp/php-error.log");
No success.
What can I do in addition to find the error?
use this package Dotenv
make a file like this
and then use multiple .env for example acceptnace.env . production.env , staging.env
make a file like environment.php in bootstrap directory like this
<?php
$envPath = realpath(dirname(__DIR__));
$env = get_current_user();
if ($env == 'staging') {
$envFile = ".staging.env";
} elseif ($env == "acceptance") {
$envFile = ".acceptance.env";
} elseif ($env == "development") {
$envFile = ".development.env";
} elseif ($env == "production") {
$envFile = ".production.env";
} elseif ($env == "beta") {
$envFile = ".beta.env";
} else {
$envFile = ".local.env";
}
Dotenv\Dotenv::create($envPath, $envFile)->load();
and this will load multiple env for your app
I am wondering if its possible to test ShouldBroadcast in Laravel?
My test will trigger the even that implements ShouldBroadcast, however, I've noticed that broadcasting didn't happen.
Of course, the broadcasting event is working in the app it self.
Has any one tried such test?
It's an old question, but just in case it can help someone : i did for myself an assert function that you should add to your TestCase.php.
The idea is to set the broadcast driver to "log" and then to read the 4th line from the end to see if it's a broadcast log.
In your phpunit.xml
Add the folowing line to the node:
<env name="BROADCAST_DRIVER" value="log"/>
In your TestCase.php file
Add the folowing function :
public function assertEventIsBroadcasted($eventClassName, $channel=""){
$logfileFullpath = storage_path("logs/laravel.log");
$logfile = explode("\n", file_get_contents($logfileFullpath));
if(count($logfile) > 4){
$supposedLastEventLogged = $logfile[count($logfile)-5];
$this->assertContains("Broadcasting [", $supposedLastEventLogged, "No broadcast were found.\n");
$this->assertContains("Broadcasting [".$eventClassName."]", $supposedLastEventLogged, "A broadcast was found, but not for the classname '".$eventClassName."'.\n");
if($channel != "")
$this->assertContains("Broadcasting [".$eventClassName."] on channels [".$channel."]", $supposedLastEventLogged, "The expected broadcast (".$eventClassName.") event was found, but not on the expected channel '".$channel."'.\n");
}else{
$this->fail("No informations found in the file log '".$logfileFullpath."'.");
}
}
Instead of checking what's written in log, you can to use the assertion 'expectsEvents', which you can test if a certain event is launched.
public function testMethod(){
$this->expectsEvents(YourEventClass::class)
...your code test...
}
For more info:
https://laravel-guide.readthedocs.io/en/latest/mocking/
with Adrienc solutions with dynamically getting index of last event
private function getIndexOfLoggedEvent(array $logfile)
{
for ($i = count($logfile) - 1; $i >=0 ; $i--) {
if (strpos($logfile[$i], 'Broadcasting [Illuminate\Notifications\Events\BroadcastNotificationCreated]') !== false) {
return $i;
}
}
}
which will give you index of the line of last broadcast
I took both previous answers, and put them together.
This works with laravel 5.7.
In your TestCase.php file:
public function assertEventIsBroadcasted($eventClassName, $channel = '')
{
$date = Carbon::now()->format('Y-m-d');
$logfileFullpath = storage_path("logs/laravel-{$date}.log");
$logfile = explode("\n", file_get_contents($logfileFullpath));
$indexOfLoggedEvent = $this->getIndexOfLoggedEvent($logfile);
if ($indexOfLoggedEvent) {
$supposedLastEventLogged = $logfile[$indexOfLoggedEvent];
$this->assertContains('Broadcasting [', $supposedLastEventLogged, "No broadcast were found.\n");
$this->assertContains(
'Broadcasting [' . $eventClassName . ']',
$supposedLastEventLogged,
"A broadcast was found, but not for the classname '" . $eventClassName . "'.\n"
);
if ($channel != '') {
$this->assertContains(
'Broadcasting [' . $eventClassName . '] on channels [' . $channel . ']',
$supposedLastEventLogged,
'The expected broadcast (' . $eventClassName . ") event was found, but not on the expected channel '" . $channel . "'.\n"
);
}
} else {
$this->fail("No informations found in the file log '" . $logfileFullpath . "'.");
}
}
private function getIndexOfLoggedEvent(array $logfile)
{
for ($i = count($logfile) - 1; $i >= 0; $i--) {
if (strpos($logfile[$i], 'local.INFO: Broadcasting') !== false) {
return $i;
}
}
return false;
}
A test could look like this:
/**
* #test
*/
public function notifications_are_broadcasted()
{
$notification = factory(Notification::class)->create();
broadcast(new NewNotification($notification));
$this->assertEventIsBroadcasted(
NewNotificationEvent::class,
'private-notification.' . $notification->id
);
}
This is a Magento issue - using the Enterprise edition. Unfortunately their support technicians are all in San Francisco, and I am based in the UK, so their support to me is restricted to a certain time window.
I have categories which are active, set to display products, and/or products and static blocks, and are sub categories of the default root category.
I also have test products, which are enabled, in stock, with quantities, visible in Catalog, Search, and are assigned to these sub categories.
The problem is, my test products (or any product!) do not show on the category page. I am using the default/default themes, and have not changed the page_layout.
I have cleared/flushed all caches, and reindexed.
However, most of my indexes appear as status 'SCHEDULED' and have never been updated - there are no checkboxes next to these, so I cannot select them to 'reindex data'.
See the screenshot.
If anyone has any clues on how to fix this, I will be very happy.
Thanks
Reindex is somewhat required to display products on front, especially if you have flat tables enabled (Admin Panel > System > Configuration > Catalog > Frontend: "Use Flat Catalog Category" and "Use Flat Catalog Product").
The situation with indexes is a bit of strange. It you do it on your local workstation or you have access to shell on hosting you can manually force indexes by running this command:
pwd$ php shell/indexer.php reindexall
If you have enabled flat tables you can try to disable them, to check if products will be visible on front.
You need to also put right permissions on var and media folders and theirs content. 755 should be ok.
Problem solved. Thanks guys for your answers but it was none of the above.
I had installed a Product Feature module incorrectly. I was under the assumption that when developing in app/code/local/... anything that didn't work would fall back to app/code/core/...
Sadly this was not the case. My fault, and everyone knows the phrase about making assumptions.
Magento has a very steep learning curve!
Thats really interesting, I had a similar issue recently where a reindex was not fully working. However I didnt get scheduled being displayed.
Can I ask what version of Enterprise are you using ?
As Ventus suggested a tried and tested method of forcing a reindex is to use the shell script, To do this you need to SSH into your server. Then use the cd command ( change directory ) to where your website is located on the file system. E.g. cd /var/www/....
From here run php shell/indexer.php reindexall
Set cron to run this will take care of reindexing provided you have not changed crontab values.
From your screen it looks like you have never run a cron on this setup.
Put this code below into a .php file in your magento install and then run it from your URL, this will clean and re-index everything. You can run it from a cron job. Any errors then you have a problem with yor database in witch case you should back it up and then re-creat it in a new DB instance.
<?php
set_time_limit(0);
require_once dirname(__FILE__) . '/app/Mage.php';
//get all stores
$websites = Mage::app()->getWebsites();
$thisstore = $websites[1]->getDefaultStore()->getCode();
echo "Store: ".$thisstore."<br/>";
//clean var dir
$dirs = array(
'downloader/.cache/*',
'var/cache/',
'var/locks/',
'var/log/',
'var/report/',
'var/minifycache/',
'var/mincache/',
'var/tmp/'
);
foreach($dirs as $v => $k) {
exec('rm -rf '.$k);
}
/*
//clean out sessions
$dirs = array('var/session/');
foreach($dirs as $v => $k) {
exec('rm -rf '.$k);
}
*/
//clean db log files
$xml = simplexml_load_file('./app/etc/local.xml', NULL, LIBXML_NOCDATA);
$db['host'] = $xml->global->resources->default_setup->connection->host;
$db['name'] = $xml->global->resources->default_setup->connection->dbname;
$db['user'] = $xml->global->resources->default_setup->connection->username;
$db['pass'] = $xml->global->resources->default_setup->connection->password;
$db['pref'] = $xml->global->resources->db->table_prefix;
global $db;
$tables = array(
'catalogsearch_fulltext',
'dataflow_batch_export',
'dataflow_batch_import',
'log_customer',
'log_quote',
'log_summary',
'log_summary_type',
'log_url',
'log_url_info',
'log_visitor',
'log_visitor_info',
'log_visitor_online',
'importexport_importdata',
'core_url_rewrite',
'report_viewed_product_index',
'report_event',
'core_cache',
'core_cache_option',
'core_cache_tag'
);
mysql_connect($db['host'], $db['user'], $db['pass']) or die(mysql_error());
mysql_select_db($db['name']) or die(mysql_error());
foreach($tables as $v => $k) {
mysql_query('SET FOREIGN_KEY_CHECKS=0; '.'TRUNCATE `'.$db['pref'].$k.'`;'.' SET FOREIGN_KEY_CHECKS=1; ') or die(mysql_error());
}
///---------------------------------//
// now run standard magento cleanup file
## Function to set file permissions to 0644 and folder permissions to 0755
function AllDirChmod( $dir = "./", $dirModes = 0755, $fileModes = 0644 ){
$d = new RecursiveDirectoryIterator( $dir );
foreach( new RecursiveIteratorIterator( $d, 1 ) as $path ){
if( $path->isDir() ) chmod( $path, $dirModes );
else if( is_file( $path ) ) chmod( $path, $fileModes );
}
}
## Function to clean out the contents of specified directory
function cleandir($dir) {
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if ($file != '.' && $file != '..' && is_file($dir.'/'.$file)) {
if (unlink($dir.'/'.$file)) { }
else { echo $dir . '/' . $file . ' (file) NOT deleted!<br />'; }
}
else if ($file != '.' && $file != '..' && is_dir($dir.'/'.$file)) {
cleandir($dir.'/'.$file);
if (rmdir($dir.'/'.$file)) { }
else { echo $dir . '/' . $file . ' (directory) NOT deleted!<br />'; }
}
}
closedir($handle);
}
}
function isDirEmpty($dir){
return (($files = #scandir($dir)) && count($files) <= 2);
}
// rebuild everything!!!
$processes = Mage::getSingleton('index/indexer')->getProcessesCollection();
$processes->walk('setMode', array(Mage_Index_Model_Process::MODE_REAL_TIME));
$processes->walk('save');
$processes->walk('reindexAll');
$processes->walk('reindexEverything');
echo "----------------------- CLEANUP START -------------------------<br/>";
$start = (float) array_sum(explode(' ',microtime()));
echo "<br/>*************** SETTING PERMISSIONS ***************<br/>";
echo "Setting all folder permissions to 755<br/>";
echo "Setting all file permissions to 644<br/>";
AllDirChmod( "." );
echo "Setting pear permissions to 550<br/>";
echo "<br/>****************** CLEARING CACHE ******************<br/>";
if (file_exists("var/cache")) {
echo "Clearing var/cache<br/>";
cleandir("var/cache");
}
if (file_exists("var/session")) {
echo "Clearing var/session<br/>";
cleandir("var/session");
}
if (file_exists("var/minifycache")) {
echo "Clearing var/minifycache<br/>";
cleandir("var/minifycache");
}
if (file_exists("downloader/pearlib/cache")) {
echo "Clearing downloader/pearlib/cache<br/>";
cleandir("downloader/pearlib/cache");
}
if (file_exists("downloader/pearlib/download")) {
echo "Clearing downloader/pearlib/download<br/>";
cleandir("downloader/pearlib/download");
}
if (file_exists("downloader/pearlib/pear.ini")) {
echo "Removing downloader/pearlib/pear.ini<br/>";
unlink ("downloader/pearlib/pear.ini");
}
if (file_exists("media/catalog/product/cache/")) {
echo "Removing media/catalog/product/cache/<br/>";
unlink ("media/catalog/product/cache/");
}
if (file_exists("media/tmp/")) {
echo "Removing media/tmp/<br/>";
unlink ("media/tmp/");
}
date_default_timezone_set("Europe/London");
echo "Start Cleaning all caches at ... " . date("Y-m-d H:i:s") . "<br/>";
ini_set("display_errors", 1);
Mage::app('admin')->setUseSessionInUrl(false);
Mage::getConfig()->init();
$types = Mage::app()->getCacheInstance()->getTypes();
try {
echo "Cleaning data cache... <br/>";
flush();
foreach ($types as $type => $data) {
echo "Removing $type ... ";
echo Mage::app()->getCacheInstance()->clean($data["tags"]) ? "[OK]" : "[ERROR]";
echo "<br/>";
}
} catch (exception $e) {
die("[ERROR:" . $e->getMessage() . "]");
}
echo "<br/>";
try {
echo "Cleaning stored cache... ";
flush();
echo Mage::app()->getCacheInstance()->clean() ? "[OK]" : "[ERROR]";
echo "<br/>";
} catch (exception $e) {
die("[ERROR:" . $e->getMessage() . "]");
}
try {
echo "Cleaning merged JS/CSS...";
flush();
Mage::getModel('core/design_package')->cleanMergedJsCss();
Mage::dispatchEvent('clean_media_cache_after');
echo "[OK]<br/>";
} catch (Exception $e) {
die("[ERROR:" . $e->getMessage() . "]");
}
try {
echo "Cleaning image cache... ";
flush();
echo Mage::getModel('catalog/product_image')->clearCache();
echo "[OK]<br/>";
} catch (exception $e) {
die("[ERROR:" . $e->getMessage() . "]");
}
echo "<br/>************** CHECKING FOR EXTENSIONS ***********<br/>";
If (!isDirEmpty("app/code/local/")) {
echo "-= WARNING =- Overrides or extensions exist in the app/code/local folder<br/>";
}
If (!isDirEmpty("app/code/community/")) {
echo "-= WARNING =- Overrides or extensions exist in the app/code/community folder<br/>";
}
$end = (float) array_sum(explode(' ',microtime()));
echo "<br/>------------------- CLEANUP COMPLETED in:". sprintf("%.4f", ($end-$start))." seconds ------------------<br/>";
//sitemap refresh
$collection = Mage::getModel('sitemap/sitemap')->getCollection();
foreach ($collection as $sitemap) {
try {
$sitemap->generateXml();
}
catch (Exception $e) {
$errors[] = $e->getMessage();
}
}
?>
i receive an CSV File from the User and I want to insert it into the Database. I want to use the Form Validation:
$pf = new ProductForm();
$old_memory_usage = 0;
while($data = $csvreader->read())
{
$mem = memory_get_usage() / 1024;
echo "Memory-Usage: " . $mem . " KB; Mem-Diff: " . $mem - $old_memory_usage . "\n";
$old_memory_usage = $mem;
$p = new Product();
$p->fromArray($data);
$pf->bind($p->toArray(), array());
if($pf->isValid())
{
$p->save();
}
else
{
//display error message to the user
}
}
This works fine when isValid() returns true. The Memory Difference is 0 KB. But if there is an Error in the "form" the memory-difference is 6-7 KB. So I get an allowed_memory error when the CSV-File is very huge.
I tryed to free the form like:
unset($pf)
$pf = null;
$pf = new ProductForm();
no success. It is just worse!
ans ideas?
thx!
You can disable doctrine profiler in your databse yml:
dev:
doctrine:
class: sfDoctrineDatabase
param:
profiler: false