<?
/**
 * VoiceOne Settings/Extensions/import
 *
 * @package voiceone
 * @subpackage  contacts
 */
  include ("../../../admin/config/cfg.php");
  global $cwlang,$cwUserInfo,$cwUserId;
  require_once("$absBasePath/lib/xajax/xajax.inc.php");
  $alert=getAlert();
  //================== POST ====================
  if(is_array($_FILES['file'])){
    $alert='';
    $file=$_FILES['file'];
    if($file['error']==0){
      $lineArr=file($file['tmp_name']);
      if((is_array($lineArr))&&(count($lineArr)>0)){
        $numberOnCid=array();
        $contactArr=$asterisk->getContact(0,0,0);
        if(is_array($contactArr)){
          foreach($contactArr as $contact){
            if($contact['id_user']!=$cwUserId){
              if($contact['phonenumber_on_cid']==1) $numberOnCid[]=$contact['phonenumber'];
              if($contact['mobile_on_cid']==1) $numberOnCid[]=$contact['mobile'];
              if($contact['fax_on_cid']==1) $numberOnCid[]=$contact['fax'];
            }
          }
        }
        $linecount=0;
        foreach($lineArr as $line){
          $linecount++;
          $line=trim(str_replace(array('\r\n','\n','\r'),'',$line));
          $filedArr=explode(";",$line);
          if( (count($filedArr)!=12) ||
              (!in_array($filedArr[3],array('name','surname','company'))) ||
              (!in_array($filedArr[4],array('1','0'))) ||
              (!in_array($filedArr[5],array('1','0'))) || (($filedArr[5]==1)&&($filedArr[4]==0)) ||
              (!in_array($filedArr[7],array('1','0'))) || (($filedArr[7]==1)&&(trim($filedArr[6])=='')) ||
              (!in_array($filedArr[9],array('1','0'))) || (($filedArr[9]==1)&&(trim($filedArr[8])=='')) ||
              (!in_array($filedArr[11],array('1','0'))) || (($filedArr[11]==1)&&(trim($filedArr[10])==''))
            ){
            $alert="<div class=\"AlertBad\">".T_("Error: malformed row at line ").$linecount."</div>";
            break;
          }
          if(($filedArr[7]==1)&&(in_array($filedArr[6],$numberOnCid))) $filedArr[7]=0;
          if(($filedArr[9]==1)&&(in_array($filedArr[8],$numberOnCid))) $filedArr[9]=0;
          if(($filedArr[11]==1)&&(in_array($filedArr[10],$numberOnCid))) $filedArr[11]=0;
          $entryArr[]=Array(
              "id" => '',
              "id_user" => $cwUserId,
              "name" => $filedArr[0],
              "surname" => $filedArr[1],
              "company" => $filedArr[2],
              "order_by" => $filedArr[3],
              "read" => $filedArr[4],
              "write" => $filedArr[5],
              "phonenumber" => $filedArr[6],
              "phonenumber_on_cid" => $filedArr[7],
              "phonenumber_speed_id" => 0,
              "phonenumber_speed_ext" => '',
              "mobile" => $filedArr[8],
              "mobile_on_cid" => $filedArr[9],
              "mobile_speed_id" => 0,
              "mobile_speed_ext" => '',
              "fax" => $filedArr[10],
              "fax_on_cid" => $filedArr[11],
              "fax_speed_id" => 0,
              "fax_speed_ext" => '',
              "email" => '',
              "cid_name" => '',
              "groups" => ''
            );
        }
      }else $alert="<div class=\"AlertBad\">".T_("Error: file is empty")."</div>";
    }else $alert="<div class=\"AlertBad\">".T_("Error: cannot upload file")."</div>";
    //process request
    if(trim($alert)==''){
      //simulate import
      if($_POST['simulate']=='1'){
        $alert="<div class=\"AlertGood\">".sprintf(T_("File is well formatted and ready to be imported (%s contacts)"),$linecount)."</div>";
      }
      //import contacts
      else{
        $errorcount=0;
        foreach($entryArr as $entry){
          $ret=$asterisk->putContact($entry,$cwUserId);
          if($ret==0) $errorcount++;
        }
        $alert="<div class=\"AlertGood\">".sprintf(T_("Contacts have been imported (%s success | %s errors)"),($linecount-$errorcount),$errorcount)."</div>";
      }
    }
    //return alert
    goToMainPage($alert,"./");
  }
  //================ PAGE LOGIC ================

  //================ MAIN CONTENTS ================
  ob_start();
  ?>
  <div class="SectionHeader">
    <div id="loading" style="float: right;"></div>
    <h1><?=T_("Import Contacts")?></h1>
    <h3><a href="../" class="admin" ><?=T_("Return to contact list")?></a></h3>
  </div>
  <div id="alert"><?=$alert?></div>
  <div id="basic_form">
    <form id="mainform" action="<?=$PHP_SELF?>" method="post" enctype="multipart/form-data">
    	<!--  Info -->
      <h2><?=T_("Upload CSV file")?></h2>
      <p><?=T_("Select and upload the csv file which contains contacts.")?>
      <div class="block" style="background:#FFF;margin:10px 0 6px 0;">
        <dl>
        	<dt class="required"><label for="file"><?=T_("CSV File")?>:</label></dt>
          <dd>
          	<input type="file" size="25" id="file" name="file" />
            <input style="margin-left:10px;" type="checkbox" id="simulate" name="simulate" value="1"/> <span class="help"><?=T_("Only verify file, DO NOT import")?></span>
          </dd>
        </dl>
      </div>
      <p>
        <?=T_("File must has one entry per line and line fields must be separated by semicolon.")?><br/>
        <?=T_("Every line has to conform to the following structure: ")?><br/>
      </p>
      <table style="margin: 5px 0;color:#666;" cellpadding="0" cellspacing="0">
        <tr><td style="text-align:right;vertical-align:top;" width="1%">&lt;name&gt;:</td><td style="text-align:left;"><?=T_("Name of the contact")?></td></tr>
        <tr><td style="text-align:right;vertical-align:top;" width="1%">&lt;surname&gt;:</td><td style="text-align:left"><?=T_("Surname of the contact")?></td></tr>
        <tr><td style="text-align:right;vertical-align:top;" width="1%">&lt;company&gt;:</td><td style="text-align:left"><?=T_("Company name of the contact")?></td></tr>
        <tr><td style="text-align:right;vertical-align:top;" width="1%">&lt;order_by&gt;:</td><td style="text-align:left"><?=T_("Contacts order field (accepted values: name|surname|company)")?></td></tr>
        <tr><td style="text-align:right;vertical-align:top;" width="1%">&lt;read&gt;:</td><td style="text-align:left"><?=T_("Read permission on the contact. If 1 every user can see this contact (accepted values: 1|0)")?></td></tr>
        <tr><td style="text-align:right;vertical-align:top;" width="1%">&lt;write&gt;:</td><td style="text-align:left"><?=T_("Write permission on the contact. If 1 every user can modify this contact. To be on the contact must be readable. (accepted values: 1|0)")?></td></tr>
        <tr><td style="text-align:right;vertical-align:top;" width="1%">&lt;phonenumber&gt;:</td><td style="text-align:left"><?=T_("Contact's phonenumber. Empty for no phonenumber")?></td></tr>
        <tr><td style="text-align:right;vertical-align:top;" width="1%">&lt;phonenumber_on_cid&gt;:</td><td style="text-align:left"><?=T_("If 1 show caller informations on phones when an incoming call comes from this phonenumber. To be on the contact must be readable and phonenumber must be not null. (accepted values: 1|0)")?></td></tr>
        <tr><td style="text-align:right;vertical-align:top;" width="1%">&lt;mobile&gt;:</td><td style="text-align:left"><?=T_("Contact's mobile number. Empty for no mobile number")?></td></tr>
        <tr><td style="text-align:right;vertical-align:top;" width="1%">&lt;mobile_on_cid&gt;:</td><td style="text-align:left"><?=T_("If 1 show caller informations on phones when an incoming call comes from this mobile number. To be on the contact must be readable and mobile number must be not null. (accepted values: 1|0)")?></td></tr>
        <tr><td style="text-align:right;vertical-align:top;" width="1%">&lt;fax&gt;:</td><td style="text-align:left"><?=T_("Contact's fax number. Empty for no fax number")?></td></tr>
        <tr><td style="text-align:right;vertical-align:top;" width="1%">&lt;fax_on_cid&gt;:</td><td style="text-align:left"><?=T_("If 1 show caller informations on phones when an incoming call comes from this fax number. To be on the contact must be readable and fax number must be not null. (accepted values: 1|0)")?></td></tr>
      </table>
      <p style="margin-bottom:15px;">
        <?=T_("For example an entry could be:")?>&nbsp;&nbsp;Joe;Doe;Matrix Ltd;surname;1;0;555898965;1;;0;55587475;0
      </p>
      <!-- Buttons -->
      <div class="action">
        <a href=""><img src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-cancel.gif" alt="Cancel" onclick="history.back(); return false;"/></a>
        <a href=""><img src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-save.gif" alt="Save" onclick=" document.getElementById('alert').innerHTML=''; document.getElementById('mainform').submit(); return false;"/></a>
      </div>
    </form>
  </div>

  <?
  $contents=ob_get_contents();
  ob_end_clean();

  //================ SIDEBAR ================
  ob_start();
  ?>
    <div class="Sidebar">
      <?$sel="list";include("../../sidebar.php");?>
      <h1><?=T_("Informations")?></h1>
      <p><?=T_("This page allows you to import contacts from a CSV file. To import contacts you have to select the file to upload and to press save button on the end of the page.")?></p>
      <div style="text-align: center"><img src="<?=$relBasePath?>public/img/book.jpg" align="center"/></div>
    </div>
  <?
  $sidebar=ob_get_contents();
  ob_end_clean();

  //================ SETTINGS ================
  $smarty->assign("section", "contacts");
  $smarty->assign("subsection", "");
  $smarty->assign("contents", $contents);
  $smarty->assign("sidebar", $sidebar);
  $smarty->display('main.tpl');
?>