<?php
class ErgophoneHelper {


    public static function createErgophoneConfigFilesForExtension($extension) {

        if (app()->params->enableErgophoneProvisioning) {
                Yii::import('application.commands.*');
                $command = new ErgophoneCommand("ergophoneConfigCreator","PhonalisaWebApp");
                $command->run(array(
                    "-ext",$extension,
                    "-ftp",app()->params->ergophoneConfigRootPath,
                ));
        //         ErgophoneHelper::triggerConfigDownload($extension);
        }
    }
    
    public static function triggerConfigDownload($extension) {
        
        $user = User::model()->findByAttributes(array('extension'=>$extension));
        $sipAccounts =  $user->getSipAccounts();
        foreach($sipAccounts as $sipAccount) {
            $phone = $sipAccount->getPhone();
            if ($phone) {
                if ($phone->getManufactor() == 'Ergophone') {
                    $header = ErgophoneHelper::getErgophoneData($phone->ipv4_address.'/cgi-bin/do.cgi?cmd=downloadNowCmd');
                }
            }
        }
    }

    public static function getErgophoneData( $url )
    {
        $options = array(
            CURLOPT_RETURNTRANSFER => true,     // return web page
            CURLOPT_HEADER         => false,    // don't return headers
            CURLOPT_FOLLOWLOCATION => true,     // follow redirects
            CURLOPT_ENCODING       => "",       // handle all encodings
            CURLOPT_AUTOREFERER    => true,     // set referer on redirect
            CURLOPT_CONNECTTIMEOUT => 120,      // timeout on connect
            CURLOPT_TIMEOUT        => 120,      // timeout on response
            CURLOPT_MAXREDIRS      => 10,       // stop after 10 redirects
            CURLOPT_USERPWD        => "admin:1450",
        );

        $ch      = curl_init( $url );
        curl_setopt_array( $ch, $options );
        $content = curl_exec( $ch );
        $err     = curl_errno( $ch );
        $errmsg  = curl_error( $ch );
        $header  = curl_getinfo( $ch );
        curl_close( $ch );

        $header['errno']   = $err;
        $header['errmsg']  = $errmsg;
        $header['content'] = $content;
        return $header;
    }   
}
?>