/**
  * Destroy stuff in the database
  */
 function __destruct()
 {
     $conn = AIR2_DBManager::get_master_connection();
     // build the "where"
     $where = array();
     foreach ($this->where_fields as $idx => $fld) {
         $where[] = "{$fld} = ?";
     }
     $where = implode(' and ', $where);
     // count before deleting
     $q = "select count(*) from {$this->tbl_name} where {$where}";
     $num = $conn->fetchOne($q, $this->where_values, 0);
     if ($num > $this->max_delete) {
         $msg = "UNABLE TO CLEANUP - more than {$this->max_delete} rows";
         $msg .= " returned by query --> {$q}";
         throw new Exception($msg);
     }
     // execute delete
     $q = "delete from {$this->tbl_name} where {$where}";
     $del = $conn->exec($q, $this->where_values);
     if ($del != $num) {
         $msg = "PROBLEM CLEANING UP: expected to delete {$num}, got {$del}!";
         $msg .= "  Query --> {$q}";
         throw new Exception($msg);
     }
     // debug output
     if (getenv('AIR_DEBUG')) {
         diag("TestCleanup deleted {$del} stale {$this->tbl_name}");
     }
 }
 /**
  * Static function to refresh src_org_cache from src_org
  *
  * @param Source|src_id|src_uuid $source
  * @return int number of rows cached
  */
 public static function refresh_cache($source)
 {
     $conn = AIR2_DBManager::get_master_connection();
     // get the src_id
     $src_id;
     if (is_numeric($source)) {
         $src_id = $source;
     } elseif (is_string($source)) {
         $q = 'select src_id from source where src_uuid = ?';
         $src_id = $conn->fetchOne($q, array($source), 0);
     } elseif (is_object($source)) {
         $src_id = $source->src_id;
     }
     // sanity!
     if (!$src_id) {
         Carper::carp("Source !exists");
         return;
     }
     // delete all src_org_cache recs for this source
     $conn->execute("delete from src_org_cache where soc_src_id = {$src_id}");
     // array of org_id => status
     $org_status = Source::get_authz_status($src_id);
     // bulk-insert
     $vals = array();
     foreach ($org_status as $org_id => $status) {
         $vals[] = "({$src_id},{$org_id},'{$status}')";
     }
     if (count($vals)) {
         $vals = implode(',', $vals);
         $stmt = "insert into src_org_cache (soc_src_id, soc_org_id, soc_status)";
         $conn->execute("{$stmt} values {$vals}");
     }
     return count($vals);
 }
 /**
  * Redirect to perl!
  *
  * @param  array $args
  * @return array $resp
  */
 public function rec_query($args)
 {
     $bid = $this->parent_rec->bin_id;
     $uid = $this->user->user_id;
     // max csv  export size - #4458
     $conn = AIR2_DBManager::get_connection();
     $num = $conn->fetchOne("select count(*) from bin_source where bsrc_bin_id={$bid}", array(), 0);
     if ($num > Bin::$MAX_CSV_EXPORT && !$this->user->is_system()) {
         $msg = "Can only CSV export up to " . Bin::$MAX_CSV_EXPORT . " Sources";
         throw new Rframe_Exception(Rframe::BAD_DATA, $msg);
     }
     // get options
     $cpx = isset($args['allfacts']) && $args['allfacts'] ? 1 : 0;
     $log = 1;
     //default
     if (isset($args['logging']) && !$args['logging']) {
         $log = 0;
     }
     $notes = 0;
     if ($this->parent_rec->bin_status == Bin::$STATUS_ACTIVE_PROMPT_NOTES) {
         $notes = 1;
     }
     $opts = array('complex_facts' => $cpx, 'log_activity' => $log, 'bin_notes' => $notes);
     // download results, or email
     $data = array();
     if (isset($args['email']) && $args['email']) {
         // fix param names
         $extra = array();
         if ($opts['complex_facts']) {
             $extra[] = 'complex_facts';
         }
         if ($opts['log_activity']) {
             $extra[] = 'logging';
         }
         if ($opts['bin_notes']) {
             $extra[] = 'notes';
         }
         try {
             $this->parent_rec->queue_csv_export($this->user, $extra);
         } catch (Exception $e) {
             throw new Rframe_Exception(Rframe::BAD_DATA, $e->getMessage());
         }
         // success, but we want a non-200, so throw up!
         $msg = 'CSV export scheduled for background processing';
         throw new Rframe_Exception(Rframe::BGND_CREATE, $msg);
     } else {
         $r = CallPerl::exec('AIR2::CSVWriter->from_bin', $bid, $uid, $opts);
         $this->fields = $r[0];
         $this->reset_fields();
         // unflatten ... yeah, I know this is inefficient
         // but it's backwards compatible
         for ($i = 1; $i < count($r); $i++) {
             $data[$i - 1] = array();
             foreach ($this->fields as $colnum => $name) {
                 $data[$i - 1][$name] = $r[$i][$colnum];
             }
         }
     }
     return $data;
 }
 /**
  * Prequery hook
  */
 public function preQuery()
 {
     if ($this->gettype() == Doctrine_Query::SELECT) {
         $this->set_connection(AIR2_DBManager::get_slave_connection());
     } else {
         $this->set_connection(AIR2_DBManager::get_master_connection());
     }
 }
 /**
  * Delete from the database on exit
  */
 function __destruct()
 {
     if ($this->my_uuid) {
         $conn = AIR2_DBManager::get_master_connection();
         $conn->exec('delete from tag where tag_tm_id in (select tm_id from ' . 'tag_master where tm_name = ?)', array($this->my_uuid));
     }
     trec_destruct($this);
 }
Ejemplo n.º 6
0
 /**
  * Fetch
  *
  * @param string $uuid
  * @return Doctrine_Record $rec
  */
 protected function air_fetch($uuid)
 {
     $q = $this->air_query();
     $q->andWhere('t.tag_tm_id = ?', $uuid);
     $conn = AIR2_DBManager::get_connection();
     $usage = $conn->fetchOne('select count(*) from tag where tag_tm_id = ?', array($uuid), 0);
     $q->addSelect("{$usage} as usage");
     return $q->fetchOne();
 }
 /**
  * Delete from the database on exit
  */
 function __destruct()
 {
     if ($this->my_uuid) {
         // make sure any src_export records are cleaned up
         $conn = AIR2_DBManager::get_master_connection();
         $bid = 'select bin_id from bin where bin_uuid = ?';
         $del = "delete from src_export where se_xid = ({$bid}) and se_ref_type = ?";
         $conn->exec($del, array($this->my_uuid, SrcExport::$REF_TYPE_BIN));
     }
     trec_destruct($this);
 }
 /**
  * Produce custom statistics for Project Dashboard
  *
  * TODO: move this to the API
  *
  * @param string $uuid
  * @return array $data
  */
 private function _stats_data($uuid)
 {
     // Sources and Submissions (stats) panel data
     $conn = AIR2_DBManager::get_connection();
     $id = "(select prj_id from project where prj_uuid='{$uuid}')";
     $sent = 0;
     //$conn->fetchOne(''); TODO: tie to src_activity log
     $recv = $conn->fetchOne("select count(*) from src_response_set where srs_inq_id in (select pinq_inq_id from project_inquiry where pinq_prj_id = {$id})");
     $num_src = $conn->fetchOne("select count(distinct(srs_src_id)) from src_response_set where srs_inq_id in (select pinq_inq_id from project_inquiry where pinq_prj_id = {$id})");
     $pin_total = $conn->fetchOne("select count(*) from source where src_status = 'A'");
     return array('success' => true, 'radix' => array('prj_uuid' => $uuid, 'SubmissionCount' => $recv, 'SubmissionRate' => $sent > 0 ? $recv / $sent : 'N/A', 'SourceCount' => $num_src, 'SourceRate' => $pin_total > 0 ? $num_src / $pin_total : 'N/A'), 'meta' => array('identifier' => 'prj_uuid', 'fields' => array('prj_uuid', 'SubmissionCount', 'SubmissionRate', 'SourceCount', 'SourceRate')));
 }
 /**
  * Get some raw statistics for a specific source.
  *
  * @param string $uuid
  * @return array
  */
 private function _stats_data($uuid)
 {
     $conn = AIR2_DBManager::get_connection();
     $id = "(select src_id from source where src_uuid='{$uuid}')";
     $radix = array('src_uuid' => $uuid);
     // exported in bin
     $q = "select count(*) from src_inquiry where si_src_id = {$id}";
     $radix['exp_count'] = $conn->fetchOne($q, array(), 0);
     // sent query
     $q = "{$q} and si_status = ?";
     $radix['sent_count'] = $conn->fetchOne($q, array(SrcInquiry::$STATUS_COMPLETE), 0);
     // responded
     $q = "select count(*) from src_response_set where srs_src_id = {$id}";
     $radix['resp_count'] = $conn->fetchOne($q, array(), 0);
     return array('success' => true, 'radix' => $radix, 'meta' => array('identifier' => 'src_uuid', 'fields' => array('src_uuid', 'exp_count', 'sent_count', 'resp_count')));
 }
 /**
  * Merge 2 source records together, including all related data.
  *
  * @param Source  $prime   the record to merge into (will be preserved)
  * @param Source  $merge   the record to merge from (will be deleted)
  * @param array   $options (optional) options to use in merging conflicting data
  * @param boolean $commit  (optional)
  * @return boolean|string|array
  */
 public static function merge($prime, $merge, $options = array(), $commit = false)
 {
     self::$MERGE_OPTS = $options;
     self::$MERGE_RESULT = array('errs' => array(), 'prime' => array(), 'merge' => array(), 'moved' => array(), 'skipped' => array());
     // make sure we have fresh objects
     $prime->clearRelated();
     $merge->clearRelated();
     // start a transaction
     $conn = AIR2_DBManager::get_master_connection();
     $conn->beginTransaction();
     // run the merges
     try {
         self::merge_source($prime, $merge);
         self::merge_facts($prime, $merge);
         // remaining data produces no errors... so only run on commit
         if ($commit) {
             self::merge_easy($prime, $merge);
             self::combine_orgs($prime, $merge);
             self::combine_stat($prime, $merge);
         }
         // delete the merged source
         $merge->delete();
     } catch (Exception $e) {
         $conn->rollback();
         self::$MERGE_RESULT['fatal_error'] = $e->getMessage();
         return self::$MERGE_RESULT['fatal_error'];
     }
     // cache the merge result
     self::$MERGE_RESULT['result'] = $prime->toArray(true);
     // commit or rollback
     $errors = self::$MERGE_RESULT['errs'];
     if (count($errors) == 0 && $commit) {
         $conn->commit();
     } else {
         $conn->rollback();
         $prime->clearRelated();
         $prime->refresh();
         $merge->clearRelated();
         $merge->refresh();
     }
     // return errors or true on success
     if (count($errors) > 0) {
         return $errors;
     } else {
         return true;
     }
 }
 /**
  * Constructor
  *
  * Parse configuration file and cache some DB tables
  *
  * @param boolean $less_facts (optional) false to create full fact csv
  */
 public function __construct($less_facts = true)
 {
     $this->ini = parse_ini_file(self::$INI_FILE, true);
     // remove some of the secondary fact fields
     if ($less_facts) {
         foreach ($this->ini as $header => $def) {
             if (preg_match('/ Src Map$/', $header)) {
                 unset($this->ini[$header]);
             } elseif (preg_match('/ Src Text$/', $header)) {
                 unset($this->ini[$header]);
             }
         }
     }
     // cache code_master
     $conn = AIR2_DBManager::get_connection();
     $rs = $conn->fetchAll('select cm_field_name, cm_code, cm_disp_value ' . 'from code_master where cm_status = ?', array(CodeMaster::$STATUS_ACTIVE));
     foreach ($rs as $row) {
         $fld = $row['cm_field_name'];
         $code = $row['cm_code'];
         $disp = $row['cm_disp_value'];
         if (!isset($this->code_master[$fld])) {
             $this->code_master[$fld] = array($code => $disp);
         } else {
             $this->code_master[$fld][$code] = $disp;
         }
     }
     // cache state
     $rs = $conn->fetchAll('select state_code, state_name from state');
     foreach ($rs as $row) {
         $this->state[$row['state_code']] = $row['state_name'];
     }
     // cache country
     $rs = $conn->fetchAll('select cntry_code, cntry_name from country');
     foreach ($rs as $row) {
         $this->country[$row['cntry_code']] = $row['cntry_name'];
     }
     // cache fact
     $rs = $conn->fetchAll('select fact_id, fact_identifier from fact');
     foreach ($rs as $row) {
         $this->fact[$row['fact_identifier']] = $row['fact_id'];
     }
     // cache fact_value
     $rs = $conn->fetchAll('select fv_id, fv_value from fact_value');
     foreach ($rs as $row) {
         $this->fact_value[$row['fv_id']] = $row['fv_value'];
     }
 }
 /**
  * Constructor. Children who define a __construct method should call this.
  *
  * Connect to db, setup request params, etc.
  */
 public function __construct()
 {
     // Let CI init things (e.g. loader, etc.).
     parent::__construct();
     AIR2_DBManager::init();
     // load output library ASAP, in case anything goes wrong
     $this->load->library('AirOutput');
     // set the is_production flag based on setting in app/init.php
     if (AIR2_ENVIRONMENT == 'prod') {
         $this->is_production = true;
     }
     // request data
     $this->method = $this->router->http_method;
     $this->view = $this->router->http_view;
     $this->decode_input($this->method);
     $this->begin();
 }
Ejemplo n.º 13
0
 /**
  * Create
  *
  * @param array $data
  * @return UserOrg $rec
  */
 protected function air_create($data)
 {
     $this->require_data($data, array('osid_type', 'osid_xuuid'));
     if (!in_array($data['osid_type'], array('E', 'M'))) {
         throw new Rframe_Exception(Rframe::BAD_DATA, "invalid osid_type");
     }
     // unique osid_type per organization
     $conn = AIR2_DBManager::get_master_connection();
     $q = 'select count(*) from org_sys_id where osid_org_id = ? and osid_type = ?';
     $p = array($this->parent_rec->org_id, $data['osid_type']);
     $n = $conn->fetchOne($q, $p, 0);
     if ($n > 0) {
         throw new Rframe_Exception(Rframe::BAD_DATA, "osid_type already in use");
     }
     $os = new OrgSysId();
     $os->osid_org_id = $this->parent_rec->org_id;
     return $os;
 }
 /**
  * Schedule an export
  *
  * @param array $data
  */
 protected function air_create($data)
 {
     $bid = $this->parent_rec->bin_id;
     $uid = $this->user->user_id;
     // max export size
     $conn = AIR2_DBManager::get_connection();
     $q = "select count(*) from bin_src_response_set where bsrs_bin_id={$bid}";
     $num = $conn->fetchOne($q, array(), 0);
     if ($num > Bin::$MAX_CSV_EXPORT && !$this->user->is_system()) {
         $msg = "Can only CSV export up to " . Bin::$MAX_CSV_EXPORT . " Submissions";
         throw new Rframe_Exception(Rframe::BAD_DATA, $msg);
     }
     // email results
     try {
         $this->parent_rec->queue_xls_export($this->user);
     } catch (Exception $e) {
         throw new Rframe_Exception(Rframe::BAD_DATA, $e->getMessage());
     }
     // success, but we want a non-200, so throw up!
     $msg = 'Submissions export scheduled for background processing';
     throw new Rframe_Exception(Rframe::BGND_CREATE, $msg);
 }
 /**
  * Add sources to a PINfluence
  *
  * @param  Outcome  $outcome
  * @param  Bin      $bin
  * @param  string   $type
  */
 public static function add_sources_from_bin($outcome, $bin, $type)
 {
     $stats = array('total' => 0, 'insert' => 0, 'duplicate' => 0, 'invalid' => 0);
     $bin_id = $bin->bin_id;
     $b_where = "where bsrc_bin_id={$bin_id}";
     //hardcode so i don't get mixed up
     // totals
     $conn = AIR2_DBManager::get_master_connection();
     $stats['total'] = $conn->fetchOne("select count(*) from bin_source {$b_where}", array(), 0);
     // duplicates
     $b_s = "select bsrc_src_id from bin_source {$b_where}";
     $b_q = "select count(*) from src_outcome where sout_out_id=? and sout_src_id in ({$b_s})";
     $stats['duplicate'] += $conn->fetchOne($b_q, array($outcome->out_id), 0);
     // insert
     $user_id = $outcome->UpdUser->user_id;
     $s_where = "where src_id in ({$b_s})";
     $s_s = "select ?, src_id, ?, ?, ?, ?, ? from source {$s_where}";
     $s_q = "insert ignore into src_outcome (sout_out_id,sout_src_id, sout_type, sout_cre_user, sout_cre_dtim, sout_upd_user, sout_upd_dtim) {$s_s}";
     $stats['insert'] += $conn->exec($s_q, array($outcome->out_id, $type, $user_id, air2_date(), $user_id, air2_date()));
     $stats['invalid'] += $stats['total'] - $stats['insert'] - $stats['duplicate'];
     return $stats;
 }
 /**
  * Get some raw statistics for a specific inquiry.
  *
  * @param string  $uuid
  * @return array
  */
 private function _stats_data($inquiry)
 {
     $conn = AIR2_DBManager::get_connection();
     $id = $inquiry->inq_id;
     $radix = array('inq_uuid' => $inquiry->inq_uuid);
     $status = array(SrcInquiry::$STATUS_COMPLETE, SrcInquiry::$STATUS_AIR1, SrcInquiry::$STATUS_LYRIS);
     // find when the inquiry was sent, and by whom
     $select = 'select user_first_name, user_last_name, user_username, ' . 'user_type, DATE(si_cre_dtim) as sent_date, count(*) as sent_count';
     $from = 'from src_inquiry join user on (si_cre_user = user_id)';
     $group = 'group by si_inq_id, si_cre_user, sent_date';
     $order = 'order by sent_date desc';
     $q = "{$select} {$from} where si_inq_id = {$id} and si_status in (?, ?, ?) {$group} {$order}";
     $radix['SentBy'] = $conn->fetchAll($q, $status);
     // submission total
     $q = "select count(*) from src_response_set where srs_inq_id = ({$id})";
     $radix['recv_count'] = $conn->fetchOne($q, array(), 0);
     // published submissions total
     $radix['published_submissions_count'] = $inquiry->has_published_submissions();
     // emails sent total
     $q = "select count(*) from src_inquiry where si_inq_id = {$id} and si_status in (?, ?, ?)";
     $radix['sent_count'] = $conn->fetchOne($q, $status, 0);
     return array('success' => true, 'radix' => $radix, 'meta' => array('identifier' => 'inq_uuid', 'fields' => array('inq_uuid', 'SentBy', 'published_submissions_count', 'recv_count', 'sent_count')));
 }
Ejemplo n.º 17
0
 /**
  * Calls set_src_status() (which just returns the status)
  * and then executes a SQL update directly on the source table.
  */
 public function set_and_save_src_status()
 {
     // this only works AFTER the source is saved
     if ($this->src_id) {
         AIR2_DBManager::$FORCE_MASTER_ONLY = true;
         $stat = $this->set_src_status();
         $conn = AIR2_DBManager::get_master_connection();
         $conn->execute("update source set src_status='{$stat}' where src_id=" . $this->src_id);
     }
 }
Ejemplo n.º 18
0
 /**
  * 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;
 }
#!/usr/bin/env php
<?php 
require_once realpath(dirname(__FILE__) . '/../app/init.php');
require_once 'AIR2_DBManager.php';
/**
 * create-tbl.php
 *
 * This utility lets you create single tables from doctrine models.
 *
 */
AIR2_DBManager::init();
$conn = AIR2_DBManager::get_master_connection();
echo "Enter the name of the Doctrine model > ";
$modelname = trim(fgets(STDIN));
if (strlen($modelname) < 1) {
    echo "Error! No model specified!\n";
    exit(1);
}
try {
    $tbl = Doctrine::getTable($modelname);
} catch (Exception $e) {
    echo "Error!\n" . $e->getMessage() . "\n";
    exit(1);
}
try {
    $conn->execute('describe ' . $tbl->getTableName());
    echo "Table already exists in database!\nDrop table and recreate? (y/n) > ";
    $drop = strtolower(trim(fgets(STDIN)));
    if ($drop == 'y') {
        try {
            $conn->execute('drop table ' . $tbl->getTableName());
 /**
  * Apply authz rules for who may manage a SrcResponseSet.
  *
  * @param AIR2_Query $q
  * @param User    $u
  * @param string  $alias (optional)
  */
 public static function query_may_manage(AIR2_Query $q, User $u, $alias = null)
 {
     if ($u->is_system()) {
         return;
     }
     $a = $alias ? "{$alias}." : "";
     // manageable
     $mg_org_ids = $u->get_authz_str(ACTION_ORG_PRJ_INQ_SRS_DELETE, 'porg_org_id', true);
     $prj_ids = "select porg_prj_id from project_org where {$mg_org_ids}";
     $inq_ids = "select pinq_inq_id from project_inquiry where pinq_prj_id in ({$prj_ids})";
     // fetch actual id's, to prevent doctrine from adding its own alias to
     // our columns (pinq fields will get re-aliased by doctrine).
     $conn = AIR2_DBManager::get_connection();
     $rs = $conn->fetchColumn($inq_ids, array(), 0);
     $inq_ids = count($rs) ? implode(',', $rs) : 'NULL';
     // add to query
     $q->addWhere("{$a}srs_inq_id in ({$inq_ids})");
 }
/**
 * Fix a primary column on a table, making sure that each source only has
 * one primary set.
 *
 * @param AIR2_Record $rec
 * @param boolean $delete
 */
function air2_fix_src_primary($rec, $delete = false)
{
    $conn = AIR2_DBManager::get_master_connection();
    $tbl = $rec->getTable()->getTableName();
    // find column names
    $idcol = false;
    $fkcol = false;
    $flagcol = false;
    $updcol = false;
    $cols = $rec->getTable()->getColumnNames();
    foreach ($cols as $col) {
        if (preg_match('/^[a-z]+_id$/', $col)) {
            $idcol = $col;
        } elseif (preg_match('/^[a-z]+_src_id$/', $col)) {
            $fkcol = $col;
        } elseif (preg_match('/_primary_flag$/', $col) || preg_match('/_home_flag$/', $col)) {
            $flagcol = $col;
        } elseif (preg_match('/_upd_dtim$/', $col)) {
            $updcol = $col;
        }
    }
    // sanity!
    if (!$idcol || !$fkcol || !$flagcol || !$updcol) {
        throw new Exception("Missing a column");
    }
    // saved? or deleted?
    if (!$delete) {
        if ($rec[$flagcol]) {
            // unset everyone else
            $q = "update {$tbl} set {$flagcol}=0 where {$fkcol}=? and {$idcol}!=?";
            $conn->exec($q, array($rec[$fkcol], $rec[$idcol]));
        } else {
            // check for existing primary
            $q = "select {$idcol}, {$flagcol} from {$tbl} where {$fkcol} = ?";
            $rs = $conn->fetchAll($q, array($rec[$fkcol]));
            $has_primary = false;
            foreach ($rs as $row) {
                if ($row[$flagcol]) {
                    $has_primary = true;
                }
            }
            // should I or someone else be primary?
            if (!$has_primary && count($rs) == 1) {
                // it's me!
                $q = "update {$tbl} set {$flagcol}=1 where {$fkcol}=? and {$idcol}=?";
                $conn->exec($q, array($rec[$fkcol], $rec[$idcol]));
                //TODO: better solution? Can't figure out why refresh fails
                if ($rec->exists()) {
                    try {
                        $rec->refresh();
                    } catch (Doctrine_Record_Exception $e) {
                        if ($e->getCode() == 0 && preg_match('/does not exist/i', $e->getMessage())) {
                            // ignore, I guess
                        } else {
                            throw $e;
                            //rethrow
                        }
                    }
                }
            } elseif (!$has_primary && count($rs) > 1) {
                // pick most recent that isn't me
                $q = "update {$tbl} set {$flagcol}=1 where {$fkcol}=? and {$idcol}!=?";
                // find upd_dtim column
                $data = $rec->toArray();
                foreach ($data as $key => $val) {
                    if (preg_match('/upd_dtim$/', $key)) {
                        $q .= " order by {$key} desc";
                    }
                }
                $conn->exec("{$q} limit 1", array($rec[$fkcol], $rec[$idcol]));
            }
        }
    } else {
        //deleted - pick most recent
        $q = "update {$tbl} set {$flagcol}=1 where {$fkcol}=? and {$idcol}!=?";
        // find upd_dtim column
        $data = $rec->toArray();
        foreach ($data as $key => $val) {
            if (preg_match('/upd_dtim$/', $key)) {
                $q .= " order by {$key} desc";
            }
        }
        $conn->exec("{$q} limit 1", array($rec[$fkcol], $rec[$idcol]));
    }
}
 /**
  * Custom validation to enforce uniqueness-per-fact of xm_xlate_from.
  *
  * @param array   $data
  * @return array
  */
 public static function remote_validate($data)
 {
     $errs = array();
     if (isset($data['xm_xlate_from']) && isset($data['xm_fact_id'])) {
         $conn = AIR2_DBManager::get_connection();
         $q = 'select count(*) from translation_map where xm_fact_id = ? ' . 'and xm_xlate_from = ?';
         $n = $conn->fetchOne($q, array($data['xm_fact_id'], $data['xm_xlate_from']), 0);
         if ($n > 0) {
             $errs['xm_xlate_from'] = 'unique';
         }
     }
     return $errs;
 }
 /**
  * Override parent method to set internal readiness var, preventing multiple initializations.
  */
 public static function init($profile_name = null, $app_path = null)
 {
     $air2_profile = parent::init($profile_name, $app_path);
     if (self::$i_am_ready) {
         return $air2_profile;
     }
     self::$i_am_ready = true;
     return $air2_profile;
 }
 /**
  * Find the number of active Users in any given Organization
  *
  * @param int     $org_id
  * @return int
  */
 public static function get_user_count($org_id)
 {
     $uost = UserOrg::$STATUS_ACTIVE;
     $ust1 = User::$STATUS_ACTIVE;
     $ust2 = User::$STATUS_PUBLISHABLE;
     $conn = AIR2_DBManager::get_connection();
     $active_users = "select user_id from user where user_status " . "= '{$ust1}' or user_status = '{$ust2}'";
     $q = "select count(*) from user_org where uo_org_id = ? and " . "uo_status = '{$uost}' and uo_user_id in ({$active_users})";
     $n = $conn->fetchOne($q, array($org_id), 0);
     return $n;
 }
Ejemplo n.º 25
0
 /**
  * Custom delete procedure to cleanup bin_src_response_sets
  *
  * @throws Rframe_Exceptions
  * @param  BinSource $rec
  */
 protected function rec_delete(BinSource $rec)
 {
     $sid = $rec->bsrc_src_id;
     $bid = $rec->bsrc_bin_id;
     // normal delete stuff
     $this->check_authz($rec, 'delete');
     $rec->delete();
     $this->update_parent($rec);
     // delete any orphaned submissions
     $conn = AIR2_DBManager::get_master_connection();
     $conn->exec("delete from bin_src_response_set where bsrs_bin_id={$bid} and bsrs_src_id={$sid}");
 }
 /**
  * Mark inquiry as stale
  *
  * @param InqOrg  $rec
  */
 protected function update_parent(InqOrg $rec)
 {
     // raw sql update rather than calling parent_rec->save()
     // because nested objects cascade
     $upd = 'update inquiry set inq_stale_flag=1 where inq_id = ?';
     AIR2_DBManager::get_master_connection()->exec($upd, array($rec->iorg_inq_id));
 }
 /**
  * Make sure a record has unique from/to translation
  *
  * @param TranslationMap $rec
  */
 private function check_translation($rec)
 {
     $conn = AIR2_DBManager::get_master_connection();
     // build query
     $w = "xm_fact_id= ? and xm_xlate_from = ?";
     $q = "select count(*) from translation_map where {$w}";
     $params = array($rec->xm_fact_id, $rec->xm_xlate_from);
     if ($rec->xm_id) {
         $q .= " and xm_id != ?";
         $params[] = $rec->xm_id;
     }
     $n = $conn->fetchOne($q, $params, 0);
     if ($n > 0) {
         $s = "fact_id(" . $rec->xm_fact_id . ") - text(" . $rec->xm_xlate_from . ")";
         throw new Rframe_Exception("Non unique translation - {$s}");
     }
 }
 /**
  * Magic path to mark submissions as unfavorite
  *
  * @param string @srs_uuid
  * @param unknown $srs_uuid
  */
 public function unfavorite($srs_uuid)
 {
     $conn = AIR2_DBManager::get_master_connection();
     $srsid = $conn->fetchOne('select srs_id from src_response_set where srs_uuid = ?', array($srs_uuid), 0);
     if (!$srsid) {
         return;
     }
     $now = air2_date();
     $flds = "usrs_user_id, usrs_srs_id, usrs_favorite_flag, usrs_cre_dtim, usrs_upd_dtim";
     $ondup = "on duplicate key update usrs_favorite_flag=0,usrs_upd_dtim='{$now}'";
     $ins = "insert into user_srs ({$flds}) values (?,{$srsid},0,'{$now}','{$now}') {$ondup}";
     $n = $conn->exec($ins, array($this->user->user_id));
     air2_touch_stale_record('src_response_set', $srsid);
 }
 /**
  * Load database connection in constructor
  */
 public function __construct()
 {
     parent::__construct();
     AIR2_DBManager::init();
 }
 /**
  * Run a merge using the AIR2Merge library.
  *
  * @param array   $response_data
  */
 protected function run($response_data = array())
 {
     // turn off logging during the merge
     $was_logging_enabled = AIR2Logger::$ENABLE_LOGGING;
     AIR2Logger::$ENABLE_LOGGING = false;
     // run the merge and reset logging
     $type = $this->my_type;
     $errs = AIR2Merge::merge($this->prime, $this->merge, $this->ops, $this->commit_on_success);
     $result = AIR2Merge::get_result();
     AIR2Logger::$ENABLE_LOGGING = $was_logging_enabled;
     // what happened?
     $status = 200;
     if ($errs === true) {
         $response_data['success'] = true;
         $response_data['message'] = "Successfully merged {$type}s";
         // attach the "merged" object to data
         $response_data['ResultSource'] = $result['result'];
         air2_clean_radix($response_data['ResultSource'], $this->radix_whitelist);
         // attach ops used
         $response_data['op_prime'] = $result['prime'];
         $response_data['op_merge'] = $result['merge'];
         // log the merge
         if ($this->commit_on_success) {
             $this->log_activity($result, $response_data);
         }
     } elseif (is_string($errs)) {
         $response_data['success'] = false;
         $response_data['message'] = $errs;
         $status = 500;
     } else {
         $response_data['success'] = false;
         $response_data['message'] = "Unable to merge {$type}s";
         $response_data['errors'] = $errs;
         $status = 400;
         // attach ops used
         $response_data['op_prime'] = $result['prime'];
         $response_data['op_merge'] = $result['merge'];
     }
     // attach fact data
     $rs = AIR2_DBManager::get_connection()->fetchAll('select * from fact');
     $response_data['facts'] = array();
     foreach ($rs as $row) {
         $response_data['facts'][$row['fact_id']] = $row;
     }
     // respond with data
     $this->response($response_data, $status);
 }