Example #1
0
 /**
  * 显示录播节目单
  */
 function show()
 {
     #####节点权限认证需要将节点数据放在nodes=>标志=>节点id=>节点所有父级节点
     $nodes = array();
     if (intval($this->input['channel_id']) > 0) {
         $nodes['nodes'][intval($this->input['channel_id'])] = intval($this->input['channel_id']);
         $this->verify_content_prms($nodes);
     }
     #####
     $condition = $this->get_condition();
     if ($this->user['group_type'] > MAX_ADMIN_TYPE) {
         if ($this->user['prms']['app_prms'][APP_UNIQUEID]['nodes']) {
             $condition .= " AND channel_id IN (" . implode(',', $this->user['prms']['app_prms'][APP_UNIQUEID]['nodes']) . ")";
         } else {
             $this->errorOutput(NO_PRIVILEGE);
         }
     }
     $offset = $this->input['offset'] ? $this->input['offset'] : 0;
     $count = $this->input['count'] ? intval($this->input['count']) : 20;
     $data_limit = " LIMIT " . $offset . " , " . $count;
     $info = $this->obj->show($condition, $data_limit, trim($this->input['dates']));
     if (!empty($info)) {
         include_once ROOT_PATH . 'lib/class/program.class.php';
         $program_plan = new program();
         foreach ($info as $key => $value) {
             $spa = '';
             $start_time = strtotime($value['dates'] . " " . $value['start_time']);
             $end_time = strtotime($value['dates'] . " " . $value['start_time']) + $value['toff'];
             $value['title'] = $value['title'] ? $value['title'] : (trim($program_plan->get_program_plan($value['channel_id'], $start_time, $end_time)) ? $program_plan->get_program_plan($value['channel_id'], $start_time, $end_time) : '精彩节目');
             $value['source'] = $value['program_id'] ? '节目单' : ($value['plan_id'] ? '节目单计划' : '计划收录');
             //hg_pre($value);
             $this->addItem($value);
         }
         $this->output();
     }
 }
Example #2
0
/**
 * Prints out a list of program types, along with checkboxes.
/**/
function category_list()
{
    echo "<select multiple name='categories[]' size='5'>";
    echo "<option " . (in_array(t('All'), $_SESSION['search']['categories']) ? 'selected' : '') . ">" . t('All') . "</option>";
    foreach (program::categories() as $category) {
        echo "<option " . (in_array($category, $_SESSION['search']['categories']) ? 'selected' : '') . ">{$category}</option>";
    }
    echo "</select>";
}
Example #3
0
 private function rebuild_program($id)
 {
     include ROOT_PATH . 'lib/class/program.class.php';
     $program = new program();
     $program->rebuild_program($id);
 }
Example #4
0
 public function detail($condition = '')
 {
     $sql = "SELECT p.* FROM " . DB_PREFIX . "program_record p " . $condition;
     $row = $this->db->query_first($sql);
     if (is_array($row) && $row) {
         include_once ROOT_PATH . 'lib/class/program.class.php';
         $program_plan = new program();
         include_once ROOT_PATH . 'lib/class/live.class.php';
         $newLive = new live();
         $channel = $newLive->getChannelById($row['channel_id']);
         $channel = $channel[0];
         $row['create_time'] = date('Y-m-d H:i:s', $row['create_time']);
         $row['update_time'] = date('Y-m-d H:i:s', $row['update_time']);
         $row['end_time'] = date('Y-m-d H:i:s', $row['start_time'] + $row['toff']);
         $row['start_time'] = date('Y-m-d H:i:s', $row['start_time']);
         $row['week_day'] = $row['week_day'] ? unserialize($row['week_day']) : array();
         $start_time = strtotime($row['dates'] . " " . $row['start_time']);
         $end_time = strtotime($row['dates'] . " " . $row['start_time']) + $row['toff'];
         $row['title'] = $row['title'] ? $row['title'] : (trim($program_plan->get_program_plan($row['channel_id'], $start_time, $end_time)) ? trim($program_plan->get_program_plan($row['channel_id'], $start_time, $end_time)) : '精彩节目');
         $mins = floor($row['toff'] / 60);
         $sen = $row['toff'] - $mins * 60;
         $row['toff_decode'] = ($mins ? $mins . "'" : '') . ($sen ? $sen . "''" : '');
         $row['channel_name'] = $channel['name'];
         return $row;
     }
 }
 /**
  * Check if program is accessible before displaying in search results
  *
  * @access  public
  * @param   $programid  integer
  * @return  boolean
  */
 public function search_can_display_result($programid) {
     $prog = new program($programid);
     return $prog->is_accessible();
 }
Example #6
0
 public function update()
 {
     $id = intval($this->input['id']);
     if (!$id) {
         $this->ReportError('指定记录不存在或已删除!');
     }
     $name = trim($this->input['name']);
     if (!$name) {
         $this->form('请填写名称');
     }
     $op = $this->db->query_first('SELECT * FROM ' . DB_PREFIX . 'module_op WHERE id=' . $id);
     if (!$op) {
         $this->ReportError('指定记录不存在或已删除!');
     }
     $module_id = intval($this->input['module_id']);
     foreach ($this->fields as $field) {
         ${$field} = trim(urldecode($this->input[$field]));
         /*$$field = unserialize($op[$field]);
         		if (!$$field)
         		{
         			$$field = array();
         		}
         		$_field = $$field;
         		if ($this->input[$field])
         		{
         			$_field[$module_id] = $this->input[$field];
         		}
         		else
         		{
         			unset($_field[$module_id]);
         		}
         		if ($_field)
         		{
         			$$field = serialize($_field);
         		}
         		else
         		{
         			$$field = '';
         		}*/
     }
     /*$ban = unserialize($op['ban']); //禁用某操作以窜行化数组纪录
     		$isban = intval($this->input['ban']);
     		if ($isban)
     		{
     			$ban[$module_id] = $module_id;
     		}
     		else
     		{
     			unset($ban[$module_id]);
     		}
     		$is_global = intval($this->input['is_global']);
     		if ($is_global)
     		{
     			$module_id = 0;
     		}
     		$ban = serialize($ban);//禁用某操作以窜行化数组纪录
     		*/
     //检测是否添加过
     $data = array('name' => $name, 'module_id' => $module_id, 'op' => $this->input['op'], 'brief' => $this->input['brief'], 'host' => $this->input['host'], 'dir' => $this->input['dir'], 'file_name' => $file_name, 'func_name' => $this->input['func_name'], 'template' => $template, 'has_batch' => $this->input['has_batch'], 'need_confirm' => $this->input['need_confirm'], 'callback' => $callback, 'request_type' => $request_type, 'direct_return' => $direct_return, 'group_op' => $this->input['group_op'], 'trigger_pub' => $trigger_pub, 'show_pub' => $show_pub, 'is_show' => $this->input['is_show'], 'ban' => intval($this->input['ban']), 'order_id' => $this->input['order_id']);
     hg_fetch_query_sql($data, 'module_op', 'id=' . $id);
     include ROOT_PATH . 'lib/class/program.class.php';
     $program = new program();
     $id = $program->compile($module_id, $data['op']);
     $this->redirect('更新成功');
 }
Example #7
0
 public function get_program()
 {
     if (!$this->input['channel_id']) {
         $this->errorOutput(NOID);
     }
     //根据频道id查询出该频道对应的节目单
     $program = new program();
     $program_data = $program->getTimeshift($this->input['channel_id']);
     if ($program_data) {
         $this->addItem($program_data);
         $this->output();
     }
 }
Example #8
0
 public function doupgrade()
 {
     $installinfo = array('host' => $this->settings['mcphost'], 'ip' => $this->settings['mcphost'], 'port' => 6233);
     if (!is_writeable('conf/config.php')) {
         hg_run_cmd($installinfo, 'runcmd', 'chmod -Rf 777 ' . realpath('conf/config.php'));
     }
     if (!is_writeable('conf/config.php')) {
         $message = '平台无法升级,请将此文件(conf/config.php)设为可写';
         $this->upgrade($message);
     }
     $curl = new curl($this->product_server['host'] . ':' . $this->product_server['port'], $this->product_server['dir']);
     $curl->mAutoInput = false;
     $curl->setClient(CUSTOM_APPID, CUSTOM_APPKEY);
     $curl->initPostData();
     $postdata = array('app' => 'livworkbench', 'a' => 'checklastversion');
     foreach ($postdata as $k => $v) {
         $curl->addRequestData($k, $v);
     }
     $lastversion = $curl->request('check_version.php');
     if ($this->settings['version'] >= $lastversion) {
         $this->ReportError('当前已是最新版本');
     }
     $db = $this->dbconfig;
     $db['user'] = $this->input['dbuser'];
     $db['pass'] = $_REQUEST['dbpass'];
     $link = @mysql_connect($db['host'], $db['user'], $db['pass']);
     if (!$link) {
         $message = '此数据库无法连接,请确认密码是否准确';
         $this->show($message);
     }
     mysql_query("SET character_set_connection=utf8, character_set_results=utf8, character_set_client=binary", $link);
     $socket = new hgSocket();
     $con = $socket->connect($installinfo['host'], $installinfo['port']);
     if (!intval($con)) {
         $message = '服务器无法连接,请确认服务器ip是否正确或服务程序hogeMonitor.py是否监听在' . $installinfo['ip'] . ':' . $installinfo['port'] . '上';
         $this->show($message);
     }
     $socket->close();
     $app_path = realpath(ROOT_PATH);
     $app_path .= '/';
     $curl = new curl($this->product_server['host'] . ':' . $this->product_server['port'], '');
     $curl->mAutoInput = false;
     $curl->setClient(CUSTOM_APPID, CUSTOM_APPKEY);
     $curl->setSubmitType('get');
     $curl->setReturnFormat('json');
     $curl->initPostData();
     $curl->addRequestData('app', 'livworkbench');
     $ret = $curl->request('db.php');
     ob_start();
     if (is_array($ret)) {
         //更新数据库
         hg_flushMsg('开始更新数据库');
         mysql_select_db($db['database'], $link);
         $structs = $this->getDbStruct($db['database'], $link);
         if (!$ret['app']) {
             $ret['app'] = array();
         }
         foreach ($ret['app'] as $tab => $v) {
             $pre = substr($tab, 0, 4);
             if ($pre == 'liv_') {
                 $newtab = DB_PREFIX . substr($tab, 4);
             }
             if ($pre == 'm2o_') {
                 $newtab = DB_PREFIX . substr($tab, 4);
             }
             if (!$structs[$newtab]) {
                 $addsql = $ret['create'][$tab];
                 if ($addsql) {
                     $addsql = preg_replace('/CREATE\\s+TABLE\\s+([`]{0,1})' . $pre . '/is', 'CREATE TABLE \\1' . DB_PREFIX, $addsql);
                     hg_flushMsg('新增数据表' . $newtab);
                     mysql_query($addsql, $link);
                 }
                 continue;
             }
             $struct = $v['struct'];
             $index = $v['index'];
             if ($struct) {
                 $altersql = array();
                 foreach ($struct as $f => $a) {
                     if (!$structs[$newtab]['struct'][$f]) {
                         if ($a['Null'] == 'NO') {
                             $null = ' NOT NULL';
                         } else {
                             $null = ' NULL';
                         }
                         if ($a['Default']) {
                             $default = " DEFAULT '{$a['Default']}'";
                         } else {
                             $default = '';
                         }
                         if ($a['Comment']) {
                             $comment = " COMMENT '{$a['Comment']}'";
                         } else {
                             $comment = '';
                         }
                         $altersql[] = " ADD `{$f}` {$a['Type']}{$null}{$default}{$comment}";
                     } else {
                         $cur = $structs[$newtab]['struct'][$f];
                         if ($a['Null'] == 'NO') {
                             $null = ' NOT NULL';
                         } else {
                             $null = ' NULL';
                         }
                         if ($a['Default']) {
                             $default = " DEFAULT '{$a['Default']}'";
                         } else {
                             $default = '';
                         }
                         if ($a['Comment']) {
                             $comment = " COMMENT '{$a['Comment']}'";
                         } else {
                             $comment = '';
                         }
                         if ($a['Type'] != $cur['Type'] || $a['Default'] != $cur['Default']) {
                             $altersql[] = " CHANGE `{$f}` `{$f}` {$a['Type']}{$null}{$default}{$comment}";
                         }
                     }
                 }
                 if ($altersql) {
                     hg_flushMsg('开始更新数据表' . $newtab);
                     $altersql = 'ALTER TABLE ' . $newtab . ' ' . implode(',', $altersql);
                     mysql_query($altersql, $link);
                 }
             }
             if ($index) {
                 foreach ($index as $unique => $ind) {
                     if (!$ind) {
                         continue;
                     }
                     if (!$unique) {
                         $typ = 'UNIQUE';
                     } else {
                         $typ = 'INDEX';
                     }
                     foreach ($ind as $pk => $f) {
                         if ($pk == 'PRIMARY') {
                             continue;
                         }
                         $curind = $structs[$newtab]['index'][$unique][$pk];
                         if (!$curind) {
                             $altersql = 'ALTER TABLE  ' . $newtab . ' ADD ' . $typ . ' (' . implode(',', $f) . ')';
                             //									echo $altersql . '<br />';
                             mysql_query($altersql, $link);
                         } else {
                             $change = array_diff($curind, $f);
                             $change1 = array_diff($f, $curind);
                             if ($change || $change1) {
                                 $altersql = 'ALTER TABLE  ' . $newtab . ' DROP INDEX ' . $pk . ', ADD ' . $typ . ' (' . implode(',', $f) . ')';
                                 //								echo $altersql . '<br />';
                                 mysql_query($altersql, $link);
                             }
                         }
                     }
                 }
             }
             $newindex = $index;
             $index = $structs[$newtab]['index'];
             if ($index) {
                 foreach ($index as $unique => $ind) {
                     if (!$ind) {
                         continue;
                     }
                     if (!$unique) {
                         $typ = 'UNIQUE';
                     } else {
                         $typ = 'INDEX';
                     }
                     foreach ($ind as $pk => $f) {
                         if ($pk == 'PRIMARY') {
                             continue;
                         }
                         $newind = $newindex[$unique][$pk];
                         if (!$curind) {
                             $altersql = 'ALTER TABLE  ' . $newtab . ' DROP INDEX ' . $pk;
                             mysql_query($altersql, $link);
                         }
                     }
                 }
             }
             $sql = 'OPTIMIZE TABLE  ' . $newtab;
             mysql_query($sql, $link);
         }
         hg_flushMsg('数据库更新完毕');
     }
     //下载程序
     hg_flushMsg('开始下载应用程序更新包');
     $curl = new curl($this->product_server['host'] . ':' . $this->product_server['port'], '');
     $curl->mAutoInput = false;
     $curl->setClient(CUSTOM_APPID, CUSTOM_APPKEY);
     $curl->setSubmitType('get');
     $curl->setReturnFormat('json');
     $curl->initPostData();
     $curl->addRequestData('app', 'livworkbench');
     $program_url = $curl->request('check_version.php');
     if (!(strstr($program_url, 'http://') && strstr($program_url, '.zip')) || $program_url == 'NO_VERSION') {
         $message = '获取应用程序失败或程序版本不存在.';
         $this->show($message);
     }
     hg_run_cmd($installinfo, 'download', $program_url, $app_path);
     $appversion = @file_get_contents($app_path . 'version');
     $match = preg_match('/^[0-9]+\\.[0-9]+\\.[0-9]+$/is', $appversion);
     if (!$match) {
         $appversion = '';
     }
     if ($appversion < $lastversion) {
         $message = '平台程序更新失败,请重试.';
         $this->upgrade($message);
     }
     hg_run_cmd($installinfo, 'runcmd', 'chmod +x ' . $app_path . 'cron/*.py');
     $domain = $installinfo['host'];
     $dir = $installinfo['dir'];
     hg_flushMsg('应用程序包下载完成');
     hg_flushMsg('应用设置更新完成');
     hg_flushMsg('开始更新模板');
     hg_flushMsg('模板更新完成');
     $content = @file_get_contents('conf/config.php');
     $match = preg_match("/\\\$gGlobalConfig\\['version'\\]\\s*=\\s*\\'.*\\';/is", $content);
     if ($match) {
         $content = preg_replace("/\\\$gGlobalConfig\\['version'\\]\\s*=\\s*\\'.*?\\';/is", "\$gGlobalConfig['version'] = '{$lastversion}';", $content);
     } else {
         $content = preg_replace("/\\?>/is", "\n\$gGlobalConfig['version'] = '{$lastversion}';\n?>", $content);
     }
     @file_put_contents('conf/config.php', $content);
     $sql = 'SELECT * FROM ' . DB_PREFIX . 'modules';
     $q = $this->db->query($sql);
     $program = array();
     while ($mod = $this->db->fetch_array($q)) {
         $program[$mod['id']][$mod['func_name']] = $mod['func_name'];
     }
     $sql = 'SELECT * FROM ' . DB_PREFIX . 'module_op';
     $q = $this->db->query($sql);
     while ($mod = $this->db->fetch_array($q)) {
         $program[$mod['module_id']][$mod['op']] = $mod['op'];
     }
     if ($program) {
         hg_flushMsg('开始重建应用程序');
         include ROOT_PATH . 'lib/class/program.class.php';
         $rebuildprogram = new program();
         foreach ($program as $mid => $ops) {
             if ($ops) {
                 foreach ($ops as $op) {
                     $rebuildprogram->compile($mid, $op);
                 }
             }
         }
         hg_flushMsg('应用程序重建完成');
     }
     //清理模板
     $this->clearfile(CACHE_DIR . 'tpl/livworkbench/');
     $this->clearfile(CACHE_DIR . 'tpl/css/livworkbench/');
     $update_apps = @file_get_contents(CACHE_DIR . 'onekupdate');
     $update_apps = json_decode($update_apps, 1);
     $tdb = $update_apps['okupdatedbinfo'];
     unset($update_apps['okupdatedbinfo']);
     if ($update_apps) {
         unset($update_apps['livworkbench']);
         if ($update_apps) {
             $update_apps['okupdatedbinfo'] = $tdb;
             $onekupdate = json_encode($update_apps);
         } else {
             $onekupdate = '';
         }
         file_put_contents(CACHE_DIR . 'onekupdate', $onekupdate);
     }
     if ($this->input['onekupdate']) {
         $url = 'appstore.php?a=goonekupdate';
     } else {
         $url = 'index.php';
     }
     $this->appstore->initPostData();
     $this->appstore->addRequestData('a', 'updated');
     $this->appstore->addRequestData('app', 'livworkbench');
     $this->appstore->request('index.php');
     hg_flushMsg('平台更新成功', $url);
     //$this->redirect('应用更新成功', $url);
 }
Example #9
0
 /**
  * 显示录播节目单
  */
 function show()
 {
     $sql = "SELECT * FROM " . DB_PREFIX . "server_config WHERE 1 AND state=1";
     $q = $this->db->query($sql);
     $server_config = array();
     while ($row = $this->db->fetch_array($q)) {
         $server_config[$row['id']] = $row;
     }
     $sql = "SELECT * FROM " . DB_PREFIX . "program_record WHERE is_record=0 and start_time < " . (strtotime(date('Y-m-d', TIMENOW)) + 86399);
     $record_info = $channel_info = $item_info = array();
     $q = $this->db->query($sql);
     while ($row = $this->db->fetch_array($q)) {
         $channel_info[$row['channel_id']] = $row['channel_id'];
         $item_info[$row['item']] = $row['item'];
         $record_info[] = $row;
     }
     if (empty($record_info)) {
         return '';
     }
     $channel = array();
     if (!empty($channel_info)) {
         $channel_ids = implode(',', $channel_info);
         include_once ROOT_PATH . 'lib/class/live.class.php';
         $newLive = new live();
         $channel_tmp = $newLive->getChannelInfoById(array('id' => $channel_ids, 'is_stream' => 1, 'live' => 1, 'is_sys' => -1, 'fetch_live' => 1));
         foreach ($channel_tmp as $k => $v) {
             $channel[$v['id']] = $v;
         }
         if (empty($channel)) {
             return '';
         }
     }
     if (!empty($item_info)) {
         include_once ROOT_PATH . 'lib/class/livmedia.class.php';
         $livmedia = new livmedia();
         $item_info = $livmedia->getAutoItem();
     }
     include_once ROOT_PATH . 'lib/class/program.class.php';
     $program_plan = new program();
     foreach ($record_info as $k => $row) {
         if (empty($server_config[$row['server_id']])) {
             continue;
         }
         $check_server = $this->checkServer($server_config[$row['server_id']]['host'] . ':' . $server_config[$row['server_id']]['port'] . $server_config[$row['server_id']]['dir']);
         if (!$check_server) {
             continue;
         }
         $channel_tmp = $channel[$row['channel_id']];
         $row['code'] = $channel_tmp['code'];
         $row['name'] = $channel_tmp['name'];
         $row['is_audio'] = $channel_tmp['is_audio'];
         $row['save_time'] = $channel_tmp['time_shift'];
         $row['main_stream_name'] = $channel_tmp['main_stream_name'];
         $row['stream_state'] = $channel_tmp['status'];
         $row['record_time'] = $channel_tmp['record_time'];
         $row['stream_id'] = $channel_tmp['stream_id'];
         $row['sort_name'] = $row['item'] > 0 ? $item_info[$row['item']]['name'] : '';
         $return = array();
         if (!$row['channel_id']) {
             continue;
         }
         $ret = $log_data = array();
         $ret['id'] = $log_data['id'] = $row['id'];
         $ret['channel_id'] = $log_data['channel_id'] = $row['channel_id'];
         $ret['name'] = rawurlencode($row['name']);
         $ret['startTime'] = date('YmdHis', $row['start_time'] + $row['record_time'] - 1);
         $row['toff'] = $row['toff'] + 2;
         $program = $row['title'] ? $row['title'] : trim($program_plan->get_program_plan($ret['channel_id'], $ret['starttime'], $ret['endtime']));
         $ret['title'] = base64_encode(json_encode(trim($program ? $program : '精彩节目')));
         $log_data['title'] = rawurlencode(trim($program ? $program : '精彩节目'));
         $log_data['start_time'] = $row['start_time'];
         $log_data['toff'] = $row['toff'];
         $log_data['week_day'] = $row['week_day'];
         $log_data['item'] = $row['item'];
         $log_data['columnid'] = $row['columnid'];
         $log_data['column_name'] = $row['column_name'];
         $log_data['ip'] = $row['ip'];
         if (empty($channel_tmp['record_stream'])) {
             continue;
         }
         $ret['stream'] = $channel_tmp['record_uri'] ? $channel_tmp['record_uri'] : $channel_tmp['record_stream'][0]['output_url_rtmp'];
         $callback = $this->settings['App_program_record']['protocol'] . $this->settings['App_program_record']['host'] . '/' . $this->settings['App_program_record']['dir'] . 'admin/record_callback.php';
         $ret['vod_sort_id'] = $row['item'];
         $ret['week_flag'] = $row['week_day'] ? 1 : 0;
         $ret['column_id'] = $row['columnid'] ? $row['columnid'] : 0;
         $ret['audit_auto'] = $row['audit_auto'] ? 2 : 0;
         $ret['exit_status'] = $row['audit_auto'];
         $ret['save_time'] = $row['save_time'];
         //$ret['delay_time'] = $row['live_delay'] * 60;
         //$ret['source'] = $row['channel_id'];
         $ret['is_allow'] = $row['is_mark'];
         $ret['is_audio'] = $row['is_audio'];
         $ret['extend'] = base64_encode(json_encode(array('_user_id' => $row['user_id'], '_user_name' => $row['user_name'], 'org_id' => $row['org_id'], 'force_codec' => $row['force_codec'], 'source' => $row['name'], 'callback_extra' => $row['callback_extra'])));
         if (!$row['stream_state']) {
             $ret = array('errortext' => '视频流未开启!');
             $str = 'ID-' . $row['id'] . ($ret['errortext'] ? $ret['errortext'] : '录制成功');
             $this->tips($str, TIMENOW);
         } else {
             switch ($row['is_record']) {
                 case 0:
                     //录制未进行提交
                     $this->curl = new curl($server_config[$row['server_id']]['host'] . ':' . $server_config[$row['server_id']]['port'], $server_config[$row['server_id']]['dir']);
                     $this->curl->setSubmitType('get');
                     $this->curl->initPostData();
                     $this->curl->addRequestData('action', 'INSERT');
                     $this->curl->addRequestData('url', $ret['stream']);
                     $this->curl->addRequestData('callback', $callback);
                     //urlencode
                     //$this->curl->addRequestData('startTime', $ret['starttime']-1);
                     $this->curl->addRequestData('duration', $row['toff']);
                     $this->curl->addRequestData('uploadFile', '0');
                     $this->curl->addRequestData('app', 'live');
                     $this->curl->addRequestData('streamname', $channel_tmp['code'] . '_' . $channel_tmp['main_stream_name']);
                     $this->curl->addRequestData('html', 1);
                     $this->curl->addRequestData('appid', $this->input['appid']);
                     $this->curl->addRequestData('appkey', $this->input['appkey']);
                     foreach ($ret as $k => $v) {
                         $this->curl->addRequestData($k, $v);
                     }
                     $ret = array();
                     $record_xml = $this->curl->request('');
                     $record_array = xml2Array($record_xml);
                     if (is_array($record_array)) {
                         $ret['id'] = $record_array['record']['id'] ? $record_array['record']['id'] : 0;
                         if (!$record_array['result']) {
                             $ret['errortext'] = '录制超时,重复提交';
                             //报错
                             $ret['isError'] = 1;
                             $ret['id'] = -1;
                         } else {
                             $ret['errortext'] = '等待录制';
                             $ret['isError'] = 0;
                         }
                     } else {
                         $ret['id'] = 0;
                         $ret['errortext'] = '录制失败,无内容!';
                         $ret['isError'] = 1;
                     }
                     $is_record = $ret['id'] ? 1 : 0;
                     $conid = $this->add_queue($row['id']);
                     if (!$ret['isError']) {
                         $sql_update = "UPDATE " . DB_PREFIX . "program_record SET is_out=0,conid=" . $conid . ",is_record=" . $is_record . " WHERE id=" . $row['id'];
                         $this->db->query($sql_update);
                         $log_data['text'] = $ret['errortext'];
                         $log_data['state'] = $ret['isError'] ? 2 : 0;
                         $log_id = $this->record->addLogs($log_data);
                         $this->update_queue($conid, $log_id);
                     } else {
                         $week_day = unserialize($row['week_day']);
                         $select_curl = new curl($server_config[$row['server_id']]['host'] . ':' . $server_config[$row['server_id']]['port'], $server_config[$row['server_id']]['dir']);
                         $select_curl->setSubmitType('get');
                         $select_curl->initPostData();
                         $select_curl->addRequestData('action', 'SELECT');
                         $select_curl->addRequestData('id', $row['id']);
                         $select_record = $this->curl->request('');
                         $select_array = xml2Array($select_record);
                         if (is_array($select_array)) {
                             if (!$select_array['result']) {
                                 if (is_array($week_day) && $week_day) {
                                     $week_now = date('N', $row['start_time']);
                                     $new_arr = array_flip($week_day);
                                     if (count($week_day) > $new_arr[$week_now] + 1) {
                                         $ks = $new_arr[$week_now] + 1;
                                     } else {
                                         $ks = 0;
                                     }
                                     $week_day = array_flip($new_arr);
                                     $next_week = $week_day[$ks] - $week_now > 0 ? $week_day[$ks] - $week_now : $week_day[$ks] - $week_now + 7;
                                     $start_time = $row['start_time'] + $next_week * 86400;
                                     $sql_update = "UPDATE " . DB_PREFIX . "program_record SET conid=0,is_record=0,start_time=" . $start_time . " WHERE id=" . $row['id'];
                                     $this->db->query($sql_update);
                                 } else {
                                     $sql_update = "UPDATE " . DB_PREFIX . "program_record SET is_out=1,conid=0,is_record=1 WHERE id=" . $row['id'];
                                     $this->db->query($sql_update);
                                 }
                             } else {
                             }
                         }
                         $log_data['text'] = $ret['errortext'];
                         $log_data['state'] = 2;
                         $log_id = $this->record->addLogs($log_data);
                         $this->update_queue($conid, $log_id);
                     }
                     $str = 'ID-' . $row['id'] . ($ret['errortext'] ? $ret['errortext'] : '录制成功');
                     $this->tips($str, TIMENOW);
                     break;
                 case 1:
                     //正在录制,录制超时,只处理周期性的录制超时
                     if ($row['start_time'] + $row['toff'] < TIMENOW - 120) {
                         $week_day = unserialize($row['week_day']);
                         if (is_array($week_day) && $week_day) {
                             $week_now = date('N', $row['start_time']);
                             $new_arr = array_flip($week_day);
                             if (count($week_day) > $new_arr[$week_now] + 1) {
                                 $ks = $new_arr[$week_now] + 1;
                             } else {
                                 $ks = 0;
                             }
                             $week_day = array_flip($new_arr);
                             $next_week = $week_day[$ks] - $week_now > 0 ? $week_day[$ks] - $week_now : $week_day[$ks] - $week_now + 7;
                             $start_time = $row['start_time'] + $next_week * 86400;
                             $sql_update = "UPDATE " . DB_PREFIX . "program_record SET conid=0,is_record=0,start_time=" . $start_time . " WHERE id=" . $row['id'];
                             $this->db->query($sql_update);
                             $str = 'ID-' . $row['id'] . '录制超时处理成功';
                             $this->tips($str, TIMENOW);
                         }
                     }
                     break;
             }
         }
     }
 }
Example #10
0
 /**
  * 串联单生成节目单
  * $channel_id 频道id
  * $dates 日期
  * $theme 节目
  * $id 串联单id
  * Enter description here ...
  */
 public function schedule2program()
 {
     $channel_id = intval($this->input['channel_id']);
     $dates = trim($this->input['dates']);
     $id = $this->input['ids'];
     $theme = $this->input['theme'];
     if (!$channel_id) {
         $this->errorOutput('未传入频道id');
     }
     if (!$dates) {
         $this->errorOutput('未传入日期');
     }
     if (empty($id)) {
         $this->errorOutput('未传入串联单id');
     }
     foreach ($id as $k => $v) {
         if (!$v) {
             $this->errorOutput('串联单id不能为空');
         }
     }
     $schedule_field = 'id, start_time, toff';
     $schedule = $this->mSchedule->get_schedule_info_by_id(implode(',', $id), $schedule_field);
     if (empty($schedule)) {
         $this->errorOutput($dates . '串联单不存在或已删除');
     }
     $schdeule_info = array();
     foreach ($schedule as $v) {
         $schdeule_info[$v['id']] = $v;
     }
     require_once ROOT_PATH . 'lib/class/program.class.php';
     $mProgram = new program();
     if (!$mProgram) {
         $this->errorOutput('节目单应用没有安装');
     }
     if (!$this->settings['App_program']) {
         $this->errorOutput('节目单应用没有安装');
     }
     $delete_data = array('channel_id' => $channel_id, 'dates' => $dates);
     $ret_delete = $mProgram->delete_by_channel_id($delete_data);
     if (!$ret_delete) {
         $this->errorOutput('删除已有的节目单失败');
     }
     $start_time = $end_time = $_theme = array();
     $tmp_toff = 0;
     $i = 0;
     foreach ($id as $k => $v) {
         $tmp_toff += $schdeule_info[$v]['toff'];
         if ($tmp_toff >= $this->settings['schedule2program_min_toff'] * 60) {
             $start_time[$i] = strtotime(date('Y-m-d H:i', $schdeule_info[$v]['start_time']));
             $end_time[$i] = strtotime(date('Y-m-d H:i', $schdeule_info[$v]['start_time'])) + $schdeule_info[$v]['toff'];
             $_theme[$i] = $theme[$k];
             $tmp_toff = 0;
             $i++;
         }
     }
     $program_data = array('channel_id' => $channel_id, 'dates' => $dates, 'schedule_id' => implode(',|', $id), 'start_time' => implode(',|', $start_time), 'end_time' => implode(',|', $end_time), 'theme' => implode(',|', $_theme));
     $return = $mProgram->schedule2program($program_data);
     $this->addItem($return);
     $this->output();
 }
Example #11
0
 public function rebuild_templates($appid = 0)
 {
     if ($appid) {
         $cond = ' WHERE application_id=' . $appid;
     }
     $sql = 'SELECT a.*, m.* FROM ' . DB_PREFIX . 'modules m LEFT JOIN ' . DB_PREFIX . 'applications a ON m.application_id=a.id ' . $cond;
     $q = $this->db->query($sql);
     $templates = array();
     $program = array();
     $modid = array();
     $modules = array();
     while ($mod = $this->db->fetch_array($q)) {
         $modid[] = $mod['id'];
         if ($mod['template']) {
             $templates[$mod['id']][] = $mod['template'];
         }
         $program[$mod['id']][$mod['func_name']] = $mod['func_name'];
         $modules[$mod['id']] = $mod;
     }
     $cond = '';
     if ($appid && $modid) {
         $cond = ' WHERE module_id IN (' . implode(',', $modid) . ')';
     }
     $sql = 'SELECT * FROM ' . DB_PREFIX . 'module_op' . $cond;
     $q = $this->db->query($sql);
     while ($mod = $this->db->fetch_array($q)) {
         $program[$mod['module_id']][$mod['op']] = $mod['op'];
         if ($mod['template']) {
             $templates[$mod['module_id']][] = $mod['template'];
         }
     }
     if ($templates) {
         hg_flushMsg('开始更新模板');
         $configtpls = array('settings', 'iframe_list');
         foreach ($templates as $m => $tpl) {
             if ($modules[$m]) {
                 hg_flushMsg('开始更新' . $modules[$m]['name'] . '模板');
                 $this->tpl->setSoftVar($modules[$m]['softvar']);
                 //设置软件界面
                 if (DEVELOP_MODE) {
                     $this->tpl->setTemplateVersion('');
                     $this->tpl->setScriptDir('');
                 } else {
                     $this->tpl->setScriptDir('app_' . $modules[$m]['softvar'] . '/');
                     $this->tpl->setTemplateVersion($modules[$m]['softvar'] . '/' . $modules[$m]['version']);
                 }
                 if (is_array($tpl)) {
                     foreach ($tpl as $t) {
                         hg_flushMsg('开始更新模板' . $t);
                         $this->tpl->recacheTemplate($t);
                     }
                 }
                 hg_flushMsg($modules[$m]['name'] . '模板更新完成');
             }
         }
         foreach ($configtpls as $t) {
             hg_flushMsg('开始更新模板' . $t);
             $this->tpl->recacheTemplate($t);
         }
         hg_flushMsg('模板更新完成');
     }
     if ($appid && $program) {
         hg_flushMsg('开始重建模块程序');
         include ROOT_PATH . 'lib/class/program.class.php';
         $rebuildprogram = new program();
         foreach ($program as $mid => $ops) {
             if ($ops) {
                 foreach ($ops as $op) {
                     $rebuildprogram->compile($mid, $op);
                 }
             }
         }
         hg_flushMsg('模块程序重建完成');
     }
 }
Example #12
0
 function show()
 {
     //$id = '126,106,100,127,217,111,134,139,119';
     $id = $this->input['id'];
     $condition = '';
     if ($id) {
         $condition .= ' pr.id IN(' . $this->input['id'] . ')';
         $day = intval($this->input['day']);
     } else {
         $condition .= "is_record=1 and (pr.start_time) > " . strtotime(date('Y-m-d', TIMENOW)) . " and (pr.start_time+pr.toff) < " . TIMENOW;
     }
     $sql = "SELECT * FROM " . DB_PREFIX . "program_record pr WHERE " . $condition;
     $record_info = $channel_info = array();
     $q = $this->db->query($sql);
     while ($row = $this->db->fetch_array($q)) {
         $channel_info[$row['channel_id']] = $row['channel_id'];
         $record_info[] = $row;
     }
     if (!empty($channel_info)) {
         $channel_ids = implode(',', $channel_info);
         include_once ROOT_PATH . 'lib/class/live.class.php';
         $newLive = new live();
         $channel_tmp = $newLive->getChannelById($channel_ids);
         foreach ($channel_tmp as $k => $v) {
             $channel[$v['id']] = $v;
         }
     }
     include_once ROOT_PATH . 'lib/class/program.class.php';
     $program_plan = new program();
     $info = array();
     foreach ($record_info as $k => $row) {
         $channel_tmp = $channel[$row['channel_id']];
         $row['name'] = $channel_tmp['name'];
         $row['save_time'] = $channel_tmp['save_time'];
         $row['record_time'] = $channel_tmp['record_time'];
         $program = $row['title'] ? $row['title'] : trim($program_plan->get_program_plan($row['channel_id'], $row['starttime'], $row['endtime']));
         if ($id) {
             $row['start_time'] = $row['start_time'] - $day * 86400;
         }
         $start_time = date('YmdHis', $row['start_time'] + $row['record_time'] - 1);
         /*
         $data = array(
         	'start_time' => $start_time,
         	'id' =>  $row['id'],
         	'duration' => $row['toff'],
         	'exit_status' => 1,
         	'save_time' => $row['save_time'],
         	'source' => $row['channel_id'],
         	'is_allow' => $row['is_mark'],
         	'vod_sort_id' => $row['item'],
         	'week_flag' => $row['week_day'] ? 1 : 0,
         	'column_id' => $row['columnid'],
         	'audit_auto' => $row['audit_auto'] ? 2 : 0,
         	'title' => base64_encode(json_encode(trim($program ? $program : '精彩节目'))),
         	'name' => $row['name'],
         	'channel_id' => $row['channel_id'],
         	'file_path' => substr($start_time,0,4) . '/' . substr($start_time,4,2). '/' . substr($start_time,6,2). '/' . substr($start_time,8,2). '/' . substr($start_time,10,2). '/' . substr($start_time,12,2) . '/' . $row['id'] . '.mp4',
         	'extend' => base64_encode(json_encode(array('user_id' => $row['user_id'],'user_name' => $row['user_name'],'org_id' => $row['org_id'],'force_codec'=>$row['force_codec']))),
         	'update_state' => 1,
         );
         */
         $data = array('id' => $row['id'], 'is_time_shift' => $row['time_shift'] ? 1 : 0, 'title' => $program ? $program : '精彩节目', 'filepath' => substr($start_time, 0, 4) . '/' . substr($start_time, 4, 2) . '/' . substr($start_time, 6, 2) . '/' . substr($start_time, 8, 2) . '/' . substr($start_time, 10, 2) . '/' . substr($start_time, 12, 2) . '/' . $row['id'] . '.flv', 'source' => $row['name'], 'is_mark' => $row['is_mark'], 'vod_sort_id' => $row['item'], 'audit_auto' => $row['audit_auto'] ? 2 : 0, 'column_id' => $row['columnid'], 'channel_id' => $row['channel_id'], 'vod_leixing' => 3, 'start' => '0', 'end' => $row['toff'] * 1000, 'starttime' => $start_time, 'create_time' => -1, 'appid' => $this->input['appid'], 'appkey' => $this->input['appkey'], 'user_id' => $row['user_id'], 'user_name' => $row['user_name'], 'org_id' => $row['org_id'], 'force_codec' => $row['force_codec']);
         hg_pre($data);
         exit;
         $info[] = $data;
         if ($this->input['debug']) {
             hg_pre($data);
             exit;
         }
         foreach ($data as $k => $v) {
             $curl->addRequestData($k, $v);
         }
         $ret = $curl->request('create.php');
         /*	
         			$this->curl->setSubmitType('post');
         			$this->curl->initPostData();
         			$this->curl->addRequestData('a','callBack');
         			$this->curl->addRequestData('appkey',$this->input['appkey']);
         			$this->curl->addRequestData('appid',$this->input['appid']);
         			$this->curl->addRequestData('data',json_encode($data));
         			$this->curl->addRequestData('html',1);
         			$ret = $this->curl->request('record_callback.php');
         			hg_pre($ret);
         */
     }
     //hg_pre($info);
 }
Example #13
0
 public function create()
 {
     $ret = array();
     $ret['channel_id'] = $this->input['channel_id'];
     if (!$ret['channel_id']) {
         $this->errorOutput('未传入频道ID');
     }
     //请求频道信息
     include_once ROOT_PATH . 'lib/program.class.php';
     $program = new program();
     $channel = $program->getTimeshift($ret['channel_id']);
     //		$live_channel = new curl($this->settings['App_live']['host'],$this->settings['App_live']['dir']);
     //		$live_channel->setSubmitType('post');
     //		$live_channel->setReturnFormat('json');
     //		$live_channel->initPostData();
     //		$live_channel->addRequestData('id',$ret['channel_id']);
     //		$channel_ret = $live_channel->request('admin/channel.php');
     //		$channel = $channel_ret[0];
     if (!$channel) {
         $this->errorOutput('该频道已经不存在!');
     }
     if (!$channel['open_ts']) {
         $this->errorOutput('该频道未启动手机流,无法获取时移数据!');
     }
     $channel_exists = 1;
     //视频信息入库
     $ret['title'] = urldecode($this->input['title']) ? urldecode($this->input['title']) : '精彩节目';
     $ret['starttime'] = strtotime(trim(urldecode($this->input['start_time'])));
     $ret['endtime'] = strtotime(trim(urldecode($this->input['end_time'])));
     $ret['duration'] = $ret['endtime'] - $ret['starttime'];
     if ($ret['starttime'] >= $ret['endtime']) {
         $this->errorOutput('时间设置不正确!');
     }
     $save_time = TIMENOW - ($channel['time_shift'] * 3600 - $channel['delay']);
     if ($ret['starttime'] < $save_time) {
         $this->errorOutput('此条录制已超过回看时间!');
     }
     if ($ret['endtime'] > TIMENOW) {
         $this->errorOutput('录制节目的结束时间必须小于当前时间!');
     }
     $data = array('title' => $ret['title'], 'user_id' => $this->user['user_id'], 'addperson' => $this->user['user_name'], 'subtitle' => $this->input['subtitle'], 'author' => $this->input['author'], 'keywords' => $this->input['keywords'], 'vod_sort_id' => $this->input['item'], 'delay_time' => $channel['delay_time'], 'starttime' => $ret['starttime'], 'channel_id' => $ret['channel_id'], 'duration' => $ret['duration'], 'column_id' => $this->input['column_id'], 'comment' => $this->input['comment'], 'create_time' => $ret['starttime'], 'update_time' => $ret['starttime']);
     $sql = 'INSERT INTO ' . DB_PREFIX . 'vodinfo SET ';
     $space = '';
     foreach ($data as $key => $value) {
         $sql .= $space . $key . '="' . $value . '"';
         $space = ',';
     }
     $this->db->query($sql);
     $insert_id = $this->db->insert_id();
     $sql = "UPDATE " . DB_PREFIX . "vodinfo SET video_order_id = " . $insert_id . " WHERE id = " . $insert_id;
     $this->db->query($sql);
     //请求转码服务器路径配置
     $record_config = new curl($this->settings['App_live']['host'], $this->settings['App_live']['dir']);
     $record_config->setSubmitType('post');
     $record_config->setReturnFormat('json');
     $record_config->initPostData();
     $record_config->addRequestData('open_ts', 1);
     $record_config = $record_config->request('admin/record_server_config.php');
     $record_config = $record_config[0]['mms']['record_server'];
     $this->curl = new curl($record_config['host'], $record_config['dir']);
     //向转码服务器提交数据
     $duration = $ret['duration'] . '000';
     $starttime = $ret['starttime'] . '000';
     $url = $channel['streams'][0]['m3u8_dvr'] . '?dvr&duration=' . $duration . '&starttime=' . $starttime;
     $callback = $this->settings['App_mediaserver']['protocol'] . $this->settings['App_mediaserver']['host'] . '/' . $this->settings['App_mediaserver']['dir'] . 'admin/record_callback.php';
     $data = array();
     $data = array('id' => $insert_id, 'time_shift' => 1, 'video_order_id' => $insert_id, 'action' => 'TIMESHIFT', 'url' => urlencode($url), 'callback' => urlencode($callback), 'uploadFile' => 0, 'title' => $ret['title'], 'program' => $ret['title'], 'appid' => $this->user['appid'], 'appkey' => $this->input['appkey'], 'access_token' => $this->user['token'], 'vod_sort_id' => $this->input['item'], 'comment' => $this->input['comment']);
     foreach ($data as $k => $v) {
         if (empty($v) && $v != 0) {
             continue;
         }
         $this->curl->addRequestData($k, $v);
     }
     $record_xml = $this->curl->request('');
     //返回视频信息
     $sql = "SELECT id,name as sort_name FROM " . DB_PREFIX . "vod_media_node WHERE id=" . $this->input['item'];
     $sort = $this->db->query_first($sql);
     $return = array('id' => $insert_id, 'row_id' => $insert_id, 'video_order_id' => $insert_id, 'title' => $ret['title'], 'bitrate' => 0, 'vod_sort_id' => $sort['sort_name'], 'status' => '转码中', 'bitrate' => 0, 'author' => '', 'addperson' => 'MCP网页版', 'comment' => '', 'starttime' => '(' . date('Y-m-d', $ret['starttime']) . ')', 'delay_time' => $ret['delay_time'], 'copyright' => '', 'subtitle' => '', 'height' => 0, 'start' => 0, 'duration' => time_format(intval($ret['endtime']) - intval($ret['starttime'])), 'width' => 0, 'keywords' => $this->input['keywords'], 'type' => '', 'transize' => '', 'totalsize' => '', 'audit' => '', 'flag' => '', 'collects' => '', 'create_time' => date("Y-m-d H:i:s", TIMENOW), 'update_time' => date("Y-m-d H:i:s", TIMENOW), 'ip' => hg_getip(), 'original_id' => 0, 'mark_count' => 0, 'mark_etime' => 0, 'isfile' => 0, 'audio' => '', 'audio_channels' => '', 'sampling_rate' => '', 'video' => '', 'frame_rate' => '', 'aspect' => '', 'trans_use_time' => '', 'sort_name' => $sort['sort_name'], 'vod_sort_color' => $sort['color'], 'bitrate_color' => '#2f4974', 'vodurl' => '', 'etime' => intval($ret['duration']) + intval($ret['start']), 'is_go' => $this->input['goon']);
     $this->addItem($return);
     $this->output();
 }
Example #14
0
/**
 * Get the number of visible items in or below the selected categories
 *
 * This function counts the number of items within a set of categories, only including
 * items that are visible to the user.
 *
 * By default returns the course count, but will work for programs, certifications too.
 *
 * We need to jump through some hoops to do this efficiently:
 *
 * - To avoid having to do it recursively it relies on the context
 *   path to find courses within a category
 *
 * - To avoid having to check capabilities for every item it only
 *   checks hidden courses, and only if user isn't a siteadmin
 *
 * @param integer|array $categoryids ID or IDs of the category/categories to fetch
 * @param boolean $viewtype  - type of item to count: course,program,certification
 *
 * @return integer|array Associative array, where keys are the sub-category IDs and value is the count.
 * If $categoryids is a single integer, just returns the count as an integer
 */
function local_get_category_item_count($categoryids, $viewtype = 'course') {
    global $CFG, $USER, $DB;
    require_once($CFG->dirroot . '/cohort/lib.php');

    list($insql, $params) = $DB->get_in_or_equal(is_array($categoryids) ? $categoryids : array($categoryids));

    if (!$categories = $DB->get_records_select('course_categories', "id $insql", $params)) {
        return array();
    }

    // What items are we counting, courses, programs, or certifications?
    switch ($viewtype) {
        case 'course':
            $itemcap = 'moodle/course:viewhiddencourses';
            $itemtable = "{course}";
            $itemcontext = CONTEXT_COURSE;
            $itemalias = 'c';
            $extrawhere = '';
            break;
        case 'program':
            $itemcap = 'local/program:viewhiddenprograms';
            $itemtable = "{prog}";
            $itemcontext = CONTEXT_PROGRAM;
            $itemalias = 'p';
            $extrawhere = " AND certifid IS NULL";
            break;
        case 'certification':
            $itemcap = 'local/certification:viewhiddencertifications';
            $itemtable = "{prog}";
            $itemcontext = CONTEXT_PROGRAM;
            $itemalias = 'p';
            $extrawhere = " AND certifid IS NOT NULL";
            break;
        default:
            print_error('invalid viewtype');
    }

    list($insql, $inparams) = $DB->get_in_or_equal(array_keys($categories), SQL_PARAMS_NAMED);
    $sql = "SELECT instanceid, path
              FROM {context}
             WHERE contextlevel = :contextlvl
               AND instanceid {$insql}
             ORDER BY depth DESC";
    $params = array('contextlvl' => CONTEXT_COURSECAT);
    $params = array_merge($params, $inparams);

    $contextpaths = $DB->get_records_sql_menu($sql, $params);

    // Builds a WHERE snippet that matches any items inside the sub-category.
    // This won't match the category itself (because of the trailing slash),
    // But that's okay as we're only interested in the items inside.
    $contextwhere = array(); $contextparams = array();
    foreach ($contextpaths as $path) {
        $paramalias = 'cxt_' . rand(1, 10000);
        $contextwhere[] = $DB->sql_like('cx.path', ":{$paramalias}");
        $contextparams[$paramalias] = $path . '/%';
    }

    // Add audience visibility setting.
    $visibilitysql = '';
    $visibilityparams = array();
    $canmanagevisibility = has_capability('local/coursecatalog:manageaudiencevisibility', context_system::instance());
    if (!empty($CFG->audiencevisibility) && !$canmanagevisibility) {
        list($visibilitysql, $visibilityparams) = local_cohort_get_visible_learning_sql($itemalias, 'id', $itemcontext);
    }

    $sql = "SELECT {$itemalias}.id as itemid, {$itemalias}.visible, {$itemalias}.visible, cx.path
              FROM {context} cx
              JOIN {$itemtable} {$itemalias}
                ON {$itemalias}.id = cx.instanceid AND contextlevel = :itemcontext
                {$visibilitysql}
             WHERE (" . implode(' OR ', $contextwhere) . ")" . $extrawhere;
    $params = array('itemcontext' => $itemcontext);
    $params = array_merge($params, $contextparams);
    $params = array_merge($params, $visibilityparams);

    // Get all items inside all the categories.
    if (!$items = $DB->get_records_sql($sql, $params)) {
        // Sub-categories are all empty.
        if (is_array($categoryids)) {
            return array();
        } else {
            return 0;
        }
    }

    $results = array();
    foreach ($items as $item) {
        if (empty($CFG->audiencevisibility)) {
            // Check individual permission.
            // Get contextobj - use a switch in case this gets even more complicated in future with a third type.
            switch ($itemcontext) {
                case CONTEXT_COURSE:
                    $contextobj = context_course::instance($item->itemid);
                    break;
                case CONTEXT_PROGRAM:
                    $contextobj = context_program::instance($item->itemid);
                    break;
            }
            if (!$item->visible && !has_capability($itemcap, $contextobj)) {
                continue;
            }
        }

        // We need to check if programs are available to students.
        if ($viewtype == 'program'  && !is_siteadmin($USER->id)) {
            $program = new program($item->itemid);
            if (!$program->is_accessible()) {
                continue;
            }
        }

        // Now we need to figure out which sub-category each item is a member of.
        foreach ($contextpaths as $categoryid => $contextpath) {
            // It's a member if the beginning of the contextpath's match.
            if (substr($item->path, 0, strlen($contextpath.'/')) ==
                $contextpath.'/') {
                if (array_key_exists($categoryid, $results)) {
                    $results[$categoryid]++;
                } else {
                    $results[$categoryid] = 1;
                }
                break;
            }
        }
    }

    if (empty($results)) {
        return 0;
    } else if (is_array($categoryids)) {
        return $results;
    } else {
        return current($results);
    }

}