How can I use this extended template parser class for CodeIgniter? - php

I've been searching around for extensions of CodeIgniter's parser class that would add the use of conditional statements in the view files. The problem is that the location that I've found it at doesn't offer any explanation on how to use it and doesn't list anything about the file's author. Could anyone perhaps share any thoughts on this code?
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 4.3.2 or newer
*
* #package CodeIgniter
* #author ExpressionEngine Dev Team
* #copyright Copyright (c) 2008, EllisLab, Inc.
* #license http://codeigniter.com/user_guide/license.html
* #link http://codeigniter.com
* #since Version 1.0
* #filesource
*/
// ------------------------------------------------------------------------
/**
* MY Parser Class
*
* #package CodeIgniter
* #subpackage Libraries
* #category Parser
* #author Haloweb Ltd
*/
class MY_Parser extends CI_Parser {
/**
* Parse a template
*
* Parses pseudo-variables contained in the specified template,
* replacing them with the data in the second param
*
* #access public
* #param string
* #param array
* #param bool
* #return string
*/
function parse($template, $data, $return = FALSE, $include = FALSE)
{
$CI =& get_instance();
if ($template == '')
{
return FALSE;
}
if ($include === FALSE)
{
$template = $CI->load->view($template, $data, TRUE);
}
if (isset($data) && $data != '')
{
foreach ($data as $key => $val)
{
if (is_array($val))
{
$template = $this->_parse_pair($key, $val, $template);
}
else
{
$template = $this->_parse_single($key, (string)$val, $template);
}
}
}
// Check for conditional statments
$template = $this->conditionals($template, $data);
// populate form tags
preg_match_all('/{form:(.+)}/i', $template, $posts);
if ($posts)
{
foreach ($posts[1] as $post => $value)
{
if ($postValue = $CI->input->post($value))
{
$template = str_replace('{form:'.$value.'}', $postValue, $template);
}
else
{
$template = str_replace('{form:'.$value.'}', '', $template);
}
}
}
//$template = preg_replace('/{(.+)}/i', '', $template);
if ($return == FALSE)
{
$CI->output->append_output($template);
}
return $template;
}
// --------------------------------------------------------------------
/**
* Parse conditional statments
*
* #access public
* #param string
* #param bool
* #return string
*/
function conditionals($template, $data)
{
if (preg_match_all('/'.$this->l_delim.'if (.+)'.$this->r_delim.'(.+)'.$this->l_delim.'\/if'.$this->r_delim.'/siU', $template, $conditionals, PREG_SET_ORDER))
{
if (count($conditionals) > 0)
{
// filter through conditionals
foreach($conditionals as $condition)
{
// get conditional and the string inside
$code = (isset($condition[0])) ? $condition[0] : FALSE;
$condString = (isset($condition[1])) ? str_replace(' ', '', $condition[1]) : FALSE;
$insert = (isset($condition[2])) ? $condition[2] : '';
// check code is valid
if (!preg_match('/('.$this->l_delim.'|'.$this->r_delim.')/', $condString, $condProblem))
{
if (!empty($code) || $condString != FALSE || !empty($insert))
{
if (preg_match("/^!(.*)$/", $condString, $matches))
{
$condVar = (#!$data[trim($matches[1])]) ? 0 : $data[trim($matches[1])];
#$result = (!$condVar) ? TRUE : FALSE;
}
elseif (preg_match("/([a-z0-9\-_:\(\)]+)(\!=|=|==|>|<)([a-z0-9\-_\/]+)/", $condString, $matches))
{
$condVar = (#!$data[$matches[1]]) ? 0 : $data[trim($matches[1])];
if ($matches[2] == '==' || $matches[2] == '=')
{
#$result = ($condVar === $matches[3]) ? TRUE : FALSE;
}
elseif ($matches[2] == '!=')
{
#$result = ($condVar !== $matches[3]) ? TRUE : FALSE;
}
elseif ($matches[2] == '>')
{
#$result = ($condVar > $matches[3]) ? TRUE : FALSE;
}
elseif ($matches[2] == '<')
{
#$result = ($condVar < $matches[3]) ? TRUE : FALSE;
}
}
else
{
// if the variable is set
if (isset($data[$condString]) && is_array($data[$condString]))
{
$result = (count($data[$condString]) > 0) ? TRUE : FALSE;
}
else
{
$result = (isset($data[$condString]) && $data[$condString] != '') ? TRUE : FALSE;
}
}
// filter for else
$insert = preg_split('/'.$this->l_delim.'else'.$this->r_delim.'/siU', $insert);
if ($result == TRUE)
{
// show the string inside
$template = str_replace($code, $insert[0], $template);
}
else
{
if (is_array($insert))
{
$insert = (isset($insert[1])) ? $insert[1] : '';
$template = str_replace($code, $insert, $template);
}
else
{
$template = str_replace($code, '', $template);
}
}
}
}
else
{
// remove any conditionals we cant process
$template = str_replace($code, '', $template);
}
}
}
//print_r($conditionals);
}
return $template;
}
// --------------------------------------------------------------------
/**
* Matches a variable pair
*
* #access private
* #param string
* #param string
* #return mixed
*/
function _match_pair($string, $variable)
{
$variable = str_replace('(', '\(', $variable);
$variable = str_replace(')', '\)', $variable);
if ( ! preg_match("|".$this->l_delim . $variable . $this->r_delim."(.+?)".$this->l_delim . '/' . $variable . $this->r_delim."|s", $string, $match))
{
return FALSE;
}
return $match;
}
}

Related

Magento cron script "Call to undefined method"

I'm getting a PHP fatal error on a cron script used for Commission Junction. It seems in the error_log it keeps updating with
PHP Fatal error: Call to undefined method Mage_Core_Helper_Data::getEscapedCSVData() in /home/lovescen/public_html/app/code/core/Mage/Dataflow/Model/Convert/Parser/Csv.php on line 269
The code on line 269 is
$escapedValue = Mage::helper("core")->getEscapedCSVData(array($value));
And here is the entire code in Csv.php.
<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license#magento.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magento.com for more information.
*
* #category Mage
* #package Mage_Dataflow
* #copyright Copyright (c) 2006-2016 X.commerce, Inc. and affiliates (http://www.magento.com)
* #license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* Convert csv parser
*
* #category Mage
* #package Mage_Dataflow
* #author Magento Core Team <core#magentocommerce.com>
*/
class Mage_Dataflow_Model_Convert_Parser_Csv extends Mage_Dataflow_Model_Convert_Parser_Abstract
{
protected $_fields;
protected $_mapfields = array();
public function parse()
{
// fixed for multibyte characters
setlocale(LC_ALL, Mage::app()->getLocale()->getLocaleCode().'.UTF-8');
$fDel = $this->getVar('delimiter', ',');
$fEnc = $this->getVar('enclose', '"');
if ($fDel == '\t') {
$fDel = "\t";
}
$adapterName = $this->getVar('adapter', null);
$adapterMethod = $this->getVar('method', 'saveRow');
if (!$adapterName || !$adapterMethod) {
$message = Mage::helper('dataflow')->__('Please declare "adapter" and "method" nodes first.');
$this->addException($message, Mage_Dataflow_Model_Convert_Exception::FATAL);
return $this;
}
try {
$adapter = Mage::getModel($adapterName);
}
catch (Exception $e) {
$message = Mage::helper('dataflow')->__('Declared adapter %s was not found.', $adapterName);
$this->addException($message, Mage_Dataflow_Model_Convert_Exception::FATAL);
return $this;
}
if (!method_exists($adapter, $adapterMethod)) {
$message = Mage::helper('dataflow')->__('Method "%s" not defined in adapter %s.', $adapterMethod, $adapterName);
$this->addException($message, Mage_Dataflow_Model_Convert_Exception::FATAL);
return $this;
}
$batchModel = $this->getBatchModel();
$batchIoAdapter = $this->getBatchModel()->getIoAdapter();
if (Mage::app()->getRequest()->getParam('files')) {
$file = Mage::app()->getConfig()->getTempVarDir().'/import/'
. urldecode(Mage::app()->getRequest()->getParam('files'));
$this->_copy($file);
}
$batchIoAdapter->open(false);
$isFieldNames = $this->getVar('fieldnames', '') == 'true' ? true : false;
if (!$isFieldNames && is_array($this->getVar('map'))) {
$fieldNames = $this->getVar('map');
}
else {
$fieldNames = array();
foreach ($batchIoAdapter->read(true, $fDel, $fEnc) as $v) {
$fieldNames[$v] = $v;
}
}
$countRows = 0;
while (($csvData = $batchIoAdapter->read(true, $fDel, $fEnc)) !== false) {
if (count($csvData) == 1 && $csvData[0] === null) {
continue;
}
$itemData = array();
$countRows ++; $i = 0;
foreach ($fieldNames as $field) {
$itemData[$field] = isset($csvData[$i]) ? $csvData[$i] : null;
$i ++;
}
$batchImportModel = $this->getBatchImportModel()
->setId(null)
->setBatchId($this->getBatchModel()->getId())
->setBatchData($itemData)
->setStatus(1)
->save();
}
$this->addException(Mage::helper('dataflow')->__('Found %d rows.', $countRows));
$this->addException(Mage::helper('dataflow')->__('Starting %s :: %s', $adapterName, $adapterMethod));
$batchModel->setParams($this->getVars())
->setAdapter($adapterName)
->save();
//$adapter->$adapterMethod();
return $this;
// // fix for field mapping
// if ($mapfields = $this->getProfile()->getDataflowProfile()) {
// $this->_mapfields = array_values($mapfields['gui_data']['map'][$mapfields['entity_type']]['db']);
// } // end
//
// if (!$this->getVar('fieldnames') && !$this->_mapfields) {
// $this->addException('Please define field mapping', Mage_Dataflow_Model_Convert_Exception::FATAL);
// return;
// }
//
// if ($this->getVar('adapter') && $this->getVar('method')) {
// $adapter = Mage::getModel($this->getVar('adapter'));
// }
//
// $i = 0;
// while (($line = fgetcsv($fh, null, $fDel, $fEnc)) !== FALSE) {
// $row = $this->parseRow($i, $line);
//
// if (!$this->getVar('fieldnames') && $i == 0 && $row) {
// $i = 1;
// }
//
// if ($row) {
// $loadMethod = $this->getVar('method');
// $adapter->$loadMethod(compact('i', 'row'));
// }
// $i++;
// }
//
// return $this;
}
public function parseRow($i, $line)
{
if (sizeof($line) == 1) return false;
if (0==$i) {
if ($this->getVar('fieldnames')) {
$this->_fields = $line;
return;
} else {
foreach ($line as $j=>$f) {
$this->_fields[$j] = $this->_mapfields[$j];
}
}
}
$resultRow = array();
foreach ($this->_fields as $j=>$f) {
$resultRow[$f] = isset($line[$j]) ? $line[$j] : '';
}
return $resultRow;
}
/**
* Read data collection and write to temporary file
*
* #return Mage_Dataflow_Model_Convert_Parser_Csv
*/
public function unparse()
{
$batchExport = $this->getBatchExportModel()
->setBatchId($this->getBatchModel()->getId());
$fieldList = $this->getBatchModel()->getFieldList();
$batchExportIds = $batchExport->getIdCollection();
$io = $this->getBatchModel()->getIoAdapter();
$io->open();
if (!$batchExportIds) {
$io->write("");
$io->close();
return $this;
}
if ($this->getVar('fieldnames')) {
$csvData = $this->getCsvString($fieldList);
$io->write($csvData);
}
foreach ($batchExportIds as $batchExportId) {
$csvData = array();
$batchExport->load($batchExportId);
$row = $batchExport->getBatchData();
foreach ($fieldList as $field) {
$csvData[] = isset($row[$field]) ? $row[$field] : '';
}
$csvData = $this->getCsvString($csvData);
$io->write($csvData);
}
$io->close();
return $this;
}
public function unparseRow($args)
{
$i = $args['i'];
$row = $args['row'];
$fDel = $this->getVar('delimiter', ',');
$fEnc = $this->getVar('enclose', '"');
$fEsc = $this->getVar('escape', '\\');
$lDel = "\r\n";
if ($fDel == '\t') {
$fDel = "\t";
}
$line = array();
foreach ($this->_fields as $f) {
$v = isset($row[$f]) ? str_replace(array('"', '\\'), array($fEnc.'"', $fEsc.'\\'), $row[$f]) : '';
$line[] = $fEnc.$v.$fEnc;
}
return join($fDel, $line);
}
/**
* Retrieve csv string from array
*
* #param array $fields
* #return string
*/
public function getCsvString($fields = array()) {
$delimiter = $this->getVar('delimiter', ',');
$enclosure = $this->getVar('enclose', '');
$escapeChar = $this->getVar('escape', '\\');
if ($delimiter == '\t') {
$delimiter = "\t";
}
$str = '';
foreach ($fields as $value) {
$escapedValue = Mage::helper("core")->getEscapedCSVData(array($value));
$value = $escapedValue[0];
if (strpos($value, $delimiter) !== false ||
empty($enclosure) ||
strpos($value, $enclosure) !== false ||
strpos($value, "\n") !== false ||
strpos($value, "\r") !== false ||
strpos($value, "\t") !== false ||
strpos($value, ' ') !== false) {
$str2 = $enclosure;
$escaped = 0;
$len = strlen($value);
for ($i=0;$i<$len;$i++) {
if ($value[$i] == $escapeChar) {
$escaped = 1;
} else if (!$escaped && $value[$i] == $enclosure) {
$str2 .= $enclosure;
} else {
$escaped = 0;
}
$str2 .= $value[$i];
}
$str2 .= $enclosure;
$str .= $str2.$delimiter;
} else {
$str .= $enclosure.$value.$enclosure.$delimiter;
}
}
return substr($str, 0, -1) . "\n";
}
}
Not sure how to fix this problem. If I could get some help I'd really appreciate it.
Thanks
UPDATE
Here is the code from my app/code/core/Mage/Core/Helper/Data.php file: http://pastie.org/10815259
Does the file app/code/core/Mage/Core/Helper/Data.php have the getEscapedCSVData function in it?
It appears that this function is added by SUPEE-7405. Have you patched your store with this SUPEE?
In my case some previous programer have copy the file
from core
\app\code\core\Mage\Core\Helper\Data.php
to local
app\code\local\Mage\Core\Helper\Data.php
and then apply SUPE PATCH 7405...
it cause that all modifications made by SUPE in data.php where rewrite by the old ones in local folder...
Solution: copy the new data.php to local or made a extension of class (better solution)

Can't find what I should change from "Undefined offset: 1" PHP notice

I've got this error :
PHP Notice: Undefined offset: 1 in /var/www/joomla/Joomla_3/modules/mod_menu/helper.php on line 59
I found after searching that it might be due to the first parameter of an array that is not defined. But I tried many things and I can't find what I should change to make this work without the notice.
Here is the helper.php :
<?php
/**
* #package Joomla.Site
* #subpackage mod_menu
*
* #copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* #license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('_JEXEC') or die;
/**
* Helper for mod_menu
*
* #package Joomla.Site
* #subpackage mod_menu
* #since 1.5
*/
class ModMenuHelper
{
/**
* Get a list of the menu items.
*
* #param JRegistry $params The module options.
*
* #return array
*
* #since 1.5
*/
public static function getList(&$params)
{
$app = JFactory::getApplication();
$menu = $app->getMenu();
// Get active menu item
$base = self::getBase($params);
$user = JFactory::getUser();
$levels = $user->getAuthorisedViewLevels();
asort($levels);
$key = 'menu_items' . $params . implode(',', $levels) . '.' . $base->id;
$cache = JFactory::getCache('mod_menu', '');
if (!($items = $cache->get($key)))
{
$path = $base->tree;
$start = (int) $params->get('startLevel');
$end = (int) $params->get('endLevel');
$showAll = $params->get('showAllChildren');
$items = $menu->getItems('menutype', $params->get('menutype'));
$lastitem = 0;
if ($items)
{
foreach ($items as $i => $item)
{
if (($start && $start > $item->level)
|| ($end && $item->level > $end)
|| (!$showAll && $item->level > 1 && !in_array($item->parent_id, $path))
//THIS IS LINE 59 || ($start > 1 && !in_array($item->tree[$start - 2], $path)))
{
unset($items[$i]);
continue;
}
$item->deeper = false;
$item->shallower = false;
$item->level_diff = 0;
if (isset($items[$lastitem]))
{
$items[$lastitem]->deeper = ($item->level > $items[$lastitem]->level);
$items[$lastitem]->shallower = ($item->level < $items[$lastitem]->level);
$items[$lastitem]->level_diff = ($items[$lastitem]->level - $item->level);
}
$item->parent = (boolean) $menu->getItems('parent_id', (int) $item->id, true);
$lastitem = $i;
$item->active = false;
$item->flink = $item->link;
// Reverted back for CMS version 2.5.6
switch ($item->type)
{
case 'separator':
case 'heading':
// No further action needed.
continue;
case 'url':
if ((strpos($item->link, 'index.php?') === 0) && (strpos($item->link, 'Itemid=') === false))
{
// If this is an internal Joomla link, ensure the Itemid is set.
$item->flink = $item->link . '&Itemid=' . $item->id;
}
break;
case 'alias':
// If this is an alias use the item id stored in the parameters to make the link.
$item->flink = 'index.php?Itemid=' . $item->params->get('aliasoptions');
break;
default:
$router = JSite::getRouter();
if ($router->getMode() == JROUTER_MODE_SEF)
{
$item->flink = 'index.php?Itemid=' . $item->id;
}
else
{
$item->flink .= '&Itemid=' . $item->id;
}
break;
}
if (strcasecmp(substr($item->flink, 0, 4), 'http') && (strpos($item->flink, 'index.php?') !== false))
{
$item->flink = JRoute::_($item->flink, true, $item->params->get('secure'));
}
else
{
$item->flink = JRoute::_($item->flink);
}
// We prevent the double encoding because for some reason the $item is shared for menu modules and we get double encoding
// when the cause of that is found the argument should be removed
$item->title = htmlspecialchars($item->title, ENT_COMPAT, 'UTF-8', false);
$item->anchor_css = htmlspecialchars($item->params->get('menu-anchor_css', ''), ENT_COMPAT, 'UTF-8', false);
$item->anchor_title = htmlspecialchars($item->params->get('menu-anchor_title', ''), ENT_COMPAT, 'UTF-8', false);
$item->menu_image = $item->params->get('menu_image', '') ? htmlspecialchars($item->params->get('menu_image', ''), ENT_COMPAT, 'UTF-8', false) : '';
}
if (isset($items[$lastitem]))
{
$items[$lastitem]->deeper = (($start?$start:1) > $items[$lastitem]->level);
$items[$lastitem]->shallower = (($start?$start:1) < $items[$lastitem]->level);
$items[$lastitem]->level_diff = ($items[$lastitem]->level - ($start?$start:1));
}
}
$cache->store($items, $key);
}
return $items;
}
/**
* Get base menu item.
*
* #param JRegistry $params The module options.
*
* #return object
*
* #since 3.0.2
*/
public static function getBase(&$params)
{
// Get base menu item from parameters
if ($params->get('base'))
{
$base = JFactory::getApplication()->getMenu()->getItem($params->get('base'));
}
else
{
$base = false;
}
// Use active menu item if no base found
if (!$base)
{
$base = self::getActive($params);
}
return $base;
}
/**
* Get active menu item.
*
* #param JRegistry $params The module options.
*
* #return object
*
* #since 3.0.2
*/
public static function getActive(&$params)
{
$menu = JFactory::getApplication()->getMenu();
return $menu->getActive() ? $menu->getActive() : $menu->getDefault();
}
}
Change it to:
|| ($start > 1 && !empty($item->tree[$start - 2]) && !in_array($item->tree[$start - 2], $path)))
empty() will check for existence and that it isn't empty at the same time.

Fatal error: Cannot redeclare fputcsv()

I have found a php inventory http://inventory-management.org/ easy but was written in PHP4? and I run now on PHP5. I have found some errors that I have already managed to fix but they are keep coming up so I would like to see if I can managed to run at the end. (As it is really simple script only has 5-7 php files).
Could someone help me please how to fix this error?
Fatal error: Cannot redeclare fputcsv() in C:\xampp\htdocs\Inventory\lib\common.php on line 935
which is:
function fputcsv ($fp, $array, $deliminator=",") {
return fputs($fp, putcsv($array,$delimitator));
}#end fputcsv()
here is the full code:
<?php
/*
*/
/**
* description returns an array with filename base name and the extension
*
* #param filemane format
*
* #return array
*
* #access public
*/
function FileExt($filename) {
//checking if the file have an extension
if (!strstr($filename, "."))
return array("0"=>$filename,"1"=>"");
//peoceed to normal detection
$filename = strrev($filename);
$extpos = strpos($filename , ".");
$file = strrev(substr($filename , $extpos + 1));
$ext = strrev(substr($filename , 0 , $extpos));
return array("0"=>$file,"1"=>$ext);
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function UploadFile($source, $destination , $name ="") {
$name = $name ? $name : basename($source);
$name = FileExt($name);
$name[2]= $name[0];
$counter = 0 ;
while (file_exists( $destination . $name[0] . "." . $name[1] )) {
$name[0] = $name[2] . $counter;
$counter ++;
}
copy($source , $destination . $name[0] . "." . $name[1] );
#chmod($destination . $name[0] . "." . $name[1] , 0777);
}
function UploadFileFromWeb($source, $destination , $name) {
$name = FileExt($name);
$name[2]= $name[0];
$counter = 0 ;
while (file_exists( $destination . $name[0] . "." . $name[1] )) {
$name[0] = $name[2] . $counter;
$counter ++;
}
SaveFileContents($destination . $name[0] . "." . $name[1] , $source);
#chmod($destination . $name[0] . "." . $name[1] , 0777);
}
/**
* returns the contents of a file in a string
*
* #param string $file_name name of file to be loaded
*
* #return string
*
* #acces public
*/
function GetFileContents($file_name) {
// if (!file_exists($file_name)) {
// return null;
// }
//echo "<br>:" . $file_name;
$file = fopen($file_name,"r");
//checking if the file was succesfuly opened
if (!$file)
return null;
if (strstr($file_name,"://"))
while (!feof($file))
$result .= fread($file,1024);
else
$result = #fread($file,filesize($file_name));
fclose($file);
return $result;
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function SaveFileContents($file_name,$content) {
// echo $file_name;
$file = fopen($file_name,"w");
fwrite($file,$content);
fclose($file);
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function Debug($what,$pre = 1,$die = 0) {
if (PB_DEBUG_EXT == 1) {
if ($pre == 1)
echo "<pre style=\"background-color:white;\">";
print_r($what);
if ($pre == 1)
echo "</pre>";
if ($die == 1)
die;
}
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function SendMail($to,$from,$subject,$message,$to_name,$from_name) {
if ($to_name)
$to = "$to_name <$to>";
$headers = "MIME-Version: 1.0\n";
$headers .= "Content-type: text; charset=iso-8859-1\n";
if ($from_name) {
$headers .= "From: $from_name <$from>\n";
$headers .= "Reply-To: $from_name <$from>\n";
}
else {
$headers .= "From: $from\n";
$headers .= "Reply-To: $from\n";
}
$headers .= "X-Mailer: PHP/" . phpversion();
return mail($to, $subject, $message,$headers);
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function FillVars($var,$fields,$with) {
$fields = explode (",",$fields);
foreach ($fields as $field)
if (!$var[$field])
!$var[$field] = $with;
return $var;
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function CleanupString($string,$strip_tags = TRUE) {
$string = addslashes(trim($string));
if ($strip_tags)
$string = strip_tags($string);
return $string;
}
define("RX_EMAIL","^[a-z0-9]+([_\\.-][a-z0-9]+)*#([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}$");
define("RX_CHARS","[a-z\ ]");
define("RX_DIGITS","[0-9]");
define("RX_ALPHA","[^a-z0-9_]");
define("RX_ZIP","[0-9\-]");
define("RX_PHONE","[0-9\-\+\(\)]");
/**
* description
*
* #param
*
* #return
*
* #access
*/
function CheckString($string,$min,$max,$regexp = "",$rx_result = FALSE) {
if (get_magic_quotes_gpc() == 0)
$string = CleanupString($string);
if (strlen($string) < $min)
return 1;
elseif (($max != 0) && (strlen($string) > $max))
return 2;
elseif ($regexp != "")
if ($rx_result == eregi($regexp,$string))
return 3;
return 0;
}
/**
* description
*
* #param
*
* #return
*
* #access
*/// FIRST_NAME:S:3:60,LAST_NAME:S...
function ValidateVars($source,$vars) {
$vars = explode(",",$vars);
foreach ($vars as $var) {
list($name,$type,$min,$max) = explode(":",$var);
switch ($type) {
case "S":
$type = RX_CHARS;
$rx_result = FALSE;
break;
case "I":
$type = RX_DIGITS;
$rx_result = TRUE;
break;
case "E":
$type = RX_EMAIL;
$rx_result = FALSE;
break;
case "P":
$type = RX_PHONE;
$rx_result = TRUE;
break;
case "Z":
$type = RX_ZIP;
$rx_result = FALSE;
break;
case "A":
$type = "";
break;
case "F":
//experimental crap
$type = RX_ALPHA;
$rx_result = TRUE;
//$source[strtolower($name)] = str_replace(" ", "" , $source[strtolower($name)] );
break;
}
//var_dump($result);
if (($result = CheckString($source[strtolower($name)],$min,$max,$type,$rx_result)) != 0)
$errors[] = $name;
}
return is_array($errors) ? $errors : 0;
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function ResizeImage($source,$destination,$size) {
if (PB_IMAGE_MAGICK == 1)
system( PB_IMAGE_MAGICK_PATH . "convert $source -resize {$size}x{$size} $destination");
else
copy($source,$destination);
}
/**
* uses microtime() to return the current unix time w/ microseconds
*
* #return float the current unix time in the form of seconds.microseconds
*
* #access public
*/
function GetMicroTime() {
list($usec,$sec) = explode(" ",microtime());
return (float) $usec + (float) $sec;
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function GetArrayPart($input,$from,$count) {
$return = array();
$max = count($input);
for ($i = $from; $i < $from + $count; $i++ )
if ($i<$max)
$return[] = $input[$i];
return $return;
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function ReplaceAllImagesPath($htmldata,$image_path) {
$htmldata = stripslashes($htmldata);
// replacing IE formating style
$htmldata = str_replace("<IMG","<img",$htmldata);
// esmth, i dont know why i'm doing
preg_match_all("'<img.*?>'si",$htmldata,$images);
//<?//ing edit plus
foreach ($images[0] as $image)
$htmldata = str_replace($image,ReplaceImagePath($image,$image_path),$htmldata);
return $htmldata;//implode("\n",$html_out);
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function ReplaceImagePath($image,$replace) {
// removing tags
$image = stripslashes($image);
$image = str_replace("<","",$image);
$image = str_replace(">","",$image);
// exploging image in proprietes
$image_arr = explode(" ",$image);
for ($i = 0;$i < count($image_arr) ;$i++ ) {
if (stristr($image_arr[$i],"src")) {
// lets it :]
$image_arr[$i] = explode("=",$image_arr[$i]);
// modifing the image path
// i doing this
// replacing ',"
$image_arr[$i][1] = str_replace("'","",$image_arr[$i][1]);
$image_arr[$i][1] = str_replace("\"","",$image_arr[$i][1]);
//getting only image name
$image_arr[$i][1] = strrev(substr(strrev($image_arr[$i][1]),0,strpos(strrev($image_arr[$i][1]),"/")));
// building the image back
$image_arr[$i][1] = "\"" . $replace . $image_arr[$i][1] . "\"";
$image_arr[$i] = implode ("=",$image_arr[$i]);
}
}
// adding tags
return "<" . implode(" ",$image_arr) . ">";
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function DowloadAllImages($images,$path) {
foreach ($images as $image)
#SaveFileContents($path ."/".ExtractFileNameFromPath($image),#implode("",#file($image)));
}
function GetAllImagesPath($htmldata) {
$htmldata = stripslashes($htmldata);
// replacing IE formating style
$htmldata = str_replace("<IMG","<img",$htmldata);
// esmth, i dont know why i'm doing
preg_match_all("'<img.*?>'si",$htmldata,$images);
//<?//ing edit plus
foreach ($images[0] as $image)
$images_path[] = GetImageName($image);
return $images_path;
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function GetImagePath($image) {
// removing tags
$image = stripslashes($image);
$image = str_replace("<","",$image);
$image = str_replace(">","",$image);
// exploging image in proprietes
$image_arr = explode(" ",$image);
for ($i = 0;$i < count($image_arr) ;$i++ ) {
if (stristr($image_arr[$i],"src")) {
// lets it :]
$image_arr[$i] = explode("=",$image_arr[$i]);
// modifing the image path
// i doing this
// replacing ',"
$image_arr[$i][1] = str_replace("'","",$image_arr[$i][1]);
$image_arr[$i][1] = str_replace("\"","",$image_arr[$i][1]);
return strrev(substr(strrev($image_arr[$i][1]),0,strpos(strrev($image_arr[$i][1]),"/")));;
}
}
// adding tags
return "";
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function GetImageName($image) {
// removing tags
$image = stripslashes($image);
$image = str_replace("<","",$image);
$image = str_replace(">","",$image);
// exploging image in proprietes
$image_arr = explode(" ",$image);
for ($i = 0;$i < count($image_arr) ;$i++ ) {
if (stristr($image_arr[$i],"src")) {
// lets it :]
$image_arr[$i] = explode("=",$image_arr[$i]);
// modifing the image path
// i doing this
// replacing ',"
$image_arr[$i][1] = str_replace("'","",$image_arr[$i][1]);
$image_arr[$i][1] = str_replace("\"","",$image_arr[$i][1]);
return $image_arr[$i][1];
}
}
// adding tags
return "";
}
/**
* reinventing the wheel [badly]
*
* #param somthin
*
* #return erroneous
*
* #access denied
*/
function ExtractFileNameFromPath($file) {
//return strrev(substr(strrev($file),0,strpos(strrev($file),"/")));
// sau ai putea face asha. umpic mai smart ca mai sus dar tot stupid
// daca le dai path fara slashes i.e. un filename prima returneaza "" asta taie primu char
//return substr($file,strrpos($file,"/") + 1,strlen($file) - strrpos($file,"/"));
// corect ar fi cred asha [observa smart usage`u de strRpos]
//return substr($file,strrpos($file,"/") + (strstr($file,"/") ? 1 : 0),strlen($file) - strrpos($file,"/"));
// sau putem folosi tactica `nute mai caca pe tine and rtm' shi facem asha
return basename($file);
// har har :]]
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function RemoveArraySlashes($array) {
if ($array)
foreach ($array as $key => $item)
if (is_array($item))
$array[$key] = RemoveArraySlashes($item);
else
$array[$key] = stripslashes($item);
return $array;
}
function AddArraySlashes($array) {
if ($array)
foreach ($array as $key => $item)
if (is_array($item))
$array[$key] = AddArraySlashes($item);
else
$array[$key] = addslashes($item);
return $array;
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function Ahtmlentities($array) {
if (is_array($array))
foreach ($array as $key => $item)
if (is_array($item))
$array[$key] = ahtmlentities($item);
else
$array[$key] = htmlentities(stripslashes($item),ENT_COMPAT);
else
return htmlentities(stripslashes($array),ENT_COMPAT);
return $array;
}
function AStripSlasshes($array) {
if (is_array($array))
foreach ($array as $key => $item)
if (is_array($item))
$array[$key] = AStripSlasshes($item);
else
$array[$key] = stripslashes($item);
else
return stripslashes($array);
return $array;
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function Ahtml_entity_decode($array) {
if ($array)
foreach ($array as $key => $item)
if (is_array($item))
$array[$key] = ahtml_entity_decode($item);
else
$array[$key] = html_entity_decode($item,ENT_COMPAT);
return $array;
}
function array2xml ($name, $value, $indent = 1)
{
$indentstring = "\t";
for ($i = 0; $i < $indent; $i++)
{
$indentstring .= $indentstring;
}
if (!is_array($value))
{
$xml = $indentstring.'<'.$name.'>'.$value.'</'.$name.'>'."\n";
}
else
{
if($indent === 1)
{
$isindex = False;
}
else
{
$isindex = True;
while (list ($idxkey, $idxval) = each ($value))
{
if ($idxkey !== (int)$idxkey)
{
$isindex = False;
}
}
}
reset($value);
while (list ($key, $val) = each ($value))
{
if($indent === 1)
{
$keyname = $name;
$nextkey = $key;
}
elseif($isindex)
{
$keyname = $name;
$nextkey = $name;
}
else
{
$keyname = $key;
$nextkey = $key;
}
if (is_array($val))
{
$xml .= $indentstring.'<'.$keyname.'>'."\n";
$xml .= array2xml ($nextkey, $val, $indent+1);
$xml .= $indentstring.'</'.$keyname.'>'."\n";
}
else
{
$xml .= array2xml ($nextkey, $val, $indent);
}
}
}
return $xml;
}
function GetPhpContent($file) {
if (file_exists($file) ) {
$data = GetFileContents($file);
//replacing special chars in content
$data = str_replace("<?php","",$data);
$data = str_replace("?>","",$data);
return $data;
}
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function KeyArray($array,$recurse = 0 , $count = 1) {
if (is_array($array)) {
foreach ($array as $key => $val) {
$array[$key]["key"] = $count ++;
if ($recurse) {
foreach ($array[$key] as $k => $val)
if (is_array($val)) {
KeyArray($array[$key][$k] , $recurse , $count);
}
}
}
}
return $count + 1;
}
function RandomWord( $passwordLength ) {
$password = "";
for ($index = 1; $index <= $passwordLength; $index++) {
// Pick random number between 1 and 62
$randomNumber = rand(1, 62);
// Select random character based on mapping.
if ($randomNumber < 11)
$password .= Chr($randomNumber + 48 - 1); // [ 1,10] => [0,9]
else if ($randomNumber < 37)
$password .= Chr($randomNumber + 65 - 10); // [11,36] => [A,Z]
else
$password .= Chr($randomNumber + 97 - 36); // [37,62] => [a,z]
}
return $password;
}
function DeleteFolder($file) {
if (file_exists($file)) {
chmod($file,0777);
if (is_dir($file)) {
$handle = opendir($file);
while($filename = readdir($handle)) {
if ($filename != "." && $filename != "..") {
DeleteFolder($file."/".$filename);
}
}
closedir($handle);
rmdir($file);
} else {
unlink($file);
}
}
}
function GenerateRecordID($array) {
$max = 0;
if (is_array($array)) {
foreach ($array as $key => $val)
$max = ($key > $max ? $key : $max);
return $max + 1;
}
else return 1;
}
/*****************************************************
Links cripting for admin
DO NOT TOUCH UNLKESS YOU KNOW WHAT YOU ARE DOING
*****************************************************/
/**
* description
*
* #param
*
* #return
*
* #access
*/
function CryptLink($link) {
if (defined("PB_CRYPT_LINKS") && (PB_CRYPT_LINKS == 1)) {
if (stristr($link,"javascript:")) {
/* if (stristr($link,"window.location=")) {
$pos = strpos($link , "window.location=");
$js = substr($link , 0 , $pos + 17 );
$final = substr($link , $pos + 17 );
$final = substr($final, 0, strlen($final) - 1 );
//well done ... crypt the link now
$url = #explode("?" , $final);
if (!is_array($url))
$url[0] = $final;
$tmp = str_replace( $url[0] . "?" , "" , $final);
$uri = urlencode(urlencode(base64_encode(str_rot13($tmp))));
$link = $js . $url[0] . "?" . $uri . md5($uri) . "'";
}
*/
} else {
$url = #explode("?" , $link);
if (!is_array($url))
$url[0] = $link;
$tmp = str_replace( $url[0] . "?" , "" , $link);
$uri = urlencode(urlencode(base64_encode(str_rot13($tmp))));
$link = $url[0] . "?" . $uri . md5($uri);
}
}
return $link;
}
/************************************************************************/
/* SOME PREINITIALISATION CRAP*/
if (defined("PB_CRYPT_LINKS") && (PB_CRYPT_LINKS == 1) ) {
$key = key($_GET);
if (is_array($_GET) && (count($_GET) == 1) && ($_GET[$key] == "")) {
$tmp = $_SERVER["QUERY_STRING"];
//do the md5 check
$md5 = substr($tmp , -32);
$tmp = substr($tmp , 0 , strlen($tmp) - 32);
if ($md5 != md5($tmp)) {
//header("index.php?action=badrequest");
//exit;
die("Please dont change the links!");
}
$tmp = str_rot13(base64_decode(urldecode(urldecode($tmp))));
$tmp_array = #explode("&" , $tmp);
$tmp_array = is_array($tmp_array) ? $tmp_array : array($tmp);
if (is_array($tmp_array)) {
foreach ($tmp_array as $key => $val) {
$tmp2 = explode("=" , $val);
$out[$tmp2[0]] = $tmp2[1];
}
} else {
$tmp2 = explode("=" , $tmp);
$out[$tmp2[0]] = $tmp2[1];
}
$_GET = $out;
}
}
/***********************************************************************/
function ArrayReplace($what , $with , $array ) {
if ($array)
foreach ($array as $key => $item)
if (is_array($item))
$array[$key] = ArrayReplace($what , $with , $item);
else
$array[$key] = str_replace($what , $with , $item);
return $array;
}
function stri_replace( $find, $replace, $string )
{
$parts = explode( strtolower($find), strtolower($string) );
$pos = 0;
foreach( $parts as $key=>$part ){
$parts[ $key ] = substr($string, $pos, strlen($part));
$pos += strlen($part) + strlen($find);
}
return( join( $replace, $parts ) );
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function GMTDate($format , $date) {
global $_GMT;
return date($format , $date - $_GMT);
}
function putcsv ($array, $deliminator=",") {
$line = "";
foreach($array as $val) {
# remove any windows new lines,
# as they interfere with the parsing at the other end
$val = str_replace("\r\n", "\n", $val);
# if a deliminator char, a double quote char or a newline
# are in the field, add quotes
if(ereg("[$deliminator\"\n\r]", $val)) {
$val = '"'.str_replace('"', '""', $val).'"';
}#end if
$line .= $val.$deliminator;
}#end foreach
# strip the last deliminator
$line = substr($line, 0, (strlen($deliminator) * -1));
# add the newline
$line .= "\n";
# we don't care if the file pointer is invalid,
# let fputs take care of it
return $line;
}#end fputcsv()
function fputcsv ($fp, $array, $deliminator=",") {
return fputs($fp, putcsv($array,$delimitator));
}#end fputcsv()
/**
* description
*
* #param
*
* #return
*
* #access
*/
function is_subaction($sub,$action) {
return (bool)($_GET["sub"] == $sub) && ($_GET["action"] == $action);
}
?>
many thanks in advance
fputcsv() is a built in PHP function. This means you cannot name your own function the same thing.
If you need this code to work with PHP4, just check to see if the function exists first, then if not, create your own.
if (!function_exists('fputcsv')) {
// Your definition here
}

Non-abstract method showing as abstract in PHP fatal error message

I am getting this PHP fatal error message: "Fatal error: Class PT_Fieldtype contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (EE_Fieldtype::display_field) in /.../pt_fieldtype.php on line 148"
However, when I open the file and do a search, the word "abstract" is nowhere to be found at all. Thanks for the help!
Edit: Here's the code in question. My bad for not showing it before.
<?php if (! defined('BASEPATH')) exit('No direct script access allowed');
if (! defined('PT_FIELD_PACK_VER'))
{
// get the version from config.php
require PATH_THIRD.'pt_field_pack/config.php';
define('PT_FIELD_PACK_VER', $config['version']);
}
/**
* P&T Fieldtype Base Class
*
* #package P&T Field Pack
* #author Brandon Kelly <brandon#pixelandtonic.com>
* #copyright Copyright (c) 2010 Pixel & Tonic, LLC
*/
class PT_Fieldtype extends EE_Fieldtype {
/**
* PT_Fieldtype Constructor
*/
function PT_Fieldtype()
{
parent::EE_Fieldtype();
}
// --------------------------------------------------------------------
/**
* Options Setting
*/
function options_setting($options=array(), $indent = '')
{
$r = '';
foreach($options as $name => $label)
{
if ($r !== '') $r .= "\n";
// is this just a blank option?
if (! $name && ! $label) $name = $label = ' ';
$r .= $indent . htmlentities($name);
// is this an optgroup?
if (is_array($label)) $r .= "\n".$this->options_setting($label, $indent.' ');
else if ($name != $label) $r .= ' : '.$label;
}
return $r;
}
// --------------------------------------------------------------------
/**
* Save Options Setting
*/
function save_options_setting($options = '', $total_levels = 1)
{
// prepare options
$options = preg_split('/[\r\n]+/', $options);
foreach($options as &$option)
{
$option_parts = preg_split('/\s:\s/', $option, 2);
$option = array();
$option['indent'] = preg_match('/^\s+/', $option_parts[0], $matches) ? strlen(str_replace("\t", ' ', $matches[0])) : 0;
$option['name'] = trim($option_parts[0]);
$option['value'] = isset($option_parts[1]) ? trim($option_parts[1]) : $option['name'];
}
return $this->_structure_options($options, $total_levels);
}
/**
* Structure Options
*/
private function _structure_options(&$options, $total_levels, $level = 1, $indent = -1)
{
$r = array();
while ($options)
{
if ($indent == -1 || $options[0]['indent'] > $indent)
{
$option = array_shift($options);
$children = (! $total_levels OR $level < $total_levels)
? $this->_structure_options($options, $total_levels, $level+1, $option['indent']+1)
: FALSE;
$r[(string)$option['name']] = $children ? $children : (string)$option['value'];
}
else if ($options[0]['indent'] <= $indent)
{
break;
}
}
return $r;
}
// --------------------------------------------------------------------
/**
* Prep Iterators
*/
function prep_iterators(&$tagdata)
{
// find {switch} tags
$this->_switches = array();
$tagdata = preg_replace_callback('/'.LD.'switch\s*=\s*([\'\"])([^\1]+)\1'.RD.'/sU', array(&$this, '_get_switch_options'), $tagdata);
$this->_count_tag = 'count';
$this->_iterator_count = 0;
}
/**
* Get Switch Options
*/
function _get_switch_options($match)
{
global $FNS;
$marker = LD.'SWITCH['.$FNS->random('alpha', 8).']SWITCH'.RD;
$this->_switches[] = array('marker' => $marker, 'options' => explode('|', $match[2]));
return $marker;
}
/**
* Parse Iterators
*/
function parse_iterators(&$tagdata)
{
// {switch} tags
foreach($this->_switches as $i => $switch)
{
$option = $this->_iterator_count % count($switch['options']);
$tagdata = str_replace($switch['marker'], $switch['options'][$option], $tagdata);
}
// update the count
$this->_iterator_count++;
// {count} tags
$tagdata = $this->EE->TMPL->swap_var_single($this->_count_tag, $this->_iterator_count, $tagdata);
}
}
// ====================================================================
/**
* P&T Multi Fieldtype Base Class
*
* #package P&T Field Pack
* #author Brandon Kelly <brandon#pixelandtonic.com>
* #copyright Copyright (c) 2010 Pixel & Tonic, LLC
*/
class PT_Multi_Fieldtype extends PT_Fieldtype {
var $default_field_settings = array(
'options' => array(
'Option 1' => 'Option 1',
'Option 2' => 'Option 2',
'Option 3' => 'Option 3'
)
);
var $default_cell_settings = array(
'options' => array(
'Opt 1' => 'Opt 1',
'Opt 2' => 'Opt 2'
)
);
var $default_tag_params = array(
'sort' => '',
'backspace' => '0'
);
var $total_option_levels = 1;
// --------------------------------------------------------------------
/**
* Display Field Settings
*/
function display_settings($data)
{
// load the language file
$this->EE->lang->loadfile($this->class);
$options = isset($data['options']) ? $data['options'] : array();
$input_name = $this->class.'_options';
$this->EE->table->add_row(
lang($this->class.'_options', $input_name) . '<br />'
. lang('field_list_instructions') . '<br /><br />'
. lang('option_setting_examples'),
'<textarea id="'.$input_name.'" name="'.$input_name.'" rows="6">'.$this->options_setting($options).'</textarea>'
);
}
/**
* Display Cell Settings
*/
function display_cell_settings($data)
{
// load the language file
$this->EE->lang->loadfile($this->class);
$options = isset($data['options']) ? $data['options'] : array();
return array(
array(
lang($this->class.'_options'),
'<textarea class="matrix-textarea" name="options" rows="4">'.$this->options_setting($options).'</textarea>'
)
);
}
// --------------------------------------------------------------------
/**
* Save Field Settings
*/
function save_settings($data)
{
$post = $this->EE->input->post($this->class.'_options');
// replace quotes
$post = str_replace('"', '"', $post);
return array(
'options' => $this->save_options_setting($post, $this->total_option_levels)
);
}
/**
* Save Cell Settings
*/
function save_cell_settings($settings)
{
// replace quotes
$settings['options'] = str_replace('"', '"', $settings['options']);
$settings['options'] = $this->save_options_setting($settings['options'], $this->total_option_levels);
return $settings;
}
// --------------------------------------------------------------------
/**
* Prep Field Data
*
* Ensures $field_data is an array.
*/
function prep_field_data(&$data)
{
if (! is_array($data))
{
$data = array_filter(preg_split("/[\r\n]+/", $data));
}
}
// --------------------------------------------------------------------
/**
* Display Field
*/
function display_field($data)
{
if (is_string($data)) $data = html_entity_decode($data);
return $this->_display_field($data, $this->field_name);
}
/**
* Display Cell
*/
function display_cell($data)
{
return $this->_display_field($data, $this->cell_name);
}
// --------------------------------------------------------------------
/**
* Save
*/
function save($data)
{
// replace quotes
return str_replace('"', '"', $data);
}
/**
* Save Cell
*/
function save_cell($data)
{
// replace quotes
return $this->save($data);
}
// --------------------------------------------------------------------
/**
* Find Options
*/
private function _find_option($needle, $haystack)
{
foreach ($haystack as $key => $value)
{
$r = $value;
if ($needle == $key OR (is_array($value) AND (($r = $this->_find_option($needle, $value)) !== FALSE)))
{
return $r;
}
}
return FALSE;
}
// --------------------------------------------------------------------
/**
* Replace Tag
*/
function replace_tag($data, $params = array(), $tagdata = FALSE)
{
if (! isset($this->settings['options']) || ! $this->settings['options'])
{
return $data;
}
if (! $tagdata)
{
return $this->replace_ul($data, $params);
}
$this->prep_field_data($data);
$r = '';
if ($this->settings['options'] && $data)
{
// optional sorting
if (isset($params['sort']) && $params['sort'])
{
$sort = strtolower($params['sort']);
if ($sort == 'asc')
{
sort($data);
}
else if ($sort == 'desc')
{
rsort($data);
}
}
// offset and limit
if (isset($params['offset']) || isset($params['limit']))
{
$offset = isset($params['offset']) ? $params['offset'] : 0;
$limit = isset($params['limit']) ? $params['limit'] : count($data);
$data = array_splice($data, $offset, $limit);
}
// prepare for {switch} and {count} tags
$this->prep_iterators($tagdata);
foreach($data as $option_name)
{
if (($option = $this->_find_option($option_name, $this->settings['options'])) !== FALSE)
{
// copy $tagdata
$option_tagdata = $tagdata;
// simple var swaps
$option_tagdata = $this->EE->TMPL->swap_var_single('option', $option, $option_tagdata);
$option_tagdata = $this->EE->TMPL->swap_var_single('option_name', $option_name, $option_tagdata);
// parse {switch} and {count} tags
$this->parse_iterators($option_tagdata);
$r .= $option_tagdata;
}
}
if (isset($params['backspace']) && $params['backspace'])
{
$r = substr($r, 0, -$params['backspace']);
}
}
return $r;
}
// --------------------------------------------------------------------
/**
* Unordered List
*/
function replace_ul($data, $params = array())
{
return "<ul>\n"
. $this->replace_tag($data, $params, " <li>{option}</li>\n")
. '</ul>';
}
/**
* Ordered List
*/
function replace_ol($data, $params = array())
{
return "<ol>\n"
. $this->replace_tag($data, $params, " <li>{option}</li>\n")
. '</ol>';
}
// --------------------------------------------------------------------
/**
* All Options
*/
function replace_all_options($data, $params = array(), $tagdata = FALSE, $options = FALSE, $iterator_count = 0)
{
if (! $tagdata)
{
return "<ul>\n"
. $this->replace_all_options($data, $params, " <li>{option}</li>\n")
. "</ul>";
}
PT_Multi_Fieldtype::prep_field_data($data);
$r = '';
if ($options === FALSE)
{
$options = $this->settings['options'];
}
if ($options)
{
// optional sorting
if (isset($params['sort']) && $params['sort'])
{
$sort = strtolower($params['sort']);
if ($sort == 'asc')
{
asort($options);
}
else if ($sort == 'desc')
{
arsort($options);
}
}
// prepare for {switch} and {count} tags
$this->prep_iterators($tagdata);
$this->_iterator_count += $iterator_count;
foreach($options as $option_name => $option)
{
if (is_array($option))
{
$sub_params = array_merge($params, array('backspace' => '0'));
$r .= $this->replace_all_options($data, $sub_params, $tagdata, $option, $this->_iterator_count);
}
else
{
// copy $tagdata
$option_tagdata = $tagdata;
// simple var swaps
$option_tagdata = $this->EE->TMPL->swap_var_single('option', $option, $option_tagdata);
$option_tagdata = $this->EE->TMPL->swap_var_single('option_name', $option_name, $option_tagdata);
$option_tagdata = $this->EE->TMPL->swap_var_single('selected', (in_array($option_name, $data) ? 1 : 0), $option_tagdata);
// parse {switch} and {count} tags
$this->parse_iterators($option_tagdata);
$r .= $option_tagdata;
}
}
if (isset($params['backspace']) && $params['backspace'])
{
$r = substr($r, 0, -$params['backspace']);
}
}
return $r;
}
// --------------------------------------------------------------------
/**
* Is Selected?
*/
function replace_selected($data, $params = array())
{
$this->prep_field_data($data);
return (isset($params['option']) AND in_array($params['option'], $data)) ? 1 : 0;
}
/**
* Total Selections
*/
function replace_total_selections($data, $params = array())
{
$this->prep_field_data($data);
return $field_data ? (string) count($data) : '0';
}
}
The answer of your question is on line 148 of this file...
Maybe you are using a class with abstract methods without inheriting them that is rejected, make sure you implement all of them and after show us some code. ;-)

How to find bounced or undelivered mail id using PHP

I am sending a mail using PHP Mail Function
I just need to find the status of the mail whether it is delivered or Bounced
is there any possible way to solve this Problem
You can use return-path header with specific e-mail address - for example bounce#domain.com
After that all bounced (undelivered) e-mails would be returned to inbox for bounce#domain.com
You can connect to this pop3 inbox via PHP and read all messages.
Parse every messages and find (may be via regex) error code and reason...
I use this code:
$bounce = new BounceMail();
$bounce->setDebug(false);
//create connection
$bounce->createConnection('server', 110, 'user', 'password');
//parse messages
$bounce->parseMessages();
//save parsed messages to database
$messages = $bounce->getParsedMessages();
foreach ($messages as $message_id => $message) {
/* variable $message looks like:
$message = array(
'email_address' => 'email',
'bounce_type' => 'bounce type',
'smtp_server' => 'smtp_server',
'smtp_error' => 'smtp_error',
);
*/
//save returned email to database here
}
and BounceMail class:
<?php
/*
* Depends on 'Net/POP3.php';
*/
/**
* Class BounceMail
*/
class BounceMail extends Net_POP3
{
/**
* #var array
*/
private $messages = array();
/**
* #var array
*/
private $parsed_messages = array();
/**
* #var array
*/
private $partially_parsed_messages = array();
/**
* #var array
*/
private $allowed_email_domains = array();
/**
* #var array
*/
private $allowed_email_addresses = array();
/**
* #param $host
* #param $port
* #param $username
* #param $password
* #return bool
* #throws ErrorException
*/
public function createConnection($host, $port, $username, $password)
{
if (!$this->connect($host, $port)) {
Throw new ErrorException("Error connecting to POP3 socket.");
}
if (true !== ($login = $this->login($username, $password, true))) {
Throw new ErrorException("Login failed:" . $login->getMessage());
}
if (false === ($messages = $this->getListing())) {
Throw new ErrorException("Error getting POP3 box listing.");
} else {
$this->messages = $messages;
}
return true;
}
/**
* #return bool
*/
public function parseMessages()
{
$this->newDebugMessage('PARSING ' . count($this->messages) . ' MESSAGES');
$fully_parsed = 0;
foreach ($this->messages as $message) {
$parsed_message = $this->parseMessage($message);
$email_address = $this->getEmailAddress($parsed_message);
$smtp_error = $this->getSMTPError($parsed_message);
$smtp_server = $this->getSMTPServer($parsed_message);
$bounce_type = $this->getBounceType($smtp_error);
if ($this->checkAllowedContent($parsed_message)) {
$this->newParsedMessage($message['msg_id'], $email_address, $smtp_server, $smtp_error, $bounce_type);
if (!empty($email_address) && !empty($smtp_error) && !empty($smtp_server) && !empty($bounce_type)) {
$fully_parsed++;
} elseif (!empty($email_address) && (empty($smtp_error) || empty($smtp_server) || empty($bounce_type))) {
$this->newPartiallyParsedMessage($email_address, $parsed_message, array($smtp_error, $smtp_server, $bounce_type));
}
}
}
$this->newDebugMessage('SUCCESSFULLY PARSED ' . count($this->parsed_messages) . ' MESSAGES');
$this->newDebugMessage('EVERYTHING FOUND IN ' . $fully_parsed . ' MESSAGES');
return true;
}
/**
* #return array
*/
public function getParsedMessages()
{
return $this->parsed_messages;
}
/**
* #param bool $as_text
* #return array|string
*/
public function getPartiallyParsedMessages($as_text = true)
{
if ($as_text) {
$text = '';
foreach ($this->partially_parsed_messages as $message) {
foreach ($message as $data) {
$text .= $data . "\r\n";
}
$text .= "\r\n---------------\r\n\r\n";
}
return $text;
} else {
return $this->partially_parsed_messages;
}
}
/**
* #param array $domains
*/
public function setAllowedEmailDomains(array $domains)
{
$this->allowed_email_domains = $domains;
}
/**
* #param array $addresses
*/
public function setAllowedEmailAddresses(array $addresses)
{
$this->allowed_email_addresses = $addresses;
}
/**
* #param $message
* #return bool|string
*/
public function newDebugMessage($message)
{
if ($this->_debug) {
$trace = debug_backtrace();
$debug_message = !empty($trace) && isset($trace[1]["function"]) ? $trace[1]["function"] . ' | ' : '';
$debug_message .= !empty($trace) && isset($trace[1]["method"]) ? $trace[1]["method"] . ' | ' : '';
$debug_message .= $message . "\r\n";
echo $debug_message;
return $debug_message;
}
return false;
}
/**
* #param $parsed_message
* #return bool
*/
private function checkAllowedContent($parsed_message)
{
foreach ($parsed_message as $content) {
if (!$this->parseAllowedContent($content)) {
return false;
}
}
return true;
}
/**
* #param $content
* #return bool
*/
private function parseAllowedContent($content)
{
$patterns = array(
'SENDER POLICY FRAMEWORK' => '/(5.7.1\s*Sender\s*Policy\s*Framework)/im',
'TOO MANY HOPS' => '/too\s*many\s*hops/im',
'BLOCKED' => '/554\s*Blocked\s*by\s*Reputation\s*Enabled\s*Defense/im'
);
foreach ($patterns as $name => $pattern) {
$matches = array();
preg_match($pattern, $content, $matches);
if (isset($matches[1]) && !empty($matches[1])) {
$this->newDebugMessage('DISALLOWED CONTENT FOUND (' . $name . ')');
return false;
}
}
return true;
}
/**
* #param $message_id
* #param $email_address
* #param $smtp_server
* #param $smtp_error
* #param $bounce_type
* #return array|bool
*/
private function newParsedMessage($message_id, $email_address, $smtp_server, $smtp_error, $bounce_type)
{
if (!empty($message_id) && !empty($email_address)) {
return $this->parsed_messages[$message_id] = array('email_address' => $email_address, 'smtp_server' => $smtp_server, 'smtp_error' => $smtp_error, 'bounce_type' => $bounce_type);
}
return false;
}
/**
* #param $email_address
* #param array $parsed_message
* #param array $vars
* #return array|bool
*/
private function newPartiallyParsedMessage($email_address, array $parsed_message, array $vars = array())
{
$full_content = '';
foreach ($parsed_message as $content) {
$full_content .= $content . "\r\n";
}
if (!empty($email_address) && !empty($full_content)) {
if (!empty($vars)) {
foreach ($vars as $var) {
$full_content .= "\r\n" . $var . ' | ';
}
}
return $this->partially_parsed_messages[] = array($email_address, $full_content);
} else {
return false;
}
}
/**
* #param $message
* #return array|bool
*/
private function parseMessage($message)
{
if (empty($message)) {
$this->newDebugMessage('Empty message');
return false;
}
if (!$content = $this->getMsg($message['msg_id'])) {
$this->newDebugMessage('Error reading content of message :' . $message['msg_id'] . '/' . $message['uidl']);
}
//todo add attachments
if (!empty($content)) {
return array('content' => $content);
}
return false;
}
/**
* #param $parsed_message
* #return bool
*/
private function getEmailAddress($parsed_message)
{
if (empty($parsed_message)) {
$this->newDebugMessage('Empty parsed message');
return false;
}
$found_emails = array();
foreach ($parsed_message as $content) {
$found_emails = array_unique(array_merge($found_emails, $this->parseEmailAddress($content)));
}
if (count($found_emails) > 1) {
$this->newDebugMessage('More than one e-mail address found: ' . join('; ', $found_emails));
return false;
}
if (count($found_emails) == 1) {
$this->newDebugMessage('Found e-mail address: ' . $found_emails[0]);
return $found_emails[0];
}
$this->newDebugMessage('No e-mail address found');
return false;
}
/**
* #param $content
* #return array
*/
private function parseEmailAddress($content)
{
$email_patterns = array('/[^-]To:\s?<?([a-zA-Z0-9_.-]+#[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+)>?/i',);
$found_emails = array();
foreach ($email_patterns as $pattern) {
$matches = array();
preg_match_all($pattern, $content, $matches);
if (!empty($matches) && isset($matches[1])) {
$recipient_emails = $matches[1];
$recipient_emails = array_filter($recipient_emails, array($this, 'filter_allowed_domains'));
$recipient_emails = array_filter($recipient_emails, array($this, 'filter_allowed_addresses'));
if (!empty($recipient_emails)) {
$found_emails = array_unique(array_merge($found_emails, $recipient_emails));
}
}
}
return $found_emails;
}
/**
* #param $email
* #return bool
*/
private function filter_allowed_domains($email)
{
return !in_array(substr(strrchr($email, "#"), 1), $this->allowed_email_domains);
}
/**
* #param $email
* #return bool
*/
private function filter_allowed_addresses($email)
{
return !in_array($email, $this->allowed_email_addresses);
}
/**
* #param $smtp_error
* #return bool|int
*/
private function getBounceType($smtp_error)
{
if (empty($smtp_error)) {
$this->newDebugMessage('Empty smtp error');
return false;
}
$status = substr($smtp_error, 0, 1);
switch ($status) {
case 4:
return 1; //temporary
break;
case 5:
return 2; //permanent
break;
}
return false;
}
/**
* #param $parsed_message
* #return bool
*/
private function getSMTPServer($parsed_message)
{
if (empty($parsed_message)) {
$this->newDebugMessage('Empty parsed message');
return false;
}
$found = array();
foreach ($parsed_message as $content) {
$found = array_unique(array_merge($found, $this->parseSMTPServer($content)));
}
if (count($found) > 0) {
$server = substr(join('; ', $found), 0, 254);
$this->newDebugMessage('Found SMTP server: ' . $server);
return $server;
}
$this->newDebugMessage('No SMTP server found');
return false;
}
/**
* #param $content
* #return array
*/
private function parseSMTPServer($content)
{
$patterns = array('/remote-mta:\s?dns;\s?([^\s]*)/i', '/reporting-mta:\s?dns;\s?([^\s]*)/i', '/received-from-mta:\s?dns;\s?([^\s]*)/i');
$found_statuses = array();
foreach ($patterns as $pattern) {
$matches = array();
preg_match_all($pattern, $content, $matches);
if (!empty($matches) && isset($matches[1])) {
$found_statuses = array_unique(array_merge($found_statuses, $matches[1]));
}
}
return $found_statuses;
}
/**
* #param $parsed_message
* #return bool
*/
private function getSMTPError($parsed_message)
{
if (empty($parsed_message)) {
$this->newDebugMessage('Empty parsed message');
return false;
}
$found = array();
foreach ($parsed_message as $content) {
$found = array_unique(array_merge($found, $this->parseSMTPError($content)));
}
if (count($found) > 0) {
$error = substr(join('; ', $found), 0, 19);
$this->newDebugMessage('Found SMTP Error: ' . $error);
return $error;
}
$this->newDebugMessage('No SMTP Error found');
return false;
}
/**
* #param $content
* #return array
*/
private function parseSMTPError($content)
{
//replace errors with codes
$content = str_replace('User mailbox exceeds allowed size', ' 452 4.1.1 ', $content);
$content = str_replace('user is over quota', ' 452 4.1.1 ', $content);
//find error
$patterns = array(
'/status:\s?#?(\d\.\d\.\d)/i',
'/[\d]{3}\s#?(\d\.\d\.\d)/',
'/\(#(\d\.\d\.\d)\)/',
'/Remote SMTP Server Returned:\s?#?([\d]{3})/i',
);
$found_statuses = array();
foreach ($patterns as $pattern) {
$matches = array();
preg_match_all($pattern, $content, $matches);
if (!empty($matches) && isset($matches[1])) {
$found_statuses = array_unique(array_merge($found_statuses, $matches[1]));
}
}
return $found_statuses;
}
}
you should add more regulars into parseSMTPError

Categories