/**
  * Forces a source to be opted-into APMG
  *
  * @param int     $src_id
  * @return bool $inserted
  */
 public static function force_apmg($src_id)
 {
     $data = array('so_src_id' => $src_id, 'so_org_id' => Organization::$APMPIN_ORG_ID, 'so_uuid' => air2_generate_uuid(), 'so_effective_date' => air2_date(), 'so_home_flag' => 0, 'so_status' => self::$STATUS_OPTED_IN, 'so_cre_user' => 1, 'so_upd_user' => 1, 'so_cre_dtim' => air2_date(), 'so_upd_dtim' => air2_date());
     $flds = implode(',', array_keys($data));
     $vals = air2_sql_param_string($data);
     $stmt = "insert ignore into src_org ({$flds}) values ({$vals})";
     // execute
     $conn = AIR2_DBManager::get_master_connection();
     $n = $conn->exec($stmt, array_values($data));
     return $n;
 }
 /**
  * Abstract method implementation
  *
  * @return string
  */
 protected function get_url_token()
 {
     return air2_generate_uuid(32);
 }
/**
 *
 *
 * @param unknown $model
 */
function air2_model_prevalidate(&$model)
{
    $table = $model->getTable();
    $col_defs = $table->getColumns();
    $now = air2_date();
    foreach ($col_defs as $col => $def) {
        if (preg_match('/_uuid$/', $col) && isset($def['unique']) && $def['unique']) {
            if (!isset($model->{$col}) || !strlen($model->{$col})) {
                $model->{$col} = air2_generate_uuid(12);
            }
        } elseif (preg_match('/_cre_dtim$/', $col)) {
            if (!$model->exists() && !strlen($model->{$col})) {
                $model->{$col} = $now;
            }
        } elseif (preg_match('/_upd_dtim$/', $col)) {
            $model->{$col} = $now;
        } elseif (preg_match('/_cre_user$/', $col)) {
            if (!$model->exists() && !strlen($model->{$col})) {
                if (defined('AIR2_REMOTE_USER_ID')) {
                    $model->{$col} = AIR2_REMOTE_USER_ID;
                } else {
                    $model->{$col} = 1;
                    //sysuser -- TODO: check for shell users
                }
            }
        } elseif (preg_match('/_upd_user$/', $col)) {
            if (defined('AIR2_REMOTE_USER_ID')) {
                $model->{$col} = AIR2_REMOTE_USER_ID;
            } else {
                $model->{$col} = 1;
                //sysuser -- TODO: check for shell users
            }
        } elseif ($def['type'] === 'timestamp') {
            // validate the string for non cre/upd timestamps
            if (isset($model->{$col}) && !is_null($model->{$col})) {
                //NOTE: whenever you set a column in Doctrine, it checks that
                //the value has changed.  Since '2010-01-01 01:01:01' is equal
                //to '2010-01-01T01:01:01', we need to NULL it first
                if (strpos($model->{$col}, 'T') !== false) {
                    $airformat = air2_date(strtotime($model->{$col}));
                    $model->{$col} = null;
                    $model->{$col} = $airformat;
                }
            }
        } elseif ($def['type'] === 'date') {
            // validate the string for non cre/upd timestamps
            if (isset($model->{$col}) && !is_null($model->{$col})) {
                //NOTE: whenever you set a column in Doctrine, it checks that
                //the value has changed.  Since '2010-01-01 01:01:01' is equal
                //to '2010-01-01T01:01:01', we need to NULL it first
                if (strpos($model->{$col}, 'T') !== false) {
                    $airformat = air2_date(strtotime($model->{$col}));
                    $model->{$col} = null;
                    $model->{$col} = $airformat;
                }
            }
        }
        // default values
        if (strlen($table->getDefaultValueOf($col)) && !strlen($model->{$col})) {
            $model->{$col} = $table->getDefaultValueOf($col);
        }
        // lastly, check strings for valid UTF8 chars
        if ($def['type'] === 'string' && !Encoding::is_utf8($model->{$col})) {
            $modelname = get_class($model);
            throw new Doctrine_Exception("non-UTF8 string found in {$modelname}->{$col}: " . $model->{$col});
        }
    }
}
 /**
  * Save form information
  *
  * @param unknown $name
  * @param unknown $email
  */
 protected function save($name, $email)
 {
     $ip_address = $this->input->server('REMOTE_ADDR');
     $api_key = new APIKey();
     $api_key->ak_contact = $name;
     $api_key->ak_email = $email;
     $api_key->ak_key = air2_generate_uuid(32);
     $api_key->save();
     $api_stat = new APIStat();
     $api_stat->APIKey = $api_key;
     $api_stat->as_ip_addr = $ip_address;
     $api_stat->save();
 }
 /**
  * new( $query_uuid, $params )
  *
  * @param string  $query_uuid
  * @param array   $params
  */
 public function __construct($query_uuid, $params)
 {
     $this->query_uuid = $query_uuid;
     $this->srs = $params;
     $this->uuid = air2_generate_uuid();
 }
 /**
  * Create or update a SrcOrg record for a Source.
  *
  * @param Source  $src
  */
 public function process_source(Source $src)
 {
     // run raw-sql for efficiency
     $conn = AIR2_DBManager::get_master_connection();
     $src_id = $src->src_id;
     $org_id = $this->to_org_id;
     $unset_home_flags = false;
     // check for existing (and total)
     $where = "where so_src_id = {$src_id} and so_org_id = {$org_id}";
     $status = "(select so_status from src_org {$where}) as status";
     $ishome = "(select so_home_flag from src_org {$where}) as ishome";
     $select = "select count(*) as total, {$status}, {$ishome}";
     $q = "{$select} from src_org where so_src_id = {$src_id}";
     $rs = $conn->fetchRow($q);
     // run operation
     $op = false;
     $data = array();
     if (is_null($rs['status'])) {
         // insert
         $data = array('so_src_id' => $src_id, 'so_org_id' => $org_id, 'so_uuid' => air2_generate_uuid(), 'so_effective_date' => air2_date(), 'so_home_flag' => $this->to_so_home_flag ? 1 : 0, 'so_status' => $this->to_so_status, 'so_cre_user' => $this->Tank->tank_user_id, 'so_upd_user' => $this->Tank->tank_user_id, 'so_cre_dtim' => $this->Tank->tank_cre_dtim, 'so_upd_dtim' => $this->Tank->tank_upd_dtim);
         // determine home flag
         if ($rs['total'] == 0) {
             $data['so_home_flag'] = true;
         } elseif ($this->to_so_home_flag && $data['total'] > 0) {
             $unset_home_flags = true;
         }
         // insert
         $flds = implode(',', array_keys($data));
         $vals = air2_sql_param_string($data);
         $q = "insert into src_org ({$flds}) values ({$vals})";
         $conn->exec($q, array_values($data));
     } else {
         // update
         $updates = array();
         // change to status
         if ($rs['status'] != $this->to_so_status) {
             $updates[] = "so_status='" . $this->to_so_status . "'";
         }
         // change to home flag (only allow setting, not unsetting)
         if ($this->to_so_home_flag && !$rs['ishome']) {
             $updates[] = "so_home_flag=1";
             //MUST be true
             if ($rs['total'] > 1) {
                 $unset_home_flags = true;
             }
         }
         // do we need to do anything?
         if (count($updates)) {
             $set = implode(', ', $updates);
             $where = "so_src_id={$src_id} and so_org_id={$org_id}";
             $q = "update src_org set {$set} where {$where}";
             $conn->exec($q);
         }
     }
     // optionally unset other home flags
     if ($unset_home_flags) {
         $set = 'so_home_flag=0';
         $where = "so_src_id={$src_id} and so_org_id!={$org_id}";
         $conn->exec("update src_org set {$set} where {$where}");
     }
 }
 /**
  * Create
  *
  * @param array $data
  */
 protected function air_create($data)
 {
     $this->require_data($data, array('csvfile'));
     // sanity-check file
     $file = $data['csvfile'];
     if (!preg_match('/\\.csv$/', $file['name'])) {
         throw new Rframe_Exception(Rframe::BAD_DATA, "Uploaded file must have the extension '.csv'");
     }
     $rec = new Tank();
     $rec->tank_uuid = air2_generate_uuid();
     $rec->tank_user_id = $this->user->user_id;
     $rec->tank_type = Tank::$TYPE_CSV;
     $rec->tank_status = Tank::$STATUS_CSV_NEW;
     $rec->tank_name = $file['name'];
     $rec->copy_file($file['tmp_name']);
     // save filesize in metadata
     $size_kb = number_format($file['size'] / 1024, 1);
     $rec->set_meta_field('file_size', "{$size_kb} KB");
     // meta delimiters (defaults)
     $del = isset($data['csv_delim']) ? $data['csv_delim'] : ',';
     $rec->set_meta_field('csv_delim', $del);
     $encl = isset($data['csv_encl']) ? $data['csv_encl'] : '"';
     $rec->set_meta_field('csv_encl', $encl);
     // setup submit errors and valids
     $rec->set_meta_field('submit_message', null);
     $rec->set_meta_field('submit_success', null);
     $rec->set_meta_field('valid_file', true);
     // use a CSVImporter to validate headers
     $imp = new CSVImporter($rec);
     $hdr_msg = $imp->validate_headers();
     $hdr_valid = $hdr_msg === true ? true : false;
     $rec->set_meta_field('valid_header', $hdr_valid);
     return $rec;
 }
 /**
  * Custom setter for the image.
  *
  * @param array|string $image
  */
 public function set_image($image)
 {
     if (is_array($image)) {
         $name = $image['name'];
         $path = $image['tmp_name'];
     } elseif (is_string($image) && is_readable($image)) {
         $name = basename($image);
         $path = $image;
     } else {
         throw new Exception("Invalid image");
     }
     // validate image
     if (!is_readable($path)) {
         throw new Exception("Invalid image path: {$path}");
     }
     $img_info = getimagesize($path);
     if (!$img_info) {
         throw new Exception("Invalid image file: {$name}");
     }
     // check/create image directory
     if (!$this->img_uuid) {
         $this->img_uuid = air2_generate_uuid();
     }
     $dir = self::get_directory($this->img_ref_type, $this->img_uuid);
     air2_mkdir($dir);
     if (!is_writable($dir)) {
         throw new Exception("Cannot write to: {$dir}");
     }
     // looks okay... raw-set the info
     $this->_set('img_file_name', air2_fileify($name));
     $this->_set('img_file_size', filesize($path));
     $this->_set('img_content_type', $img_info['mime']);
     $this->_set('img_dtim', air2_date());
     $this->_set_image = $path;
 }
 /**
  * Identify a Source from a TankSource, or create a new Source.
  *
  * @param TankSource $tsrc
  * @return boolean|Source success
  */
 protected function identify_source($tsrc)
 {
     // src_id and src_uuid ONLY identify existing records
     if ($tsrc->src_id || $tsrc->src_uuid) {
         $col = $tsrc->src_id ? 'src_id' : 'src_uuid';
         $q = Doctrine_Query::create()->from('Source');
         $q->where("{$col} = ?", $tsrc->{$col});
         $rec = $q->fetchOne();
         $q->free();
         // return early
         if ($rec) {
             return $rec;
         } else {
             $tsrc->add_error("Invalid {$col}!");
             return false;
         }
     } elseif ($tsrc->src_username || $tsrc->sem_email) {
         // trim on first run
         if ($tsrc->src_username) {
             $tsrc->src_username = trim($tsrc->src_username);
         }
         if ($tsrc->sem_email) {
             $tsrc->sem_email = trim($tsrc->sem_email);
         }
         $q = Doctrine_Query::create()->from('Source a');
         if ($tsrc->src_username) {
             $q->where('a.src_username = ?', $tsrc->src_username);
         } else {
             $q->leftJoin('a.SrcEmail e');
             $q->where('e.sem_email = ?', $tsrc->sem_email);
         }
         $rec = $q->fetchOne();
         $q->free();
         // create if DNE
         if (!$rec) {
             $rec = new Source();
             $rec->src_uuid = air2_generate_uuid();
             // special case: handle nosuchemail.org
             $nosuch = '/@nosuchemail.org$/i';
             if (preg_match($nosuch, $tsrc->src_username) || preg_match($nosuch, $tsrc->sem_email)) {
                 $tsrc->src_username = $rec->src_uuid . '@nosuchemail.org';
                 $tsrc->sem_email = $tsrc->src_username;
             } elseif (!$tsrc->src_username) {
                 $tsrc->src_username = strtolower($tsrc->sem_email);
                 // make sure username isn't taken
                 $chk = 'select count(*) from source where src_username = ?';
                 $n = $this->conn->fetchOne($chk, array($tsrc->src_username), 0);
                 // if taken, prepend UUID to username
                 if ($n > 0) {
                     $tsrc->src_username = $rec->src_uuid . '@' . $tsrc->src_username;
                 }
             }
         }
         return $rec;
     }
     // no identifiers set!
     $tsrc->add_error('Unable to resolve a Source record!');
     return false;
 }
echo "Enter the username of an AIR2 User:\n > ";
$username = trim(fgets(STDIN));
if (strlen($username) < 1) {
    echo "Error! No username specified!\n";
    exit(0);
}
$user = Doctrine::getTable('User')->findOneBy('user_username', $username);
if (!$user) {
    $user = new User();
    $user->user_username = $username;
    $user->user_first_name = '[First]';
    $user->user_last_name = '[Last]';
    $user->user_cre_dtim = air2_date();
    $user->user_cre_user = 1;
    // system user
    $user->user_uuid = air2_generate_uuid();
    $user->user_type = 'A';
    // system type
    $user->user_status = 'A';
    // active
    echo "AIR2 User '{$username}' not found!\n";
    echo "Enter new password to create User. (Blank to cancel)\n > ";
} else {
    echo "Enter new password:\n > ";
}
$userpass = trim(fgets(STDIN));
$pinpass = new PINPassword(array('username' => $username, 'phrase' => $userpass));
if (!$pinpass->validate()) {
    die("Password " . $pinpass->get_error() . "\n");
}
if (strlen($userpass) > 0) {