/**
  * 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;
 }
 /**
  * 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();
 }
 /**
  * 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')));
 }
 /**
  * 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'];
     }
 }
 /**
  * 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);
 }
 /**
  * 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')));
 }
 /**
  * Inherit from Project
  *
  * @param AIR2_Query $q
  * @param User    $u
  * @param string  $alias (optional)
  */
 public static function query_may_read(AIR2_Query $q, User $u, $alias = null)
 {
     if ($u->is_system()) {
         return;
     }
     $a = $alias ? "{$alias}." : "";
     // readable projects
     $tmp = AIR2_Query::create();
     Project::query_may_read($tmp, $u);
     $tmp = array_pop($tmp->getDqlPart('where'));
     $prj_ids = "select prj_id from project where {$tmp}";
     // fetch actual id's, to prevent doctrine from adding its own alias to
     // our columns (porg fields will get re-aliased by doctrine).
     $conn = AIR2_DBManager::get_connection();
     $rs = $conn->fetchColumn($prj_ids, array(), 0);
     $prj_ids = count($rs) ? implode(',', $rs) : 'NULL';
     $q->addWhere("{$a}porg_prj_id in ({$prj_ids})");
 }
 /**
  * Returns number of related active Sources. src_status is factored in,
  * so Sources who are not active in the PIN are not counted.
  *
  * @param boolean $use_cached (optional)
  * @return integer count_of_sources
  */
 public function get_num_sources($use_cached = false)
 {
     $conn = AIR2_DBManager::get_connection();
     if ($use_cached) {
         $q = "select count(soc_src_id) from src_org_cache, source where soc_src_id=src_id and src_status in ('A','E','T') and soc_status='A' and soc.soc_org_id=" . $this->org_id;
     } else {
         $q = "select count(so_src_id) from src_org,source where src_status in ('A','E','T') and so_status = 'A' and so_src_id=src_id and so_org_id=" . $this->org_id;
     }
     return $conn->fetchOne($q, array(), 0);
 }
 /**
  * Add live_sran_counts to search responses
  *
  * @param string $data
  * @param string $index
  * @param array  $ids
  */
 private function _add_sran_counts(&$data, $index, $ids)
 {
     $ids = implode(',', $ids);
     $ids = "select sr_id from src_response where sr_srs_id in ({$ids})";
     $fk = 'sran_sr_id';
     $tbl = 'sr_annotation';
     // fetch counts
     $conn = AIR2_DBManager::get_connection();
     $sel = "select {$fk}, count(*) as num from {$tbl} where {$fk} in ({$ids}) group by {$fk}";
     $annots = $conn->fetchAll($sel);
     $lookup = array();
     foreach ($annots as $ann) {
         $lookup[$ann[$fk]] = $ann['num'];
     }
     // add back into the results
     foreach ($data['results'] as $idx => $row) {
         $data['results'][$idx]['live_sran_counts'] = array();
         $srids = explode(':', $row['sr_ids']);
         foreach ($srids as $sr_id) {
             $count = isset($lookup[$sr_id]) ? $lookup[$sr_id] : 0;
             $data['results'][$idx]['live_sran_counts'][] = $count;
         }
     }
     $data['fields'][] = 'live_sran_counts';
     $data['metaData']['fields'][] = 'live_sran_counts';
 }
 /**
  * Execute query and format results
  *
  * @param string $qry
  * @return array $radix
  */
 protected function format_query_radix($qry)
 {
     $user_id = $this->parent_rec->user_id;
     $conn = AIR2_DBManager::get_connection();
     $limit = $this->my_limit;
     $offset = $this->my_offset;
     $all = $conn->fetchAll("{$qry} order by dtim desc limit {$limit} offset {$offset}");
     // get PK id's by type
     $ids_by_type = array();
     foreach ($all as $row) {
         $type = $row['type'];
         if (!isset($ids_by_type[$type])) {
             $ids_by_type[$type] = array();
         }
         $ids_by_type[$type][] = $row['id'];
     }
     // fetch all the types
     $fetched_in_order = array();
     if (count($all)) {
         $fetched_in_order = array_fill(0, count($all), null);
     }
     foreach ($ids_by_type as $type => $ids) {
         $model = $this->actv_config[$type]['model'];
         $idcol = $this->actv_config[$type]['id'];
         $q = AIR2_Query::create()->from("{$model} a");
         $q->whereIn("a.{$idcol}", $ids);
         if (isset($this->actv_config[$type]['join'])) {
             foreach ($this->actv_config[$type]['join'] as $join) {
                 $q->leftJoin("a.{$join}");
             }
         }
         $rs = $q->fetchArray();
         // put them back in the right order
         foreach ($rs as $object) {
             $my_id = $object[$idcol];
             foreach ($all as $idx => $row) {
                 if ($row['type'] == $type && $row['id'] == $my_id) {
                     $fetched_in_order[$idx] = array('type' => $type, 'dtim' => $row['dtim'], 'id' => $type . $my_id, $model => $object);
                     break;
                 }
             }
         }
     }
     // clean data
     foreach ($fetched_in_order as &$row) {
         $row = $this->_clean($row, $this->_fields);
     }
     return $fetched_in_order;
 }
 /**
  * RSS Feed for PIN statistics
  */
 public function stats()
 {
     if ($this->method != 'GET') {
         header('Allow: GET');
         show_error("Error: Unsupported request method: {$this->method}", 405);
     }
     if ($this->view != 'rss' && $this->view != 'json') {
         show_error("Only rss and json views available", 415);
     }
     // CHECK FOR CACHE (stored as json-encoded data array)
     $data = Cache::instance()->get('stats_rss_all');
     if ($data) {
         $data = json_decode($data, true);
     } else {
         // count sources
         $conn = AIR2_DBManager::get_connection();
         $q = "select count(*) from source where (src_status in ('A','E','T'))";
         $num_sources = $conn->fetchOne($q, array(), 0);
         $q = "select count(*) from user where (user_type != 'S' and user_status in ('A','P'))";
         $num_users = $conn->fetchOne($q, array(), 0);
         // attempt to non-prospective orgs in one query... just check 4 levels down
         $nonprospect = "select org_id from organization where org_parent_id is null and org_name != 'prospect'";
         $lvl0 = "org_id in ({$nonprospect})";
         $lvl1 = "org_parent_id in ({$nonprospect})";
         $lvl2 = "org_parent_id in (select org_id from organization where {$lvl1})";
         $lvl3 = "org_parent_id in (select org_id from organization where {$lvl2})";
         $where = "{$lvl0} or {$lvl1} or {$lvl2} or {$lvl3}";
         $q = "select count(*) from organization where (org_status='A' or org_status='P') and ({$where})";
         $num_orgs = $conn->fetchOne($q, array(), 0);
         // assemble data
         $link = air2_uri_for('rss/stats', $this->input_all);
         $data = array('title' => 'PIN Statistics', 'link' => $link, 'description' => 'Statistics concerning the Public Insight Network', 'language' => 'en-us', 'lastBuildDate' => $this->_rss_datetime(), 'generator' => 'AIR2', 'item' => array(array('title' => 'PIN Organization Count', 'link' => $link, 'description' => $num_orgs, 'guid' => 'pin_org_count'), array('title' => 'Active Sources Count', 'link' => $link, 'description' => $num_sources, 'guid' => 'active_src_count'), array('title' => 'Active Users Count', 'link' => $link, 'description' => $num_users, 'guid' => 'active_user_count')));
         // cache the data
         Cache::instance()->save(json_encode($data), 'stats_rss_all');
     }
     // output data
     $this->airoutput->write($data);
 }
 /**
  * Attempt to fetch conflict-with existing record from database
  *
  * @param type    $key
  * @param type    $confl
  * @return type
  */
 private function _get_with($key, $confl)
 {
     $mname = TankSource::get_model_for($key);
     if ($mname && isset($confl['uuid'])) {
         if ($mname != 'SrcFact') {
             $rec = AIR2_Record::find($mname, $confl['uuid']);
             if ($rec) {
                 $data = $rec->toArray();
                 air2_clean_radix($data);
                 return $data;
             }
         } else {
             // facts suck ... src_id.fact_id ... use raw sql for speed!
             $ids = explode('.', $confl['uuid']);
             if ($ids && count($ids) == 2) {
                 $conn = AIR2_DBManager::get_connection();
                 $s = 'f.fact_id, f.fact_name, f.fact_identifier, f.fact_fv_type, ' . 'afv.fv_value as analyst_fv, sfv.fv_value as source_fv, ' . 'sf.sf_src_value as source_text, sf.sf_lock_flag';
                 $f = 'src_fact sf join fact f on (sf.sf_fact_id=f.fact_id) left ' . 'join fact_value afv on (sf.sf_fv_id=afv.fv_id) left join ' . 'fact_value sfv on (sf.sf_src_fv_id=sfv.fv_id)';
                 $w = 'sf_src_id=? and sf_fact_id=?';
                 $rs = $conn->fetchRow("select {$s} from {$f} where {$w}", array($ids[0], $ids[1]));
                 if ($rs) {
                     return $rs;
                 }
             }
         }
     }
     return false;
 }
 /**
  * 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);
 }
 /**
  * Cache any preferences in the CSV header
  *
  * @param array $headers
  * @param array $ini
  */
 protected function cache_preference_mappings($headers, $ini)
 {
     $conn = AIR2_DBManager::get_connection();
     $q = 'select pt_id from preference_type where pt_identifier = ?';
     $this->map_preferences = array();
     foreach ($headers as $idx => $col) {
         if (isset($ini[$col]) && isset($ini[$col]['pref'])) {
             $ident = $ini[$col]['pref'];
             $field_name = $ini[$col]['tank_pref_fld'];
             $map = isset($ini[$col]['map']) ? $ini[$col]['map'] : false;
             //look up pt_id
             $preference_id = $conn->fetchOne($q, array($ident), 0);
             if (!isset($this->map_preferences[$preference_id])) {
                 $this->map_preferences[$preference_id] = array();
             }
             //add this mapping
             $this->map_preferences[$preference_id][$idx] = $field_name;
         }
     }
 }
 /**
  * Process the locked tank_sources for the loaded tank.  Optionally allows
  * you to process a subset of tank_sources identified by their keys.
  *
  * @param array   $tsrc_ids
  * @param array   $ops
  */
 protected function process_tank_sources($tsrc_ids = null, $ops = null)
 {
     if (!$tsrc_ids) {
         // get the ID's of everything we're going to process
         $q = 'SELECT tsrc_id FROM tank_source WHERE tsrc_tank_id = ? AND tsrc_status = ?';
         $params = array($this->tank->tank_id, TankSource::$STATUS_LOCKED);
         $conn = AIR2_DBManager::get_connection();
         $tsrc_ids = $this->conn->fetchColumn($q, $params, 0);
         if (count($tsrc_ids) == 0) {
             return;
         }
     }
     // process query in chunks
     $chunks = array_chunk($tsrc_ids, self::$TSRC_BATCH_SIZE);
     foreach ($chunks as $idx => $ids) {
         // debugging for memory leaks
         if (defined('DISCRIM_MEM_DEBUG')) {
             echo "RUNNING CHUNK {$idx} => " . memory_get_usage() / 1024 . "\n";
         }
         $q = Doctrine_Query::create()->from('TankSource');
         $q->andWhere('tsrc_tank_id = ?', $this->tank->tank_id);
         $q->andWhereIn('tsrc_id', $ids);
         $recs = $q->execute();
         $this->run_batch($recs, $ops);
         // cleanup
         $recs->free(true);
         unset($recs);
         $q->free();
     }
 }
 /**
  * Returns number of submissions to this Inquiry.
  *
  * @return integer number of submissions
  */
 public function has_submissions()
 {
     $sql = "select count(*) from src_response_set where srs_inq_id = ?";
     $conn = AIR2_DBManager::get_connection();
     return $conn->fetchOne($sql, array($this->inq_id), 0);
 }
 /**
  * Query
  *
  * @param array $args
  * @return Doctrine_Query $q
  */
 protected function air_query($args = array())
 {
     $q = Doctrine_Query::create()->from('User u');
     $q->leftJoin('u.UserOrg uo WITH uo.uo_home_flag = true');
     $q->leftJoin('uo.Organization o');
     $q->leftJoin('u.UserEmailAddress e with e.uem_primary_flag = true');
     $q->leftJoin('u.UserPhoneNumber p with p.uph_primary_flag = true');
     $q->leftJoin("u.Avatar av WITH av.img_ref_type = ?", 'A');
     $q->leftJoin('u.CreUser cu');
     $q->leftJoin('u.UpdUser uu');
     // flatten
     $q->addSelect('e.uem_address as uem_address');
     $q->addSelect('p.uph_number as uph_number');
     $q->addSelect('p.uph_ext as uph_ext');
     $q->addSelect('uo.uo_user_title as uo_user_title');
     $q->addSelect('o.org_uuid as org_uuid');
     $q->addSelect('o.org_name as org_name');
     $q->addSelect('o.org_display_name as org_display_name');
     $q->addSelect('o.org_html_color as org_html_color');
     // sort by some home_org first
     if (isset($args['sort_home'])) {
         $q->addSelect("(o.org_name = '{$args['sort_home']}') as myhome");
         $q->addOrderBy('myhome desc');
     }
     // restrict to some home_org
     if (isset($args['home_org'])) {
         $q->addWhere("o.org_name = '{$args['home_org']}'");
     }
     // status and type
     if (isset($args['status'])) {
         air2_query_in($q, $args['status'], 'u.user_status');
     }
     if (isset($args['type'])) {
         air2_query_in($q, $args['type'], 'u.user_type');
     }
     // text filter
     $str = isset($args['filter']) ? $args['filter'] : false;
     if ($str && strlen($str) > 0) {
         $usrs = "u.user_username LIKE '{$str}%' OR u.user_first_name " . "LIKE '{$str}%' OR u.user_last_name LIKE '{$str}%'";
         $orgs = "o.org_display_name LIKE '{$str}%' OR o.org_name LIKE '{$str}%'";
         $titles = "uo.uo_user_title LIKE '{$str}%'";
         $emails = "e.uem_address LIKE '{$str}%'";
         $q->addWhere("(({$usrs}) OR ({$orgs}) OR ({$titles}) OR ({$emails}))");
     }
     // exclude users belonging to an organization
     if (isset($args['excl_org'])) {
         $conn = AIR2_DBManager::get_connection();
         $orgq = "select z.org_id from organization z where z.org_uuid = ?";
         $excl = "select uo_user_id from user_org where uo_org_id = ({$orgq})";
         $exclude = $conn->fetchColumn($excl, array($args['excl_org']), 0);
         if (count($exclude) > 0) {
             $q->whereNotIn('u.user_id', $exclude);
         }
     }
     // users that are eligible contacts for an organization
     if (isset($args['incl_contact_org'])) {
         $org = AIR2_Record::find('Organization', $args['incl_contact_org']);
         if (!$org) {
             throw new Rframe_Exception(Rframe::BAD_DATA, 'invalid incl_contact_org');
         }
         $orgids = Organization::get_org_parents($org->org_id);
         $orgids[] = $org->org_id;
         // assemble query
         $orgids = implode(',', $orgids);
         $orgids = "uo_org_id in ({$orgids})";
         $arids = "select ar_id from admin_role where ar_code in ('M','W')";
         $arids = "uo_ar_id in ({$arids})";
         $uids = "select uo_user_id from user_org where {$orgids} and {$arids}";
         $q->addWhere("u.user_id in ({$uids})");
     }
     return $q;
 }
 /**
  * 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;
 }
 /**
  * Like get_authz() but returns org_uuid as key instead of org_id.
  *
  * @return array $authz_uuids
  */
 public function get_authz_uuids()
 {
     if (!$this->authz) {
         $this->get_authz();
     }
     if ($this->authz_uuids) {
         return $this->authz_uuids;
     }
     $conn = AIR2_DBManager::get_connection();
     $rs = $conn->fetchAll('select org_id, org_uuid from organization');
     $map = array();
     foreach ($rs as $row) {
         $map[$row['org_id']] = $row['org_uuid'];
     }
     foreach ($this->authz as $org_id => $role) {
         $uuid = $map[$org_id];
         $this->authz_uuids[$uuid] = $role;
     }
     return $this->authz_uuids;
 }
 /**
  * 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;
 }
#!/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.
 *
 * @package default
 */
AIR2_DBManager::init();
$conn = AIR2_DBManager::get_connection();
$q = new Doctrine_RawSql($conn);
$q->select('*')->from('image i')->where("img_ref_type = 'L'")->addComponent('i', 'ImageOrgLogo i');
$logos = $q->execute();
foreach ($logos as $logo) {
    if (!$logo->get_path_to_orig_asset()) {
        continue;
    }
    printf("org %s logo %s\n", $logo->Organization->org_name, $logo->get_path_to_orig_asset());
    // must copy to temp path because make_sizes() will unlink all the orig files
    $tmp_path = "/tmp/" . $logo->img_file_name;
    copy($logo->get_path_to_orig_asset(), $tmp_path);
    $logo->set_image($tmp_path);
    $logo->make_sizes();
}
 /**
  * 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})");
 }
 /**
  * Get a count of bin src_response_sets (not bin_src_response_set, but the
  * actual src_response_set table) with the given authorization.
  *
  * @param  Bin $rec
  * @param  int $action
  * @return int $count
  */
 private function _get_bin_subm_count($rec, $action)
 {
     $read_org_ids = $this->user->get_authz_str($action, 'porg_org_id', true);
     $prj_ids = "select porg_prj_id from project_org where {$read_org_ids}";
     $inq_ids = "select pinq_inq_id from project_inquiry where pinq_prj_id in ({$prj_ids})";
     // exec count query
     $conn = AIR2_DBManager::get_connection();
     $bin_subms = "select count(*) from bin_src_response_set where bsrs_bin_id=? and bsrs_inq_id in ({$inq_ids})";
     return $conn->fetchOne($bin_subms, array($rec->bin_id), 0);
 }