Background
Using Centos 5.5 final, Apache Tomcat 6, Java 1.6.0_24, PHP/Java Bridge 6.2.1, and JasperReports 4.0.1.
Problem
PHP fails to add a text value to a java.util.HashMap.
Question
Does any one have any suggestions on how to accomplish this task?
Source
If I comment out the line $map->put("text", "This is a test string");, the report compiles and runs.
<?php
/**
* see if the java extension was loaded.
*/
function checkJavaExtension()
{
if(!extension_loaded('java'))
{
$sapi_type = php_sapi_name();
$port = (isset($_SERVER['SERVER_PORT']) && (($_SERVER['SERVER_PORT'])>1024)) ? $_SERVER['SERVER_PORT'] : '8080';
if ($sapi_type == "cgi" || $sapi_type == "cgi-fcgi" || $sapi_type == "cli")
{
if(!(PHP_SHLIB_SUFFIX=="so" && #dl('java.so'))&&!(PHP_SHLIB_SUFFIX=="dll" && #dl('php_java.dll'))&&!(#include_once("java/Java.inc"))&&!(require_once("http://127.0.0.1:$port/java/Java.inc")))
{
return "java extension not installed.";
}
}
else
{
if(!(#include_once("java/Java.inc")))
{
require_once("http://www.webserver.net:$port/JavaBridge/java/Java.inc");
}
}
}
if(!function_exists("java_get_server_name"))
{
return "The loaded java extension is not the PHP/Java Bridge";
}
return true;
}
/**
* convert a php value to a java one...
* #param string $value
* #param string $className
* #returns boolean success
*/
function convertValue($value, $className)
{
// if we are a string, just use the normal conversion
// methods from the java extension...
try
{
if ($className == 'java.lang.String')
{
$temp = new Java('java.lang.String', $value);
return $temp;
}
else if ($className == 'java.lang.Boolean' ||
$className == 'java.lang.Integer' ||
$className == 'java.lang.Long' ||
$className == 'java.lang.Short' ||
$className == 'java.lang.Double' ||
$className == 'java.math.BigDecimal')
{
$temp = new Java($className, $value);
return $temp;
}
else if ($className == 'java.sql.Timestamp' ||
$className == 'java.sql.Time')
{
$temp = new Java($className);
$javaObject = $temp->valueOf($value);
return $javaObject;
}
}
catch (Exception $err)
{
echo ( 'unable to convert value, ' . $value .
' could not be converted to ' . $className);
return false;
}
echo ( 'unable to convert value, class name '.$className.
' not recognised');
return false;
}
checkJavaExtension();
$map = new Java("java.util.HashMap");
$map->put("text", "This is a test string");
$compileManager = new JavaClass("net.sf.jasperreports.engine.JasperCompileManager");
$report = $compileManager->compileReport(realpath("test.jrxml"));
$fillManager = new JavaClass("net.sf.jasperreports.engine.JasperFillManager");
$emptyDataSource = new Java("net.sf.jasperreports.engine.JREmptyDataSource");
$jasperPrint = $fillManager->fillReport($report, $map, $emptyDataSource);
$outputPath = realpath(".")."/"."output.pdf";
$exportManager = new JavaClass("net.sf.jasperreports.engine.JasperExportManager");
$exportManager->exportReportToPdfFile($jasperPrint, $outputPath);
header("Content-type: application/pdf");
readfile($outputPath);
unlink($outputPath);
?>
Source
Here is some code to pass parameters from PHP to JasperReports automatically, based on a naming convention for user input fields.
<?php
include_once( 'db-account.php' );
checkjavaExtension();
function report_parse_post_parameters() {
# Automatically extract report parameters (data types converted in report).
$params = new java('java.util.HashMap');
# Pass the remaining POST "report_TYP" variables as report parameters.
foreach( $_POST as $name => $value ) {
if( strpos( $name, 'report_' ) === 0 ) {
$length = strlen( 'report_' );
if( strpos( $name, 'report_int_' ) === 0 ) {
$value = intval( $value );
$length = strlen( 'report_int_' );
$value = convertValue( $value, 'java.lang.Integer' );
$params->put( substr( $name, $length ), $value );
}
else if( strpos( $name, 'report_arr_' ) === 0 ) {
$length = strlen( 'report_arr_' );
$arrays = array_filter( explode( ',', $_POST[ $name ] ) );
# Map the values of the array form parameter to a java.util.ArrayList.
$arrayList = new java( 'java.util.ArrayList' );
foreach( $arrays as $value ) {
$arrayList->add( $value );
}
# Pass values into the report (without the "report_arr_" prefix).
$params->put( substr( $name, $length ), $arrayList );
}
else {
$params->put( substr( $name, $length ), $value );
}
}
}
return $params;
}
function report_execute( $filename = 'FILENAME' ) {
global $dbhost;
global $dbname;
global $dbuser;
global $dbpass;
$conn = null;
$report = realpath( '/PATH/TO/REPORT.jasper' );
try {
$params = report_parse_post_parameters();
# Load the PostgreSQL database driver.
java( 'java.lang.Class' )->forName( 'org.postgresql.Driver' );
# Attempt a database connection.
$conn = java( 'java.sql.DriverManager' )->getConnection(
"jdbc:postgresql://$dbhost/$dbname?user=$dbuser&password=$dbpass" );
# Use the fill manager to produce the report.
$fm = java('net.sf.jasperreports.engine.JasperFillManager');
$pm = $fm->fillReport($report, $params, $conn);
header('Cache-Control: private');
header('Content-Description: File Transfer');
header("Content-Disposition: attachment, filename=$filename.pdf");
header('Content-Type: application/pdf');
header('Content-Transfer-Encoding: binary');
java_set_file_encoding('ISO-8859-1');
$em = java('net.sf.jasperreports.engine.JasperExportManager');
$result = $em->exportReportToPdf($pm);
$conn->close();
header('Content-Length: ' . strlen( $result ) );
echo $result;
}
catch( Exception $ex ) {
if( $conn != null ) {
$conn->close();
}
throw $ex;
}
}
?>
Usage
Change this line:
function report_execute( $filename = 'FILENAME' ) {
Change this line:
$report = realpath( '/PATH/TO/REPORT.jasper' );
Change these lines to match your database software:
java( 'java.lang.Class' )->forName( 'org.postgresql.Driver' );
$conn = java( 'java.sql.DriverManager' )->getConnection(
"jdbc:postgresql://$dbhost/$dbname?user=$dbuser&password=$dbpass" );
Edit db-account.php:
<?php
$dbhost = 'HOSTNAME';
$dbname = 'DATABASE';
$dbuser = 'USERNAME';
$dbpass = 'PASSWORD';
?>
Example Form Input
Use a report_ prefix for user inputs, such as:
<form method="post" action='report.dhtml' class="climate" id="report-form">
<input type="hidden" name="report_int_ReportId" value="1" />
<input type="hidden" name="report_int_Radius" value="35" />
<input type="hidden" name="report_int_Trend" value="0" />
<input type="hidden" name="report_int_Relevance" value="1" />
<select id="category" name="report_int_CategoryId" value="2"></select>
<input type="text" id="city" name="report_int_CityId" />
<input class="submit-button" id="submit" type="submit" name="submit" value="Report" />
</form>
These values are then passed automatically into the report.
Note
You should not have to change the code for checkjavaExtension().
Related
I want to call my function but when I call it I have a problem with curly Brackets at the end of my code and i have this error Error SYMFONY ( {} ) in my Controller.
I have no idea where to put them for my code to work. I have this problem when I add my function that allows me to retrieve the
history of the action. The mentioned function goes as this:
$this->logHistory->addHistoryConnection($project->getId(), $user->getId(), 'Delete Local Suf', $sf_code);
Function Supp Suf
/**
* #Route("/creation/suf/supp", name="suf_supp")
*/
public function suf(
Request $request,
ShapesRepository $shapesRepository
) {
$params = $this->requestStack->getSession();
$projet = $params->get('projet');
$modules = $params->get('modules');
$fonctionnalites = $params->get('fonctionnalites');
$user = $this->getUser()->getUserEntity();
$manager = $this->graceManager;
$mapManager = $this->mapManager;
$countElements = $mapManager->getCount();
$shapes = $shapesRepository->findBy(array('projet' => $projet->getId()));
$adresseWeb = $this->getParameter('adresse_web');
$carto = $params->get('paramCarto');
$centrage = $params->get('centrage');
$cableColor = $params->get('cableColor');
$sf_code = '';
if ($request->get('suf') != '') {
$sf_code = $request->get('suf');
}
$suf = $manager->getSuf($sf_code);
$success = '';
$error = '';
$warning = '';
if ($request->query->get('success')) {
$success = $request->query->get('success');
} elseif ($request->query->get('error')) {
$error = $request->query->get('error');
} elseif ($request->query->get('warning')) {
$warning = $request->query->get('warning');
}
if ($request->isMethod('POST')) {
if ($request->request->get('sf_code') != '') {
$sf_code = $request->request->get('sf_code');
}
if ($request->get('val') != '') {
$val = $request->get('val');
}
$dir = $this->getparameter('client_directory');
$dossier = str_replace(' ', '_', $projet->getProjet());
$dir = $dir . $dossier . '/documents/';
$cable = $val[0];
$chem = $val[1];
$t_suf = $this->graceCreator->supprimeSuf($sf_code, $cable, $chem);
if ($t_suf[0][0] == '00000') {
$this->logHistorique->addHistoryConnection($projet->getId(), $user->getId(), 'Suppression Suf Local', $sf_code);
// $creator->delDirObjet( $st_code, $dir );
$data = new JsonResponse(array("success" => "create!"));
return $data;
} else {
$data = new JsonResponse(array("error" => "Error : " . $t_suf));
return $data;
}
return $this->render('Modifications/supSuf.html.twig', array(
'user' => $user,
'paramCarto' => $carto,
'cableColor' => $cableColor,
'suf' => $suf,
'adresseWeb' => $adresseWeb,
'centrage' => $centrage,
'shapes' => $shapes,
'projet' => $projet,
'modules' => $modules,
'fonctionnalites' => $fonctionnalites,
'countElements' => $countElements
));
}
}
Your only return statement is inside of an if condition. If the code does not pass the condition, it has nothing to return. The code must return something in all possible cases. If you are not still used to these practices, an IDE might guide you until it becomes a routine. PHPStorm is my personal preference.
BTW, I recommend you to switch from the array() syntax to the more globally accepted [] although you must be in PHP 5.4 or higher.
i using a wordpress plugin, i notice that returns a error on
$alias = (string)end(array_keys($settings));
above line .the error is
PHP Strict Standards: Only variables should be passed by reference in on wordpress function
i added that function below. anyone know how to solve that error please, becoz admin dashboard of the plugin not loading because of this error.
/*
* GET modules lists
*/
function load_modules ()
{
$folder_path = $this->cfg['paths']['plugin_dir_path'] . 'modules/';
$cfgFileName = 'config.php';
// static usage, modules menu order
$menu_order = array();
foreach(glob($folder_path . '*/' . $cfgFileName) as $module_config ){
$module_folder = str_replace($cfgFileName, '', $module_config);
// Turn on output buffering
ob_start();
if( is_file( $module_config ) ) {
require_once( $module_config );
}
$settings = ob_get_clean(); //copy current buffer contents into $message variable and delete current output buffer
if(trim($settings) != "") {
$settings = json_decode($settings, true);
$alias = (string) end(array_keys($settings));
// create the module folder URI
// fix for windows server
$module_folder = str_replace( DIRECTORY_SEPARATOR, '/', $module_folder );
$__tmpUrlSplit = explode("/", $module_folder);
$__tmpUrl = '';
$nrChunk = count($__tmpUrlSplit);
if($nrChunk > 0) {
foreach ($__tmpUrlSplit as $key => $value){
if( $key > ( $nrChunk - 4) && trim($value) != ""){
$__tmpUrl .= $value . "/";
}
}
}
// get the module status. Check if it's activate or not
$status = false;
// default activate all core modules
if(in_array( $alias, $this->cfg['core-modules'] )) {
$status = true;
}else{
// activate the modules from DB status
$db_alias = $this->alias . '_module_' . $alias;
if(get_option($db_alias) == 'true'){
$status = true;
}
}
// push to modules array
$this->cfg['modules'][$alias] = array_merge(array(
'folder_path' => $module_folder,
'folder_uri' => $this->cfg['paths']['plugin_dir_url'] . $__tmpUrl,
'db_alias' => $this->alias . '_' . $alias,
'status' => $status
), $settings );
// add to menu order arrayhttp://cc.aa-team.com/wp-plugins/smart-seo-v2/wp-admin/admin-ajax.php?action=pspLoadSection§ion=Social_Stats
if(!isset($this->cfg['menu_order'][(int)$settings[$alias]['menu']['order']])){
$this->cfg['menu_order'][(int)$settings[$alias]['menu']['order']] = $alias;
}else{
// add the menu to next free key
$this->cfg['menu_order'][] = $alias;
}
// add module to activate modules array
if($status == true){
$this->cfg['activate_modules'][$alias] = true;
}
// load the init of current loop module
if( $status == true && isset( $settings[$alias]['module_init'] ) ){
if( is_file($module_folder . $settings[$alias]['module_init']) ){
//if( is_admin() ) {
$current_module = array($alias => $this->cfg['modules'][$alias]);
require_once( $module_folder . $settings[$alias]['module_init'] );
//}
}
}
}
}
// order menu_order ascendent
ksort($this->cfg['menu_order']);
}
End rereceives value by reference, but result of function is not variable.
You could rewrite your code.
$array_keys = array_keys($settings);
$alias = (string)end($array_keys);
unset($array_keys);
I'm using a WordPress plugin called User Submitted Posts. The plugin allows for users to upload multiple photos. I have it set up so that users can upload 0 to a max of 3. When I try to upload more than one pic, however, only one of them gets posted.
HTML:
<div id="usp">
<form id="usp_form" method="post" enctype="multipart/form-data" action="">
<ul id="usp_list">
<li class="usp_title">
<label for="user-submitted-title" class="usp_label">Post Title</label>
<div>
<input class="usp_input" type="text" name="user-submitted-title" id="user-submitted-title" value="" />
</div>
</li>
<li class="usp_tags">
<label for="user-submitted-tags" class="usp_label">Post Tags <small>(separate tags with commas)</small></label>
<div>
<input class="usp_input" type="text" name="user-submitted-tags" id="user-submitted-tags" value="" />
</div>
</li>
<li class="usp_content">
<label for="user-submitted-content" class="usp_label">Post Content</label>
<div>
<textarea class="usp_textarea" name="user-submitted-content" id="user-submitted-content" rows="5"></textarea>
</div>
</li>
<li class="usp_images">
<label for="user-submitted-image" class="usp_label">Upload an Image</label>
<div id="usp_upload-message"></div>
<div>
<input class="usp_input usp_clone" type="file" size="25" id="user-submitted-image" name="user-submitted-image[]" />
Add another image
</div>
</li>
<li class="usp_submit">
<input class="usp_input" type="submit" name="user-submitted-post" id="user-submitted-post" value="Submit Post" />
</li>
</ul>
</form>
PHP:
if (!class_exists('Public_Submission_Form')) {
class Public_Submission_Form {
var $version = '1.0';
var $_post_meta_IsSubmission = 'is_submission';
var $_post_meta_Submitter = 'user_submit_name';
var $_post_meta_SubmitterUrl = 'user_submit_url';
var $_post_meta_SubmitterIp = 'user_submit_ip';
var $_post_meta_Image = 'user_submit_image';
var $_post_meta_ImageInfo = 'user_submit_image_info';
var $settings = null;
function Public_Submission_Form() {
register_activation_hook(__FILE__, array(&$this, 'saveDefaultSettings'));
add_action('admin_init', array(&$this, 'checkForSettingsSave'));
add_action('admin_menu', array(&$this, 'addAdministrativeElements'));
add_action('init', array(&$this, 'enqueueResources'));
add_action('parse_request', array(&$this, 'checkForPublicSubmission'));
add_action('parse_query', array(&$this, 'addSubmittedStatusClause'));
add_action('restrict_manage_posts', array(&$this, 'outputUserSubmissionLink'));
add_filter('the_author', array(&$this, 'replaceAuthor'));
add_filter('the_author_link', array(&$this, 'replaceAuthorLink'));
add_filter('post_stati', array(&$this, 'addNewPostStatus'));
add_shortcode('user-submitted-posts', array(&$this, 'getPublicSubmissionForm'));
}
function addAdministrativeElements() {
add_options_page(__('User Submitted Posts'), __('User Submitted Posts'), 'manage_options', 'user-submitted-posts', array(&$this, 'displaySettingsPage'));
}
function addNewPostStatus($postStati) {
$postStati['submitted'] = array(__('Submitted'), __('User submitted posts'), _n_noop('Submitted', 'Submitted'));
return $postStati;
}
function addSubmittedStatusClause($wp_query) {
global $pagenow;
if (is_admin() && $pagenow == 'edit.php' && $_GET['user_submitted'] == '1') {
set_query_var('meta_key', $this->_post_meta_IsSubmission);
set_query_var('meta_value', 1);
set_query_var('post_status', 'pending');
}
}
function checkForPublicSubmission() {
if (isset($_POST['user-submitted-post']) && ! empty($_POST['user-submitted-post'])) {
$settings = $this->getSettings();
$title = stripslashes($_POST['user-submitted-title']);
$content = stripslashes($_POST['user-submitted-content']);
$authorName = stripslashes($_POST['user-submitted-name']);
$authorUrl = stripslashes($_POST['user-submitted-url']);
$tags = stripslashes($_POST['user-submitted-tags']);
$category = intval($_POST['user-submitted-category']);
$fileData = $_FILES['user-submitted-image'];
$publicSubmission = $this->createPublicSubmission($title, $content, $authorName, $authorUrl, $tags, $category, $fileData);
if (false == ($publicSubmission)) {
$errorMessage = empty($settings['error-message']) ? __('An error occurred. Please go back and try again.') : $settings['error-message'];
if( !empty( $_POST[ 'redirect-override' ] ) ) {
$redirect = stripslashes( $_POST[ 'redirect-override' ] );
$redirect = add_query_arg( array( 'submission-error' => '1' ), $redirect );
wp_redirect( $redirect );
exit();
}
wp_die($errorMessage);
} else {
$redirect = empty($settings['redirect-url']) ? $_SERVER['REQUEST_URI'] : $settings['redirect-url'];
if (! empty($_POST['redirect-override'])) {
$redirect = stripslashes($_POST['redirect-override']);
}
$redirect = add_query_arg(array('success'=>1), $redirect);
wp_redirect($redirect);
exit();
}
}
}
function checkForSettingsSave() {
if (isset($_POST['save-post-submission-settings']) && current_user_can('manage_options') && check_admin_referer('save-post-submission-settings')) {
$settings = $this->getSettings();
$settings['author'] = get_userdata($_POST['author']) ? $_POST['author'] : $settings['author'];
$settings['categories'] = is_array($_POST['categories']) && ! empty($_POST['categories']) ? array_unique($_POST['categories']) : array(get_option('default_category'));
$settings['number-approved'] = is_numeric($_POST['number-approved']) ? intval($_POST['number-approved']) : - 1;
$settings['redirect-url'] = stripslashes($_POST['redirect-url']);
$settings['error-message'] = stripslashes($_POST['error-message']);
$settings['min-images'] = is_numeric($_POST['min-images']) ? intval($_POST['min-images']) : $settings['max-images'];
$settings['max-images'] = (is_numeric($_POST['max-images']) && ($settings['min-images'] <= $_POST['max-images'])) ? intval($_POST['max-images']) : $settings['max-images'];
$settings['min-image-height'] = is_numeric($_POST['min-image-height']) ? intval($_POST['min-image-height']) : $settings['min-image-height'];
$settings['min-image-width'] = is_numeric($_POST['min-image-width']) ? intval($_POST['min-image-width']) : $settings['min-image-width'];
$settings['max-image-height'] = (is_numeric($_POST['max-image-height']) && ($settings['min-image-height'] <= $_POST['max-image-height'])) ? intval($_POST['max-image-height']) : $settings['max-image-height'];
$settings['max-image-width'] = (is_numeric($_POST['max-image-width']) && ($settings['min-image-width'] <= $_POST['max-image-width'])) ? intval($_POST['max-image-width']) : $settings['max-image-width'];
$settings['usp_name'] = stripslashes($_POST['usp_name']);
$settings['usp_url'] = stripslashes($_POST['usp_url']);
$settings['usp_title'] = stripslashes($_POST['usp_title']);
$settings['usp_tags'] = stripslashes($_POST['usp_tags']);
$settings['usp_category'] = stripslashes($_POST['usp_category']);
$settings['usp_content'] = stripslashes($_POST['usp_content']);
$settings['usp_images'] = stripslashes($_POST['usp_images']);
$settings['upload-message'] = stripslashes($_POST['upload-message']);
$settings['usp_form_width'] = stripslashes($_POST['usp_form_width']);
$this->saveSettings($settings);
wp_redirect(admin_url('options-general.php?page=user-submitted-posts&updated=1'));
}
}
function displaySettingsPage() {
include ('views/settings.php');
}
function enqueueResources() {
wp_enqueue_script('usp_script', WP_PLUGIN_URL.'/'.basename(dirname(__FILE__)).'/resources/user-submitted-posts.js', array('jquery'), $this->version);
wp_enqueue_style('usp_style', WP_PLUGIN_URL.'/'.basename(dirname(__FILE__)).'/resources/user-submitted-posts.css', false, $this->version, 'screen');
}
function getPublicSubmissionForm($atts = array(), $content = null) {
if ($atts === true) {
$redirect = $this->currentPageURL();
}
ob_start();
include (WP_PLUGIN_DIR.'/'.basename(dirname(__FILE__)).'/views/submission-form.php');
return ob_get_clean();
}
function outputUserSubmissionLink() {
global $pagenow;
if ($pagenow == 'edit.php') {
echo '<a id="usp_admin_filter_posts" class="button-secondary" href="'.admin_url('edit.php?post_status=pending&user_submitted=1').'">'.__('User Submitted Posts').'</a>';
}
}
function replaceAuthor($author) {
global $post;
$isSubmission = get_post_meta($post->ID, $this->_post_meta_IsSubmission, true);
$submissionAuthor = get_post_meta($post->ID, $this->_post_meta_Submitter, true);
if ($isSubmission && ! empty($submissionAuthor)) {
return $submissionAuthor;
} else {
return $author;
}
}
function replaceAuthorLink($authorLink) {
global $post;
$isSubmission = get_post_meta($post->ID, $this->_post_meta_IsSubmission, true);
$submissionAuthor = get_post_meta($post->ID, $this->_post_meta_Submitter, true);
$submissionLink = get_post_meta($post->ID, $this->_post_meta_SubmitterUrl, true);
if ($isSubmission && ! empty($submissionAuthor)) {
if ( empty($submissionLink)) {
return $submissionAuthor;
} else {
return "<a href='{$submissionLink}'>{$submissionAuthor}</a>";
}
} else {
return $authorLink;
}
}
function saveDefaultSettings() {
$settings = $this->getSettings();
if ( empty($settings)) {
$currentUser = wp_get_current_user();
$settings = array();
$settings['author'] = $currentUser->ID;
$settings['categories'] = array(get_option('default_category'));
$settings['number-approved'] = -1;
$settings['redirect-url'] = ''; //site_url();
$settings['error-message'] = __('There was an error. Please ensure that you have added a title, some content, and that you have uploaded only images.');
$settings['min-images'] = 0;
$settings['max-images'] = 1;
$settings['min-image-height'] = 0;
$settings['min-image-width'] = 0;
$settings['max-image-height'] = 500;
$settings['max-image-width'] = 500;
$settings['usp_name'] = 'show';
$settings['usp_url'] = 'show';
$settings['usp_title'] = 'show';
$settings['usp_tags'] = 'show';
$settings['usp_category'] = 'show';
$settings['usp_content'] = 'show';
$settings['usp_images'] = 'hide';
$settings['upload-message'] = ''; // 'Please select your image(s) to upload:';
$settings['usp_form_width'] = '300'; // in pixels
$this->saveSettings($settings);
}
}
function getSettings() {
if ($this->settings === null) {
$defaults = array();
$this->settings = get_option('User Submitted Posts Settings', array());
}
return $this->settings;
}
function saveSettings($settings) {
if (!is_array($settings)) {
return;
}
$this->settings = $settings;
update_option('User Submitted Posts Settings', $this->settings);
}
function createPublicSubmission($title, $content, $authorName, $authorUrl, $tags, $category, $fileData) {
$settings = $this->getSettings();
$authorName = strip_tags($authorName);
$authorUrl = strip_tags($authorUrl);
$authorIp = $_SERVER['REMOTE_ADDR'];
if (!$this->validateTitle($title)) {
return false;
}
if (!$this->validateContent($title)) {
return false;
}
if (!$this->validateTags($tags)) {
return false;
}
$postData = array();
$postData['post_title'] = $title;
$postData['post_content'] = $content;
$postData['post_status'] = 'pending';
$postData['author'] = $settings['author'];
$numberApproved = $settings['number-approved'];
if ($numberApproved < 0) {} elseif ($numberApproved == 0) {
$postData['post_status'] = 'publish';
} else {
$posts = get_posts(array('post_status'=>'publish', 'meta_key'=>$this->_post_meta_Submitter, 'meta_value'=>$authorName));
$counter = 0;
foreach ($posts as $post) {
$submitterUrl = get_post_meta($post->ID, $this->_post_meta_SubmitterUrl, true);
$submitterIp = get_post_meta($post->ID, $this->_post_meta_SubmitterIp, true);
if ($submitterUrl == $authorUrl && $submitterIp == $authorIp) {
$counter++;
}
}
if ($counter >= $numberApproved) {
$postData['post_status'] = 'publish';
}
}
$newPost = wp_insert_post($postData);
if ($newPost) {
wp_set_post_tags($newPost, $tags);
wp_set_post_categories($newPost, array($category));
if (!function_exists('media_handle_upload')) {
require_once (ABSPATH.'/wp-admin/includes/media.php');
require_once (ABSPATH.'/wp-admin/includes/file.php');
require_once (ABSPATH.'/wp-admin/includes/image.php');
}
$attachmentIds = array();
$imageCounter = 0;
for ($i = 0; $i < count($fileData['name']); $i++) {
$imageInfo = getimagesize($fileData['tmp_name'][$i]);
if (false === $imageInfo || !$this->imageIsRightSize($imageInfo[0], $imageInfo[1])) {
continue;
}
$key = "public-submission-attachment-{$i}";
$_FILES[$key] = array();
$_FILES[$key]['name'] = $fileData['name'][$i];
$_FILES[$key]['tmp_name'] = $fileData['tmp_name'][$i];
$_FILES[$key]['type'] = $fileData['type'][$i];
$_FILES[$key]['error'] = $fileData['error'][$i];
$_FILES[$key]['size'] = $fileData['size'][$i];
$attachmentId = media_handle_upload($key, $newPost);
if (!is_wp_error($attachmentId) && wp_attachment_is_image($attachmentId)) {
$attachmentIds[] = $attachmentId;
add_post_meta($newPost, $this->_post_meta_Image, wp_get_attachment_url($attachmentId));
$imageCounter++;
} else {
wp_delete_attachment($attachmentId);
}
if ($imageCounter == $settings['max-images']) {
break;
}
}
if (count($attachmentIds) < $settings['min-images']) {
foreach ($attachmentIds as $idToDelete) {
wp_delete_attachment($idToDelete);
}
wp_delete_post($newPost);
return false;
}
update_post_meta($newPost, $this->_post_meta_IsSubmission, true);
update_post_meta($newPost, $this->_post_meta_Submitter, htmlentities(($authorName)));
update_post_meta($newPost, $this->_post_meta_SubmitterUrl, htmlentities(($authorUrl)));
update_post_meta($newPost, $this->_post_meta_SubmitterIp, $authorIp);
}
return $newPost;
}
function imageIsRightSize($width, $height) {
$settings = $this->getSettings();
$widthFits = ($width <= intval($settings['max-image-width'])) && ($width >= $settings['min-image-width']);
$heightFits = ($height <= $settings['max-image-height']) && ($height >= $settings['min-image-height']);
return $widthFits && $heightFits;
}
function validateContent($content) {
return ! empty($content);
}
function validateTags($tags) {
return true;
}
function validateTitle($title) {
return ! empty($title);
}
function currentPageURL() {
$pageURL = 'http';
if ($_SERVER["HTTPS"] == "on") {
$pageURL .= "s";
}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $pageURL;
}
}
$publicSubmissionForm = new Public_Submission_Form();
include ('library/template-tags.php');
}
== Template Tags ==
To display the images attached to user-submitted posts, use this template tag:
<?php post_attachments(); ?>
This template tag prints the URLs for all post attachments and accepts the following paramters:
<?php post_attachments($size, $beforeUrl, $afterUrl, $numberImages, $postId); ?>
$size = image size as thumbnail, medium, large or full -> default = full
$beforeUrl = text/markup displayed before the image URL -> default = <img src="
$afterUrl = text/markup displayed after the image URL -> default = " />
$numberImages = the number of images to display for each post -> default = false (display all)
$postId = an optional post ID to use -> default = uses global post
Additionally, the following template tag returns an array of URLs for the specified post image:
<?php get_post_images(); ?>
This tag returns a boolean value indicating whether the specified post is a public submission:
<?php is_public_submission(); ?>
What does var_dump($_FILES) look like? It looks like you're generating a unique field name for each file upload field, using $key = "public-submission-attachment-{$i}";. if that's the case, then your file access structure is incorrect. PHP will generate the $_FILES data for each fieldname 1 of 2 ways:
If you're using a unique somestring field name, you get a structure like:
$_FILES['somestring'] = array(
'name' => 'somefile.txt',
'type' => 'text/plain',
'size' => 1234,
'error' => 0,
'tmp_name'] => '/tmp/asdfasdfasdfa'
);
If you're using the PHP-centric array notation, somestring[] (note the []) for the field name, you get:
$_FILES['somestring'] = array(
'name' => array(
0 => 'somefile1.txt',
1 => 'somepic.jpg'
),
'type' => array(
0 => 'text/plain',
1 => 'image.jpeg'
)
etc...
);
Given that it you seem to be generating a unique field name, WITHOUT the array notation, you'd have to use option #1.
All of my application is written in PHP, bar 1 script which happens to create a md5 hash which is used later via PHP scripts. Problem being they dont match up.
PERL:
#$linkTrue = 'http://www.themobilemakeover.co.uk/mobile-makeover-appointment-booking-signup.php'
md5_hex($linkTrue);
And for testing purposes i did this in PHP:
echo md5("http://www.themobilemakeover.co.uk/mobile-makeover-appointment-booking-signup.php");
both return different values. Does anyone know why this is?
EDIT:
WHOLE PHP SCRIPT
<?php
echo md5("http://www.themobilemakeover.co.uk/mobile-makeover-appointment-booking-signup.php");
?>
WHOLE PERL SCRIPT (sorry its long)
#!/usr/bin/perl
use strict;
use warnings;
use LWP::Simple;
require LWP::UserAgent;
sub trim($);
use DBI;
use Net::FTP;
use Digest::MD5 qw(md5 md5_hex md5_base64);
print "Content-type: text/html\n\n";
print "<html>\n<head>\n</head><body>\n";
my $ua = LWP::UserAgent->new;
$ua->timeout(10);
$ua->env_proxy;
$ua->max_redirect(0);
#my %get = ();
#for (split /\&/, $ENV{'QUERY_STRING'}) { my ($key, $val) = split /=/; $val =~ s/\+/ /g; $val =~ s/%([0-9a-fA-F]{2})/chr(hex($1))/ge; $get{$key} = $val; }
#my %post = ();
#for (split /\&/, <STDIN>) { my ($key, $val) = split /=/; $val =~ s/\+/ /g; $val =~ s/%([0-9a-fA-F]{2})/chr(hex($1))/ge; $post{$key} = $val; }
my %get = ('findAllPages' => 'true' );
my %post = ('ki' => '############################' );
sub trim($){
my $string = shift;
$string =~ s/^\s+//;
$string =~ s/\s+$//;
return $string;
}
sub extention {
my($data) = #_;
if( substr( trim($data), -1) eq "/" ){
my #extArray = ('.html', '.php', '.htm', '.asp', '.shtml', '.aspx');
foreach(#extArray){
my $ext = $_;
my $testResponse = $ua->get('http://' . trim($data . "index" . $ext));
my $testResponseCode = $testResponse->code;
if( $testResponseCode == 200 || $testResponseCode == 301 || $testResponseCode == 302 ){
return trim($data . "index" . $ext);
last;
}
}
}else{
return $data;
}
}
if( defined( $get{findAllPages} ) && defined( $post{ki} ) ){
my ($database, $hostname, $port, $password, $user );
$database = "##########";
$hostname = "############";
$password = "##########";
$user = "#########";
my $KI = $post{ki};
# connect to the database
my $dsn = "DBI:mysql:database=$database;host=$hostname;";
my $dbh = DBI->connect($dsn, $user, $password);
my $sth = $dbh->prepare("SELECT * FROM accounts WHERE KI = '$KI' ") or die "Could not select from table" . $DBI::errstr;
$sth->execute();
if( $sth->rows != 0 ) {
my $ref = $sth->fetchrow_hashref();
my $domain = $ref->{website};
my $DB_username = $ref->{db_name};
my $DB_password = $ref->{db_pass};
my $DB_ftpuser = $ref->{ftpuser};
my $DB_ftppass = $ref->{ftppass};
my $DB_ftpserver = $ref->{ftpserver};
$sth->finish();
$dbh->disconnect();
chomp(my $url = trim($domain));
# try and find full path
sub findFullPath {
my($link, $landingPage) = #_;
# strip ./ and / from beggining of string
$link =~ s/^(?:(?:\/)|(?:\.\/))//g;
# find out whether link is backtracing to previous folder
if( $link =~ m/^\.\.\// ) { # link desination is back tracing
if( $landingPage =~ m/(?:(?:\.html)|(?:\.php)|(?:\.htm)|(?:\.asp)|(?:\.shtml)|(?:\.aspx))$/g ) {
# find destination folder from landing page
my #folders = split( "/", $landingPage );
#find size of array
my $foldersSize = scalar #folders;
delete $folders[$foldersSize - 1];
$foldersSize = scalar #folders;
my #backFolders = ( $link =~ m/\.\.\//g ); # get rid of ../
my $amountOfBackFolders = scalar #backFolders; # find how many folders back
for( my $x=0; $x < $amountOfBackFolders; $x++ ) {
my $numberToDelete = ($foldersSize - 1) - $x;
delete $folders[$numberToDelete];
}
$landingPage = join( "/", #folders );
$link =~ s/\.\.\///g;
return $landingPage . "/" . $link . "\n";
} elsif( $landingPage =~ m/(?:\/)$/g ) {
my #folders = split( "/", $landingPage );
#find size of array
my $foldersSize = scalar #folders;
delete $folders[$foldersSize - 1];
$foldersSize = scalar #folders;
my #backFolders = ( $link =~ m/\.\.\//g ); # get rid of ../
my $amountOfBackFolders = scalar #backFolders; # find how many folders back
for( my $x=0; $x < $amountOfBackFolders; $x++ ) {
my $numberToDelete = ($foldersSize) - $x;
delete $folders[$numberToDelete];
}
$landingPage = join( "/", #folders );
$link =~ s/\.\.\///g;
return $landingPage . "/" . $link . "\n";
} else {
}
}else{
if( substr( $landingPage, -1) eq "/" ){
return $landingPage . $link;
}else{
my #splitLandingPage = split( "/", $landingPage );
my $amountSplit = scalar #splitLandingPage;
my $toDelete = $amountSplit - 1;
my $lastEntry = $splitLandingPage[$toDelete];
if( $lastEntry =~ m/(?:(?:com)|(?:co\.uk)|(?:net)|(?:org)|(?:cc)|(?:tv)|(?:info)|(?:org\.uk)|(?:me\.uk)|(?:biz)|(?:name)|(?:eu)|(?:uk\.com)|(?:eu\.com)|(?:gb\.com)|(?:gb\.net)|(?:uk\.net)|(?:me)|(?:mobi))$/g ) {
return join( "/", #splitLandingPage ) . "/" . $link . "\n";
}else{
delete $splitLandingPage[$toDelete];
return join( "/", #splitLandingPage ) . "/" . $link . "\n";
}
}
}
}
# get HTTP details
my $response = $ua->get('http://' . trim($url));
my $responseCode = $response->code;
my $responseLocation = $response->header( 'Location' );
# contintue only if status code is 200 or 301
if( $responseCode != 200 && $responseCode != 301 && $responseCode != 302 ){
print "<span class=\"red\"> error: http://" . trim($url) . "Domain name invalid, please use differnet domain name: http status - " . $responseCode . "</span><br />\n";
die;
}
# change url if domain status eq 301
if( $responseCode == 301 || $responseCode == 302 ){
if($response->header( 'Location' ) =~ m/^http:\/\/www\./g ) {
$url = substr( $response->header( 'Location' ), 11 );
}elsif($response->header( 'Location' ) =~ m/^http:\/\//g ) {
$url = substr( $response->header( 'Location' ), 7 );
}else{
$url = findFullPath($response->header( 'Location' ), $url);
}
}
my #pagesArray = ($url);
my #pagesScannedArray;
my #mainPagesArray;
my #pagesNotScanned;
my $z = 0;
#print "\nGethering all valid links from " . $domain . "...\n\n";
while ( #pagesArray && $z < 100 ) {
# get the next in queue for proccessing
my $page = trim(shift #pagesArray);
if( ! grep {$_ eq trim($page)} #pagesNotScanned ) {
# check page http status
$response = $ua->get("http://" . trim($page));
$responseCode = $response->code;
if( $responseCode == 200 || $responseCode == 301 || $responseCode == 302 ){
# change page url if 301 redirect
if( $responseCode == 301 || $responseCode == 302 ){
if($response->header( 'Location' ) =~ m/^http:\/\/www\./g ) {
$page = substr( $response->header( 'Location' ), 11 );
}elsif($response->header( 'Location' ) =~ m/^http:\/\//g ) {
$page = substr( $response->header( 'Location' ), 7 );
}else{
$page = findFullPath($response->header( 'Location' ), $url);
}
}
# connect to page and get contents
if( my $pageData = get "http://" . trim($page) ) {
# get all links on page
my #pageLinksArray = ( $pageData =~ m/href=["']([^"']*)["']/g );
# foreach link on the page
foreach( #pageLinksArray ) {
my $link = trim($_);
# remove url if located on same domain
$link =~ s/(?:http:\/\/)?(?:www\.)?$url//g;
# if link is format we are looking for
if( $link =~ m/(?:(?:\.html)|(?:\.php)|(?:\.htm)|(?:\.asp)|(?:\.shtml)|(?:\.aspx)|(?:\/))$/ ) {
# if link is outbound
if( $link =~ m/^http:\/\//g ) {
if( ! grep {$_ eq trim($link)} #pagesNotScanned ) {
if( ! grep {$_ eq trim($page)} #mainPagesArray ) {
push ( #pagesNotScanned, trim($link) );
}
}
}else{
# find full path for link
my $newUrl = &findFullPath(trim($link), trim($page));
# if link has not already been claimed to be a main page
if( ! grep {$_ eq trim($newUrl)} #mainPagesArray ) {
# if link is not already in queue
if( ! grep {$_ eq trim($newUrl)} #pagesArray ) {
push ( #pagesArray, trim($newUrl) );
}
}
}
}
}
if( ! grep {$_ eq trim($page)} #mainPagesArray ) {
push ( #mainPagesArray, trim($page) );
}
}
}else{
if( ! grep {$_ eq trim($page)} #pagesNotScanned ) {
if( ! grep {$_ eq trim($page)} #mainPagesArray ) {
push ( #pagesNotScanned, trim($page) );
}
}
}
}
$z++;
}
if( scalar #mainPagesArray != 0 ) {
my ($database, $hostname, $port, $password, $user );
$database = $DB_username;
$hostname = "###########";
$password = $DB_password;
$user = $DB_username;
# connect to the database
my $dsn = "DBI:mysql:database=$database;host=$hostname;";
my $dbh = DBI->connect($dsn, $user, $password) or die " error: Couldn't connect to database: " . DBI->errstr;
print "\nTesting links' extentions from " . $domain . "...\n\n";
my $root;
my $ftp = Net::FTP->new($DB_ftpserver, Debug => 0) or die "Cannot connect to some.host.name: $#";
$ftp->login($DB_ftpuser, $DB_ftppass) or die "Cannot login ", $ftp->message;
my #list = $ftp->dir;
if( scalar #list != 0 ) {
foreach( #list ){
if( $_ =~ m/((?:www)|(?:public_html)|(?:htdocs))$/g ){
$root = $1;
last;
}
}
}
if( $root eq "" ) {
print "error: could not identify root directory.<br />\n";
die;
}
foreach( #mainPagesArray ) {
my $webpage = &extention(trim($_));
if( trim($webpage) ne trim($domain) ){
my $webpageQuote = $dbh->quote("http://www." . $webpage);
my $sth = $dbh->prepare("SELECT * FROM page_names WHERE linkTrue = $webpageQuote ") or die "Could not select from table" . $DBI::errstr;
$sth->execute();
if( $sth->rows == 0 ) {
print "http://www." . $webpage . "<br />\n";
my $linkTrue = $dbh->quote("http://www." . $webpage);
my $string = ($webpage =~ s/^$domain//g);
my $linkFromRoot = $dbh->quote($root . $webpage);
my $page_name = $dbh->quote("");
my $table_name = $dbh->quote(md5_hex(trim($linkTrue)));
my $navigation = $dbh->quote("");
my $location = $dbh->quote("");
$dbh->do("INSERT INTO page_names (linkFromRoot, linkTrue, page_name, table_name, navigation, location) VALUES ( $linkFromRoot, $linkTrue, $page_name, $table_name, $navigation, $location )") or die " error: Couldn't connect to database: " . DBI->errstr;
}
}
}
}else{
print "<span class=\"red\"> error: No pages where found. This CMS is designed for pre-existing sites. Please contact support for more information.</span><br />\n";
}
}else{
print "<span class=\"red\"> error: input key incorrerct.</span><br />\n";
}
}else{
print "<span class=\"red\"> error: This area is forbidden please locate back to www.plugnplaycms.co.uk</span><br />\n";
}
print "</body>\n</html>";
I believe its on line 274. The code might be messy but its my first script with perl, only been at it a week.
thing i got it. $dbh->quote() adds single quotes around the value.
http://www.themobilemakeover.co.uk/index.php
HEX: 58030da397e8a071bc192e67744faeb3 VALUE: ['http://www.themobilemakeover.co.uk/index.php']
http://www.themobilemakeover.co.uk/about-us-the-mobile-makeover.php
HEX: 569c081a2974da39758a3cbf3c3407d2 VALUE: ['http://www.themobilemakeover.co.uk/about-us-the-mobile-makeover.php']
http://www.themobilemakeover.co.uk/beauty-products-used.php
HEX: ac94f84cf6b27bca0c23cd6b0e0f1fc9 VALUE: ['http://www.themobilemakeover.co.uk/beauty-products-used.php']
http://www.themobilemakeover.co.uk/beauty-treatments.php
HEX: e88d7e8e16ffc0a72b56a884d4c6c06b VALUE: ['http://www.themobilemakeover.co.uk/beauty-treatments.php']
http://www.themobilemakeover.co.uk/contact.php
HEX: 8924fa24bdde1c4e072f99826d957b77 VALUE: ['http://www.themobilemakeover.co.uk/contact.php']
http://www.themobilemakeover.co.uk/pamper-parties.php
HEX: 1f2fae70048359734a9d1b3ca29cce55 VALUE: ['http://www.themobilemakeover.co.uk/pamper-parties.php']
http://www.themobilemakeover.co.uk/mobile-makeover-appointment-booking.php
HEX: 9961f75109590c3924e4018768ecd44e VALUE: ['http://www.themobilemakeover.co.uk/mobile-makeover-appointment-booking.php']
http://www.themobilemakeover.co.uk/sitemap/index.php
HEX: fbca4996156b038f4635467ee13e1615 VALUE: ['http://www.themobilemakeover.co.uk/sitemap/index.php']
http://www.themobilemakeover.co.uk/accessibility/index.php
HEX: 6f03046cbe90c490e4993c5325a44aa7 VALUE: ['http://www.themobilemakeover.co.uk/accessibility/index.php']
http://www.themobilemakeover.co.uk/terms/index.php
HEX: 5304b5e9bd933fb920a4f8749c27094b VALUE: ['http://www.themobilemakeover.co.uk/terms/index.php']
http://www.themobilemakeover.co.uk/beauty-treatments2.php
HEX: 96225fa657ef60b4969d277d01d8b577 VALUE: ['http://www.themobilemakeover.co.uk/beauty-treatments2.php']
http://www.themobilemakeover.co.uk/beauty-treatments3.php
HEX: 327c1bc37354aad202c90efe0dfa756b VALUE: ['http://www.themobilemakeover.co.uk/beauty-treatments3.php']
http://www.themobilemakeover.co.uk/wedding-and-special-occasions.php
HEX: 54c074a1881a0c958c7c2b8ff88f63d6 VALUE: ['http://www.themobilemakeover.co.uk/wedding-and-special-occasions.php']
http://www.themobilemakeover.co.uk/mobile-makeover-appointment-booking-signup.php
HEX: 486c944b10ef539aa7ba4bfe607861f2 VALUE: ['http://www.themobilemakeover.co.uk/mobile-makeover-appointment-booking-signup.php']
When I try it, both programs return a4cbeef10b3c6d44ca30d96370619eef
I have the feeling you're not giving us the whole picture. Show us the code leading up to this. In particular, check for newlines. Have you used chomp in the perl script?
Try for yourself. Here is the complete php script I used:
<?php
echo md5("http://www.themobilemakeover.co.uk/mobile-makeover-appointment-booking-signup.php");
?>
And here is a complete perl script I used:
#!/usr/bin/perl
use Digest::Perl::MD5 'md5_hex';
$linkTrue = 'http://www.themobilemakeover.co.uk/mobile-makeover-appointment-booking-signup.php';
print md5_hex($linkTrue);
edit:
Which if the two scripts is not returning that value for md5? That's the one that has a bug. Log the value that you're passing to md5, (with '[' before and ']' after to detect extra whitespace). Does that value match what you expect?
edit 2:
It looks like you found it, right? It's the single quotes. This:
print md5_hex("'http://www.themobilemakeover.co.uk/mobile-makeover-appointment-booking-signup.php'");
Notice the extra quotes. The above line gives me: 486c944b10ef539aa7ba4bfe607861f2
I have a script that parses the page for the link tag, but as there are multiple ways to download a page ( wget, file_get_contents, curl, etc ... ) and there are multiple ways to include a favicon, the script is getting to big.
Is there a concise way to do this? Maybe an API that could be used?
Below is the growing script:
<?php
// Use a direct GET request for debugging, just pass in the domain ( ?domain=test.com )
if($_GET)
{
$obj = new FaviconFinder();
$obj->invokeDebug($_GET);
}
class FaviconFinder
{
// domain before and after redirects
private $domain;
private $real_domain;
// the file and how it was obtained
private $file_code = '0';
private $file_page;
// the favicon and how it was obtained
private $favicon_code = 'z';
private $file_favicon;
private $ext;
// paths local to server and on the internet (URL)
private $path_local1 = "../../favicons/";
private $path_local;
private $path_internet;
/****************************************************************************************************
invokeTest
****************************************************************************************************/
public function invokeTest($pipe)
{
exec('wget ' . $pipe['domain'] . ' -O ../sites/temp.html 2>&1', $output);
print_r($output);
}
/****************************************************************************************************
invokeDebug
****************************************************************************************************/
public function invokeDebug($pipe)
{
echo "<br><br> domain: " . $pipe['domain'] . "";
$pipe = $this->invoke($pipe);
echo "<br><br> real_domain: " . $this->real_domain . "";
echo "<br><br> file_code | " . $this->file_code;
echo "<br><br> favicon_code | " . $this->favicon_code;
echo "<br><br> favicon_path | " . $this->path_internet;
echo "<br><br> favicon_file | " . $this->file_favicon;
echo "<br><br> favicon_file type | " . gettype($this->file_favicon);
echo "<br><br> favicon_file length | " . strlen($this->file_favicon);
echo "<br><br> IMAGE: ";
if ($this->file_favicon)
{
echo "<br><br> path_local | " . $this->path_local . "<br><br>";
$file64 = base64_encode($this->file_favicon);
echo "<img src= 'data:image/" . $this->ext . ";base64," . $file64 . "'></img>";
}
echo "<br><br>";
}
/****************************************************************************************************
invoke
****************************************************************************************************/
public function invoke( $pipe )
{
$domain = $pipe['domain'];
if ( $this->pageFound($domain) && $this->linkFound() && $this->faviconFoundFromLink() )
{
$pipe = $this->saveFavicon($pipe);
$pipe['favicon'] = $this->path_internet;
$pipe['favicon_local'] = $this->path_local;
} else {
$pipe['favicon'] = 'NULL';
$pipe['favicon_local'] = 'image_generic.png';
}
$pipe['method'] = $this->file_code . $this->favicon_code;
return $pipe;
}
/****************************************************************************************************
pageFound - uses the facade pattern to find a page and record how it was found
****************************************************************************************************/
private function pageFound ($domain)
{
return $this->pageFoundCurl($domain) || $this->pageFoundGet($domain);
}
// wget is another way to get past login page
// https://stackoverflow.com/questions/1324421/how-to-get-past-the-login-page-with-wget
// uses curl_exec to retreive a page
private function pageFoundCurl ($domain)
{
$types = array(
"curl - 4"=>'https://www.' . $domain,
"curl - 3"=>'http://www.' . $domain,
"curl - 6"=>'https://' . $domain,
"curl - 5"=>'http://' . $domain,
// returned 302 errors for test.com
"curl - 1"=>$domain,
"curl - 2"=>'www.' . $domain
);
foreach ($types as $key => $value) {
$this->file_page = $this->curlExec($value, true);
if ($this->file_page)
{
$this->file_code = $key;
return true;
}
}
return false;
}
// uses file_get_contents to retreive a page
private function pageFoundGet( $domain )
{
$types = array(
"file_get - 3"=>'http://www.' . $domain,
"file_get - 4"=>'https://www.' . $domain,
"file_get - 5"=>'http://' . $domain,
"file_get - 6"=>'https://' . $domain,
"file_get - 1"=>$domain,
"file_get - 2"=>'www.' . $domain
);
foreach ($types as $key => $value) {
if ($this->file_page = $this->fileGetContents( $value ))
{
$this->file_code = $key;
return true;
}
}
return false;
}
/****************************************************************************************************
linkFound
****************************************************************************************************/
private function linkFound()
{
$domain = $this->real_domain;
$regex = '#<link\s+(?=[^>]*rel=(?:\'|")(?:shortcut\s)?icon(?:\'|")\s*)(?:[^>]*href=(?:\'|")(.+?)(?:\'|")).*>#i';
$link_found = preg_match( $regex , $this->file_page, $matches );
if($link_found === 1)
{
$path = $matches[1];
// handles ( // )
if ( $path[0] === '/' && $path[1] === '/' )
{
$this->favicon_code = 'a';
$this->path_internet = 'http:' . $path;
}
// handles ( / )
else if( $path[0] === '/' )
{
$this->favicon_code = 'b';
$this->path_internet = 'http://www.' . $domain . $path;
}
// handles ( http:// || https:// )
else if ( substr($path, 0, 4) === 'http' )
{
$this->favicon_code = 'c';
$this->path_internet = $path;
}
// difference between b and d?
else
{
$this->favicon_code = 'd';
$this->path_internet = 'http://www.' . $domain . '/' . $path;
}
}
else
{
$default_location = 'http://www.' . $domain . '/favicon.ico';
/*
if( $this->faviconFound($default_location) )
{
$this->favicon_code = 'e';
$this->path_internet = $default_location;
}
*/
$this->path_internet = null;
$this->favicon_code = 'g';
return false;
}
return true;
}
/****************************************************************************************************
faviconFound
****************************************************************************************************/
private function faviconFoundFromLink ()
{
$this->file_favicon = $this->faviconFoundFacade( $this->path_internet );
return $this->file_favicon ? true : false;
}
private function faviconFound ($default_location)
{
$this->file_favicon = $this->faviconFoundFacade( $default_location );
return $this->file_favicon ? true : false;
}
/****************************************************************************************************
More
****************************************************************************************************/
private function faviconFoundFacade($url)
{
return $this->faviconFoundCurl($url) ;
}
private function faviconFoundExec($url)
{
exec('wget ' . $url . ' -O ../sites/temp.html 2>&1', $output);
}
private function faviconFoundGet($url)
{
return #file_get_contents( $url );
}
// make less than 10 characters equate to false so I don't save bogus files
// prisonexp.org does this
// bestbuy.com does similar
private function faviconFoundCurl($url)
{
$temp = $this->curlExec( $url, false );
if($temp === false)
{
return false;
}
if(strlen($temp) < 20)
{
return false;
}
return $temp;
}
/****************************************************************************************************
saveFavicon
****************************************************************************************************/
public function saveFavicon( $pipe )
{
// this will remove any query parameters on the favicon link
// and create a valid file name from the real domain
$arr = parse_url($this->path_internet);
$this->ext = pathinfo($arr['path'], PATHINFO_EXTENSION);
$name = str_replace('.', '_', $this->real_domain);
// add the extension if it exists, verify you need to to do this
if ($this->ext) {
$name = $name . "." . $this->ext;
}
// finally save it
file_put_contents($this->path_local1 . $name, $this->file_favicon);
$this->path_local = $name;
return $pipe;
}
/****************************************************************************************************
helper and wrapper functions
****************************************************************************************************/
// curl_exec wrapper
private function curlExec ($url, $set)
{
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
));
$temp = curl_exec($curl);
if ($set) $this->setRealDomain($curl);
curl_close($curl);
return $temp;
}
private function setRealDomain ($curl)
{
$url = curl_getinfo( $curl )['url'];
$url = parse_url($url);
$url = $url['host'];
$this->real_domain = preg_replace('#^www\.(.+\.)#i', '$1', $url);
}
// deprecated as curl can do everything I need, just in case though
// https://stackoverflow.com/questions/
// 6009284/how-do-i-ignore-a-moved-header-with-file-get-contents-in-php
private function fileGetContents($value)
{
$opts = array(
'http'=>array(
'follow_location' => true,
'max_redirects' => 20
)
);
$context = stream_context_create($opts);
return #file_get_contents( $value, false, $context );
}
/****************************************************************************************************
removed
****************************************************************************************************/
private function removed ()
{
$res = preg_match('#(.*?)([^\.]*)(\.)([^\.]*)$#', $domain, $matches);
if($matches[1])
{
$main = $matches[2] . $matches[3] . $matches[4];
$default_location = 'http://www.' . $main . '/favicon.ico';
$this->file_favicon = #file_get_contents( $default_location );
if( $this->file_favicon )
{
$this->path_internet = $default_location;
$this->favicon_code = 'f';
return true;
}
}
}
}
Here is one API for the front-side.
To check favicon using Google API
There is no strategy or API for favicons. Parse the HTML, look for:
<link rel="shortcut icon" href="...">
or just:
<link rel="icon" href="...">
and extract the value of the href attribute.
If no such tag exists (or the referenced icon is not there) then check for /favicon.ico (this is how everything started in 1999, on Internet Explorer 5).
Additionally, iOS (and some versions of Android) searches for extra <link> elements having rel="apple-touch-icon" or rel="apple-touch-icon-precomposed".
Everything else is just guessing and speculations.
See also: https://en.wikipedia.org/wiki/Favicon#History