<?php
    // Not sure whether we need the license header here, or if this is so deep
    // in the guts of horde that this may as well be licensed same as horde.
    // Some of this certainly did get copied from horde's UI based exporter,
    // for example.

    ini_set('display_errors', true);
    ini_set('display_startup_errors', true );

    require_once '/usr/local/cpanel/base/horde/turba/lib/Application.php';
    require_once '/usr/local/cpanel/base/horde/turba/lib/Turba.php';

    // I'm only making a class to avoid an explicit exit :(
    class Turban_Application extends Turba_Application {

        function download() {
            global $injector, $cfgSources;
            $sources = array();

            $all_fields = $data = array();
            $tfd = $injector->getInstance('Turba_Factory_Driver');
            
            $shares = Turba::listShares(true);
            foreach( $shares as $source => $object ) {
                $cfgSources[$source] = Turba::getSourceFromShare($object);

                /* Create a Turba storage instance. */
                $driver = $tfd->create($source);
                $blobs = $driver->getBlobs();

                /* Get the full, sorted contact list. */
                try {
                    $results = $driver->search(array())->objects;
                } catch (Turba_Exception $e) {
                    throw new Turba_Exception(sprintf(_("Failed to search the directory: %s"), $e->getMessage()));
                }

                $fields = array_keys($driver->map);
                $all_fields = array_merge($all_fields, $fields);

                $params = $driver->getParams();
                foreach ($results as $ob) {
                    $data[] = $driver->tovCard($ob, '3.0', null, true);
                }
            }

            $injector->getInstance('Horde_Core_Factory_Data')->create('Vcard', array('cleanup' => array($this, 'cleanupData')))->exportFile(_("contacts.vcf"), $data, true);
            return;
        }
    }

    // Read from stdin for the addressbook IDs we want.
    $stdin = fopen('php://stdin', 'r');
    global $session, $cfgSources;
    $users = [];
    while( $input = trim(fgets($stdin)) ) {
        $users[] = $input;
    }
    if( empty($users) ) die("No user(s) passed in!");

    Horde_Registry::appInit('turba', array( 'cli' => true ));

    foreach( $users as $user ) {
        global $session;
        echo "Processing user '$user'...\n";
        $session->set( 'horde', 'auth/userId', $user );

        // constructor is wanting some strange things since it inherits from
        // another module. First arg is template location, which we don't need
        // but throws if it doesn't exist. Second is name of module.
        $turban = new Turban_application( '/dev/null', 'Turba_application' );

        // OK, so this exits, so you gotta catch it.
        $turban->download($vars);
    }
?>
