Skip to content

Instantly share code, notes, and snippets.

@jaketoolson
Created November 20, 2012 16:43
Show Gist options
  • Save jaketoolson/4119142 to your computer and use it in GitHub Desktop.
Save jaketoolson/4119142 to your computer and use it in GitHub Desktop.
Google Apps check
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
*
* @author Jake Toolson
*
*/
class Uploadify extends CI_Controller
{
public $upload_path;
public function __construct()
{
parent::__construct();
$this->load->library(array('csvreader','html_dom', 'curl'));
$this->load->helper(array('form','url', 'download','file', 'common'));
$this->upload_path = $_SERVER['DOCUMENT_ROOT'].'/assets/uploads/';
}
public function index()
{
if ( ! empty($_FILES))
{
$path = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';
$file_temp = $_FILES['Filedata']['tmp_name'];
$file_name = $this->_prep_filename($_FILES['Filedata']['name']);
$file_ext = $this->_get_extension($_FILES['Filedata']['name']);
// Fail safe -- invalid filetype uploaded
if (strtolower($file_ext) <> '.csv')
{
echo 2;
break;
}
$original_name = $file_name;
$newf_name = $this->_set_filename($path, $file_name, $file_ext, true);
$file_size = round($_FILES['Filedata']['size']/1024, 2);
$file_type = preg_replace("/^(.+?);.*$/", "\\1", $_FILES['Filedata']['type']);
$file_type = strtolower($file_type);
$targetFile = str_replace('//','/',$path) . $newf_name;
move_uploaded_file($file_temp,$targetFile);
$filearray = array();
$filearray['file_name'] = $newf_name;
$filearray['real_name'] = $original_name;
$filearray['file_ext'] = $file_ext;
$filearray['file_size'] = $file_size;
$filearray['file_path'] = $targetFile;
$filearray['file_temp'] = $file_temp;
$json_array = json_encode($filearray);
echo $json_array;
}
else
{
// No files processed, return 1
echo 1;
}
exit;
}
/**
* Process uploaded results.
* If the upload was an invalid file or empty or an error occured during upload,
* return error messages and stop.
*
* Successful upload will be JSON encoded and contain file details.
* Iterate through the CSV file and determine if the 1st column, the company name,
* uses GOOGLE APPS.
*
* Generate a results CSV file with findings.
* @return string
*/
public function save()
{
// Decode JSON returned by /js/uploadify/upload.php
// Response of < 1 means we have valid data so proceed.
$file = $this->input->post('filearray');
//print_r($file);
switch($file)
{
case 1 :
echo 'No file was processed.';
break;
case 2 :
echo 'Invalid file type.';
break;
default :
// Do we even have valid JSON data?
if ( ! is_json($file))
{
echo 'Invalid Submission - Please try again';
break;
}
$time_start = microtime(true);
// Decode json data
$data['json'] = json_decode($file);
// Full file path . file name
$file_path_name = $data['json']->{'file_path'};
// File name
$file_name = $data['json']->{'file_name'};
// New CSV file path . file name
$new_csv_name = $this->upload_path.'f_'.$file_name;
// Read in the uploaded file
$incoming_csv = $this->csvreader->parse_file($file_path_name, true);
// Create results CSV
$output_csv = fopen($new_csv_name, 'w') or die ('Something broke');
// Total Rows
$total_count = count($incoming_csv);
// Create header for results CSV
fputcsv($output_csv, array('Company', 'Uses App'));
foreach ($incoming_csv as $k => $company)
{
$final_csv = array();
// Place company name in first column of results CSV
$final_csv['url'] = $company_url;
// trim the company name and conver to lowercase
$company_url = strtolower(trim($company));
// The company name may have www, http, backslahes etc so strip them
$search = array("www.", "www", "http://", "http", ":/", "http://www.", "/", "\\");
$stripped_company_url = str_replace($search, '', $company_url);
$company_url = $stripped_company_url;
// TODO: Remove CURL as this is FAR Slower than expected.
// Send CURL request with certificate
// $this->curl->ssl(false, 1, '/assets/cert.pem');
// $html = $this->curl->simple_get('https://www.google.com/a/'.$company_url);
// Variable containing HTML DOM
$html = $this->using_fopen('https://www.google.com/a/'.$company_url.'/ServiceLogin?service=CPanel');
// Pass HTML file to DOM reader
$this->html_dom->loadHTML($html);
// If DOM has an element called 'serverErrorMessage', we can assume the company doesn't use APPS
// And can therefore flag it as invalid. Rather than boolean results, use strings as this is being
// written to CSV file for human consumption.
if (count($this->html_dom->find('#serverErrorMessage')) >= 1)
{
$final_csv['valid'] = "No";
}
else
{
$final_csv['valid'] = "Yes";
}
// Write the company name, results string to the CSV file
fputcsv($output_csv, $final_csv);
// Clear existing HTML DOM in order to continue to next company
$html = null;
}
// Close and save results CSV file
fclose($output_csv) or die("Something broke while saving results");
$time_end = microtime(true);
$time = $time_end - $time_start;
// Generate download link to results CSV file
echo anchor('/assets/uploads/f_'.$file_name.'','Download Results ('.$total_count.' were processed)', array('id'=>'download_results', 'class' => 'btn-large btn-success'));
echo anchor('#','Upload New File', array('id'=>'start_over', 'class' => 'btn-large btn-inverse'));
echo '<span style="font-size: 10px; margin: 11px auto; display: block; color: #999;">Processed '.$total_count.' in about '.round($time,2).' seconds</span>';
break;
}
}
/**
*
* @param string $path
* @param string $filename
* @param string $file_ext
* @param boolean $encrypt_name
* @return string
*/
private function _set_filename($path, $filename, $file_ext, $encrypt_name = FALSE)
{
if ($encrypt_name == TRUE)
{
mt_srand();
$filename = md5(uniqid(mt_rand())).$file_ext;
}
if ( ! file_exists($path.$filename))
{
return $filename;
}
$filename = str_replace($file_ext, '', $filename);
$new_filename = '';
for ($i = 1; $i < 100; $i++)
{
if ( ! file_exists($path.$filename.$i.$file_ext))
{
$new_filename = $filename.$i.$file_ext;
break;
}
}
if ($new_filename == '')
{
return FALSE;
}
else
{
return $new_filename;
}
}
/**
*
* @param string $filename
* @return string
*/
private function _prep_filename($filename)
{
if (strpos($filename, '.') === FALSE)
{
return $filename;
}
$parts = explode('.', $filename);
$ext = array_pop($parts);
$filename = array_shift($parts);
foreach ($parts as $part)
{
$filename .= '.'.$part;
}
$filename .= '.'.$ext;
return $filename;
}
/**
*
* @param string $filename
* @return string
*/
private function _get_extension($filename)
{
$x = explode('.', $filename);
return '.'.end($x);
}
public function using_fsockopen($url)
{
$parsedUrl = parse_url($url);
$host = $parsedUrl['host'];
if (isset($parsedUrl['path']))
{
$path = $parsedUrl['path'];
}
else
{
$path = '/';
}
if (isset($parsedUrl['query']))
{
$path .= '?' . $parsedUrl['query'];
}
if (isset($parsedUrl['port']))
{
$port = $parsedUrl['port'];
}
else
{
$port = '80';
}
$timeout = 100;
$response = '';
$fp = @fsockopen($host, '80', $errno, $errstr, $timeout );
if( ! $fp )
{
echo "Cannot retrieve $url";
die;
}
else
{
fputs($fp, "GET $path HTTP/1.0\r\n" .
"Host: $host\r\n" .
"User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.3) Gecko/20060426 Firefox/1.5.0.3\r\n" .
"Accept: */*\r\n" .
"Accept-Language: en-us,en;q=0.5\r\n" .
"Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n" .
"Keep-Alive: 300\r\n" .
"Connection: keep-alive\r\n" .
"Referer: http://$host\r\n\r\n");
while ( $line = fread( $fp, 1096 ) )
{
$response .= $line;
}
fclose( $fp );
$pos = strpos($response, "\r\n\r\n");
$response = substr($response, $pos + 4);
}
return $response;
}
/**
* Currently fastest method. Took ~ 63 seconds to process 100 domains.
*/
public function using_fopen($url)
{
if ($fp = fopen($url, 'r'))
{
$content = '';
stream_set_timeout($fp, 2);
while ($line = fread($fp, 4068))
{
$content .= $line;
}
return $content;
}
else
{
echo 'An Error Occured';
exit;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment