I am having this below code, It is work perfectly. But am having a small issue messuring the "$username_index" count.
the main idea of my code is following:
having accounts.txt [92 lines] usernames:pass format.
having usernames.txt [99999 lines] usernames format.
It will login to account1, then it will add 95 usernames, then next account2 , then add next 95 usernames.
But some accounts are giving response "Too many add friends". In this case response, I will skip the account and go to next.
But below code will contiue to the next 95!, so its skip 95 from usernames!
I want it contiue adding where the left username from skipped account.
I want it as soon it will login to the next account AND CONTIUING ADD THE NEXT LINE OF USERNAMES! no need to jump to next 95 username to add!
Example how i want it:
login account1
add username1
add username2
ERROR APPEARS!
login account2
add username3
add username4
add username5
add username6
error appears!
login account3
add username7
add username8
etc..
Current Code:
$username_index = 0;
while(true) { // This is our while.. yes but this not for login()!
try {
$names = readFromFile("usernames.txt", 95, $username_index);
if(count($names) <= 0)
break;
sleep(1);
$fuckc = 0;
foreach($names as $name){
$ans = $API->addFriend($name);
$var_response = $ans->getMessage();
if (strpos($var_response, 'too many friends!') !== false) {
printf("[!] Too many friends!, Skipping account now.\n");
break;
}
if (strpos($var_response, 'Sorry') === false) {
$fuckc++;
printf("[+]" . "[" . date("h:i:s") . "]" . "[" . $fuckc . "] " . "response: " . $var_response . "\n");
//printf("[" . $fuckc . "] " . "response: " . $var_response . "\n");
}
//sleep(SLEEP_TIME);
}
$username_index += 95;
$API->logout();
//rotate_proxy();
$API = null;
//sleep(waiting);
//$results = $findFriends->getResults();
if (!isset($results) || count($results) == 0) {
if(!login()) die("Could not find a valid account.\n");
}
} catch(Exception $e){
echo $e->getMessage() . "\n";
if(!login()) die("Could not find a valid account.\n");
}
}
Edited again : the counter $username_index only increasse when $var_response is not "too many friends!" :
$username_index = 0;
while(true) { // This is our while.. yes but this not for login()!
try {
$names = readFromFile("usernames.txt", 95, $username_index);
if(count($names) <= 0)
break;
sleep(1);
$fuckc = 0;
foreach($names as $name){
$ans = $API->addFriend($name);
$var_response = $ans->getMessage();
if (strpos($var_response, 'too many friends!') !== false) {
printf("[!] Too many friends!, Skipping account now.\n");
break;
}
else $username_index++; //◄■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
if (strpos($var_response, 'Sorry') === false) {
$fuckc++;
printf("[+]" . "[" . date("h:i:s") . "]" . "[" . $fuckc . "] " .
"response: " . $var_response . "\n");
//printf("[" . $fuckc . "] " . "response: " . $var_response . "\n");
}
//sleep(SLEEP_TIME);
}
// $username_index += 95; //◄■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
$API->logout();
//rotate_proxy();
$API = null;
//sleep(waiting);
//$results = $findFriends->getResults();
if (!isset($results) || count($results) == 0) {
if(!login()) die("Could not find a valid account.\n");
}
} catch(Exception $e){
echo $e->getMessage() . "\n";
if(!login()) die("Could not find a valid account.\n");
}
}
Related
First of all I am not sure if this the correct place to post about this particular problem because I don't know what the root cause is. If it isn't the right place, please say so and close the topic.
In a Windows Server 2012 64bit environment with 32GB RAM and an intel i7-4770, recently (last 4 months - before that it never happened) errors have started to appear in php_error.log with a totally random pattern as to when.
The errors say that functions or variables defined in other files included with require_once() do not exist. Once these errors start happening a reboot of the server machine "fixes" the issue. It takes a random amount of time for the problem to appear again, from 3 days to 10 days or 4 weeks. I have made disk checks for errors but nothing has come up
example1:
[21-Apr-2018 07:36:26 Asia/Kuwait] PHP Notice: Undefined variable: APPLICATIONDIRECTORY in C:\inetpub\wwwroot\ell\makeIdent.php on line 18
[21-Apr-2018 07:36:26 Asia/Kuwait] PHP Notice: Undefined variable: DLLDIR in C:\inetpub\wwwroot\ell\makeIdent.php on line 18
makeIdent.php:
require_once('dirpath.php');
if ( isset($_GET['GreekWord']) ) {
$curword = trim($_GET['GreekWord']);
$strRes = "";
if (strlen($curword) > 1) {
try {
$obj = new COM("Ellinognosia.ExtFunctions") or die("Unable to instantiate Ellinognosia");
$sid = 0;
$mdr = 0;
$output = $obj->fnInitialize("arxaia", $APPLICATIONDIRECTORY . "\\elllex", $DLLDIR, "utf8");
$output = $obj->fnIdentify($curword);
echo $output;
}
catch (Exception $e) {
$errmsg = $e->getMessage();
echo "Fatal error: " . $errmsg . " :internal error";
$logfile = fopen("error.log", "a");
if (flock($logfile, LOCK_EX)) {
fputs($logfile, date('d-m-Y') . " # " . date('H:i:s') . " # " . $_SERVER['REMOTE_ADDR'] . " # " . $_SERVER['HTTP_USER_AGENT'] . " # " . ($ref = (isset($_SERVER['HTTP_REFERER'])) ? $_SERVER['HTTP_REFERER'] : "NO_REFERER") . " # " . $_SERVER['REQUEST_URI'] . " # " . $errmsg . " # " . "Variables:\r\n" . print_r($_POST, true) . " # " . print_r($_GET, true) . "\r\n\r\n");
flock($logfile, LOCK_UN);
fclose($logfile);
}
}
} else {
echo "Fatal error: Parameters Length Incorrect :internal error";
}
} else {
echo "Fatal error: Missing Parameters :internal error";
}
?>
dirpath.php:
<?php
date_default_timezone_set("Europe/Athens");
$APPLICATIONDIRECTORY = "C:\\inetpub\\wwwroot\\ell";
if (strpos(php_uname("v"), " R2 ") > 0 || strpos(php_uname("v"), "ild 92") > 0) {
$DLLDIR = "C:\\Windows\\SysWOW64";
} else {
$DLLDIR = $APPLICATIONDIRECTORY . "\\elldll";
}
?>
example2:
[21-Apr-2018 07:36:27 Asia/Kuwait] PHP Fatal error: Call to undefined function toMonotonic() in C:\inetpub\wwwroot\ell\ajaxGetWordsFromLet.php on line 15
ajaxGetWordsFromLet.php:
<?php
require_once('phpcommonscripts/functions/fn_application.php');
try {
if ( isset($_GET['Letters']) && isset($_GET['CurLex']) ) {
$letters = trim($_GET['Letters']);
$curlex = trim($_GET['CurLex']);
if (mb_strlen($letters, "UTF-8") > 2 && mb_strlen($curlex, "UTF-8") > 0) {
$strReturn = "";
if ($curlex == "newg" || $curlex == "arch" || $curlex == "phrases") {
$letters = mb_substr($letters, 0, 32, "UTF-8");
$letters = toMonotonic($letters);
$letters = RemoveSimeiaStiksisArx($letters);
// more irrelevant php code here, the error is 2 lines above
}
echo $strReturn;
} else {
echo "Fatal error: Parameters Length Incorrect :internal error";
}
} else {
echo "Fatal error: Missing Parameters :internal error";
}
}
catch(Exception $e) {
$errmsg = $e->getMessage();
echo "Fatal error: " . $errmsg . " :internal error";
$logfile = fopen("error.log", "a");
if (flock($logfile, LOCK_EX)) {
fputs($logfile, date('d-m-Y') . " # " . date('H:i:s') . " # " . $_SERVER['REMOTE_ADDR'] . " # " . $_SERVER['HTTP_USER_AGENT'] . " # " . ($ref = (isset($_SERVER['HTTP_REFERER'])) ? $_SERVER['HTTP_REFERER'] : "NO_REFERER") . " # " . $_SERVER['REQUEST_URI'] . " # " . $errmsg . " # " . "Variables:\r\n" . print_r($_POST, true) . " # " . print_r($_GET, true) . "\r\n\r\n");
flock($logfile, LOCK_UN);
fclose($logfile);
}
}
?>
fn_application.php:
<?php
function toMonotonic($s) {
$s = str_replace(":α", "ά", $s);
$s = str_replace(":ε", "έ", $s);
$s = str_replace(":η", "ή", $s);
$s = str_replace(":ι", "ί", $s);
$s = str_replace(":ο", "ό", $s);
$s = str_replace(":υ", "ύ", $s);
$s = str_replace(":ω", "ώ", $s);
$s = str_replace(":ϊ", "ΐ", $s);
$s = str_replace(":ϋ", "ΰ", $s);
$s = str_replace(":Α", "Ά", $s);
$s = str_replace(":Ε", "Έ", $s);
$s = str_replace(":Η", "Ή", $s);
$s = str_replace(":Ι", "Ί", $s);
$s = str_replace(":Ο", "Ό", $s);
$s = str_replace(":Υ", "Ύ", $s);
$s = str_replace(":Ω", "Ώ", $s);
$s = str_replace(":Ϊ", "Ϊ", $s);
$s = str_replace(":Ϋ", "Ϋ", $s);
return $s;
}
// more functions here
?>
example3:
[21-Apr-2018 07:36:27 Asia/Kuwait] PHP Notice: Undefined variable: LGCACHEPDO in C:\inetpub\wwwroot\ell\displayOmor.php on line 38
[21-Apr-2018 07:36:27 Asia/Kuwait] PHP Fatal error: Call to undefined function getCache() in C:\inetpub\wwwroot\ell\displayOmor.php on line 39
displayOmor.php:
<?php
require_once('dirpath.php');
require_once("phpcommonscripts/connections/con_cache.php");
require_once("phpcommonscripts/functions/cache.php");
function get_data($url) {
$ch = curl_init();
$timeout = 100;
$userAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)";
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch,CURLOPT_USERAGENT, $userAgent);
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
function mb_ucfirst($str, $enc = 'utf-8') {
return mb_strtoupper(mb_substr($str, 0, 1, $enc), $enc).mb_substr($str, 1, mb_strlen($str, $enc), $enc);
}
if ( isset($_GET['GreekWord']) && isset($_GET['selectedRes']) ) {
$curword = trim($_GET['GreekWord']);
$selres = trim($_GET['selectedRes']);
$strRes = "";
if (strlen($curword) > 1 && strlen($selres) > 0) {
try {
$cacheoutput = "";
$useCache = true;
if ($LGCACHEPDO === null) $useCache = false;
$cacheoutput = getCache($useCache, $_SERVER['QUERY_STRING'], $_POST, pathinfo(__FILE__, PATHINFO_FILENAME));
if ($cacheoutput != "") {
$output = $cacheoutput;
} else {
//more code
}
$strRes = $output;
echo $strRes;
}
catch (Exception $e) {
$errmsg = $e->getMessage();
echo "Fatal error: " . $errmsg . " :internal error";
$logfile = fopen("error.log", "a");
if (flock($logfile, LOCK_EX)) {
fputs($logfile, date('d-m-Y') . " # " . date('H:i:s') . " # " . $_SERVER['REMOTE_ADDR'] . " # " . $_SERVER['HTTP_USER_AGENT'] . " # " . ($ref = (isset($_SERVER['HTTP_REFERER'])) ? $_SERVER['HTTP_REFERER'] : "NO_REFERER") . " # " . $_SERVER['REQUEST_URI'] . " # " . $errmsg . " # " . "Variables:\r\n" . print_r($_POST, true) . " # " . print_r($_GET, true) . "\r\n\r\n");
flock($logfile, LOCK_UN);
fclose($logfile);
}
}
} else {
echo "Fatal error: Parameters Length Incorrect :internal error";
}
} else {
echo "Fatal error: Missing Parameters :internal error";
}
?>
con_cache.php:
<?php
//Cache
$hostname_LGCACHE = "127.0.0.1";
$database_LGCACHE = "xxx";
$username_LGCACHE = "xxx";
$password_LGCACHE = "xxx";
$errorreporting = error_reporting();
try {
error_reporting(E_ALL ^ E_WARNING);
$LGCACHEPDO = new PDO("mysql:host=".$hostname_LGCACHE.";dbname=".$database_LGCACHE, $username_LGCACHE, $password_LGCACHE, array(PDO::ATTR_PERSISTENT => true, PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING, PDO::ATTR_TIMEOUT => 2));
} catch (PDOException $ex) {
$LGCACHEPDO = null;
}
error_reporting($errorreporting);
?>
cache.php:
<?php
$gl_TBLNAME = "";
$gl_QUERYSTRING = "";
function getCache($useCache, $serverQUERYSTRING, $serverPOST, $serverFILENAME) {
$ret = "";
if ($useCache === true) {
global $LGCACHEPDO;
global $gl_TBLNAME;
global $gl_QUERYSTRING;
$gl_QUERYSTRING = $serverQUERYSTRING;
if ($gl_QUERYSTRING == "") {
foreach ($serverPOST as $key => $value) $gl_QUERYSTRING = $gl_QUERYSTRING . $key . "=". urlencode($value) . "&";
$gl_QUERYSTRING = rtrim($gl_QUERYSTRING, "&");
}
$gl_TBLNAME = $serverFILENAME;
$getcache_PRST = $LGCACHEPDO->prepare("SELECT output FROM " . $gl_TBLNAME . " WHERE querystring = :querystring");
$getcache_PRST->bindValue(":querystring", $gl_QUERYSTRING);
$getcache_PRST->execute() or die($LGCACHEPDO->errorInfo());
if ($getcache_PRST->rowCount() == 1) {
$getcache_RSLT = $getcache_PRST->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_NEXT);
$ret = $getcache_RSLT["output"];
}
}
return $ret;
}
// more functions here
?>
What I understand is that for some reason PHP or Windows fails some times to load those files.
We have had this server box for ~4 years and only recently started to show these problems. This server handles 70% of the website load and runs a MYSQL server (the website load is ~80% of what it was a year ago, so no it hasn't gone up). There is a same hardware second machine which has Windows Server 2012 R2 64bit which handles 30% of the load and doesn't run any MYSQL server and never shows these kind of problems. Both servers have PHP 5.3.28
Any ideas and help on what to do to pinpoint the issue would be welcome. Thank you in advance.
I took the cookbook example and modified it to use add_textflow() instead of create_textflow() but I can't get it to work. Instead of interpreting the macros it just writes it as plain text. What am I doing wrong?
From documentation I got the understanding that I should define the macros inline - or did I misunderstand it? Have tried everything I could think of...
$tf = 0;
$optlist = "";
$llx = 100; $lly = 50; $urx = 450; $ury = 800;
$t_fontsize = 16; // font size of the text
$t_leading = 20; // leading of the text
$c_num = 3; // no. of lines for the drop cap to cover
$c_textrise = -(($c_num - 1) * $t_leading); // text rise of the drop cap
$c_fontsize = -($c_textrise * 1.8); // font size of the drop cap
try {
$p = new pdflib();
$p->set_option("errorpolicy=exception");
$p->set_option("stringformat=utf8");
$p->begin_document("", "");
$optlist = "fontname=Helvetica fontsize=" . $t_fontsize . " encoding=unicode ";
$text = "<macro " .
"{cap_start {fontsize=" . $c_fontsize . " leading=" . $t_leading .
" textrise=" . $c_textrise .
" matchbox={createwrapbox boxheight={leading textrise}}} " .
"cap_end {matchbox=end fontsize=" . $t_fontsize . " textrise=0}}>";
$text .= "<&cap_start>O<&cap_end>ver the mountains... ";
$tf = $p->add_textflow($tf, $text, $optlist);
$text =
"Paper Planes are the ideal way of " .
"passing the time. We offer revolutionary " .
"new developments of the traditional common " .
"paper planes. If your lesson, conference, or lecture " .
"turn out to be deadly boring, you can have a wonderful time " .
"with our planes. ";
$tf = $p->add_textflow($tf, $text, $optlist);
do {
$p->begin_page_ext(0, 0, "width=a4.width height=a4.height");
$result = $p->fit_textflow($tf, $llx, $lly, $urx, $ury, "");
$p->end_page_ext("");
} while ($result == "_boxfull" || $result == "_nextpage");
/* Check for errors */
if (!$result == "_stop") {
if ($result == "_boxempty")
throw new Exception ("Error: Textflow box too small");
else {
throw new Exception ("User return '" . $result .
"' found in Textflow");
}
}
$p->delete_textflow($tf);
$p->end_document("");
$buf = $p->get_buffer();
$len = strlen($buf);
header("Content-type: application/pdf");
header("Content-Length: $len");
header("Content-Disposition: inline; filename=drop_caps.pdf");
print $buf;
} catch (PDFlibException $e) {
die("PDFlib exception occurred:\n".
"[" . $e->get_errnum() . "] " . $e->get_apiname() .
": " . $e->get_errmsg() . "\n");
} catch (Exception $e) {
die($e->getMessage());
}
$p = 0;
this is simple: only create_texflow() support inline options (because you must specify the data in a single chunk). With add_textflow() you have the possibility to "build" the textflow handle in multiple steps, for each text fragment with the related options.
In your case, it might look like the following way:
$optlistmacro = " macro " .
"{cap_start {fontsize=" . $c_fontsize . " leading=" . $t_leading .
" textrise=" . $c_textrise .
" matchbox={createwrapbox boxheight={leading textrise}}} " .
"cap_end {matchbox=end fontsize=" . $t_fontsize . " textrise=0}}";
$tf = $p->add_textflow($tf, "", $optlist . $optlistmacro);
$tf = $p->add_textflow($tf, "O", "&cap_start");
$tf = $p->add_textflow($tf, "ver the mountains... ", "&cap_end");
In this code fragment, I do the first add_textflow() without text but all the
macros settings. Then it place the "O" with the macro (&cap_start) in
the option list. The following text "ver the mountains... " is done
in the next add_textflow() and as option I place the &cap_end.
Is there a way I could read the entire file-system on my PC? I was trying to list all the files in W: directory, but the code doesn't work.
<?php
$fso = new COM('Scripting.FileSystemObject');
$D = $fso->Drives;
$type = array("Unknown","Removable","Fixed","Network","CD-ROM","RAM Disk");
foreach($D as $d ){
$dO = $fso->GetDrive($d);
$s = "";
if($dO->DriveType == 3){
$n = $dO->Sharename;
}else if($dO->IsReady){
$n = $dO->VolumeName;
$s = file_size($dO->FreeSpace) . " free of: " . file_size($dO->TotalSize);
}else{
$n = "[Drive not ready]";
}
echo "Drive " . $dO->DriveLetter . ": - " . $type[$dO->DriveType] . " - " . $n . " - " . $s . "<br>";
$dir = $dO->DriveLetter;
if (is_dir($dir.':\\')){ // NEVER ENTERS THE IF BLOCK
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
echo "filename:" . $file . "<br>";
}
closedir($dh);
}
}
}
function file_size($size)
{
$filesizename = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
return $size ? round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) . $filesizename[$i] : '0 Bytes';
}
?>
In the above code is_dir call always fails. What could be the reason for this? What is the correct way to read the windows file system?
try this http://php.net/manual/en/class.recursivedirectoryiterator.php
<?php
$path = realpath('/etc');
$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);
foreach($objects as $name => $object){
echo "$name\n";
}
I seem to be having a weird issue when attempting to run pthreads in php. I'm currently attempting to use the threads to manage additional calling of other php scripts, but my program is exiting prematurely, whenever I attempt to use Mutex::unlock. I've tried re-installing different versions of 64 bit pthreads as well as tested examples (of which, the mutex here works ). I think it may be a problem with popen. Has anyone hit this error before or know of a good way to debug it?
The code I'm using is as follows:
<?php
class lockedThread extends Thread {
public function __construct($func, $megalog, $mutex){
$numargs = func_num_args();
$this->megalog = $megalog;
$this->func = $func;
if ($numargs == 3) {
$this->mutex = array($mutex);
} else {
$arg_list = func_get_args();
$this->mutex = array_slice($arg_list, 2);
}
}
public function run() {
echo "Beginning " . $this->func . " \n";
for ($i = 0; $i < count($this->mutex); $i++) {
$locked = Mutex::lock($this->mutex[$i]);
while($locked == false) {
sleep(0.5);
$locked = Mutex::lock($this->mutex[$i]);
}
printf($this->getThreadId() . " acquired lock " . $this->mutex[$i] . "\n");
}
$this->res = popen("php Functions/" . $this->func . ".php"
. " >> logs/" . $this->func . ".log", 'r');
printf("closing " . $this->func . ": " . pclose($this->res) . "\n");
for ($i = count($this->mutex) - 1; $i >= 0; $i -= 1) {
printf($this->getThreadId() . " attempting to release lock " . $this->mutex[$i] . "\n");
Mutex::unlock($this->mutex[$i]);
echo $this->getThreadId() . " released lock " . $this->mutex[$i] . "\n";
}
echo "really closing " . $this->func . "\n";
}
}
}
// Create the mutex. Note, the connections mutex will always come first
$connMutex = Mutex::create(true);
$eventMutex = Mutex::create(true);
$workers["checkRecurrence"] = new lockedThread("checkRecurrence", $megalog, $eventMutex);
$workers["checkRecurrence"]->start();
echo "checkRecurrence is " . $workers["checkRecurrence"]->getThreadId() . "\n";
$workers["checkDeletion"] = new lockedThread("checkDeletion", $megalog, $eventMutex);
$workers["checkDeletion"]->start();
echo "checkDeletion is " . $workers["checkDeletion"]->getThreadId() . "\n";
echo "Unlocking conn: " . Mutex::unlock($connMutex) . "\n";
echo "Unlocking event: " . Mutex::unlock($eventMutex) . "\n";
foreach($workers as $i=>$worker) {
echo "Joining $i \n";
while ($worker->join() === false) {
echo "Attempt of $i \n";
}
echo "Joined $i \n";
}
sleep(1);
echo "Finishing destruction of workers!\n";
/* please remember to destroy mutex and condition variables */
Mutex::destroy($connMutex);
Mutex::destroy($eventMutex);
The logs I'm getting are:
"C:\wamp\bin\php\php5.5.12\php.exe" "C:\wamp\www\hang\PHPAutomation\index.php"
Beginning checkRecurrence
checkRecurrence is 8576
Beginning checkDeletion
checkDeletion is 9144
Started all workers
Unlocking conn: 1
Unlocking event: 1
Joining checkRecurrence
8576 acquired lock 52687024
closing checkRecurrence: 0
8576 attempting to release lock 52687024
Done.
I have used to the Rackspace API to upload files to the RackSpace cloud. But this method seems to be a little on the slow side. Is there a better or faster way to upload a file to the cloud(curl, http adapters, etc)?
I am currently uploading with PHP and using the provided API.
Here is my solution how to make it fast:
I'm uploading only missing files using simple PHP script below. Thanks to it I do it in just one click and in just a few seconds.
PHP source code:
function UploadMissingFilesToRackFileCDN($file_paths_to_upload, $b_force_upload = false)
{
include_once("cloudfiles.php");
// Connect to Rackspace
$username = cloudfile_username; // username
echo "Connecting to CDN..." . date("H:i:s") . "<br>"; ob_flush();
$key = cloudfile_api_key; // api key
$auth = new CF_Authentication($username, $key);
$auth->authenticate();
$conn = new CF_Connection($auth);
echo " Connected!" . date("H:i:s") . "<br>"; ob_flush();
// Get the container we want to use
$container_name = 'vladonai';//'test_container';
echo "Obtaining container $container_name..." . date("H:i:s") . "<br>"; ob_flush();
$container = $conn->get_container($container_name);
echo " The container is obtained." . date("H:i:s") . "<br>"; ob_flush();
if (!$b_force_upload)
{
echo "Receiving container objects list..." . date("H:i:s") . "<br>"; ob_flush();
$existing_object_names = $container->list_objects();
$existing_files_count = count($existing_object_names);
echo " Objects list obtained: $existing_files_count." . date("H:i:s") . "<br>"; ob_flush();
$existing_object_names_text .= "\r\n";
foreach ($existing_object_names as $obj_name)
{
$existing_object_names_text .= $obj_name . "\r\n";
}
}
// upload files to Rackspace
$uploaded_file_n = 0;
$skipped_file_n = 0;
$errors_count = 0;
foreach ($file_paths_to_upload as $localfile_path => $file_info)
{
$filename = basename($localfile_path);
if (!file_exists($localfile_path))
{
echo "<font color=red>Error! File $localfile_path doesn't exists!</font>" . date("H:i:s") . "<br>"; ob_flush();
$errors_count ++;
} else
if (is_dir($localfile_path))
{
//simply skip it
} else
if (strpos($existing_object_names_text, "\r\n" . $filename . "\r\n") !== false)
{
//file is already uploaded to CDN (at least file name is present there). Would be good to have date/size checked, but CDN api has no such feature
//echo "<font color=gray>Skipped file $localfile_path - it already exists!</font><br>"; ob_flush();
$skipped_file_n ++;
} else
{
echo "<font color=green>Uploading file $localfile_path (file #$uploaded_file_n)..." . date("H:i:s") . "</font><br>"; ob_flush();
try
{
$object = $container->create_object($filename);
$object->load_from_filename($localfile_path);
$uploaded_file_n ++;
}
catch (Exception $e)
{
echo "<font color=red>Error! Caught exception: ", $e->getMessage(), " on uploading file <strong>$localfile_path</strong>!</font>" . date("H:i:s") . "<br>"; ob_flush();
$errors_count ++;
}
}
// if ($uploaded_file_n >= 10)
// break;
}
echo "Done! $uploaded_file_n files uploaded. Disconnecting :)" . date("H:i:s") . "<br>"; ob_flush();
echo "Skipped files: $skipped_file_n<br>"; ob_flush();
if ($errors_count > 0)
echo "<font color=red>Erorrs: $errors_count</font><br>"; ob_flush();
}
function UploadChangedImagesToRackFileCDN($b_force_upload = false)
{
$exclude = array
(
'.',
'..',
'*.html',
'*.htm',
'*.php',
'*.csv',
'*.log',
'*.txt',
'*.cfg',
//'*sub/forum/files/*',
);
$files_array_images = get_dirlist("/var/www/html/vladonai.com/images/", '*', $exclude, false);
$files_array = array_merge(get_dirlist("/var/www/html/vladonai.com/js/", '*', $exclude, false), $files_array_images);
UploadMissingFilesToRackFileCDN($files_array, $b_force_upload);
}
function get_dirlist($path, $match = '*', $exclude = array( '.', '..' ), $b_short_path = true)
{
$result = array();
if (($handle = opendir($path)))
{
while (false !== ($fname = readdir($handle)))
{
$skip = false;
if (!empty($exclude))
{
if (!is_array($exclude))
{
$skip = fnmatch($exclude, $fname) || fnmatch($exclude, $path . $fname);
} else
{
foreach ($exclude as $ex)
{
if (fnmatch($ex, $fname) || fnmatch($ex, $path . $fname))
$skip = true;
}
}
}
if (!$skip && (empty($match) || fnmatch($match, $fname)))
{
$file_full_path_and_name = $path . $fname;
//echo "$file_full_path_and_name<br>";
$b_dir = is_dir($file_full_path_and_name);
$b_link = is_link($file_full_path_and_name);
$file_size = ($b_dir || $b_link) ? 0 : filesize($file_full_path_and_name);
$file_mod_time = ($b_dir || $b_link) ? 0 : filemtime($file_full_path_and_name);
$new_result_element = array();
if ($b_short_path)
$file_name = str_replace("/var/www/html/vladonai.com/", "", $file_full_path_and_name);//'[' . str_replace("/var/www/html/vladonai.com/", "", $file_full_path_and_name) . ']';
else
$file_name = $file_full_path_and_name;
$result[$file_name] = array();
$result[$file_name]['size'] = $file_size;
$result[$file_name]['modtime'] = $file_mod_time;
if ($b_dir && !$b_link)
{
//recursively enumerate files in sub-directories
$result = array_merge(get_dirlist($file_full_path_and_name . "/", $match, $exclude, $b_short_path), $result);
}
}
}
closedir($handle);
}
return $result;
}