PHP preg_replace supplement link URL pattern - preg-replace

I have the following URLs structure:
http://example.com/item/example-descriptions/6454986
http://example.com/item/example-bla-bla-bla/6545455
http://example.com/item/example-other-url/5454555
I need to add text to the numbers to get so (add "/demo/" and "?id=test")
http://example.com/item/example-descriptions/demo/6454986?id=test
http://example.com/item/example-bla-bla-bla/demo/6545455?id=test
http://example.com/item/example-other-url/demo/5454555?id=test
Here are a couple of ways imperfect:
$myurl = 'http://example.com/item/example-descriptions/6454986';
if (substr_count($myurl, 'example.com')){
$url = "$myurl.html";
$url = preg_replace('/^(.*)\/([^.]+)\.html$/','$1/demo/$2?id=test', $url);
echo "$url";
} else {
echo "$myurl";
}
and
$myurl = 'http://example.com/item/example-descriptions/6454986';
if (substr_count($myurl, 'example.com')){
$url = explode('/', $myurl);
echo "" . $url[0] . "/" . $url[1] . "/" . $url[2] . "/" . $url[3] . "/" . $url[4] . "/demo/" . $url[5] . "/?id=test";
} else {
echo "$myurl";
}
Help me improve the code.

You can use parse_url:
if (parse_url($myurl, PHP_URL_HOST) == 'example.com') {
$arr = explode('/', $myurl);
$arr[] = 'demo/' . array_pop($arr) . '?id=test';
$myurl = implode('/', $arr);
}

Related

page has Too many redirects from mail.php file?

I hope someone can help me. I have a page with a form and then the information
is emailed to me. the code below seems to be redirecting to the same page over and over again. It used to work for years now its not always working.
any help appreciated. Thanks Steve
<?php
//****************************************
//edit here
$senderName = 'WEB';
$senderEmail = 'site#example.com';
$targetEmail = 'contact#sellmydiabeticteststrips.com';
$messageSubject = 'Message from web-site';
$redirectToReferer = true;
$redirectURL = 'contact.html';
//****************************************
// mail content
$ufname = $_POST['ufname'];
$uaddress = $_POST['uaddress'];
$uemail = $_POST['uemail'];
$utel = $_POST['utel'];
$ucity = $_POST['ucity'];
$ustate = $_POST['ustate'];
$uzip = $_POST['uzip'];
$ubrand = $_POST['ubrand'];
$unumber = $_POST['unumber'];
$ucheck = $_POST['ucheck'];
$agree = $_POST['agree'];
// collect interests data
$interestsString = '';
for($i = 0; $i < count($interests); $i++) {
$interestsString .= $interests[$i].($i < count($interests) - 1 ? ', ' : '');
}
// prepare message text
$messageText = 'First Name: '.$ufname."\n".
'Address: '.$uaddress."\n".
'Email: '.$uemail."\n".
'Telephone: '.$utel."\n".
'City: '.$ucity."\n".
'State: '.$ustate."\n".
'Zip: '.$uzip."\n".
'Brand of test strips: '.$ubrand."\n".
'Number of boxes: '.$unumber."\n".
'Check: '.$ucheck."\n".
'Terms and Conditions: '.$agree."\n";
if($interestsString) {
$messageText .= 'Kinderen wonen bij mij: '.$interestsString."\n";
}
// send email
$senderName = "=?UTF-8?B?" . base64_encode($senderName) . "?=";
$messageSubject = "=?UTF-8?B?" . base64_encode($messageSubject) . "?=";
$messageHeaders = "From: " . $senderName . " <" . $senderEmail . ">\r\n"
. "MIME-Version: 1.0" . "\r\n"
. "Content-type: text/plain; charset=UTF-8" . "\r\n";
if (preg_match('/^[_.0-9a-z-]+#([0-9a-z][0-9a-z-]+.)+[a-z]{2,4}$/',$targetEmail,$matches))
mail($targetEmail, $messageSubject, $messageText, $messageHeaders);
// redirect
if($redirectToReferer) {
header("Location: ".#$_SERVER['HTTP_REFERER'].'#sent');
} else {
header("Location: ".$redirectURL);
}
?>

Showing course image on custom page in Moodle

I have created a custom page on which all available courses are displayed. I have also uploaded the image for the course and now want to show the name of the course along with the image. I am able to get the names of courses from the database but how to get the image.
Try something like this
// Create a course_in_list object to use the get_course_overviewfiles() method.
require_once($CFG->libdir . '/coursecatlib.php');
$course = new course_in_list($courseid);
$outputimage = '';
foreach ($course->get_course_overviewfiles() as $file) {
if ($file->is_valid_image()) {
$imagepath = '/' . $file->get_contextid() .
'/' . $file->get_component() .
'/' . $file->get_filearea() .
$file->get_filepath() .
$file->get_filename();
$imageurl = file_encode_url($CFG->wwwroot . '/pluginfile.php', $imagepath,
false);
$outputimage = html_writer::tag('div',
html_writer::empty_tag('img', array('src' => $imageurl)),
array('class' => 'courseimage'));
// Use the first image found.
break;
}
}
echo $outputimage;
You may get course image directly from 'overviewfiles' files area.
function get_course_image()
{
global $COURSE;
$url = '';
require_once( $CFG->libdir . '/filelib.php' );
$context = context_course::instance( $COURSE->id );
$fs = get_file_storage();
$files = $fs->get_area_files( $context->id, 'course', 'overviewfiles', 0 );
foreach ( $files as $f )
{
if ( $f->is_valid_image() )
{
$url = moodle_url::make_pluginfile_url( $f->get_contextid(), $f->get_component(), $f->get_filearea(), null, $f->get_filepath(), $f->get_filename(), false );
}
}
return $url;
}

replace text with url in twitter feed

I have this code:
public function linkify($status_text)
{
$status_text = preg_replace('/(https?:\/\/\S+)/','\1', $status_text);
$status_text = preg_replace('/(^|\s)#(\w+)/','\1#\2',$status_text);
$status_text = preg_replace('/(^|\s)#(\w+)/','\1#\2',$status_text);
return $status_text;
}
and display feeds from twitter like this
foreach($feed as $feed_item) {
$html .= '<li>';
$html .= '' . $this->linkify($feed_item->text) . '';
$html .= '' . $this->relativedate((strtotime($feed_item->created_at))) . '';
$html .= '</li>';
}
echo $html;
result of this code is
<li>Twitter Feed Text http://t.co/TnkNfxCdRu</li>
if anyone can help me, how can I add text inside tag <a></a>. for example, to be exactly like this:
<li>Twitter Feed Text</li>
Thank you so much
Just change your first preg_replace to:
$status_text = preg_replace('~(https?://(\S+))~','$2',$status_text);

Integrate Authorize.net (Echeck.net) payment method in Magento 1.7.0.2

I need to integrate the Authorize.net (Echeck.net) payment method for my magento site.I have googled but i dont find Please suggest if there is any extensions for the payment method or else can we achieve this by coding.I am using magento 1.7.0.2.
Thanks in Advance!
The Official Beta release from authorize.net is available on Magento market(Magento Connect). This module is tested only in sandbox and currently in Beta status and probably compateble with 1.4 and 1.6. have not tried with 1.7 yet. you can try it if works. Please find the module at following link
http://www.magentocommerce.com/magento-connect/echeck-payment-method-authorize-net.html
If you need to customise the extention feel free to contact at contact#sgssandhu.com or http://oxosolutions.com/
Thanks
Hi here is working example of ECHECK through curl request & parsing of Response with delimiter:
public function curlProcessECHECK(){
$query = "";
// Login Information
$query .= "x_login=" . urlencode($this->credentials->username) . "&";
$query .= "x_tran_key=" . urlencode($this->credentials->password) . "&";
$query .= "x_version=" . "3.1" . "&";
$query .= "x_delim_data=" . "TRUE" . "&";
$query .= "x_delim_char=" . "|" . "&";
$query .= "x_relay_response=" . "FALSE" . "&";
$query .= "x_amount=" . urlencode(number_format($data['orderTotalAmt'], 2, ".", "")) . "&";
// ECHECk payments..... code to check ECHECK request
switch ($data['bank_acct_type'])
{
case 'checking':
$echecktype = 'PPD';
break;
case 'businessChecking':
$echecktype = 'CCD';
break;
case 'savings':
$echecktype = 'PPD';
break;
default:
$echecktype = 'PPD';
break;
}
$query .= "x_method=ECHECK&";
$query .= "x_bank_name=" . urlencode($data['bank_name']) . "&";
$query .= "x_echeck_type=" . urlencode($echecktype) . "&"; //CCD, PPD, TEL ---[ARC, BOC]- bank_check_number ll be required, [WEB] recurring_billing ll be required.
$query .= "x_bank_acct_type=" . urlencode($data['bank_acct_type']) . "&";
$query .= "x_bank_acct_num=" . urlencode($data['bank_acct_num']) . "&";
$query .= "x_bank_aba_code=" . urlencode($data['bank_aba_code']) . "&"; // aba code should be valid get from google US based banks
$query .= "x_bank_acct_name=" . urlencode($data['bank_acct_name']) . "&";
$query .= "x_description=" . (isset($data['orderDescription']) ? urlencode($data['orderDescription']) : "") . "&";
$query .= "x_first_name=" . (isset($data['billingFirstName']) ? urlencode($data['billingFirstName']) : $data['firstName']) . "&";
$query .= "x_last_name=" . (isset($data['billingLastName']) ? urlencode($data['billingLastName']) : $data['lastName']) . "&";
$query .= "x_address=" . (isset($data['billingAddress1']) ? urlencode($data['billingAddress1']) : "") . "&";
$query .= "x_state=" . (isset($data['billingState']) ? urlencode($data['billingState']) : "") . "&";
$query .= "x_zip=" . (isset($data['billingZip']) ? urlencode($data['billingZip']) : "") . "&";
if($this->env == 1) {
$query .= "x_test_request=TRUE&";
}
$query .= "x_type=AUTH_CAPTURE";
$output = array();
$url = 'https://test.authorize.net/gateway/transact.dll';// TestMode
$ch_response = null;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
// curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
$ch_response = curl_exec($ch);
// Check that a connection was made
if (curl_error($ch)) {
// If it wasn't...
$output['status'] = "Failure";
$output['response']['code'] = '-1';
$output['data'] = null;
$output['response']['responseMsg'] = curl_error($ch);
$output['response']['gateway_response_code'] ='000';
$output['response']['responsetext']= " No response from gateway";
$output['response']['transactionid'] = '';
$output['response']['init'] ="no";
$output['response']['response_code']='000';
} else {
$output['status'] = 'Success';
$output['data'] = $ch_response;
$output = $this->processResponse($output);
}
echo '<pre>';print_r($output);die;
}
Now parse the result
public function processResponse($output){
$response_array=$output;
if ($response_array) {
// Split Array
$encap_char = "|";
$response_array = explode($encap_char, $response_array['data']);
//echo"<pre>";print_r($response_array);die;
/**
* If AuthorizeNet doesn't return a delimited response.
*/
if (count($response_array) < 10) {
$approved = false;
$error = true;
$error_message = "Unrecognized response from AuthorizeNet: ";
return;
}
// Set all fields
$response_code = $response_array[0];
$response_subcode = $response_array[1];
$response_reason_code = $response_array[2];
$response_reason_text = $response_array[3];
$authorization_code = $response_array[4];
$avs_response = $response_array[5];
$transaction_id = $response_array[6];
$invoice_number = $response_array[7];
$description = $response_array[8];
$amount = $response_array[9];
$method = $response_array[10];
$transaction_type = $response_array[11];
$customer_id = $response_array[12];
$first_name = $response_array[13];
$last_name = $response_array[14];
$company = $response_array[15];
$address = $response_array[16];
$city = $response_array[17];
$state = $response_array[18];
$zip_code = $response_array[19];
$country = $response_array[20];
$phone = $response_array[21];
$fax = $response_array[22];
$email_address = $response_array[23];
$ship_to_first_name = $response_array[24];
$ship_to_last_name = $response_array[25];
$ship_to_company = $response_array[26];
$ship_to_address = $response_array[27];
$ship_to_city = $response_array[28];
$ship_to_state = $response_array[29];
$ship_to_zip_code = $response_array[30];
$ship_to_country = $response_array[31];
$tax = $response_array[32];
$duty = $response_array[33];
$freight = $response_array[34];
$tax_exempt = $response_array[35];
$purchase_order_number = $response_array[36];
$md5_hash = $response_array[37];
$card_code_response = $response_array[38];
$cavv_response = $response_array[39];
$account_number = $response_array[50];
$card_type = $response_array[51];
$split_tender_id = $response_array[52];
$requested_amount = $response_array[53];
$balance_on_card = $response_array[54];
// $approved = ($response_code == self::APPROVED);
// $declined = ($response_code == self::DECLINED);
// $error = ($response_code == self::ERROR);
// $held = ($response_code == self::HELD);
$approved = "";
$declined = "";
$error = "";
$held = "";
if ($response_code == 1) {
$result['response']['response_code'] = 100;
$result['response']['gateway_response_code'] = 100;
$result['response']['responsetext'] = "Success";
$result['status'] = 'success';
} elseif ($response_code == 2) {
$result['response']['response_code'] = 800;
$result['response']['gateway_response_code'] = 800;
$result['response']['responsetext'] = "Declined";
$result['status'] = $response_reason_text;
} else {
$result['response']['response_code'] = $response_code;
$result['response']['gateway_response_code'] = $response_code;
$result['response']['responsetext'] = $response_reason_text;
$result['status'] = $response_reason_text;
}
$result['method'] = $method;
$result['md5_hash'] = $md5_hash;
$result['card_type'] = $card_type;
$result['account_number'] = $account_number;
$result['response']['transactionid'] = $transaction_id;
$result['response']['processor_id'] = "";
$result['response']['cvvresponse'] = $cavv_response;
$result['response']['avsresponse'] = $avs_response;
$result['response']['authcode'] = $authorization_code;
$result['response']['type'] = "Sale";
$result['response']['init'] = "no";
return $result;
}
}

Magento - Get list of all Manufacturers with product count

I am using the following code to list all the manufacturers and it works like a charm:
$attribute = Mage::getModel('eav/entity_attribute')
->loadByCode('catalog_product', 'manufacturer');
$valuesCollection = Mage::getResourceModel('eav/entity_attribute_option_collection')
->setAttributeFilter($attribute->getData('attribute_id'))
->setStoreFilter(0, false);
$preparedManufacturers = array();
foreach($valuesCollection as $value) {
$preparedManufacturers[$value->getOptionId()] = $value->getValue();
}
if (count($preparedManufacturers)) {
echo "<h2>Manufacturers</h2><ul>";
foreach($preparedManufacturers as $optionId => $value) {
echo "<li>" . $value . " - (" . $optionId . ")</li>";
}
echo "</ul>";
}
What I am looking for is a way to display the number of products associated with each of the manufacturers. Can someone please tell me the way of doing this?
Many thanks
Not all mine, but works for me in 1.6+?
<?php
include_once 'app/Mage.php';
Mage::app();
$attribute = Mage::getModel('eav/entity_attribute')
->loadByCode('catalog_product', 'manufacturer');
$valuesCollection = Mage::getResourceModel('eav/entity_attribute_option_collection')
->setAttributeFilter($attribute->getData('attribute_id'))
->setStoreFilter(0, false);
$preparedManufacturers = array();
foreach ($valuesCollection as $value) {
$preparedManufacturers[$value->getOptionId()] = $value->getValue();
}
if (count($preparedManufacturers)) {
echo "<h2>Manufacturers</h2><ul>";
foreach ($preparedManufacturers as $optionId => $value) {
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addFieldToFilter(array(array('attribute' => 'manufacturer', 'eq' => $optionId)));
$mumberOfProducrt = count($collection);
echo "<li>" . $value . " - (" . $mumberOfProducrt . ")</li>";
}
echo "</ul>";
}
?>
This would work but won't be the most efficient:
foreach($valuesCollection as $value) {
$preparedManufacturers[$value->getOptionId()] = $value->getValue();
$collection = Mage::getModel('catalog/product')->getCollection();
$collection
->addAttributeToSelect('*') // '*' not efficient though
->addAttributeToFilter('manufacturer', array('eq' => $value->getOptionId()))
//->addAttributeToFilter('manufacturer', $value->getOptionId())
;
$count = $collection->->getSize();
}
It's an extra query for each manufacturer so it's not great, if you have some caching etc it won't be too bad though.
Working code should do it
$collection = Mage::getModel('catalog/product')->getCollection()->groupByAttribute('manufacturer')
->addFieldToFilter('status',Mage_Catalog_Model_Product_Status::STATUS_ENABLED)
->addExpressionAttributeToSelect("count",'COUNT({{entity_id}})', 'entity_id');
Mage::getSingleton('cataloginventory/stock')->addInStockFilterToCollection($collection);