<?php
/**
 * Yellowpages class
 * 
 * Provides methods related to yellowpages module
 * 
 * @package linea21\modules\yellowpages
 * @author $Author$ - linea21 <info@linea21.com>
 * @version $Id$ 
 * @access public
 * @license http://opensource.org/licenses/gpl-3.0.html
 * Yellowpages Management
 */

class yellowpages {
  /* @param
   * */
  var $TDB_YELLOWPAGES = T_YELLOWPAGES; // nom de la table.
  var $ID;
  var $NAME;
  var $ACTIVITY;
  var $LEVEL;
  var $STREET;
  var $POSTAL_CODE;
  var $CITY;
  var $COUNTRY;
  var $PHONE;
  var $FAX;
  var $EMAIL;
  var $WEBSITE;
  var $LONG = 0;
  var $LAT = 0;
  var $DATE_CREA;
  var $LAST_MODIFY;
  var $STATUT;
  protected $dispatcher = null;

  public function __construct()
  {
    $this->dispatcher = $GLOBALS['dispatcher'];
  }

  public function __call($method, $arguments)
  {
    $event = $this->dispatcher->notifyUntil(new sfEvent($this, 'yellowpages.extensible_function', array(
      'method'    => $method,
      'arguments' => $arguments
    )));
    if (!$event->isProcessed())
    {
      throw new Exception(sprintf('Call to undefined method %s::%s.', get_class($this), $method));
    }

    return $event->getReturnValue();
  }

  /**
   * yellowpages::CheckDataIntegrity()
   * Vérification des données d'une entreprise
   *
   * @access public
   * @param array $table_yp : contient les composants d'une entreprise
   * @return boolean si ok renvoie true sinon message d'erreurs (string)
   */
  function CheckDataIntegrity($table)
  {

  	// Filter data event + return value
  	$r = $this->dispatcher->filter(new sfEvent($this, 'yellowpages.before_datacheck', array('data' => $table)), $table);
  	$table = $r->getReturnValue();

    if (strlen($table[0]) < 2) return _t('yp','object_notname');
    if (strlen($table[1]) < 2) return _t('yp','object_notactivity');
    if (strlen($table[3]) < 2) return _t('yp','object_notstreet');
    if (strlen($table[4]) < 2) return _t('yp','object_notpostal_code');
    if (strlen($table[5]) < 2) return _t('yp','object_notcity');
    //if (strlen($table[6]) < 2) return $notcountry;
    $testmail = $this->_checkEmailValidity($table[9]);
    if ($testmail===false) return _t('yp','object_notemail');

    if (strlen($table[10]) > 10) {
      if (!$this->IsValidProtocol($table[10])) return _t('yp','invalid_protocol');
    }

    if (trim($table[7]) != '' && !is_numeric($table[7])) return _t('yp','object_notphone');
    if (trim($table[8]) != '' && !is_numeric($table[8])) return _t('yp','object_notfax');

    // Notify the beginning of the current method
    $this->dispatcher->notify(new sfEvent($this, 'yellowpages.after_datacheck', array('data' => $table)));

    return true;
  }

  /**
   * yellowpages::_checkEmailValidity()
   * Vérification de la grammaire du mail
   *
   * @access private
   * @param string $email
   * @return int 1 ou 0
   */
  function _checkEmailValidity($email)
  {
  	$this->dispatcher->notify(new sfEvent($this, 'yellowpages.check_email_validity', array('email' => $email)));

    return validEmail($email);
  }

  /**
   * resources::IsValidProtocol()
   * vérifie si une url donnée a un protocole reconnu par un client web standard
   *
   * @access public
   * @param array $url : chemin absolu
   * @return boolean
   */
  function IsValidProtocol($url)
  {
  	$this->dispatcher->notify(new sfEvent($this, 'yellowpages.is_valid_protocol', array('url' => $url)));

    if (substr($url, 0, 7) != 'http://' && substr($url, 0, 8) != 'https://' && substr($url, 0, 6) != 'ftp://' && substr($url, 0, 7) != 'ftps://') return false;
    else return true;
  }

  /**
   * yellowpages::AddYellowPages()
   * Ajout d'une nouvelle entreprise dans l'annuaire
   *
   * @access public
   * @param array $table contient les composants d'une organisation
   * @param object $sql_object
   * @return integer $last_id
   */
  function AddYellowPages($table, $sql_object)
  {
  	global $l21auth;
  	
  	// Filter data event + return value
  	$r = $this->dispatcher->filter(new sfEvent($this, 'yellowpages.before_add', array('data' => $table)), $table);
  	$table = $r->getReturnValue();

    $table = array_map('sanitize_string', $table);

    $table=$sql_object->DBescape($table);

    $this->NAME = strip_input($table[0]);
    $this->ACTIVITY = strip_input($table[1]);
    $this->LEVEL = $table[2];
    $this->STREET = strip_input($table[3]);
    $this->POSTAL_CODE = strip_input($table[4]);
    $this->CITY = strip_input($table[5]);
    $this->COUNTRY = strip_input($table[6]);
    $this->PHONE = strip_input($table[7]);
    $this->FAX = strip_input($table[8]);
    $this->EMAIL = strip_input($table[9]);
    $this->WEBSITE = strip_input($table[10]);

    if ($table[11] != '') {
      $table[11] = strtoupper($table[11]);
      switch ($table[11]) {
        case 'P':
          $this->STATUT = $table[11];
          break;
        case 'AA':
          $this->STATUT = $table[11];
          break;
        case 'D':
          $this->STATUT = $table[11];
          break;
        default:
          $this->STATUT = 'AA';
          break;
      }
    } else $this->STATUT = 'AA';

    $this->_geocode();

    $q = "INSERT INTO " . $this->TDB_YELLOWPAGES . " (yellowp_name, yellowp_activity, yellowp_level, yellowp_street, " . "yellowp_postal_code, yellowp_city, yellowp_country, yellowp_phone, yellowp_fax, yellowp_email, " . "yellowp_website, yellowp_longitude, yellowp_latitude,  yellowp_statut, yellowp_date_crea) " . "VALUES('" . $this->NAME . "', '" . $this->ACTIVITY . "', " . $this->LEVEL . ", '" . $this->STREET . "', '" . $this->POSTAL_CODE . "', '" . $this->CITY . "', '" . $this->COUNTRY . "', '" . $this->PHONE . "', '" . $this->FAX . "', '" . $this->EMAIL . "', '" . $this->WEBSITE . "', '" . $this->LONG. "', '" . $this->LAT. "', '" . $this->STATUT . "', NOW());";
    $last_id = $sql_object->DBInsert ($q, 1);

    // we log add action
    if(is_numeric($last_id))	logfile(LOG_MAINFILE, array('[action] add directory entry', 'ID='.$last_id, 'by_id='.$l21auth->GetSessionElement('id'), 'by_login='.$l21auth->GetSessionElement('login')));
    
    // Notify the end of the current method
    $this->dispatcher->notify(new sfEvent($this, 'yellowpages.after_add', array('data' => $table, 'id' => $last_id)));

    return $last_id;
  }

  /**
   * yellowpages::StateYellowPages()
   * modification du statut d'une organisation
   *
   * @access public
   * @param int $ID identifiant de l'organisation
   * @param string $state (facultatif) 'P' Public/'D' Draft/'AA' AdminArchive/'PA' PublicArchive
   * @param object $sql_object
   * @return bool $result
   */

  function StateYellowPages($ID, $state, $sql_object)
  {
  	// Notify the end of the current method
  	$this->dispatcher->notify(new sfEvent($this, 'yellowpages.change_state', array('id' => $ID, 'state' => $state)));

    if (is_numeric($ID)) {
      $this->ID = $ID;
    }
    $this->STATUT = $state;

    $q = "UPDATE  " . $this->TDB_YELLOWPAGES . " set yellowp_statut='" . $this->STATUT . "' WHERE yellowp_id=" . $this->ID . ";";
    $result = $sql_object->DBQuery($q);
    return $result;
  }


  /*
   * yellowpages::DeleteYellowPages()
   * suppression d'une organisatione
   *
   * @access public
   * @param int $ID identifiant de l'organisation
   * @param object $sql_object
   * @return bool $result
   */
  function DeleteYellowPages($ID, $sql_object)
  {
  	global $l21auth;
  	
  	// Notify the end of the current method
  	$this->dispatcher->notify(new sfEvent($this, 'yellowpages.delete', array('id' => $ID)));

    $this->ID = $ID;
    $q = "UPDATE " . $this->TDB_YELLOWPAGES . " SET yellowp_statut='E', yellowp_last_modify = NOW() WHERE yellowp_id=" . $this->ID . ";";
    $result = $sql_object->DBQuery ($q);
    
    // we log delete action
    if($result)	logfile(LOG_MAINFILE, array('[action] delete directory entry', 'ID='.$ID, 'by_id='.$l21auth->GetSessionElement('id'), 'by_login='.$l21auth->GetSessionElement('login')));
    
    return $result;
  }

  /**
   * yellowpages::ModifyYellowPages()
   * modification d'une organisation
   *
   * @access public
   * @param int $ID identifiant de l'organisation
   * @param array $table contient les composants d'une entreprise
   * @param object $sql_object
   * @return bool $result
   */
  function ModifyYellowPages($ID, $table, $sql_object)
  {
  	// Filter data event + return value
  	$r = $this->dispatcher->filter(new sfEvent($this, 'yellowpages.before_modify', array('data' => $table, 'id' => $ID)), $table);
  	$table = $r->getReturnValue();

    $table=$sql_object->DBescape($table);

    $this->ID = $ID;
    $this->NAME = strip_input($table[0]);
    $this->ACTIVITY = strip_input($table[1]);
    $this->LEVEL = $table[2];
    $this->STREET = strip_input($table[3]);
    $this->POSTAL_CODE = strip_input($table[4]);
    $this->CITY = strip_input($table[5]);
    $this->COUNTRY = strip_input($table[6]);
    $this->PHONE = strip_input($table[7]);
    $this->FAX = strip_input($table[8]);
    $this->EMAIL = strip_input($table[9]);
    $this->WEBSITE = strip_input($table[10]);

    if ($table[11] != '') {
      $table[11]=strtoupper($table[11]);
      switch ($table[11]) {
        case 'P':
          $this->STATUT = $table[11];
          break;
        case 'AA':
          $this->STATUT = $table[11];
          break;
        case 'D':
          $this->STATUT = $table[11];
          break;
        default:
          $this->STATUT = 'AA';
          break;
      }
    } else $this->STATUT = 'AA';

    $this->_geocode();

    $q = "UPDATE  " . $this->TDB_YELLOWPAGES . " set yellowp_name='" . $this->NAME . "', yellowp_activity='" . $this->ACTIVITY . "' , yellowp_level=" . $this->LEVEL . ", yellowp_street='" . $this->STREET . "', yellowp_postal_code='" . $this->POSTAL_CODE . "', yellowp_city='" . $this->CITY . "', yellowp_country='" . $this->COUNTRY . "', yellowp_phone='" . $this->PHONE . "', yellowp_fax='" . $this->FAX . "', yellowp_email='" . $this->EMAIL . "', yellowp_longitude='" . $this->LONG . "', yellowp_latitude='" . $this->LAT . "', yellowp_website='" . $this->WEBSITE . "', yellowp_statut='" . $this->STATUT . "', yellowp_last_modify = NOW() WHERE yellowp_id=" . $this->ID . ";";

    $result = $sql_object->DBQuery($q);

    // Notify the end of the current method
    $this->dispatcher->notify(new sfEvent($this, 'yellowpages.after_modify', array('data' => $table, 'id' => $this->ID)));

    return $result;
  }

  /**
   * yellowpages::_geocode()
   * prepare and geocode a given address
   *
   * @access private
   */
  private function _geocode() {

  	// Notify the end of the current method
  	$this->dispatcher->notify(new sfEvent($this, 'yellowpages.geocode_address'));

    $address = $this->STREET .',' . $this->CITY .',' . $this->COUNTRY;
    $o = geocode($address);

    if($o->{'status'}=='OK') {
      $this->LONG = $o->{'results'}[0]->{'geometry'}->{'location'}->{'lng'};
      $this->LAT =  $o->{'results'}[0]->{'geometry'}->{'location'}->{'lat'};
    }

  }

}

?>