I got this class code from https://github.com/ricardotiago/sec-gov-api, which is used to retrieve and parse quarterly and yearly reports from the U.S Securities Exchange website.I do not understand how to print the results and what sort of parameters it's accepts. Is$sSmbol an input parameter, how do I pass this parameter so that it displays the quarterly and yearly report
<?php
require_once "parallelCurl.php";
class SecGovAPI {
const SEARCH_LINK = "http://www.sec.gov/cgi-bin/browse-edgar";
const BASE_LINK = "http://www.sec.gov/";
const QUARTERLY_REPORT = '10-Q';
const YEARLY_REPORT = '10-K';
const MOST_RECENT_REPORT = 0;
const ALL_REPORTS = 1;
public function __construct($sSymbol) {
$this->oParallelCurl = new ParallelCurl();
$this->sSymbol = $sSymbol;
$this->oDoc = new DOMDocument();
$this->report = array();
}
public function getQuaterlyReport($iSearchType = SecGovAPI::MOST_RECENT_REPORT) {
if ($iSearchType !== SecGovAPI::MOST_RECENT_REPORT && $iSearchType !== SecGovAPI::ALL_REPORTS) {
return array();
}
$aReportLinks = $this->search(SecGovAPI::QUARTERLY_REPORT, $iSearchType);
var_dump($aReportLinks);
foreach ($aReportLinks as $link) {
$this->oParallelCurl->addUrl(SecGovAPI::BASE_LINK."/".$link);
}
$aData = $this->oParallelCurl->run();
foreach ($aData as $link => $xml) {
$this->oDoc->loadXML($xml);
$oXPath = new DOMXPath($this->oDoc);
$oXPath->registerNamespace("xbrli", "http://www.xbrl.org/2003/instance");
$this->getReportData($oXPath, $link, "dei:EntityCommonStockSharesOutstanding", "CommonStockSharesOutstanding");
$this->getReportData($oXPath, $link, "us-gaap:NetIncomeLoss", "NetIncomeLoss");
}
var_dump($this->report);
}
public function getYearlyReport($iSearchType = SecGovAPI::MOST_RECENT_REPORT) {
if ($iSearchType !== SecGovAPI::MOST_RECENT_REPORT && $iSearchType !== SecGovAPI::ALL_REPORTS) {
return array();
}
$aReportLinks = $this->search(SecGovAPI::YEARLY_REPORT, $iSearchType);
var_dump($aReportLinks);
foreach ($aReportLinks as $link) {
$this->oParallelCurl->addUrl(SecGovAPI::BASE_LINK."/".$link);
}
$aData = $this->oParallelCurl->run();
foreach ($aData as $link => $xml) {
$this->oDoc->loadXML($xml);
$oXPath = new DOMXPath($this->oDoc);
$oXPath->registerNamespace("xbrli", "http://www.xbrl.org/2003/instance");
$this->getReportData($oXPath, $link, "dei:EntityCommonStockSharesOutstanding", "CommonStockSharesOutstanding");
$this->getReportData($oXPath, $link, "us-gaap:NetIncomeLoss", "NetIncomeLoss");
}
var_dump($this->report);
}
public function getReportData($oXPath, $link, $sEntity, $sSaveAs) {
$oNodelist = $oXPath->query("//xbrli:xbrl/".$sEntity);
for ($i = 0; $i < $oNodelist->length; $i++) {
$this->report[$link][$sSaveAs][$i] = $oNodelist->item($i)->nodeValue;
}
}
protected function search($sType, $iSearchType) {
$aParams = array("company" => "",
"match" => "",
"CIK" => $this->sSymbol,
"filenum" => "",
"State" => "",
"Country" => "",
"SIC" => "",
"count" => "40",
"owner" => "exclude",
"Find" => "Find Companies",
"action" => "getcompany",
"type" => $sType,
"output" => "atom");
$sUrl = SecGovAPI::SEARCH_LINK . "?". http_build_query($aParams);
$this->oDoc->load($sUrl);
$oXPath = new DOMXPath($this->oDoc);
$oXPath->registerNamespace("atom", "http://www.w3.org/2005/Atom");
$aLinks = $this->getReportLinks($oXPath, $iSearchType);
$aReportLinks = array();
foreach ($aLinks as $link) {
$this->oParallelCurl->addUrl($link);
}
$aHtmls = $this->oParallelCurl->run();
foreach ($aHtmls as $html) {
$this->oDoc->loadHTML($html);
$oXPath = new DOMXPath($this->oDoc);
$oNodeList = $oXPath->query('//table[#summary="Data Files"]/tr[2]/td[3]/a');
if ($oNodeList->length === 0) continue;
$aReportLinks[] = $oNodeList->item(0)->getAttribute("href");
}
return $aReportLinks;
}
protected function getReportLinks($oXPath, $iSearchType) {
if ($iSearchType === SecGovAPI::MOST_RECENT_REPORT) {
$aNodeList = $oXPath->query("//atom:feed/atom:entry[1]/atom:link");
if ($aNodeList->length === 1)
return array($aNodeList->item(0)->getAttribute("href"));
else
return null;
}
else if ($iSearchType === SecGovAPI::ALL_REPORTS) {
$aNodeList = $oXPath->query("//atom:feed/atom:entry/atom:link");
for ($i = 0; $i < $aNodeList->length; $i++) {
$aReportLinks[] = $aNodeList->item($i)->getAttribute("href");
}
return $aReportLinks;
}
else return null;
}
protected function getAccessionNumber($oXPath, $iSearchType) {
if ($iSearchType === SecGovAPI::MOST_RECENT_REPORT) {
$aNodeList = $oXPath->query("//atom:feed/atom:entry[1]/atom:id");
if ($aNodeList->length === 1) $sRawAccessNumber = $aNodeList->item(0)->nodeValue;
else return null;
return $this->processAccessionNumber($sRawAccessNumber);
}
else if ($iSearchType === SecGovAPI::ALL_REPORTS) {
$aNodeList = $oXPath->query("//atom:feed/atom:entry/atom:id");
for ($i = 0; $i < $aNodeList->length; $i++) {
$sRawAccessNumber = $aNodeList->item($i)->nodeValue;
$aAccessionNumber[] = $this->processAccessionNumber($sRawAccessNumber);
}
return $aAccessionNumber;
}
else return null;
}
protected function processAccessionNumber($sRawAccessNumber) {
$aSplitData = preg_split('/accession-number=/', $sRawAccessNumber);
if (!isset($aSplitData[1])) return null;
$sAccessionNumber = str_replace('-','', $aSplitData[1]);
return $sAccessionNumber;
}
protected function getReportDate($oXPath, $iSearchType) {
if ($iSearchType === SecGovAPI::MOST_RECENT_REPORT) {
$aNodeList = $oXPath->query("//atom:feed/atom:entry[1]/atom:updated");
if ($aNodeList->length === 1)
return $sUpdated = $aNodeList->item(0)->nodeValue;
else
return null;
}
else if ($iSearchType === SecGovAPI::ALL_REPORTS) {
$aNodeList = $oXPath->query("//atom:feed/atom:entry/atom:updated");
for ($i = 0; $i < $aNodeList->length; $i++) {
$aUpdated[] = $aNodeList->item($i)->nodeValue;
}
return $aUpdated;
}
else return null;
}
}
?>
parallelCurl.php
<?php
class ParallelCurl {
protected $aHandlers;
public function __construct() {
$this->aHandlers = array();
$this->rMultiHandler = curl_multi_init();
}
public function addUrl($sUrl) {
$rHandler = curl_init();
curl_setopt($rHandler, CURLOPT_URL, $sUrl);
curl_setopt($rHandler, CURLOPT_HEADER, 0);
curl_setopt($rHandler, CURLOPT_RETURNTRANSFER, 1);
curl_multi_add_handle($this->rMultiHandler, $rHandler);
$this->aHandlers[$sUrl] = $rHandler;
}
public function run() {
$blsRunning = null;
do {
$rHandler = curl_multi_exec($this->rMultiHandler, $blsRunning);
} while ($rHandler === CURLM_CALL_MULTI_PERFORM);
while ($blsRunning && $rHandler == CURLM_OK) {
if (curl_multi_select($this->rMultiHandler) != -1) {
do {
$rHandler = curl_multi_exec($this->rMultiHandler, $blsRunning);
} while ($rHandler == CURLM_CALL_MULTI_PERFORM);
}
}
foreach ($this->aHandlers as $url => $handler) {
$data[$url] = curl_multi_getcontent($handler);
curl_multi_remove_handle($this->rMultiHandler, $handler);
}
$this->aHandlers = array();
return $data;
}
public function __destruct() {
curl_multi_close($this->rMultiHandler);
}
}
?>
To create an instance of the SecGovAPI class you can use the new keyword:
$class = new SecGovAPI($sSymbol);
then you can call the methods getQuaterlyReport and getYearlyReport with:
echo $class->getQuaterlyReport();
echo $class->getYearlyReport();
Both these methods has an argument, and by default is SecGovAPI::MOST_RECENT_REPORT. You can also use:
SecGovAPI::QUARTERLY_REPORT
SecGovAPI::YEARLY_REPORT
SecGovAPI::ALL_REPORTS
Example:
echo $class->getQuaterlyReport(SecGovAPI::QUARTERLY_REPORT);
Related
If i have a listnode with the following defination
class ListNode {
public $val = 0;
public $next = null;
function __construct($val = 0, $next = null) {
$this->val = $val;
$this->next = $next;
}
}
How can i add an element to the end of the listnode and thus add int[i] elements by interation?
class ListNode {
public int $val = 0;
public ?ListNode $next = null;
function __construct(?int $val = 0, ?ListNode $next = null) {
$this->val = $val;
$this->next = $next;
}
function appendToListEnd(int $val) {
if ($this->next == null) {
$this->next = new ListNode($val);
} else {
$temp = $this->next;
while ($temp->next != null) {
$temp = $temp->next;
}
$temp->next = new ListNode($val);
}
}
}
$arr = [ 1, 2, 3, 4 ];
$listHead = new ListNode($arr[0]);
for ($i = 1; $i < count($arr); $i++) {
$listHead->appendToListEnd($arr[$i]);
}
print_r($listHead);
$listHead->appendToListEnd(5);
print_r($listHead);
PLease Help me,
I have this errors
Warning: Illegal string offset 'formId' in
C:\xampp\htdocs\wp-content\plugins\repeater-add-on-for-gravity-forms\class-gf-field-repeater.php
on line 287
Warning: Illegal string offset 'children' in
C:\xampp\htdocs\wp-content\plugins\repeater-add-on-for-gravity-forms\class-gf-field-repeater.php
on line 291
...
if (empty($value)) {
$value['formId'] = $form_id;
if (!empty($repeater_start)) { $value['start'] = $repeater_start; }
if (!empty($repeater_min)) { $value['min'] = $repeater_min; }
if (!empty($repeater_max)) { $value['max'] = $repeater_max; }
if (!empty($repeater_children)) { $value['children'] = $repeater_children; }
$value = json_encode($value);
}
...
Hi I solved adding $value = array() in line 287.
if (empty($value)) {
$value = array();
$value['formId'] = $form_id;
if (!empty($repeater_start)) { $value['start'] = $repeater_start; }
if (!empty($repeater_min)) { $value['min'] = $repeater_min; }
if (!empty($repeater_max)) { $value['max'] = $repeater_max; }
if (!empty($repeater_children)) { $value['children'] = $repeater_children; }
$value = json_encode($value);
}
That's work for me, I hope it could help you.
<?php
class GF_Field_Repeater extends GF_Field {
public $type = 'repeater';
public static function init_admin() {
$admin_page = rgget('page');
if ($admin_page == 'gf_edit_forms' && !empty($_GET['id'])) {
add_action('gform_field_standard_settings' , array('GF_Field_Repeater', 'gform_standard_settings'), 10, 2);
add_action('gform_field_appearance_settings' , array('GF_Field_Repeater', 'gform_appearance_settings'), 10, 2);
add_action('gform_editor_js_set_default_values', array('GF_Field_Repeater', 'gform_set_defaults'));
add_action('gform_editor_js', array('GF_Field_Repeater', 'gform_editor'));
add_filter('gform_tooltips', array('GF_Field_Repeater', 'gform_tooltips'));
}
if ($admin_page == 'gf_entries') {
add_filter('gform_form_post_get_meta', array('GF_Field_Repeater', 'gform_hide_children'));
}
}
public static function init_frontend() {
add_action('gform_form_args', array('GF_Field_Repeater', 'gform_disable_ajax'));
add_action('gform_enqueue_scripts', array('GF_Field_Repeater', 'gform_enqueue_scripts'), 10, 2);
add_filter('gform_pre_render', array('GF_Field_Repeater', 'gform_unhide_children_validation'));
add_filter('gform_pre_validation', array('GF_Field_Repeater', 'gform_bypass_children_validation'));
}
public static function gform_enqueue_scripts($form, $is_ajax) {
if (!empty($form)) {
if (GF_Field_Repeater::get_field_index($form) !== false) {
wp_enqueue_script('gforms_repeater_postcapture_js', plugins_url('js/jquery.postcapture.min.js', __FILE__), array('jquery'), '0.0.1');
wp_enqueue_script('gforms_repeater_js', plugins_url('js/gf-repeater.min.js', __FILE__), array('jquery'), GF_REPEATER_VERSION);
wp_enqueue_style('gforms_repeater_css', plugins_url('css/gf-repeater.css', __FILE__), array(), GF_REPEATER_VERSION);
}
}
}
public function get_form_editor_field_title() {
return 'Repeater';
}
public function get_form_editor_field_settings() {
return array(
'admin_label_setting',
'css_class_setting',
'description_setting',
'error_message_setting',
'label_setting',
'prepopulate_field_setting'
);
}
public static function gform_set_defaults() {
echo "
case \"repeater\" :
field.label = \"Repeater\";
break;
";
}
public static function gform_standard_settings($position, $form_id) {
if ($position == 1600) {
echo "<li class=\"repeater_settings field_setting\">
<label for=\"field_repeater_start\">Start ";
gform_tooltip('form_field_repeater_start');
echo " </label>
<input type=\"number\" id=\"field_repeater_start\" min=\"1\" value=\"1\" onchange=\"SetFieldProperty('start', this.value);\">
</li>";
echo "<li class=\"repeater_settings field_setting\">
<label for=\"field_repeater_min\">Min ";
gform_tooltip('form_field_repeater_min');
echo " </label>
<input type=\"number\" id=\"field_repeater_min\" min=\"1\" value=\"1\" onchange=\"SetFieldProperty('min', this.value);\">
</li>";
echo "<li class=\"repeater_settings field_setting\">
<label for=\"field_repeater_max\">Max ";
gform_tooltip('form_field_repeater_max');
echo " </label>
<input type=\"number\" id=\"field_repeater_max\" min=\"1\" onchange=\"SetFieldProperty('max', this.value);\">
</li>";
}
}
public static function gform_appearance_settings($position, $form_id) {
if ($position == 400) {
echo "<li class=\"repeater_settings field_setting\">
<input type=\"checkbox\" id=\"field_repeater_hideLabel\" onchange=\"SetFieldProperty('hideLabel', this.checked);\">
<label for=\"field_repeater_hideLabel\" class=\"inline\">Hide Label & Description ";
gform_tooltip('form_field_repeater_hideLabel');
echo " </label>
</li>";
}
}
public static function gform_editor() {
echo "<script type=\"text/javascript\">
fieldSettings['repeater'] += ', .repeater_settings';
jQuery(document).bind('gform_load_field_settings', function(event, field, form){
jQuery('#field_repeater_start').val(field['start']);
jQuery('#field_repeater_min').val(field['min']);
jQuery('#field_repeater_max').val(field['max']);
jQuery('#field_repeater_hideLabel').prop('checked', field['hideLabel']);
});
</script>";
}
public static function gform_tooltips($tooltips) {
$tooltips['form_field_repeater_start'] = "The number of times the repeater will be repeated when the form is rendered. Leaving this field blank or setting it to a number higher than the maximum number is the same as setting it to 1.";
$tooltips['form_field_repeater_min'] = "The minimum number of times the repeater is allowed to be repeated. Leaving this field blank or setting it to a number higher than the maximum field is the same as setting it to 1.";
$tooltips['form_field_repeater_max'] = "The maximum number of times the repeater is allowed to be repeated. Leaving this field blank or setting it to a number lower than the minimum field is the same as setting it to unlimited.";
$tooltips['form_field_repeater_hideLabel'] = "If this is checked, the repeater label and description will not be shown to users on the form.";
return $tooltips;
}
function validate($value, $form) {
$repeater_required = $this->repeaterRequiredChildren;
if (!empty($repeater_required)) {
$dataArray = json_decode($value, true);
foreach ($form['fields'] as $key=>$value) {
$fieldKeys[$value['id']] = $key;
if (is_array($value['inputs'])) {
foreach ($value['inputs'] as $inputKey=>$inputValue) {
$inputKeys[$value['id']][$inputValue['id']] = $inputKey;
}
}
}
if ($dataArray['repeatCount'] < $this->min) {
$this->failed_validation = true;
$this->validation_message = "A minimum number of ".$this->min." is required.";
return;
}
if ($this->max && $dataArray['repeatCount'] > $this->max) {
$this->failed_validation = true;
$this->validation_message = "A maximum number of ".$this->max." is allowed.";
return;
}
for ($i = 1; $i < $dataArray['repeatCount'] + 1; $i++) {
foreach ($dataArray['children'] as $field_id=>$field) {
$inputNames = $field['inputs'];
$repeatSkips = $field['conditionalLogic']['skip'];
if (!is_array($inputNames)) { continue; }
if (is_array($repeatSkips)) {
if (in_array($i, $repeatSkips) || in_array('all', $repeatSkips)) { continue; }
}
foreach ($inputNames as $inputName) {
if (is_array($inputName)) { $inputName = reset($inputName); }
if (substr($inputName, -2) == '[]') {
$getInputName = substr($inputName, 0, strlen($inputName) - 2).'-'.$dataArray['repeaterId'].'-'.$i;
} else {
$getInputName = $inputName.'-'.$dataArray['repeaterId'].'-'.$i;
}
$getInputName = str_replace('.', '_', strval($getInputName));
$getInputData = rgpost($getInputName);
$getInputIdNum = preg_split("/(_|-)/", $getInputName);
if (in_array($getInputIdNum[1], $repeater_required)) {
$fieldKey = $fieldKeys[$getInputIdNum[1]];
$fieldType = $form['fields'][$fieldKey]['type'];
$failedValidation = false;
switch($fieldType) {
case 'name':
$requiredIDs = array(3, 6);
if (in_array($getInputIdNum[2], $requiredIDs) && empty($getInputData)) { $failedValidation = true; }
break;
case 'address':
$skipIDs = array(2);
if (!in_array($getInputIdNum[2], $skipIDs) && empty($getInputData)) { $failedValidation = true; }
break;
default:
if (empty($getInputData)) { $failedValidation = true; }
}
if ($failedValidation) {
$this->failed_validation = true;
if ($this->errorMessage) { $this->validation_message = $this->errorMessage; } else { $this->validation_message = "A required field was left blank."; }
return;
}
}
}
}
}
}
}
public function get_field_content($value, $force_frontend_label, $form) {
if (is_admin()) {
$admin_buttons = $this->get_admin_buttons();
$field_content = "{$admin_buttons}
<div class=\"gf-pagebreak-first gf-pagebreak-container gf-repeater gf-repeater-start\">
<div class=\"gf-pagebreak-text-before\">begin repeater</div>
<div class=\"gf-pagebreak-text-main\"><span>REPEATER</span></div>
<div class=\"gf-pagebreak-text-after\">top of repeater</div>
</div>";
} else {
$field_label = $this->get_field_label($force_frontend_label, $value);
$description = $this->get_description($this->description, 'gsection_description gf_repeater_description');
$hide_label = $this->hideLabel;
$validation_message = ( $this->failed_validation && ! empty( $this->validation_message ) ) ? sprintf( "<div class='gfield_description validation_message'>%s</div>", $this->validation_message ) : '';
if (!empty($field_label)) { $field_label = "<h2 class='gf_repeater_title'>{$field_label}</h2>"; } else { $field_label = ''; }
if ($hide_label) { $field_label = ''; $description = ''; }
$field_content = "<div class=\"ginput_container ginput_container_repeater\">{$field_label}{FIELD}</div>{$description}{$validation_message}";
}
return $field_content;
}
public function get_field_input($form, $value = '', $entry = null) {
if (is_admin()) {
return '';
} else {
$form_id = $form['id'];
$is_entry_detail = $this->is_entry_detail();
$is_form_editor = $this->is_form_editor();
$id = (int) $this->id;
$field_id = $is_entry_detail || $is_form_editor || $form_id == 0 ? "input_$id" : 'input_' . $form_id . "_$id";
$tabindex = $this->get_tabindex();
$repeater_parem = $this->inputName;
$repeater_start = $this->start;
$repeater_min = $this->min;
$repeater_max = $this->max;
$repeater_required = $this->repeaterRequiredChildren;
$repeater_children = $this->repeaterChildren;
if (!empty($repeater_parem)) {
$repeater_parem_value = GFFormsModel::get_parameter_value($repeater_parem, $value, $this);
if (!empty($repeater_parem_value)) { $repeater_start = $repeater_parem_value; }
}
if (!empty($repeater_children)) {
$repeater_children_info = array();
$repeater_parems = GF_Field_Repeater::get_children_parem_values($form, $repeater_children);
foreach($repeater_children as $repeater_child) {
$repeater_children_info[$repeater_child] = array();
$repeater_child_field_index = GF_Field_Repeater::get_field_index($form, 'id', $repeater_child);
if (!empty($repeater_required)) {
if (in_array($repeater_child, $repeater_required)) {
$repeater_children_info[$repeater_child]['required'] = true;
}
}
if (!empty($repeater_parems)) {
if (array_key_exists($repeater_child, $repeater_parems)) {
$repeater_children_info[$repeater_child]['prePopulate'] = $repeater_parems[$repeater_child];
}
}
if ($repeater_child_field_index !== false) {
if ($form['fields'][$repeater_child_field_index]['inputMask']) {
$repeater_children_info[$repeater_child]['inputMask'] = $form['fields'][$repeater_child_field_index]['inputMaskValue'];
} elseif ($form['fields'][$repeater_child_field_index]['type'] == 'phone' && $form['fields'][$repeater_child_field_index]['phoneFormat'] = 'standard') {
$repeater_children_info[$repeater_child]['inputMask'] = "(999) 999-9999";
}
if ($form['fields'][$repeater_child_field_index]['conditionalLogic']) {
$repeater_children_info[$repeater_child]['conditionalLogic'] = $form['fields'][$repeater_child_field_index]['conditionalLogic'];
}
}
}
$repeater_children = $repeater_children_info;
}
if (empty($value)) {
$value['formId'] = $form_id;
if (!empty($repeater_start)) { $value['start'] = $repeater_start; }
if (!empty($repeater_min)) { $value['min'] = $repeater_min; }
if (!empty($repeater_max)) { $value['max'] = $repeater_max; }
if (!empty($repeater_children)) { $value['children'] = $repeater_children; }
$value = json_encode($value);
}
return sprintf("<input name='input_%d' id='%s' type='hidden' class='gform_repeater' value='%s' %s />", $id, $field_id, $value, $tabindex);
}
}
public function get_value_save_entry($value, $form, $input_name, $lead_id, $lead) {
$dataArray = json_decode($value, true);
$value = Array();
for ($i = 1; $i < $dataArray['repeatCount'] + 1; $i++) {
foreach ($dataArray['children'] as $field_id=>$field) {
$inputData = Array();
if (array_key_exists('inputs', $field)) {
$inputNames = $field['inputs'];
$repeatSkips = $field['conditionalLogic']['skip'];
if (is_array($repeatSkips)) {
if (in_array($i, $repeatSkips) || in_array('all', $repeatSkips)) { continue; }
}
if (is_array($inputNames)) {
foreach ($inputNames as $inputName) {
if (substr($inputName, -2) == '[]') {
$getInputName = substr($inputName, 0, strlen($inputName) - 2).'-'.$dataArray['repeaterId'].'-'.$i;
} else {
$getInputName = $inputName.'-'.$dataArray['repeaterId'].'-'.$i;
}
$getInputData = rgpost(str_replace('.', '_', strval($getInputName)));
if (!empty($getInputData)) {
if (is_array($getInputData)) {
foreach ($getInputData as $theInputData) {
$inputData[] = $theInputData;
}
} else {
$inputData[] = $getInputData;
}
}
}
}
} else {
if (GF_Field_Repeater::get_field_type($form, $field_id) == 'section') { $inputData = '[gfRepeater-section]'; }
}
$childValue[$field_id] = $inputData;
}
$value[$i] = $childValue;
}
return maybe_serialize($value);
}
public function get_value_entry_list($value, $entry, $field_id, $columns, $form) {
if (empty($value)) {
return '';
} else {
$dataArray = GFFormsModel::unserialize($value);
$arrayCount = count($dataArray);
if ($arrayCount > 1) { $returnText = $arrayCount.' entries'; } else { $returnText = $arrayCount.' entry'; }
return $returnText;
}
}
public function get_value_entry_detail($value, $currency = '', $use_text = false, $format = 'html', $media = 'screen') {
if (empty($value)) {
return '';
} else {
$dataArray = GFFormsModel::unserialize($value);
$arrayCount = count($dataArray);
$output = "\n";
$count = 0;
$repeatCount = 0;
$display_empty_fields = rgget('gf_display_empty_fields', $_COOKIE);
$form_id = $this->formId;
$get_form = GFFormsModel::get_form_meta_by_id($form_id);
$form = $get_form[0];
foreach ($dataArray as $key=>$value) {
$repeatCount++;
$tableContents = '';
if (!empty($value) && !is_array($value)) {
$save_value = $value;
unset($value);
$value[0] = $save_value;
}
foreach ($value as $childKey=>$childValue) {
$count++;
$childValueOutput = '';
if (empty($display_empty_fields) && count($childValue) == 0) { continue; }
if (is_numeric($childKey)) {
$field_index = GF_Field_Repeater::get_field_index($form, 'id', $childKey);
if ($field_index === false) { continue; }
$entry_title = $form['fields'][$field_index]['label'];
} else {
$entry_title = $childKey;
}
$entry_title = str_replace('[gfRepeater-count]', $repeatCount, $entry_title);
if ($format == 'html') {
if ($childValue == '[gfRepeater-section]') {
if ($media == 'email') {
$tableStyling = ' style="font-size:14px;font-weight:bold;background-color:#eee;border-bottom:1px solid #dfdfdf;padding:7px 7px"';
} else {
$tableStyling = ' class="entry-view-section-break"';
}
} else {
if ($media == 'email') {
$tableStyling = ' style="background-color:#EAF2FA;font-family:sans-serif;font-size:12px;font-weight:bold"';
} else {
$tableStyling = ' class="entry-view-field-name"';
}
}
$tableContents .= "<tr>\n<td colspan=\"2\"".$tableStyling.">".$entry_title."</td>\n</tr>\n";
} else {
$tableContents .= $entry_title.": ";
}
if (is_array($childValue)) {
if (count($childValue) == 1) {
$childValueOutput = $childValue[0];
} elseif (count($childValue) > 1) {
if ($format == 'html') {
if ($media == 'email') {
$childValueOutput = "<ul style=\"list-style:none;margin:0;padding:0;\">\n";
} else {
$childValueOutput = "<ul>\n";
}
}
foreach ($childValue as $childValueData) {
if ($format == 'html') {
$childValueOutput .= "<li>".$childValueData."</li>";
} else {
$childValueOutput .= $childValueData."\n";
}
}
if ($format == 'html') { $childValueOutput .= "</ul>\n"; }
}
if ($media == 'email') { $tableStyling = ''; } else { $tableStyling = ' class=\"entry-view-field-value\"'; }
if ($format == 'html') {
$tableContents .= "<tr>\n<td colspan=\"2\"".$tableStyling.">".$childValueOutput."</td>\n</tr>\n";
} else {
$tableContents .= $childValueOutput."\n";
}
}
}
if (!empty($tableContents)) {
if ($format == 'html') {
if ($media == 'email') { $tableStyling = ' width="100%" border="0" cellpadding="5" bgcolor="#FFFFFF"'; } else { $tableStyling = ' class="widefat fixed entry-detail-view"'; }
$output .= "<table cellspacing=\"0\"".$tableStyling.">\n";
$output .= $tableContents;
$output .= "</table>\n";
} else {
$output .= $tableContents."\n";
}
}
}
}
if ($count !== 0) {
if ($format == 'text') { $output = rtrim($output); }
return $output;
} else { return ''; }
}
public function get_value_merge_tag($value, $input_id, $entry, $form, $modifier, $raw_value, $url_encode, $esc_html, $format, $nl2br) {
$output = GF_Field_Repeater::get_value_entry_detail($raw_value, '', false, $format, 'email');
$output = preg_replace("/[\r\n]+/", "\n", $output);
return trim($output);
}
public function get_value_export($entry, $input_id = '', $use_text = false, $is_csv = false) {
if (empty($input_id)) { $input_id = $this->id; }
$output = rgar($entry, $input_id);
$output = GF_Field_Repeater::get_value_entry_detail($output, '', false, 'text', 'email');
$output = preg_replace("/[\r\n]+/", ", ", trim($output));
return $output;
}
public static function gform_hide_children($form) {
$form_id = $form['id'];
$repeaterChildren = Array();
$grid_modified = false;
$grid_meta = GFFormsModel::get_grid_column_meta($form_id);
foreach($form['fields'] as $key=>$field) {
if ($field->type == 'repeater') {
if (is_array($field->repeaterChildren)) { $repeaterChildren = array_merge($repeaterChildren, $field->repeaterChildren); }
} elseif ($field->type == 'repeater-end') { array_push($repeaterChildren, $field->id); }
if (!empty($repeaterChildren)) {
if (in_array($field->id, $repeaterChildren)) {
unset($form['fields'][$key]);
if (is_array($grid_meta)) {
$grid_pos = array_search($field->id, $grid_meta);
if ($grid_pos) {
$grid_modified = true;
unset($grid_meta[$grid_pos]);
}
}
}
}
}
if ($grid_modified) { GFFormsModel::update_grid_column_meta($form_id, $grid_meta); }
$form['fields'] = array_values($form['fields']);
return $form;
}
public static function gform_disable_ajax($args) {
$get_form = GFFormsModel::get_form_meta_by_id($args['form_id']);
$form = reset($get_form);
if (GF_Field_Repeater::get_field_index($form) !== false) {
$args['ajax'] = false;
}
return $args;
}
public static function gform_bypass_children_validation($form) {
if (GF_Field_Repeater::get_field_index($form) === false) { return $form; }
$repeaterChildren = Array();
foreach($form['fields'] as $key=>$field) {
if ($field->type == 'repeater') {
if (is_array($field->repeaterChildren)) { $repeaterChildren = array_merge($repeaterChildren, $field->repeaterChildren); }
}
if (!empty($repeaterChildren)) {
if (in_array($field->id, $repeaterChildren) && !$field->adminOnly) {
$form['fields'][$key]['adminOnly'] = true;
$form['fields'][$key]['repeaterChildValidationHidden'] = true;
}
}
}
return $form;
}
public static function gform_unhide_children_validation($form) {
if (GF_Field_Repeater::get_field_index($form) === false) { return $form; }
foreach($form['fields'] as $key=>$field) {
if ($field->repeaterChildValidationHidden) {
$form['fields'][$key]['adminOnly'] = false;
$form['fields'][$key]['repeaterChildValidationHidden'] = false;
}
}
return $form;
}
public static function get_field_index($form, $key = 'type', $value = 'repeater') {
if (is_array($form)) {
if (!array_key_exists('fields', $form)) { return false; }
} else { return false; }
foreach ($form['fields'] as $field_key=>$field_value) {
if (is_object($field_value)) {
if (property_exists($field_value, $key)) {
if ($field_value[$key] == $value) { return $field_key; }
}
}
}
return false;
}
public static function get_field_type($form, $id) {
$field_index = GF_Field_Repeater::get_field_index($form, 'id', $id);
if ($field_index !== false) { return $form['fields'][$field_index]['type']; }
return false;
}
public static function get_children_parems($form, $children_ids) {
foreach($form['fields'] as $key=>$value) {
if (in_array($value['id'], $children_ids)) {
if ($value['inputName']) {
$parems[$value['id']] = $value['inputName'];
} elseif ($value['inputs']) {
foreach($value['inputs'] as $key=>$value) {
if ($value['name']) { $parems[$value['id']] = $value['name']; }
}
}
}
}
if (!empty($parems)) { return $parems; } else { return false; }
}
public static function get_children_parem_values($form, $children_ids) {
global $wp_filter;
$children_parems = GF_Field_Repeater::get_children_parems($form, $children_ids);
if (empty($children_parems)) { return false; }
// Check the URL first
foreach($_GET as $url_key=>$url_value) {
$key = array_search($url_key, $children_parems);
if ($key !== false) {
$parems[$key][0] = $url_value;
} else {
$split_key = preg_split('/\D+\K/', $url_key);
$key = array_search($split_key[0], $children_parems);
if ($key !== false) { $parems[$key][$split_key[1]] = $url_value; }
}
}
// Then check the filters
foreach($wp_filter as $key=>$value) {
$split_key = preg_split('/^gform_field_value_+\K/', $key);
if (!empty($split_key[1])) {
$key1 = array_search($split_key[1], $children_parems);
if ($key1 !== false) {
$parems[$key1][0] = apply_filters($key, '');
} else {
$split_key2 = preg_split('/\D+\K/', $split_key[1]);
$key2 = array_search($split_key2[0], $children_parems);
if ($key2 !== false) { $parems[$key2][$split_key2[1]] = apply_filters($key, ''); }
}
}
}
if (!empty($parems)) { return $parems; } else { return false; }
}
}
GF_Fields::register(new GF_Field_Repeater());
I am using the PHP imap function to get emails from a POP3 mailbox and insert the data into a MySQL database.
Here is the PHP code:
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect: ' . imap_last_error());
$emails = imap_search($inbox,'ALL');
if($emails)
{
$output = '';
rsort($emails);
foreach($emails as $email_number)
{
$header=imap_headerinfo($inbox,$email_number);
$from = $header->from[0]->mailbox . "#" . $header->from[0]->host;
$toaddress=$header->toaddress;
$replyto=$header->reply_to[0]->mailbox."#".$header->reply_to[0]->host;
$datetime=date("Y-m-d H:i:s",$header->udate);
$subject=$header->subject;
//remove the " from the $toaddress
$toaddress = str_replace('"','',$toaddress);
echo '<strong>To:</strong> '.$toaddress.'<br>';
echo '<strong>From:</strong> '.$from.'<br>';
echo '<strong>Subject:</strong> '.$subject.'<br>';
//get message body
$message = (imap_fetchbody($inbox,$email_number,1.1));
if($message == '')
{
$message = (imap_fetchbody($inbox,$email_number,1));
}
}
It works fine, however on some emails in the body I get = in between words, or =20 in between words. And other times the emails will just be blank even though they are not blank when sent.
This only happens when coming from certain emails.
How can I get round this and just make the email completely plain text?
This happens because the emails are normally Quoted-printable encoded. The = is a soft line break and =20 is a white space. I think, you could use quoted_printable_decode() on the message so it shows correctly. About the blank emails, I don't know, I would need more details.
Basically:
//get message body
$message = quoted_printable_decode(imap_fetchbody($inbox,$email_number,1.1));
$data = imap_fetchbody($this->imapStream, $Part->uid, $Part->path, FT_UID | FT_PEEK);
if ($Part->format === 'quoted-printable' && $data) {
$data = quoted_printable_decode($data);
}
This is required for mails with
Content-Transfer-Encoding: quoted-printable
But for mails with
Content-Transfer-Encoding: 8bit
simply imap_fetchbody is enough.
Above code was taken from a cake-php component created for fetching mails from mail boxes throgh IMAP.
I made an entire class some years ago, and I'm still using it when I need to get contents from emails. It will help you fetch all email bodies (sometimes you have html and plain text) in a readable format, and get all attached files, just ready to be saved somewhere or sent to a website user.
It is not really optimized so on a big mailbox you may have troubles; but the purpose of this class was to access emails in a readable format to put them on a widget of a website. I let you play with the sample below to get how it works.
ImapReader.class.php Here is the source code.
<?php
class ImapReader
{
private $host;
private $port;
private $user;
private $pass;
private $box;
private $box_list;
private $errors;
private $connected;
private $list;
private $deleted;
const FROM = 0;
const TO = 1;
const REPLY_TO = 2;
const SUBJECT = 3;
const CONTENT = 4;
const ATTACHMENT = 5;
public function __construct($host = null, $port = '143', $user = null, $pass = null)
{
$this->host = $host;
$this->port = $port;
$this->user = $user;
$this->pass = $pass;
$this->box = null;
$this->box_list = null;
$this->errors = array ();
$this->connected = false;
$this->list = null;
$this->deleted = false;
}
public function __destruct()
{
if ($this->isConnected())
{
$this->disconnect();
}
}
public function changeServer($host = null, $port = '143', $user = null, $pass = null)
{
if ($this->isConnected())
{
$this->disconnect();
}
$this->host = $host;
$this->port = $port;
$this->user = $user;
$this->pass = $pass;
$this->box_list = null;
$this->errors = array ();
$this->list = null;
return $this;
}
public function canConnect()
{
return (($this->connected == false) && (is_string($this->host)) && (!empty($this->host))
&& (is_numeric($this->port)) && ($this->port >= 1) && ($this->port <= 65535)
&& (is_string($this->user)) && (!empty($this->user)) && (is_string($this->pass)) && (!empty($this->pass)));
}
public function connect()
{
if ($this->canConnect())
{
$this->box = #imap_open("{{$this->host}:{$this->port}/imap/ssl/novalidate-cert}INBOX", $this->user,
$this->pass);
if ($this->box !== false)
{
$this->_connected();
}
else
{
$this->errors = array_merge($this->errors, imap_errors());
}
}
return $this;
}
public function boxList()
{
if (is_null($this->box_list))
{
$list = imap_getsubscribed($this->box, "{{$this->host}:{$this->port}}", "*");
$this->box_list = array ();
foreach ($list as $box)
{
$this->box_list[] = $box->name;
}
}
return $this->box_list;
}
public function fetchAllHeaders($mbox)
{
if ($this->isConnected())
{
$test = imap_reopen($this->box, "{$mbox}");
if (!$test)
{
return false;
}
$num_msgs = imap_num_msg($this->box);
$this->list = array ();
for ($id = 1; ($id <= $num_msgs); $id++)
{
$this->list[] = $this->_fetchHeader($mbox, $id);
}
return true;
}
return false;
}
public function fetchSearchHeaders($mbox, $criteria)
{
if ($this->isConnected())
{
$test = imap_reopen($this->box, "{$mbox}");
if (!$test)
{
return false;
}
$msgs = imap_search($this->box, $criteria);
if ($msgs)
{
foreach ($msgs as $id)
{
$this->list[] = $this->_fetchHeader($mbox, $id);
}
}
return true;
}
return false;
}
public function isConnected()
{
return $this->connected;
}
public function disconnect()
{
if ($this->connected)
{
if ($this->deleted)
{
imap_expunge($this->box);
$this->deleted = false;
}
imap_close($this->box);
$this->connected = false;
$this->box = null;
}
return $this;
}
/**
* Took from khigashi dot oang at gmail dot com at php.net
* with replacement of ereg family functions by preg's ones.
*
* #param string $str
* #return string
*/
private function _fix($str)
{
if (preg_match("/=\?.{0,}\?[Bb]\?/", $str))
{
$str = preg_split("/=\?.{0,}\?[Bb]\?/", $str);
while (list($key, $value) = each($str))
{
if (preg_match("/\?=/", $value))
{
$arrTemp = preg_split("/\?=/", $value);
$arrTemp[0] = base64_decode($arrTemp[0]);
$str[$key] = join("", $arrTemp);
}
}
$str = join("", $str);
}
if (preg_match("/=\?.{0,}\?Q\?/", $str))
{
$str = quoted_printable_decode($str);
$str = preg_replace("/=\?.{0,}\?[Qq]\?/", "", $str);
$str = preg_replace("/\?=/", "", $str);
}
return trim($str);
}
private function _connected()
{
$this->connected = true;
return $this;
}
public function getErrors()
{
$errors = $this->errors;
$this->errors = array ();
return $errors;
}
public function count()
{
if (is_null($this->list))
{
return 0;
}
return count($this->list);
}
public function get($nbr = null)
{
if (is_null($nbr))
{
return $this->list;
}
if ((is_array($this->list)) && (isset($this->list[$nbr])))
{
return $this->list[$nbr];
}
return null;
}
public function fetch($nbr = null)
{
return $this->_callById('_fetch', $nbr);
}
private function _fetchHeader($mbox, $id)
{
$header = imap_header($this->box, $id);
if (!is_object($header))
{
return;
}
$mail = new stdClass();
$mail->id = $id;
$mail->mbox = $mbox;
$mail->timestamp = (isset($header->udate)) ? ($header->udate) : ('');
$mail->date = date("d/m/Y H:i:s", (isset($header->udate)) ? ($header->udate) : (''));
$mail->from = $this->_fix(isset($header->fromaddress) ? ($header->fromaddress) : (''));
$mail->to = $this->_fix(isset($header->toaddress) ? ($header->toaddress) : (''));
$mail->reply_to = $this->_fix(isset($header->reply_toaddress) ? ($header->reply_toaddress) : (''));
$mail->subject = $this->_fix(isset($header->subject) ? ($header->subject) : (''));
$mail->content = array ();
$mail->attachments = array ();
$mail->deleted = false;
return $mail;
}
private function _fetch($mail)
{
$test = imap_reopen($this->box, "{$mail->mbox}");
if (!$test)
{
return $mail;
}
$structure = imap_fetchstructure($this->box, $mail->id);
if ((!isset($structure->parts)) || (!is_array($structure->parts)))
{
$body = imap_body($this->box, $mail->id);
$content = new stdClass();
$content->type = 'content';
$content->mime = $this->_fetchType($structure);
$content->charset = $this->_fetchParameter($structure->parameters, 'charset');
$content->data = $this->_decode($body, $structure->type);
$content->size = strlen($content->data);
$mail->content[] = $content;
return $mail;
}
else
{
$parts = $this->_fetchPartsStructureRoot($mail, $structure);
foreach ($parts as $part)
{
$content = new stdClass();
$content->type = null;
$content->data = null;
$content->mime = $this->_fetchType($part->data);
if ((isset($part->data->disposition))
&& ((strcmp('attachment', $part->data->disposition) == 0)
|| (strcmp('inline', $part->data->disposition) == 0)))
{
$content->type = $part->data->disposition;
$content->name = null;
if (isset($part->data->dparameters))
{
$content->name = $this->_fetchParameter($part->data->dparameters, 'filename');
}
if (is_null($content->name))
{
if (isset($part->data->parameters))
{
$content->name = $this->_fetchParameter($part->data->parameters, 'name');
}
}
$mail->attachments[] = $content;
}
else if ($part->data->type == 0)
{
$content->type = 'content';
$content->charset = null;
if (isset($part->data->parameters))
{
$content->charset = $this->_fetchParameter($part->data->parameters, 'charset');
}
$mail->content[] = $content;
}
$body = imap_fetchbody($this->box, $mail->id, $part->no);
if (isset($part->data->encoding))
{
$content->data = $this->_decode($body, $part->data->encoding);
}
else
{
$content->data = $body;
}
$content->size = strlen($content->data);
}
}
return $mail;
}
private function _fetchPartsStructureRoot($mail, $structure)
{
$parts = array ();
if ((isset($structure->parts)) && (is_array($structure->parts)) && (count($structure->parts) > 0))
{
foreach ($structure->parts as $key => $data)
{
$this->_fetchPartsStructure($mail, $data, ($key + 1), $parts);
}
}
return $parts;
}
private function _fetchPartsStructure($mail, $structure, $prefix, &$parts)
{
if ((isset($structure->parts)) && (is_array($structure->parts)) && (count($structure->parts) > 0))
{
foreach ($structure->parts as $key => $data)
{
$this->_fetchPartsStructure($mail, $data, $prefix . "." . ($key + 1), $parts);
}
}
$part = new stdClass;
$part->no = $prefix;
$part->data = $structure;
$parts[] = $part;
}
private function _fetchParameter($parameters, $key)
{
foreach ($parameters as $parameter)
{
if (strcmp($key, $parameter->attribute) == 0)
{
return $parameter->value;
}
}
return null;
}
private function _fetchType($structure)
{
$primary_mime_type = array ("TEXT", "MULTIPART", "MESSAGE", "APPLICATION", "AUDIO", "IMAGE", "VIDEO", "OTHER");
if ((isset($structure->subtype)) && ($structure->subtype) && (isset($structure->type)))
{
return $primary_mime_type[(int) $structure->type] . '/' . $structure->subtype;
}
return "TEXT/PLAIN";
}
private function _decode($message, $coding)
{
switch ($coding)
{
case 2:
$message = imap_binary($message);
break;
case 3:
$message = imap_base64($message);
break;
case 4:
$message = imap_qprint($message);
break;
case 5:
break;
default:
break;
}
return $message;
}
private function _callById($method, $data)
{
$callback = array ($this, $method);
// data is null
if (is_null($data))
{
$result = array ();
foreach ($this->list as $mail)
{
$result[] = $this->_callById($method, $mail);
}
return $result;
}
// data is an array
if (is_array($data))
{
$result = array ();
foreach ($data as $elem)
{
$result[] = $this->_callById($method, $elem);
}
return $result;
}
// data is an object
if ((is_object($data)) && ($data instanceof stdClass) && (isset($data->id)))
{
return call_user_func($callback, $data);
}
// data is numeric
if (($this->isConnected()) && (is_array($this->list)) && (is_numeric($data)))
{
foreach ($this->list as $mail)
{
if ($mail->id == $data)
{
return call_user_func($callback, $mail);
}
}
}
return null;
}
public function delete($nbr)
{
$this->_callById('_delete', $nbr);
return;
}
private function _delete($mail)
{
if ($mail->deleted == false)
{
$test = imap_reopen($this->box, "{$mail->mbox}");
if ($test)
{
$this->deleted = true;
imap_delete($this->box, $mail->id);
$mail->deleted = true;
}
}
}
public function searchBy($pattern, $type)
{
$result = array ();
if (is_array($this->list))
{
foreach ($this->list as $mail)
{
$match = false;
switch ($type)
{
case self::FROM:
$match = $this->_match($mail->from, $pattern);
break;
case self::TO:
$match = $this->_match($mail->to, $pattern);
break;
case self::REPLY_TO:
$match = $this->_match($mail->reply_to, $pattern);
break;
case self::SUBJECT:
$match = $this->_match($mail->subject, $pattern);
break;
case self::CONTENT:
foreach ($mail->content as $content)
{
$match = $this->_match($content->data, $pattern);
if ($match)
{
break;
}
}
break;
case self::ATTACHMENT:
foreach ($mail->attachments as $attachment)
{
$match = $this->_match($attachment->name, $pattern);
if ($match)
{
break;
}
}
break;
}
if ($match)
{
$result[] = $mail;
}
}
}
return $result;
}
private function _nmatch($string, $pattern, $a, $b)
{
if ((!isset($string[$a])) && (!isset($pattern[$b])))
{
return 1;
}
if ((isset($pattern[$b])) && ($pattern[$b] == '*'))
{
if (isset($string[$a]))
{
return ($this->_nmatch($string, $pattern, ($a + 1), $b) + $this->_nmatch($string, $pattern, $a, ($b + 1)));
}
else
{
return ($this->_nmatch($string, $pattern, $a, ($b + 1)));
}
}
if ((isset($string[$a])) && (isset($pattern[$b])) && ($pattern[$b] == '?'))
{
return ($this->_nmatch($string, $pattern, ($a + 1), ($b + 1)));
}
if ((isset($string[$a])) && (isset($pattern[$b])) && ($pattern[$b] == '\\'))
{
if ((isset($pattern[($b + 1)])) && ($string[$a] == $pattern[($b + 1)]))
{
return ($this->_nmatch($string, $pattern, ($a + 1), ($b + 2)));
}
}
if ((isset($string[$a])) && (isset($pattern[$b])) && ($string[$a] == $pattern[$b]))
{
return ($this->_nmatch($string, $pattern, ($a + 1), ($b + 1)));
}
return 0;
}
private function _match($string, $pattern)
{
return $this->_nmatch($string, $pattern, 0, 0);
}
}
ImapReader.demo.php Here is the usage sample
<?php
require_once("ImapReader.class.php");
$box = new ImapReader('example.com', '143', 'somebody#example.com', 'xxxxxxxxxxxx');
$box
->connect()
->fetchAllHeaders()
;
echo $box->count() . " emails in mailbox\n";
for ($i = 0; ($i < $box->count()); $i++)
{
$msg = $box->get($i);
echo "Reception date : {$msg->date}\n";
echo "From : {$msg->from}\n";
echo "To : {$msg->to}\n";
echo "Reply to : {$msg->from}\n";
echo "Subject : {$msg->subject}\n";
$msg = $box->fetch($msg);
echo "Number of readable contents : " . count($msg->content) . "\n";
foreach ($msg->content as $key => $content)
{
echo "\tContent " . ($key + 1) . " :\n";
echo "\t\tContent type : {$content->mime}\n";
echo "\t\tContent charset : {$content->charset}\n";
echo "\t\tContent size : {$content->size}\n";
}
echo "Number of attachments : " . count($msg->attachments) . "\n";
foreach ($msg->attachments as $key => $attachment)
{
echo "\tAttachment " . ($key + 1) . " :\n";
echo "\t\tAttachment type : {$attachment->type}\n";
echo "\t\tContent type : {$attachment->mime}\n";
echo "\t\tFile name : {$attachment->name}\n";
echo "\t\tFile size : {$attachment->size}\n";
}
echo "\n";
}
echo "Searching '*Bob*' ...\n";
$results = $box->searchBy('*Bob*', ImapReader::FROM);
foreach ($results as $result)
{
echo "\tMatched: {$result->from} - {$result->date} - {$result->subject}\n";
}
Enjoy
Regarding the blank emails, check the encoding of the mail.
If it is a binary encoded mail then you will get blank mails when you try to insert them into a mysql text field.
Try shifting every mail to UTF-8 and then insert it
iconv(mb_detect_encoding($mail_content, mb_detect_order(), true), "UTF-8", $mail_content);
function getmsg($mbox,$mid) {
// input $mbox = IMAP stream, $mid = message id
// output all the following:
global $charset,$htmlmsg,$plainmsg,$attachments;
$htmlmsg = $plainmsg = $charset = '';
$attachments = array();
// HEADER
$h = imap_header($mbox,$mid);
// add code here to get date, from, to, cc, subject...
// BODY
$s = imap_fetchstructure($mbox,$mid);
if (!$s->parts) // simple
getpart($mbox,$mid,$s,0); // pass 0 as part-number
else { // multipart: cycle through each part
foreach ($s->parts as $partno0=>$p)
getpart($mbox,$mid,$p,$partno0+1);
}
}
function getpart($mbox,$mid,$p,$partno) {
// $partno = '1', '2', '2.1', '2.1.3', etc for multipart, 0 if simple
global $htmlmsg,$plainmsg,$charset,$attachments;
// DECODE DATA
$data = ($partno)?
imap_fetchbody($mbox,$mid,$partno): // multipart
imap_body($mbox,$mid); // simple
// Any part may be encoded, even plain text messages, so check everything.
if ($p->encoding==4)
$data = quoted_printable_decode($data);
elseif ($p->encoding==3)
$data = base64_decode($data);
// PARAMETERS
// get all parameters, like charset, filenames of attachments, etc.
$params = array();
if ($p->parameters)
foreach ($p->parameters as $x)
$params[strtolower($x->attribute)] = $x->value;
if ($p->dparameters)
foreach ($p->dparameters as $x)
$params[strtolower($x->attribute)] = $x->value;
// ATTACHMENT
// Any part with a filename is an attachment,
// so an attached text file (type 0) is not mistaken as the message.
if ($params['filename'] || $params['name']) {
// filename may be given as 'Filename' or 'Name' or both
$filename = ($params['filename'])? $params['filename'] : $params['name'];
// filename may be encoded, so see imap_mime_header_decode()
$attachments[$filename] = $data; // this is a problem if two files have same name
}
// TEXT
if ($p->type==0 && $data) {
// Messages may be split in different parts because of inline attachments,
// so append parts together with blank row.
if (strtolower($p->subtype)=='plain')
$plainmsg. = trim($data) ."\n\n";
else
$htmlmsg. = $data ."<br><br>";
$charset = $params['charset']; // assume all parts are same charset
}
// EMBEDDED MESSAGE
// Many bounce notifications embed the original message as type 2,
// but AOL uses type 1 (multipart), which is not handled here.
// There are no PHP functions to parse embedded messages,
// so this just appends the raw source to the main message.
elseif ($p->type==2 && $data) {
$plainmsg. = $data."\n\n";
}
// SUBPART RECURSION
if ($p->parts) {
foreach ($p->parts as $partno0=>$p2)
getpart($mbox,$mid,$p2,$partno.'.'.($partno0+1)); // 1.2, 1.2.1, etc.
}
}
Reference (First user contributed note): http://php.net/manual/en/function.imap-fetchstructure.php
I tried all this answers, but neither one worked for me. Then I hit first user contributed note on this PHP page:
http://php.net/manual/en/function.imap-fetchstructure.php
and this works for all my cases. Quite old answer btw.
Hi I am using serialize & unserialize functions and fwrite & fopen for text based db
<?php
ini_set('display_errors', 'on');
header('Content-Type: text/html; charset=utf-8');
$debugged = (bool) isset($_GET['debug']);
error_reporting($debugged ? E_ALL : 0);
$data_filename = "database.txt";
$admins = array(
"admin" => "admin",
"admin2" => "admin2"
);
$superadmin = "admin";
$order = "asc";
include_once "functions.php";
?>
<?php
function clean($d) {
return str_replace(array(
"\t",
"\n",
"\s",
"\r"
), "", $d);
}
function add($email, $age_id, $gender_id, $city, $prof_id, $model, $token, $os_version, $udid, $admin) {
global $data_filename;
$datax['email'] = $email;
$datax['age_id'] = $age_id;
$datax['gender_id'] = $gender_id;
$datax['city'] = $city;
$datax['prof_id'] = $prof_id;
$datax['model'] = $model;
$datax['token'] = $token;
$datax['os_version'] = $os_version;
$datax['udid'] = $udid;
$datax['admin'] = $admin;
$data = array();
$data_content = get_file_content($data_filename);
if ($data_content !== NULL)
$data = unserialize($data_content);
$entrie = serialize($datax);
$data[] = $entrie;
$data_content = serialize($data);
put_file_content($data_filename, $data_content);
return $data_content;
}
function get_file_content($filename) {
if (!file_exists($filename))
fclose(fopen($filename, "w"));
if (!file_exists($filename))
die("sie.");
$content = (filesize($filename) > 0) ? #fread(fopen($filename, "r+"), filesize($filename)) : NULL;
if ($content === false)
die("aq");
return $content;
}
if (!$data_filename) {
die("sie-31");
}
$datasey = array();
$data_content = get_file_content($data_filename);
if ($data_content !== NULL)
$datasey = #unserialize($data_content);
function put_file_content($filename, $content) {
if (file_put_contents($filename, $content, LOCK_EX)) {
return true;
} else {
usleep(250000);
put_file_content($filename, $content, LOCK_EX);
}
}
function reverse_data($data) {
$data = array_reverse($data);
foreach ($data as $key => $entrie)
$key = $entries_num - $key - 1;
return $data;
}
function del_admin_contents($who) {
global $admin, $superadmin, $data_filename;
;
$array = array();
$data_content = get_file_content($data_filename);
if ($data_content === NULL)
return;
$array = unserialize($data_content);
foreach ($array as $key => $value) {
$bok = unserialize($value);
if ($bok["admin"] == $who) {
unset($array[$key]);
}
}
$temp = array();
foreach ($array as $value)
$temp[] = $value;
$data_content = serialize($array);
put_file_content($data_filename, $data_content);
return $data_content;
}
function del_entries($select, $udid) {
global $data_filename;
$data = array();
$data_content = get_file_content($data_filename);
if ($data_content === NULL)
return;
$data = unserialize($data_content);
$data = del_id($data, $select, $udid);
$data_content = serialize($data);
put_file_content($data_filename, $data_content);
return $data_content;
}
function del_id($array, $id_array, $udid) {
global $admin, $superadmin;
foreach ($id_array as $id)
if (isset($array[$id])) {
$bok = unserialize($array[$id]);
if ($bok["admin"] == $admin || $admin == $superadmin) {
if ($bok["udid"] == $udid) {
unset($array[$id]);
}
}
}
$temp = array();
foreach ($array as $value)
$temp[] = $value;
return $temp;
}
function up_id($array, $new_array, $id) {
global $admin, $superadmin;
if (isset($array[$id])) {
$array[$id] = serialize($new_array);
}
return $array;
}
function update_id($data, $id, $new_array) {
global $data_filename;
$data = up_id($data, $new_array, $id);
$data_content = serialize($data);
put_file_content($data_filename, $data_content);
return true;
}
function emailupdate($udid, $email) {
global $data_filename;
$data = array();
$ret = false;
$data_content = get_file_content($data_filename);
if ($data_content === NULL)
return false;
$data = unserialize($data_content);
$id = 0;
foreach ($data as $d) {
$new_array = unserialize($d);
if ($new_array["udid"] == $udid) {
$new_array["email"] = $email;
update_id($data, $id, $new_array);
$ret = true;
}
$id++;
}
return $ret;
}
function alldata() {
global $datasey;
$benimdata = array();
if (count($datasey) > 0) {
foreach ($datasey as $key => $entrie) {
$gec = unserialize($entrie);
$benimdata[] = $gec;
}
return $benimdata;
} else {
return false;
}
}
function cleaner() {
global $data_filename, $max_entries;
if ($max_entries == 0)
return;
$data = array();
$data_content = get_file_content($data_filename);
if ($data_content !== NULL)
$data = unserialize($data_content);
while (count($data) >= $max_entries)
$data = clear_id($data, array(
0
));
$data_content = serialize($data);
put_file_content($data_filename, $data_content);
return true;
}
function logincheck($user, $pass) {
global $admins;
if (array_key_exists($user, $admins)) {
if ($admins[$user] == $pass) {
return true;
} else {
return false;
}
} else {
return false;
}
}
$backup = "./backup/" . date("Ymd-H:i") . ".dat";
if (!file_exists($backup)) {
$backup_data_content = get_file_content($data_filename);
file_put_contents($backup, $backup_data_content, LOCK_EX);
}
?>
As here is an example of how I add new value(s):
$data_content=add($_POST["email"],$_POST["age_id"],$_POST["gender_id"],$_POST["city_id"],$_POST["prof_id"],$_POST["model"],"N/A",$_POST["os_version"],$randomudid,$admin);
for delete :
$data_content=del_entries(array($_GET["del"]),$_GET["delete"]);
My question is when 2 admins try to enter a value at the same time it writes to database only the last value sent and deletes the old values, how can I resolve this issue?
I want to have multiple values for checkboxes. How do I do that?
It only adds the first option that is selected
<input type="checkbox" name="fields[options]" value="option1[]">option1
<input type="checkbox" name="fields[options]" value="option2[]">option2
<input type="checkbox" name="fields[options]" value="option3[]">option3
There are two PHP files. I will post them below. I am not that experienced with php.
/**************** GOOGLE.DOCS method ************************/
if($_SETTINGS['store_to_gdocs'])
{
include_once("GoogleSpreadsheet/Google_Spreadsheet.php");
$ss = new Google_Spreadsheet($_SETTINGS['gdocs']['user'],$_SETTINGS['gdocs']['password']);
$ss->useSpreadsheet($_SETTINGS['gdocs']['spreadsheet_name']);
$ss->useWorksheet($_SETTINGS['gdocs']['worksheet_name']);
$row = array
(
"Date" => date("m/d/Y H:i"),
);
foreach($_POST['fields'] as $k=>$v)
$row[$k]=$v;
if(!$ss->addRow($row))
$ret['error']=1;
}
Second file
<?php
class Google_Spreadsheet
{
private $client;
private $spreadsheet;
private $spreadsheet_id;
private $worksheet = "Sheet1";
private $worksheet_id;
function __construct($user,$pass,$ss=FALSE,$ws=FALSE)
{
$this->login($user,$pass);
if ($ss) $this->useSpreadsheet($ss);
if ($ws) $this->useWorksheet($ws);
}
function useSpreadsheet($ss,$ws=FALSE)
{
$this->spreadsheet = $ss;
$this->spreadsheet_id = NULL;
if ($ws) $this->useWorksheet($ws);
}
function useWorksheet($ws)
{
$this->worksheet = $ws;
$this->worksheet_id = NULL;
}
function addRow($row)
{
if ($this->client instanceof Zend_Gdata_Spreadsheets)
{
$ss_id = $this->getSpreadsheetId($this->spreadsheet);
if (!$ss_id) throw new Exception('Unable to find spreadsheet by name: "' . $this->spreadsheet . '", confirm the name of the spreadsheet');
$ws_id = $this->getWorksheetId($ss_id,$this->worksheet);
if (!$ws_id) throw new Exception('Unable to find worksheet by name: "' . $this->worksheet . '", confirm the name of the worksheet');
$insert_row = array();
foreach ($row as $k => $v) $insert_row[$this->cleanKey($k)] = $v;
$entry = $this->client->insertRow($insert_row,$ss_id,$ws_id);
if ($entry instanceof Zend_Gdata_Spreadsheets_ListEntry) return TRUE;
}
throw new Exception('Unable to add row to the spreadsheet');
}
// http://code.google.com/apis/spreadsheets/docs/2.0/reference.html#ListParameters
function updateRow($row,$search)
{
if ($this->client instanceof Zend_Gdata_Spreadsheets AND $search)
{
$feed = $this->findRows($search);
if ($feed->entries)
{
foreach($feed->entries as $entry)
{
if ($entry instanceof Zend_Gdata_Spreadsheets_ListEntry)
{
$update_row = array();
$customRow = $entry->getCustom();
foreach ($customRow as $customCol)
{
$update_row[$customCol->getColumnName()] = $customCol->getText();
}
// overwrite with new values
foreach ($row as $k => $v)
{
$update_row[$this->cleanKey($k)] = $v;
}
// update row data, then save
$entry = $this->client->updateRow($entry,$update_row);
if ( ! ($entry instanceof Zend_Gdata_Spreadsheets_ListEntry)) return FALSE;
}
}
return TRUE;
}
}
return FALSE;
}
// http://code.google.com/apis/spreadsheets/docs/2.0/reference.html#ListParameters
function getRows($search=FALSE)
{
$rows = array();
if ($this->client instanceof Zend_Gdata_Spreadsheets)
{
$feed = $this->findRows($search);
if ($feed->entries)
{
foreach($feed->entries as $entry)
{
if ($entry instanceof Zend_Gdata_Spreadsheets_ListEntry)
{
$row = array();
$customRow = $entry->getCustom();
foreach ($customRow as $customCol)
{
$row[$customCol->getColumnName()] = $customCol->getText();
}
$rows[] = $row;
}
}
}
}
return $rows;
}
// user contribution by dmon (6/10/2009)
function deleteRow($search)
{
if ($this->client instanceof Zend_Gdata_Spreadsheets AND $search)
{
$feed = $this->findRows($search);
if ($feed->entries)
{
foreach($feed->entries as $entry)
{
if ($entry instanceof Zend_Gdata_Spreadsheets_ListEntry)
{
$this->client->deleteRow($entry);
if ( ! ($entry instanceof Zend_Gdata_Spreadsheets_ListEntry)) return FALSE;
}
}
return TRUE;
}
}
return FALSE;
}
function getColumnNames()
{
$query = new Zend_Gdata_Spreadsheets_ListQuery();
$query->setSpreadsheetKey($this->getSpreadsheetId());
$query->setWorksheetId($this->getWorksheetId());
$query->setMaxResults(1);
$query->setStartIndex(1);
$feed = $this->client->getListFeed($query);
$data = array();
if ($feed->entries)
{
foreach($feed->entries as $entry)
{
if ($entry instanceof Zend_Gdata_Spreadsheets_ListEntry)
{
$customRow = $entry->getCustom();
foreach ($customRow as $customCol)
{
array_push($data,$customCol->getColumnName());
}
}
}
}
return $data;
}
private function login($user,$pass)
{
// Zend Gdata package required
// http://framework.zend.com/download/gdata
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Http_Client');
Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Gdata_Spreadsheets');
$service = Zend_Gdata_Spreadsheets::AUTH_SERVICE_NAME;
$http = Zend_Gdata_ClientLogin::getHttpClient($user,$pass,$service);
$this->client = new Zend_Gdata_Spreadsheets($http);
if ($this->client instanceof Zend_Gdata_Spreadsheets) return TRUE;
return FALSE;
}
private function findRows($search=FALSE)
{
$query = new Zend_Gdata_Spreadsheets_ListQuery();
$query->setSpreadsheetKey($this->getSpreadsheetId());
$query->setWorksheetId($this->getWorksheetId());
if ($search) $query->setSpreadsheetQuery($search);
$feed = $this->client->getListFeed($query);
return $feed;
}
private function getSpreadsheetId($ss=FALSE)
{
if ($this->spreadsheet_id) return $this->spreadsheet_id;
$ss = $ss?$ss:$this->spreadsheet;
$ss_id = FALSE;
$feed = $this->client->getSpreadsheetFeed();
foreach($feed->entries as $entry)
{
if ($entry->title->text == $ss)
{
$ss_id = array_pop(explode("/",$entry->id->text));
$this->spreadsheet_id = $ss_id;
break;
}
}
return $ss_id;
}
private function getWorksheetId($ss_id=FALSE,$ws=FALSE)
{
if ($this->worksheet_id) return $this->worksheet_id;
$ss_id = $ss_id?$ss_id:$this->spreadsheet_id;
$ws = $ws?$ws:$this->worksheet;
$wk_id = FALSE;
if ($ss_id AND $ws)
{
$query = new Zend_Gdata_Spreadsheets_DocumentQuery();
$query->setSpreadsheetKey($ss_id);
$feed = $this->client->getWorksheetFeed($query);
foreach($feed->entries as $entry)
{
if ($entry->title->text == $ws)
{
$wk_id = array_pop(explode("/",$entry->id->text));
$this->worksheet_id = $wk_id;
break;
}
}
}
return $wk_id;
}
function cleanKey($k)
{
return strtolower(preg_replace('/[^A-Za-z0-9\-\.]+/','',$k));
}
}
Thank you for helping!
You have your checkbox names and values mixed up. It should be:
<input type="checkbox" name="fields[options][]" value="option1">option1
<input type="checkbox" name="fields[options][]" value="option2">option2
<input type="checkbox" name="fields[options][]" value="option3">option3
Now you can manipulate $_POST['fields']['options'] like so:
$options = (is_array($_POST['fields']['options'])) ? $_POST['fields']['options'] : array();
Then you can implode them:
$options_string = implode(',', $options) // will return option1,option2,option3 etc
or loop through them:
foreach ($options as $option)
{
echo $option.'<br>';
}
// produces option1<br>option2<br>option3 etc
Don't give the name a key in the array - it should be set to name="fields[]".
See this post.