<?php

/**
 * Class adbCopyFiles
 *
 * Copies files from a specified folder on the Android device (over USB, using adb)
 * to the specified folder on the PC.
 *
 * Usage:
 * > php acf.php <from> <to>
 * Where:
 *     <from>	- Android folder path for example: /sdcard/DCIM/100ANDRO/ (with trailing slash)
 *  <to>  	- PC folder path, for example: ./100ANDRO/ (with trailing slash)
 *
 * Sample output:

 * Z:\web\adbCopyFolder>php acf.php
List of devices attached
CB5A1PTCB4      device

/sdcard/DCIM/100ANDRO/DSC_0001.jpg      Exists
/sdcard/DCIM/100ANDRO/DSC_0002.jpg      Exists
/sdcard/DCIM/100ANDRO/DSC_0004.jpg      Exists
/sdcard/DCIM/100ANDRO/DSC_0005.jpg      Exists
/sdcard/DCIM/100ANDRO/DSC_0006.jpg      Exists
/sdcard/DCIM/100ANDRO/DSC_0007.jpg      Exists
/sdcard/DCIM/100ANDRO/DSC_0081.jpg      Missing
2203 KB/s (1963546 bytes in 0.870s)
/sdcard/DCIM/100ANDRO/DSC_0082.jpg      Missing
2319 KB/s (2215840 bytes in 0.933s)
/sdcard/DCIM/100ANDRO/DSC_0083.jpg      Missing
2466 KB/s (1788425 bytes in 0.708s)
/sdcard/DCIM/100ANDRO/DSC_0084.jpg      Missing
2621 KB/s (1312938 bytes in 0.489s)
 */

class adbCopyFiles {

	var $adbPath = 'c:\\android\\android-sdk-windows\\platform-tools\\';
	var $from = '/sdcard/DCIM/100ANDRO/';
	var $to = './100ANDRO/';

	function __construct() {
		$this->call('adb devices');
		if ($_SERVER['argc'] == 3) {
			$this->from = $_SERVER['argv'][1];
			$this->to = $_SERVER['argv'][2];
		}
	}

	function call($cmd) {
		passthru($this->adbPath.$cmd);
	}

	function grab($cmd) {
		exec($cmd, $output);
		return $output;
	}

	function noSlash($str) {
		$len = strlen($str);
		$lastChar = $str{$len-1};
		if (in_array($lastChar, array('/', '\\'))) {
			return substr($str, 0, -1);
		} else {
			return $str;
		}
	}

	function render() {
		$files = $this->grab($this->adbPath.'adb shell ls -R '.$this->from);
		array_shift($files);	// empty line
		array_shift($files);	// /sdcard/DCIM/100ANDRO:
		foreach ($files as $file) {
			$status = file_exists($this->to.$file) ? 'Exists' : 'Missing';
			echo $this->from.$file, "\t", $status, "\n";
			if ($status == 'Missing') {
				$cmd = 'adb pull '.$this->from.$file.' '.$this->noSlash($this->to);
				//echo $this->adbPath.$cmd, "\n";
				$this->call($cmd);
			}
		}
	}

}

$acf = new adbCopyFiles();
$acf->render();
