How Can I Write Logs Directly to AWS S3 in Nodejs?

 Here is the code in which you can directly work with AWS S3 Logs.

// need to install "npm install aws-sdk" first if not exist
const AWS = require('aws-sdk')
const s3 = new AWS.S3({
    // your S3 accessKeyId and your S3 secretAccessKey
    accessKeyId: process.env.ACCESS_KEY_ID.trim(),
    secretAccessKey: process.env.SECRET_ACCESS_KEY.trim()
})
// params for getting the log file from s3
var getParams = {
    // your S3 bucket name and your S3 filename Key/path
    Bucket: process.env.BUCKET.trim(),
    Key: fileNameKey
};
// get file data from s3
await s3.getObject(getParams, function(err, data) {
    // Handle any error and exit. if 404 then skip. it will create new below.
    if (err && err.statusCode !== 404) {
        return console.log(err);
    }
   
    // create content
    let content = ''
    // if file exist and no err then prepend the data in the new content
    if (!err || (err && err.statusCode !== 404)) {
        // Use the encoding necessary
        let objectData = data.Body.toString('utf-8');
        content += objectData
    }
    var date = new Date()
    content += '['+ date +'] - your text for the logs';
    content += "\n\n"; // will leave 2 line breaks at the last

    // s3 upload file params
    const params = {
    Bucket: process.env.BUCKET.trim(), // your S3 bucket name
    Key: fileNameKey, // your S3 filename Key/path
    Body: content
    }
    s3.upload(params, (err2, data) => {
    if (err2) {
        return console.log(err2)
    }
    return console.log(err2);
    })
    return console.log(err);
});

Site improvement code.. have to put in htaccess

<IfModule mod_deflate.c>
  # Compress HTML, CSS, JavaScript, Text, XML and fonts
  AddOutputFilterByType DEFLATE application/javascript
  AddOutputFilterByType DEFLATE application/rss+xml
  AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
  AddOutputFilterByType DEFLATE application/x-font
  AddOutputFilterByType DEFLATE application/x-font-opentype
  AddOutputFilterByType DEFLATE application/x-font-otf
  AddOutputFilterByType DEFLATE application/x-font-truetype
  AddOutputFilterByType DEFLATE application/x-font-ttf
  AddOutputFilterByType DEFLATE application/x-javascript
  AddOutputFilterByType DEFLATE application/xhtml+xml
  AddOutputFilterByType DEFLATE application/xml
  AddOutputFilterByType DEFLATE font/opentype
  AddOutputFilterByType DEFLATE font/otf
  AddOutputFilterByType DEFLATE font/ttf
  AddOutputFilterByType DEFLATE image/svg+xml
  AddOutputFilterByType DEFLATE image/x-icon
  AddOutputFilterByType DEFLATE text/css
  AddOutputFilterByType DEFLATE text/html
  AddOutputFilterByType DEFLATE text/javascript
  AddOutputFilterByType DEFLATE text/plain
  AddOutputFilterByType DEFLATE text/xml

  # Remove browser bugs (only needed for really old browsers)
  BrowserMatch ^Mozilla/4 gzip-only-text/html
  BrowserMatch ^Mozilla/4\.0[678] no-gzip
  BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
  Header append Vary User-Agent
</IfModule>
<IfModule mod_expires.c>
    # Enable expirations
    ExpiresActive On
    # Default directive
    ExpiresDefault "access plus 1 month"
    # My favicon
    ExpiresByType image/x-icon "access plus 1 year"
    # Images
    ExpiresByType image/gif "access plus 1 month"
    ExpiresByType image/png "access plus 1 month"
    ExpiresByType image/jpg "access plus 1 month"
    ExpiresByType image/jpeg "access plus 1 month"
    # CSS
    ExpiresByType text/css "access plus 1 month"
    # Javascript
    ExpiresByType application/javascript "access plus 1 year"
    </IfModule>
    # php -- BEGIN cPanel-generated handler, do not edit
    # Set the “ea-php71” package as the default “PHP” programming language.
    <IfModule mime_module>
      AddType application/x-httpd-ea-php71 .php .php7 .phtml
    </IfModule>
# php -- END cPanel-generated handler, do not edit
# BEGIN Cache-Control Headers
<ifModule mod_headers.c>
  <filesMatch "\.(ico|jpe?g|png|gif|swf)$">
    Header set Cache-Control "public"
  </filesMatch>
  <filesMatch "\.(css)$">
    Header set Cache-Control "public"
  </filesMatch>
  <filesMatch "\.(js)$">
    Header set Cache-Control "private"
  </filesMatch>
  <filesMatch "\.(x?html?|php)$">
    Header set Cache-Control "private, must-revalidate"
  </filesMatch>
</ifModule>
# END Cache-Control Headers

set cookie value in javascript and displaying it with php

Set in javascript

document.cookie='fcookie='+tempo; 

Get in PHP

if (isset($_COOKIE["fcookie"])) 
echo $_COOKIE["fcookie"]; 
else 
echo "Cookie Not Set";

Change url parameters using javascript

var newUrl = your url
history.pushState({}, null, newUrl);

how to use in_array in smarty

in_array in smarty


{if $variable|in_array:[14, 15, 18]}

... Your code

{/if}


Or


in_array in smarty


{if $variable|in_array:$array}

... Your code

{/if}




Convert PDF to Text in PHP

<?php function pdf2string($sourcefile) { $fp = fopen($sourcefile, 'rb'); $content = fread($fp, filesize($sourcefile)); fclose($fp); $searchstart = 'stream'; $searchend = 'endstream'; $pdfText = ''; $pos = 0; $pos2 = 0; $startpos = 0; while ($pos !== false && $pos2 !== false) { $pos = strpos($content, $searchstart, $startpos); $pos2 = strpos($content, $searchend, $startpos + 1); if ($pos !== false && $pos2 !== false){ if ($content[$pos] == 0x0d && $content[$pos + 1] == 0x0a) { $pos += 2; } else if ($content[$pos] == 0x0a) { $pos++; } if ($content[$pos2 - 2] == 0x0d && $content[$pos2 - 1] == 0x0a) { $pos2 -= 2; } else if ($content[$pos2 - 1] == 0x0a) { $pos2--; } $textsection = substr( $content, $pos + strlen($searchstart) + 2, $pos2 - $pos - strlen($searchstart) - 1 ); $data = @gzuncompress($textsection); $pdfText .= pdfExtractText($data); $startpos = $pos2 + strlen($searchend) - 1; } } return preg_replace('/(\\s)+/', ' ', $pdfText); } function pdfExtractText($psData){ if (!is_string($psData)) { return ''; } $text = ''; // Handle brackets in the text stream that could be mistaken for // the end of a text field. I'm sure you can do this as part of the // regular expression, but my skills aren't good enough yet. $psData = str_replace('\\)', '##ENDBRACKET##', $psData); $psData = str_replace('\\]', '##ENDSBRACKET##', $psData); preg_match_all( '/(T[wdcm*])[\\s]*(\\[([^\\]]*)\\]|\\(([^\\)]*)\\))[\\s]*Tj/si', $psData, $matches ); for ($i = 0; $i < sizeof($matches[0]); $i++) { if ($matches[3][$i] != '') { // Run another match over the contents. preg_match_all('/\\(([^)]*)\\)/si', $matches[3][$i], $subMatches); foreach ($subMatches[1] as $subMatch) { $text .= $subMatch; } } else if ($matches[4][$i] != '') { $text .= ($matches[1][$i] == 'Tc' ? '' : '') . $matches[4][$i]; } } // Translate special characters and put back brackets. $trans = array( '...' => '…', '\\205' => '…', '\\221' => chr(145), '\\222' => chr(146), '\\223' => chr(147), '\\224' => chr(148), '\\226' => '-', '\\267' => '•', '\\(' => '(', '\\[' => '[', '##ENDBRACKET##' => ')', '##ENDSBRACKET##' => ']', chr(133) => '-', chr(141) => chr(147), chr(142) => chr(148), chr(143) => chr(145), chr(144) => chr(146), ); $text = strtr($text, $trans); return $text; } $sourcefile = '16.pdf'; $get = pdf2string($sourcefile); echo utf8_encode($get);

php curl request

function makeCURLRequest($url, $method="GET", $params = "") {
        if ($method == "GET" && strpos($url, '?')) {
            $urlParams = substr($url, strpos($url, '?')+1);
            $url = substr($url, 0, strpos($url, '?'));
            if (is_array($params)) {
                parse_str($urlParams, $urlParamsArray);
                $params = $urlParamsArray + $params;
            } else {
                $params = $urlParams.'&'.$params;
            }
        }
        if (is_array($params)) {
            $params = http_build_query($params,'','&');
        }
        $curl = curl_init($url . ($method == "GET" && $params != "" ? "?" . $params : ""));
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE);
        curl_setopt($curl, CURLOPT_HEADER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_HTTPGET, ($method == "GET"));
        curl_setopt($curl, CURLOPT_POST, ($method == "POST"));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 2);
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        if ($method == "POST") {
            curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
        }
       
        $response = curl_exec($curl);
        return $response;
    }

Magento 2 basic command


1) clear cache  :  php bin/magento cache:flush

2) reindex :  php bin/magento indexer:reindex

3) cmd to deploy static data  :  php bin/magento setup:static-content:deploy  en_US en_AU

4) show which mode is active developer or production

         php bin/magento deploy:mode:show

        set developer mode :  php bin/magento deploy:mode:set developer
        set production mode :php bin/magento deploy:mode:set production

5) check module status
     php bin/magento module:status

6) Enable module
       php bin/magento module:enable Your_modulename --clear-static-content
       eg. php bin/magento module:enable Rain_Affiliate --clear-static-content

7) Dissable module
      php bin/magento module:disable Magento_Weee

8 ) After install module  you have to run this 2  command
        php bin/magento setup:upgrade
        php bin/magento setup:di:compile

magento 2 regenerate product url php code

please follow the step as i show below

1) backup you database 

2) create one controller name Producturl.php

3) copy my code into that controller 


<?php  

namespace Company\Module\Controller\Producturl;


use Magento\CatalogUrlRewrite\Model\ProductUrlRewriteGenerator;
use Magento\UrlRewrite\Service\V1\Data\UrlRewrite;
use Magento\Store\Model\Store;

class Producturl extends \Magento\Framework\App\Action\Action
{
       public function execute()
    { 
           //// for regenerate product url /////////////////
             $objectManager = \Magento\Framework\App\ObjectManager::getInstance();   
             $this->collection = $objectManager->create('\Magento\Catalog\Model\ResourceModel\Product\Collection');

             $this->productUrlRewriteGenerator = $objectManager->create('\Magento\CatalogUrlRewrite\Model\ProductUrlRewriteGenerator');
             
             $this->urlPersist = $objectManager->create('\Magento\UrlRewrite\Model\UrlPersistInterface');

             $this->collection->addAttributeToSelect(['url_path', 'url_key']);
              $list = $this->collection->load();
              $store_id=1; // your store id 
              
              foreach($list as $product) {                
                      if($store_id === Store::DEFAULT_STORE_ID)
                          $product->setStoreId($store_id);
                      $this->urlPersist->deleteByData([
                          UrlRewrite::ENTITY_ID => $product->getId(),
                          UrlRewrite::ENTITY_TYPE => ProductUrlRewriteGenerator::ENTITY_TYPE,
                          UrlRewrite::REDIRECT_TYPE => 0,
                          UrlRewrite::STORE_ID => $store_id
                      ]);
                      try {
                          $this->urlPersist->replace(
                              $this->productUrlRewriteGenerator->generate($product)
                          );
                      } catch(\Exception $e) {
                          $out->writeln('<error>Duplicated url for '. $product->getId() .'</error>');
                      }
              }
    }


}


?>

make url short php

This code is for make you url short through google API


<?php

// Declare the class
class GoogleUrlApi {

public $key=your key
// Constructor
function GoogleURLAPI($apiURL = 'https://www.googleapis.com/urlshortener/v1/url') {
// Keep the API Url

$this->apiURL = $apiURL.'?key='.$this->key;
}

// Shorten a URL
function shorten($url) {
// Send information along
$response = $this->send($url);
// Return the result
return isset($response['id']) ? $response['id'] : false;
}

// Expand a URL
function expand($url) {
// Send information along
$response = $this->send($url,false);
// Return the result
return isset($response['longUrl']) ? $response['longUrl'] : false;
}

// Send information to Google
function send($url,$shorten = true) {
// Create cURL
$ch = curl_init();
// If we're shortening a URL...
if($shorten) {
curl_setopt($ch,CURLOPT_URL,$this->apiURL);
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode(array("longUrl"=>$url)));
curl_setopt($ch,CURLOPT_HTTPHEADER,array("Content-Type: application/json"));
}
else {
curl_setopt($ch,CURLOPT_URL,$this->apiURL.'&shortUrl='.$url);
}
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
// Execute the post
$result = curl_exec($ch);
// Close the connection
curl_close($ch);
// Return the result
return json_decode($result,true);
}
}



// Create instance with key
$key = 'AIzaSyDUtkDIQ6uK7GCE68Lji_eQE9lPlo3Lk5Q';
$googer = new GoogleURLAPI();

// Test: Shorten a URL
$shortDWName = $googer->shorten("http://americanentrepreneurship.com/nj/entrepreneurs-featured/university-entrepreneurial-activities-draw-alumni-involvement");
echo $shortDWName; // returns http://goo.gl/i002
echo "<br>";
// Test: Expand a URL
$longDWName = $googer->expand($shortDWName);
echo $longDWName; // returns https://davidwalsh.name


?>

Create virtual host in local pc for you website in ubuntu

Create virtual host in local  pc for you website in ubuntu

1) open you terminal with sudo su

2) cd /etc/apache2/sites-available/   paste this into your terminal .

3) sudo cp 000-default.conf example1.com.conf

4) go to folder  /etc/apache2/sites-available/ and open file example1.com.conf into any editor  you want

5) than  paste below code

<VirtualHost *:80>
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html/example1/
ServerName example1.dev
ServerAlias www.example1.dev
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
6) save the file asked for password enter your root password .


7) open your terminal and run sudo a2ensite example1.com.conf


8) sudo systemctl restart apache2

or

sudo service apache2 restart

9) open file /etc/hosts
 
  enter this 2 line

   192.168.1.30 example1.dev
   192.168.1.30 www.example1.dev
   #Note: 192.168.1.30 is my pc ip so you write your ip 

Add new product image in PrestaShop by core development

// add product image...
if(count($_FILES['files']['tmp_name']) > 1){
for($i=0;$i < count($_FILES['files']['tmp_name']);$i++ ){
      $image = new Image();
      $url = $_FILES['files']['tmp_name'][$i];
     $shops = Shop::getShops(true, null, true);
$image->id_product = $id_product;
$image->position = Image::getHighestPosition($id_product) +1 ;
if($i==0){
$image->cover = true; // or false;
} else {
$image->cover = false; // or false;
}
if (($image->validateFields(false, true)) === true &&($image->validateFieldsLang(false, true)) === true && $image->add()) {
$image->associateTo($shops);
if (!$this->copyImg($id_product, $image->id, $url)){
$image->delete();
}
//$combination = new Combination((int)$idProductAttribute);
//$combination->setImages($image->id);
}
}
} else {
$image = new Image();
$url = $_FILES['files']['tmp_name'][0];
$shops = Shop::getShops(true, null, true);
$image->id_product = $id_product;
$image->position = Image::getHighestPosition($id_product) + 1;
$image->cover = true; // or false;
if (($image->validateFields(false, true)) === true &&($image->validateFieldsLang(false, true)) === true && $image->add()) {
$image->associateTo($shops);
if(!$this->copyImg($id_product, $image->id, $url)){
$image->delete();
}
//$combination = new Combination((int)$idProductAttribute);
//$combination->setImages($image->id);
}
}
// add product image...

Add new product combination in PrestaShop by core development

$attributes=array();

$attribute is a all attribute id wich you selected at the time of product add.
$p is product id
if(count(Tools::getValue('attribute'))){
$attributes=Tools::getValue('attribute');
$i=0;
$combinationAttributes = [];
foreach ($attributes as $key => $value) {
if($value==0) continue;
$combinationAttributes[] = $value;
}
if(!empty($combinationAttributes) && !$p->productAttributeExists($combinationAttributes)){
$price =0;
$weight = 0;
$ecotax = 7;
$unit_price_impact = 0;
$quantity = 1;
$reference = "";
$supplier_reference = "";
$ean13 = "";
$default = true;
$idProductAttribute = $p->addProductAttribute(
(float)$price,
(float)$weight,
$unit_price_impact,
(float)$ecotax,
(int)$quantity,
"",
strval($reference),
strval($supplier_reference),
strval($ean13),
$default,
NULL,
NULL,
1,
"");
$p->addAttributeCombinaison($idProductAttribute, $combinationAttributes);
}
}

Add new product in PrestaShop by core development

hello the below code is to add new product in PrestaShop



                                $p = new Product;
$p->name = Tools::getValue('name');
$p->id_category_default = Tools::getValue('category');
$p->indexed = 1;
$p->active = Tools::getValue('active');
$p->redirect_type = '404';
$p->visibility = 'both';
$p->id_supplier = 0;
$p->reference = strtolower(Tools::getValue('name'));
// $p->link_rewrite = array(
// 1 => strtolower(Tools::getValue('name')),
// 2 => strtolower(Tools::getValue('name')),
// ); // link rewrite must be array with every uses languages
//$product->minimal_quantity = 1;
//$product->show_price = 1;
$p->link_rewrite = array((int)(Configuration::get('PS_LANG_DEFAULT')) => Tools::link_rewrite(Tools::getValue('name')));
$p->quantity = 1;
$p->price = Tools::getValue('price');
$p->description = Tools::getValue('Description');
$p->description_short = Tools::getValue('summary');
$p->id_sponser = $this->context->customer->id;
$p->date_add = date('Y-m-d H:i:s');
$p->date_upd = date('Y-m-d H:i:s');
$p->add();
$p->addToCategories(2,Tools::getValue('category'));

WooCommerce Sample plugin is adding full price when using custom option

Is your WooCommerce Sample e is adding full price of your product rathan than custome sample price than this is the solution for it


just copy and paste this code into the respective file

/wp-content/plugins/woocommerce-sample/woocommerce-sample.php

1)  add this code in init() function
//custome RI code start
add_action( 'woocommerce_before_calculate_totals','cp_add_custom_price', 10, 2);
function cp_add_custom_price( $cart_obj ) {
// This is necessary for WC 3.0+
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;

foreach ( $cart_obj->get_cart() as $key => $value ) {
if($value['sample']){
$product_id = $value['product_id'];
$sample_price_mode = get_post_meta($product_id, 'sample_price_mode', true) ? get_post_meta($product_id, 'sample_price_mode', true) : 'default';
$sample_price = get_post_meta($product_id, 'sample_price', true) ? get_post_meta($product_id, 'sample_price', true) : 0;
if ($sample_price_mode === 'custom'){
$price = $sample_price;
}else if ($sample_price_mode === 'free'){
$price = 0;
}else{
$price = $value['data']->price;
}
$value['data']->set_price( $price );


}

}
}
//custome RI code start

2) Add this code inside the foreach loop of mini-cart file
    note: $product_id variable is before this code ,
     $_product   variable is after this code



/wp-content/plugins/woocommerce/templates/cart/mini-cart.php

//custome RI code start
$product_id   = apply_filters( 'woocommerce_cart_item_product_id', $cart_item['product_id'], $cart_item, $cart_item_key );

if($cart_item['sample']){
$sample_price_mode = get_post_meta($product_id, 'sample_price_mode', true) ? get_post_meta($product_id, 'sample_price_mode', true) : 'default';
$sample_price = get_post_meta($product_id, 'sample_price', true) ? get_post_meta($product_id, 'sample_price', true) : 0;
if ($sample_price_mode === 'custom'){
$price = $sample_price;
}else if ($sample_price_mode === 'free'){
$price = 0;
}
$cart_item['data']->set_price( $price );
//$product_price=apply_filters( 'woocommerce_cart_item_price',$price, $cart_item, $cart_item_key );
}

$_product     = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key );
//custome RI code start

How to install Sphinx Search in Ubuntu 16.04

~~~~~~~~~~~~~~Step 1 — Installing Sphinx~~~~~~~~~~~~~~~~~~

Installing Sphinx on Ubuntu is easy because it's in the native package repository. Install it using apt-get.

    sudo apt-get install sphinxsearch

~~~~~~~~~~~~~~~~Step 2 – Creating the Test Database~~~~~~~~~~~~~~~

Next, we'll set up a database using the sample data in the SQL file provided with the package. This will allow us to test that Sphinx search is working later.

Let's import the sample SQL file into the database. First, log in to the MySQL server shell.

    mysql -u root -p
Enter the password for the MySQL root user when asked. Your prompt will change to mysql>.

Create a dummy database. Here, we're calling it test, but you can name it whatever you want.

    CREATE DATABASE test;

Import the example SQL file.

    SOURCE /etc/sphinxsearch/example.sql;

Then leave the MySQL shell.

    quit

~~~~~~~~~~~~~~~~~~~~~Step 3 – Configuring Sphinx~~~~~~~~~~~~~~~~~~

First, create the sphinx.conf file.

    sudo nano /etc/sphinxsearch/sphinx.conf

Each of these index, searchd, and source blocks are described below. Then, at the end of this step, the entirety of sphinx.conf is included for you to copy and paste into the file.

The source block contains the type of source, username and password to the MySQL server. The first column of the sql_query should be a unique id. The SQL query will run on every index and dump the data to Sphinx index file. Below are the descriptions of each field and the source block itself.

    type: Type of data source to index. In our example, this is mysql. Other supported types include pgsql, mssql, xmlpipe2, odbc, and more.
    sql_host: Hostname for the MySQL host. In our example, this is localhost. This can be a domain or IP address.
    sql_user: Username for the MySQL login. In our example, this is root.
    sql_pass: Password for the MySQL user. In our example, this is the root MySQL user's password.
    sql_db: Name of the database that stores data. In our example, this is test.
    sql_query: The query thats dumps data from the database to the index.

            // full conf file sample given. You have to change all things as your requirment i.e. source name, host,user,pass,db table name etc...
            {
            source src1
              type          = mysql

              sql_host      = localhost
              sql_user      = root                      //////////////////// database username
              sql_pass      = your_root_mysql_password  //////////////////// password
              sql_db        = test                         //////////////////// database name
              sql_port      = 3306

              sql_query     = \
              SELECT id, group_id, UNIX_TIMESTAMP(date_added) AS date_added, title, content \
              FROM documents

              sql_attr_uint         = group_id
              sql_attr_timestamp    = date_added
            }
            index test1
            {
              source            = src1                                    /////////same as above source
              path              = /var/lib/sphinxsearch/data/test1        ////////// test1 is indexname. change as your requirement
              docinfo           = extern
            }
            searchd
            {
              listen            = 9306:mysql41
              log               = /var/log/sphinxsearch/searchd.log
              query_log         = /var/log/sphinxsearch/query.log
              read_timeout      = 5
              max_children      = 30
              pid_file          = /var/run/sphinxsearch/searchd.pid
              seamless_rotate   = 1
              preopen_indexes   = 1
              unlink_old        = 1
              binlog_path       = /var/lib/sphinxsearch/data
            }




~~~~~~~~~~~~~~~~~Step 4 — Managing the Index~~~~~~~~~~~~~~

In this step, we'll add data to the Sphinx index and make sure the index stays up to date using cron.

First, add data to the index using the configuration we created earlier.

    sudo indexer --all

    You should get something that looks like the following.

        Output
        Sphinx 2.2.9-id64-release (rel22-r5006)
        Copyright (c) 2001-2015, Andrew Aksyonoff
        Copyright (c) 2008-2015, Sphinx Technologies Inc (http://sphinxsearch.com)

        using config file '/etc/sphinxsearch/sphinx.conf'...
        indexing index 'test1'...
        collected 4 docs, 0.0 MB
        sorted 0.0 Mhits, 100.0% done
        total 4 docs, 193 bytes
        total 0.010 sec, 18552 bytes/sec, 384.50 docs/sec
        total 4 reads, 0.000 sec, 0.1 kb/call avg, 0.0 msec/call avg
        total 12 writes, 0.000 sec, 0.1 kb/call avg, 0.0 msec/call avg



In production environments, it is necessary to keep the index up to date. To do that let's create a cronjob. First, open crontab.

    crontab -e



The follow cronjob will run on every hour and add new data to the index using the configuration file we created earlier. Copy and paste it at the end of the file, then save and close the file.

    @hourly /usr/bin/indexer --rotate --config /etc/sphinxsearch/sphinx.conf --all


~~~~~~~~~~~~~~~~~~~~Step 5 — Starting Sphinx~~~~~~~~~~~~~~
By default, the Sphinx daemon is tuned off. First, we'll enable it by changing the line START=no to START=yes in /etc/default/sphinxsearch.

    sudo sed -i 's/START=no/START=yes/g' /etc/default/sphinxsearch

Then, use systemctl to restart the Sphinx daemon.

    sudo systemctl restart sphinxsearch.service
To check if the Sphinx daemon is running correctly, run.

    sudo systemctl status sphinxsearch.service





ALL STEPS AT A GLANCE


1    sudo apt-get install sphinxsearch
2    mysql -u root -p                              // have to give mysql password

3    CREATE DATABASE test;
4    SOURCE /etc/sphinxsearch/example.sql;

5    quit

6    sudo nano /etc/sphinxsearch/sphinx.conf       // copy given sample.conf file to this file

7    sudo indexer --all

8    crontab -e                                  //copy below line and paste it in cronjob and save it.

    @hourly /usr/bin/indexer --rotate --config /etc/sphinxsearch/sphinx.conf --all   

9    sudo sed -i 's/START=no/START=yes/g' /etc/default/sphinxsearch

10    sudo systemctl restart sphinxsearch.service

11    sudo systemctl status sphinxsearch.service

Insert google map in your website php code

<style>    
  #contact-map {
    height: 500px;
  }
</style>
<div id="contact-map"></div>

<script>
  var map;

  function initMap() {

    var myLatlng = new google.maps.LatLng(your lat,your lng);
    map = new google.maps.Map(document.getElementById('contact-map'), {
      center: myLatlng,
      zoom: 15
    });

    var marker = new google.maps.Marker({
        position: myLatlng,
        title:"TITLE "
    });
    marker.setMap(map);

  }


</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB5O1LcvjU5OnLyfwTr2dmo9zu_1zql_UQ&callback=initMap"
    async defer></script>
 

ADD random new article in joomla through php code

instruction

1) create a new php file  add code give below.
2) put this file in joomla folder of your project.
3) run this php file.


////////////////////////////////code////////////////////////////////////
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<div id="progress" style="width:500px;border:1px solid #ccc;"></div>
<!-- Progress information -->
<div id="information" style="width"></div>


</body>
</html>

<?php

define('_JEXEC', 1);
define('DS', DIRECTORY_SEPARATOR);

if (file_exists(dirname(__FILE__) . '/defines.php')) {
   include_once dirname(__FILE__) . '/defines.php';
}
if (!defined('_JDEFINES')) {
   define('JPATH_BASE', dirname(__FILE__));
   require_once JPATH_BASE.'/includes/defines.php';
}

//define('JPATH_COMPONENT_ADMINISTRATOR', dirname(__FILE__) . "/administrator");
define('JPATH_COMPONENT_ADMINISTRATOR', JPATH_BASE . DS . 'administrator' . DS . 'components' . DS . 'com_content');
require_once JPATH_BASE.'/includes/framework.php';
//$app = JFactory::getApplication('site');
//require_once JPATH_BASE.'/includes/framework.php';


//echo JPATH_BASE. "/administrator/components/com_content/models/article.php";
require_once JPATH_BASE. "/administrator/components/com_content/models/article.php";
                         //administrator/components/com_content/models


$app = JFactory::getApplication('site', array('session' => false));

$total=100;

for($i=0;$i<100;$i++){

    $title_script="title".$i;
    $main_discription="Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod";

       $data = array(
          'catid' => 80, //newsarticles
          'title' => $title_script,
          'introtext' =>$main_discription,
          'fulltext' => '',
          'state' => 1,);
     

      $title_script="";
      $main_discription="";
      $new_article = new ContentModelArticle();
      //print_r($data);

      $new_article->save($data);

    // add progress bar
    $percent = intval($i/$total * 100)."%";
    echo '<script language="javascript">
    document.getElementById("progress").innerHTML="<div style=\"width:'.$percent.';background-color:#ddd;\">&nbsp;</div>";
    document.getElementById("information").innerHTML="'.$i.' row(s) processed.";
    </script>';
    // This is for the buffer achieve the minimum size in order to flush data
    echo str_repeat(' ',1024*64);   
    // Send output to browser immediately
    flush();   
    // Sleep one second so we can see the delay
    sleep(1);
    echo '<script language="javascript">document.getElementById("information").innerHTML="Process completed"</script>';
}

?>

////////////////////////////////////////////////////////////////////////////////

progress bar through php

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<div id="progress" style="width:500px;border:1px solid #ccc;"></div>
<!-- Progress information -->
<div id="information" style="width"></div>


</body>
</html>

<?php
$total=50;
for($i=0;$i<$total;$i++){   

$percent = intval($i/$total * 100)."%";
echo '<script language="javascript">
    document.getElementById("progress").innerHTML="<div style=\"width:'.$percent.';background-color:orange;\">&nbsp;</div>";
    document.getElementById("information").innerHTML="'.$i.' row(s) processed.";
    </script>';

    // This is for the buffer achieve the minimum size in order to flush data
    echo str_repeat(' ',1024*64);

   
// Send output to browser immediately
    flush();
   
// Sleep one second so we can see the delay
    sleep(1);
    echo '<script language="javascript">document.getElementById("information").innerHTML="Process completed"</script>';
}
?>

How to make CSV file from mysql database using PHP

This example demonstrate how to make csv file form mysql table using php. in this example csv file will contain name, username and email from user table. database connection has been takem dynamically from joomla configuration.php file. you need to change it as your requirement.

<?php
    require_once "configuration.php";

    $config = new JConfig();
    $host = $config->host;
    $db = $config->db;
    $dbprefix = $config->dbprefix;
    $password = $config->password;
    $user = $config->user;

    $con = new mysqli($host,$user,$password, $db);


    $filename = "users.csv";
    $fp = fopen('php://output', 'w');
    $header = array("name","username","email");

        header('Content-type: application/csv');
        header('Content-Disposition: attachment; filename='.$filename);
        fputcsv($fp, $header);

    $query = "SELECT name, username, email FROM jnr6o_users";
    $result = $con->query($query);
    while($row = mysqli_fetch_row($result)) {
            fputcsv($fp, $row);
        }
exit;
?>