repo
stringlengths
5
75
commit
stringlengths
40
40
message
stringlengths
6
18.2k
diff
stringlengths
60
262k
blueyed/dotfiles
da7b3f0c389e6e58819f1d104e7d17c404a63248
vimrc: add missing s:systemlist
diff --git a/vimrc b/vimrc index 0309cd6..cd52ad1 100644 --- a/vimrc +++ b/vimrc @@ -1365,1024 +1365,1032 @@ endif endif " Local dirs"{{{1 set backupdir=~/.local/share/vim/backups if ! isdirectory(expand(&backupdir)) call mkdir( &backupdir, 'p', 0700 ) endif if 1 let s:xdg_cache_home = $XDG_CACHE_HOME if !len(s:xdg_cache_home) let s:xdg_cache_home = expand('~/.cache') endif let s:vimcachedir = s:xdg_cache_home . '/vim' let g:tlib_cache = s:vimcachedir . '/tlib' let s:xdg_config_home = $XDG_CONFIG_HOME if !len(s:xdg_config_home) let s:xdg_config_home = expand('~/.config') endif let s:vimconfigdir = s:xdg_config_home . '/vim' let g:session_directory = s:vimconfigdir . '/sessions' let g:startify_session_dir = g:session_directory let g:startify_change_to_dir = 0 let s:xdg_data_home = $XDG_DATA_HOME if !len(s:xdg_data_home) let s:xdg_data_home = expand('~/.local/share') endif let s:vimsharedir = s:xdg_data_home . '/vim' let &viewdir = s:vimsharedir . '/views' let g:yankring_history_dir = s:vimsharedir let g:yankring_max_history = 500 " let g:yankring_min_element_length = 2 " more that 1 breaks e.g. `xp` " Move yankring history from old location, if any.. let s:old_yankring = expand('~/yankring_history_v2.txt') if filereadable(s:old_yankring) execute '!mv -i '.s:old_yankring.' '.s:vimsharedir endif " Transfer any old (default) tmru files db to new (default) location. let g:tlib_persistent = s:vimsharedir let s:old_tmru_file = expand('~/.cache/vim/tlib/tmru/files') let s:global_tmru_file = s:vimsharedir.'/tmru/files' let s:new_tmru_file_dir = fnamemodify(s:global_tmru_file, ':h') if ! isdirectory(s:new_tmru_file_dir) call mkdir(s:new_tmru_file_dir, 'p', 0700) endif if filereadable(s:old_tmru_file) execute '!mv -i '.shellescape(s:old_tmru_file).' '.shellescape(s:global_tmru_file) " execute '!rm -r '.shellescape(g:tlib_cache) endif end let s:check_create_dirs = [s:vimcachedir, g:tlib_cache, s:vimconfigdir, g:session_directory, s:vimsharedir, &directory] if has('persistent_undo') let &undodir = s:vimsharedir . '/undo' set undofile call add(s:check_create_dirs, &undodir) endif for s:create_dir in s:check_create_dirs " Remove trailing slashes, especially for &directory. let s:create_dir = substitute(s:create_dir, '/\+$', '', '') if ! isdirectory(s:create_dir) if match(s:create_dir, ',') != -1 echohl WarningMsg | echom "WARN: not creating dir: ".s:create_dir | echohl None continue endif echom "Creating dir: ".s:create_dir call mkdir(s:create_dir, 'p', 0700 ) endif endfor " }}} if has("user_commands") " Themes " Airline: let g:airline#extensions#disable_rtp_load = 1 let g:airline_extensions_add = ['neomake'] let g:airline_powerline_fonts = 1 " to test let g:airline#extensions#branch#use_vcscommand = 1 let g:airline#extensions#branch#displayed_head_limit = 7 let g:airline#extensions#hunks#non_zero_only = 1 let g:airline#extensions#tabline#enabled = 1 let g:airline#extensions#tabline#show_buffers = 0 let g:airline#extensions#tabline#tab_nr_type = '[__tabnr__.%{len(tabpagebuflist(__tabnr__))}]' let g:airline#extensions#tmuxline#enabled = 1 let g:airline#extensions#whitespace#enabled = 0 let g:airline#extensions#tagbar#enabled = 0 let g:airline#extensions#tagbar#flags = 'f' " full hierarchy of tag (with scope), see tagbar-statusline " see airline-predefined-parts " let r += ['%{ShortenFilename(fnamemodify(bufname("%"), ":~:."), winwidth(0)-50)}'] " function! AirlineInit() " " let g:airline_section_a = airline#section#create(['mode', ' ', 'foo']) " " let g:airline_section_b = airline#section#create_left(['ffenc','file']) " " let g:airline_section_c = airline#section#create(['%{getcwd()}']) " endfunction " au VimEnter * call AirlineInit() " jedi-vim (besides YCM with jedi library) {{{1 " let g:jedi#force_py_version = 3 let g:jedi#auto_vim_configuration = 0 let g:jedi#goto_assignments_command = '' " dynamically done for ft=python. let g:jedi#goto_definitions_command = '' " dynamically done for ft=python. let g:jedi#rename_command = 'cR' let g:jedi#usages_command = 'gr' let g:jedi#completions_enabled = 1 " Unite/ref and pydoc are more useful. let g:jedi#documentation_command = '<Leader>_K' " Manually setup jedi's call signatures. let g:jedi#show_call_signatures = 1 if &rtp =~ '\<jedi\>' augroup JediSetup au! au FileType python call jedi#configure_call_signatures() augroup END endif let g:jedi#auto_close_doc = 1 " if g:jedi#auto_close_doc " " close preview if its still open after insert " autocmd InsertLeave <buffer> if pumvisible() == 0|pclose|endif " end " }}}1 endif " Enable syntax {{{1 " Switch syntax highlighting on, when the terminal has colors " Also switch on highlighting the last used search pattern. " if (&t_Co > 2 || has("gui_running")) && !exists("syntax_on") if (&t_Co > 2 || has("gui_running")) if !exists("syntax_on") syntax on " after 'filetype plugin indent on' (?!), but not on reload. endif set nohlsearch " Improved syntax handling of TODO etc. au Syntax * syn match MyTodo /\v<(FIXME|NOTE|TODO|OPTIMIZE|XXX):/ \ containedin=.*Comment,vimCommentTitle hi def link MyTodo Todo endif if 1 " has('eval') " Color scheme (after 'syntax on') {{{1 " Use light/dark background based on day/night period (according to " get-daytime-period (uses redshift)) fun! SetBgAccordingToShell(...) let variant = a:0 ? a:1 : "" if len(variant) && variant != "auto" let bg = variant elseif len($TMUX) let bg = system('tmux show-env MY_X_THEME_VARIANT') == "MY_X_THEME_VARIANT=light\n" ? 'light' : 'dark' elseif len($MY_X_THEME_VARIANT) let bg = $MY_X_THEME_VARIANT else " let daytime = system('get-daytime-period') let daytime_file = expand('/tmp/redshift-period') if filereadable(daytime_file) let daytime = readfile(daytime_file)[0] if daytime == 'Daytime' let bg = "light" else let bg = "dark" endif else let bg = "dark" endif endif if bg != &bg let &bg = bg let $FZF_DEFAULT_OPTS = '--color 16,bg+:' . (bg == 'dark' ? '18' : '21') doautocmd <nomodeline> ColorScheme endif endfun command! -nargs=? Autobg call SetBgAccordingToShell(<q-args>) fun! ToggleBg() let &bg = &bg == 'dark' ? 'light' : 'dark' endfun nnoremap <Leader>sb :call ToggleBg()<cr> " Colorscheme: prefer solarized with 16 colors (special palette). let g:solarized_hitrail=0 " using MyWhitespaceSetup instead. let g:solarized_menu=0 " Use corresponding theme from $BASE16_THEME, if set up in the shell. " BASE16_THEME should be in sudoer's env_keep for "sudo vi". if len($BASE16_THEME) let base16colorspace=&t_Co if $BASE16_THEME =~ '^solarized' let s:use_colorscheme = 'solarized' let g:solarized_base16=1 let g:airline_theme = 'solarized' else let s:use_colorscheme = 'base16-'.substitute($BASE16_THEME, '\.\(dark\|light\)$', '', '') endif let g:solarized_termtrans=1 elseif has('gui_running') let s:use_colorscheme = "solarized" let g:solarized_termcolors=256 else " Check for dumb terminal. if ($TERM !~ '256color' ) let s:use_colorscheme = "default" else let s:use_colorscheme = "solarized" let g:solarized_termcolors=256 endif endif " Airline: do not use powerline symbols with linux/screen terminal. " NOTE: xterm-256color gets setup for tmux/screen with $DISPLAY. if (index(["linux", "screen"], $TERM) != -1) let g:airline_powerline_fonts = 0 endif fun! s:MySetColorscheme() " Set s:use_colorscheme, called through GUIEnter for gvim. try exec 'NeoBundleSource colorscheme-'.s:use_colorscheme exec 'colorscheme' s:use_colorscheme catch echom "Failed to load colorscheme: " v:exception endtry endfun if has('vim_starting') call SetBgAccordingToShell($MY_X_THEME_VARIANT) endif if has('gui_running') au GUIEnter * nested call s:MySetColorscheme() else call s:MySetColorscheme() endif endif " Only do this part when compiled with support for autocommands. if has("autocmd") " Autocommands {{{1 " Put these in an autocmd group, so that we can delete them easily. augroup vimrcEx au! " Handle large files, based on LargeFile plugin. let g:LargeFile = 5 " 5mb autocmd BufWinEnter * if get(b:, 'LargeFile_mode') || line2byte(line("$") + 1) > 1000000 \ | echom "vimrc: handling large file." \ | set syntax=off \ | let &ft = &ft.".ycmblacklisted" \ | endif " Enable soft-wrapping for text files au FileType text,markdown,html,xhtml,eruby,vim setlocal wrap linebreak nolist au FileType mail,markdown,gitcommit setlocal spell au FileType json setlocal equalprg=json_pp " XXX: only works for whole files " au FileType css setlocal equalprg=csstidy\ -\ --silent=true\ --template=default " For all text files set 'textwidth' to 78 characters. " au FileType text setlocal textwidth=78 " Follow symlinks when opening a file {{{ " NOTE: this happens with directory symlinks anyway (due to Vim's chdir/getcwd " magic when getting filenames). " Sources: " - https://github.com/tpope/vim-fugitive/issues/147#issuecomment-7572351 " - http://www.reddit.com/r/vim/comments/yhsn6/is_it_possible_to_work_around_the_symlink_bug/c5w91qw function! MyFollowSymlink(...) if exists('w:no_resolve_symlink') && w:no_resolve_symlink return endif if &ft == 'help' return endif let fname = a:0 ? a:1 : expand('%') if fname =~ '^\w\+:/' " Do not mess with 'fugitive://' etc. return endif let fname = simplify(fname) let resolvedfile = resolve(fname) if resolvedfile == fname return endif let resolvedfile = fnameescape(resolvedfile) let sshm = &shm set shortmess+=A " silence ATTENTION message about swap file (would get displayed twice) redraw " Redraw now, to avoid hit-enter prompt. exec 'file ' . resolvedfile let &shm=sshm unlet! b:git_dir call fugitive#detect(resolvedfile) if &modifiable " Only display a note when editing a file, especially not for `:help`. redraw " Redraw now, to avoid hit-enter prompt. echomsg 'Resolved symlink: =>' resolvedfile endif endfunction command! -bar FollowSymlink call MyFollowSymlink() command! ToggleFollowSymlink let w:no_resolve_symlink = !get(w:, 'no_resolve_symlink', 0) | echo "w:no_resolve_symlink =>" w:no_resolve_symlink au BufReadPost * nested call MyFollowSymlink(expand('%')) " Automatically load .vimrc source when saved au BufWritePost $MYVIMRC,~/.dotfiles/vimrc,$MYVIMRC.local source $MYVIMRC au BufWritePost $MYGVIMRC,~/.dotfiles/gvimrc source $MYGVIMRC " if (has("gui_running")) " au FocusLost * stopinsert " endif " autocommands for fugitive {{{2 " Source: http://vimcasts.org/episodes/fugitive-vim-browsing-the-git-object-database/ au User Fugitive \ if fugitive#buffer().type() =~# '^\%(tree\|blob\)' | \ nnoremap <buffer> .. :edit %:h<CR> | \ endif au BufReadPost fugitive://* set bufhidden=delete " Expand tabs for Debian changelog. This is probably not the correct way. au BufNewFile,BufRead */debian/changelog,changelog.dch set expandtab " Ignore certain files with vim-stay. au BufNewFile,BufRead */.git/addp-hunk-edit.diff let b:stay_ignore = 1 " Python " irrelevant, using python-pep8-indent " let g:pyindent_continue = '&sw * 1' " let g:pyindent_open_paren = '&sw * 1' " let g:pyindent_nested_paren = '&sw' " python-mode let g:pymode_options = 0 " do not change relativenumber let g:pymode_indent = 0 " use vim-python-pep8-indent (upstream of pymode) let g:pymode_lint = 0 " prefer syntastic; pymode has problems when PyLint was invoked already before VirtualEnvActivate..!?! let g:pymode_virtualenv = 0 " use virtualenv plugin (required for pylint?!) let g:pymode_doc = 0 " use pydoc let g:pymode_rope_completion = 0 " use YouCompleteMe instead (python-jedi) let g:pymode_syntax_space_errors = 0 " using MyWhitespaceSetup let g:pymode_trim_whitespaces = 0 let g:pymode_debug = 0 let g:pymode_rope = 0 let g:pydoc_window_lines=0.5 " use 50% height let g:pydoc_perform_mappings=0 " let python_space_error_highlight = 1 " using MyWhitespaceSetup " C au FileType C setlocal formatoptions-=c formatoptions-=o formatoptions-=r fu! Select_c_style() if search('^\t', 'n', 150) setlocal shiftwidth=8 noexpandtab el setlocal shiftwidth=4 expandtab en endf au FileType c call Select_c_style() au FileType make setlocal noexpandtab " Disable highlighting of markdownError (Ref: https://github.com/tpope/vim-markdown/issues/79). autocmd FileType markdown hi link markdownError NONE augroup END " Trailing whitespace highlighting {{{2 " Map to toogle EOLWS syntax highlighting noremap <silent> <leader>se :let g:MyAuGroupEOLWSactive = (synIDattr(synIDtrans(hlID("EOLWS")), "bg", "cterm") == -1)<cr> \:call MyAuGroupEOLWS(mode())<cr> let g:MyAuGroupEOLWSactive = 0 function! MyAuGroupEOLWS(mode) if g:MyAuGroupEOLWSactive && &buftype == '' hi EOLWS ctermbg=red guibg=red syn clear EOLWS " match whitespace not preceded by a backslash if a:mode == "i" syn match EOLWS excludenl /[\\]\@<!\s\+\%#\@!$/ containedin=ALL else syn match EOLWS excludenl /[\\]\@<!\s\+$\| \+\ze\t/ containedin=ALLBUT,gitcommitDiff | endif else syn clear EOLWS hi clear EOLWS endif endfunction augroup vimrcExEOLWS au! " highlight EOLWS ctermbg=red guibg=red " based on solarizedTrailingSpace highlight EOLWS term=underline cterm=underline ctermfg=1 au InsertEnter * call MyAuGroupEOLWS("i") " highlight trailing whitespace, space before tab and tab not at the " beginning of the line (except in comments), only for normal buffers: au InsertLeave,BufWinEnter * call MyAuGroupEOLWS("n") " fails with gitcommit: filetype | syn match EOLWS excludenl /[^\t]\zs\t\+/ containedin=ALLBUT,gitcommitComment " add this for Python (via python_highlight_all?!): " au FileType python " \ if g:MyAuGroupEOLWSactive | " \ syn match EOLWS excludenl /^\t\+/ containedin=ALL | " \ endif augroup END "}}} " automatically save and reload viminfo across Vim instances " Source: http://vimhelp.appspot.com/vim_faq.txt.html#faq-17.3 augroup viminfo_onfocus au! " au FocusLost * wviminfo " au FocusGained * rviminfo augroup end endif " has("autocmd") }}} " Shorten a given (absolute) file path, via external `shorten_path` script. " This mainly shortens entries from Zsh's `hash -d` list. let s:_cache_shorten_path = {} let s:_has_functional_shorten_path = 1 let s:shorten_path_exe = executable('shorten_path') \ ? 'shorten_path' \ : filereadable(expand("$HOME/.dotfiles/usr/bin/shorten_path")) \ ? expand("$HOME/.dotfiles/usr/bin/shorten_path") \ : expand("/home/$SUDO_USER/.dotfiles/usr/bin/shorten_path") function! ShortenPath(path, ...) if !len(a:path) || !s:_has_functional_shorten_path return a:path endif let base = a:0 ? a:1 : "" let annotate = a:0 > 1 ? a:2 : 0 let cache_key = base . ":" . a:path . ":" . annotate if !exists('s:_cache_shorten_path[cache_key]') let shorten_path = [s:shorten_path_exe] if annotate let shorten_path += ['-a'] endif let cmd = shorten_path + [a:path, base] let output = s:systemlist(cmd) let lastline = empty(output) ? '' : output[-1] let s:_cache_shorten_path[cache_key] = lastline if v:shell_error try let tmpfile = tempname() let system_cmd = join(map(copy(cmd), 'fnameescape(v:val)')) call system(system_cmd.' 2>'.tmpfile) if v:shell_error == 127 let s:_has_functional_shorten_path = 0 endif echohl ErrorMsg echom printf('There was a problem running %s: %s (%d)', \ cmd, join(readfile(tmpfile), "\n"), v:shell_error) echohl None return a:path finally call delete(tmpfile) endtry endif endif return s:_cache_shorten_path[cache_key] endfun function! My_get_qfloclist_type(bufnr) let isLoc = getbufvar(a:bufnr, 'isLoc', -1) " via vim-qf. if isLoc != -1 return isLoc ? 'll' : 'qf' endif " A hacky way to distinguish qf from loclist windows/buffers. " https://github.com/vim-airline/vim-airline/blob/83b6dd11a8829bbd934576e76bfbda6559ed49e1/autoload/airline/extensions/quickfix.vim#L27-L43. " Changes: " - Caching! " - Match opening square bracket at least. Apart from that it could be " localized. " if &ft !=# 'qf' " return '' " endif let type = getbufvar(a:bufnr, 'my_qfloclist_type', '') if type != '' return type endif redir => buffers silent ls - redir END let type = 'unknown' for buf in split(buffers, '\n') if match(buf, '\v^\s*'.a:bufnr.'\s\S+\s+"\[') > -1 if match(buf, '\cQuickfix') > -1 let type = 'qf' break else let type = 'll' break endif endif endfor call setbufvar(a:bufnr, 'my_qfloclist_type', type) return type endfunction +function! s:systemlist(l) abort + let cmd = a:l + if !has('nvim') + let cmd = join(map(copy(cmd), 'fnameescape(v:val)')) + endif + return systemlist(cmd) +endfunction + " Shorten a given filename by truncating path segments. let g:_cache_shorten_filename = {} let g:_cache_shorten_filename_git = {} function! ShortenString(s, maxlen) if len(a:s) <= a:maxlen return a:s endif return a:s[0:a:maxlen-1] . '…' endfunction function! ShortenFilename(...) " {{{ " Args: bufname ('%' for default), maxlength, cwd let cwd = a:0 > 2 ? a:3 : getcwd() " Maxlen from a:2 (used for cache key) and caching. let maxlen = a:0>1 ? a:2 : max([10, winwidth(0)-50]) " get bufname from a:1, defaulting to bufname('%') {{{ if a:0 && type(a:1) == type('') && a:1 !=# '%' let bufname = expand(a:1) " tilde-expansion. else if !a:0 || a:1 == '%' let bufnr = bufnr('%') else let bufnr = a:1 endif let bufname = bufname(bufnr) let ft = getbufvar(bufnr, '&filetype') if !len(bufname) if ft == 'qf' let type = My_get_qfloclist_type(bufnr) " XXX: uses current window. Also not available after ":tab split". let qf_title = get(w:, 'quickfix_title', '') if qf_title != '' return ShortenString('['.type.'] '.qf_title, maxlen) elseif type == 'll' let alt_name = expand('#') " For location lists the alternate file is the corresponding buffer " and the quickfix list does not have an alternate buffer " (but not always)!?! if len(alt_name) return '[loc] '.ShortenFilename(alt_name, maxlen-5) endif return '[loc]' endif return '[qf]' else let bt = getbufvar(bufnr, '&buftype') if bt != '' && ft != '' " Use &ft for name (e.g. with 'startify' and quickfix windows). " if &ft == 'qf' " let alt_name = expand('#') " if len(alt_name) " return '[loc] '.ShortenFilename(alt_name) " else " return '[qf]' " endif let alt_name = expand('#') if len(alt_name) return '['.&ft.'] '.ShortenFilename(expand('#')) else return '['.&ft.']' endif else " TODO: get Vim's original "[No Name]" somehow return '[No Name]' endif endif end if ft ==# 'help' return '[?] '.fnamemodify(bufname, ':t') endif if bufname =~# '^__' return bufname endif " '^\[ref-\w\+:.*\]$' if bufname =~# '^\[.*\]$' return bufname endif endif " }}} " {{{ fugitive if bufname =~# '^fugitive:///' let [gitdir, fug_path] = split(bufname, '//')[1:2] " Caching based on bufname and timestamp of gitdir. let git_ftime = getftime(gitdir) if exists('g:_cache_shorten_filename_git[bufname]') \ && g:_cache_shorten_filename_git[bufname][0] == git_ftime let [commit_name, fug_type, fug_path] \ = g:_cache_shorten_filename_git[bufname][1:-1] else let fug_buffer = fugitive#buffer(bufname) let fug_type = fug_buffer.type() " if fug_path =~# '^\x\{7,40\}\>' let commit = matchstr(fug_path, '\v\w*') if len(commit) > 1 let git_argv = ['git', '--git-dir='.gitdir] let commit = systemlist(git_argv + ['rev-parse', '--short', commit])[0] let commit_name = systemlist(git_argv + ['name-rev', '--name-only', commit])[0] if commit_name !=# 'undefined' " Remove current branch name (master~4 => ~4). let HEAD = get(systemlist(git_argv + ['symbolic-ref', '--quiet', '--short', 'HEAD']), 0, '') let len_HEAD = len(HEAD) if len_HEAD > len(commit_name) && commit_name[0:len_HEAD-1] == HEAD let commit_name = commit_name[len_HEAD:-1] endif " let commit .= '('.commit_name.')' let commit_name .= '('.commit.')' else let commit_name = commit endif else let commit_name = commit endif " endif if fug_type !=# 'commit' let fug_path = substitute(fug_path, '\v\w*/', '', '') if len(fug_path) let fug_path = ShortenFilename(fug_buffer.repo().tree(fug_path)) endif else let fug_path = 'NOT_USED' endif " Set cache. let g:_cache_shorten_filename_git[bufname] \ = [git_ftime, commit_name, fug_type, fug_path] endif if fug_type ==# 'blob' return 'λ:' . commit_name . ':' . fug_path elseif fug_type ==# 'file' return 'λ:' . fug_path . '@' . commit_name elseif fug_type ==# 'commit' " elseif fug_path =~# '^\x\{7,40\}\>' let work_tree = fugitive#buffer(bufname).repo().tree() if cwd[0:len(work_tree)-1] == work_tree let rel_work_tree = '' else let rel_work_tree = ShortenPath(fnamemodify(work_tree.'/', ':.')) endif return 'λ:' . rel_work_tree . '@' . commit_name endif throw "fug_type: ".fug_type." not handled: ".fug_path endif " }}} " Check for cache (avoiding fnamemodify): {{{ let cache_key = bufname.'::'.cwd.'::'.maxlen if has_key(g:_cache_shorten_filename, cache_key) return g:_cache_shorten_filename[cache_key] endif " Make path relative first, which might not work with the result from " `shorten_path`. let rel_path = fnamemodify(bufname, ":.") let bufname = ShortenPath(rel_path, cwd, 1) " }}} " Loop over all segments/parts, to mark symlinks. " XXX: symlinks get resolved currently anyway!? " NOTE: consider using another method like http://stackoverflow.com/questions/13165941/how-to-truncate-long-file-path-in-vim-powerline-statusline let maxlen_of_parts = 7 " including slash/dot let maxlen_of_subparts = 1 " split at hypen/underscore; including split let s:PS = exists('+shellslash') ? (&shellslash ? '/' : '\') : "/" let parts = split(bufname, '\ze['.escape(s:PS, '\').']') let i = 0 let n = len(parts) let wholepath = '' " used for symlink check while i < n let wholepath .= parts[i] " Shorten part, if necessary: " TODO: use pathshorten(fnamemodify(path, ':~')) as fallback?! if i < n-1 && len(bufname) > maxlen && len(parts[i]) > maxlen_of_parts " Let's see if there are dots or hyphens to truncate at, e.g. " 'vim-pkg-debian' => 'v-p-d…' let w = split(parts[i], '\ze[_-]') if len(w) > 1 let parts[i] = '' for j in w if len(j) > maxlen_of_subparts-1 let parts[i] .= j[0:max([maxlen_of_subparts-2, 1])] "."…" else let parts[i] .= j endif endfor else let parts[i] = parts[i][0:max([maxlen_of_parts-2, 1])].'…' endif endif let i += 1 endwhile let r = join(parts, '') if len(r) > maxlen " echom len(r) maxlen let i = 0 let n -= 1 while i < n && len(join(parts, '')) > maxlen if i > 0 || parts[i][0] != '~' let j = 0 let parts[i] = matchstr(parts[i], '.\{-}\w') " if i == 0 && parts[i][0] != '/' " let parts[i] = parts[i][0] " else " let parts[i] = matchstr(parts[i], 1) " endif endif let i += 1 endwhile let r = join(parts, '') endif let g:_cache_shorten_filename[cache_key] = r " echom "ShortenFilename" r return r endfunction "}}} " Shorten filename, and append suffix(es), e.g. for modified buffers. {{{2 fun! ShortenFilenameWithSuffix(...) let r = call('ShortenFilename', a:000) if &modified let r .= ',+' endif return r endfun " }}} " Opens an edit command with the path of the currently edited file filled in " Normal mode: <Leader>e nnoremap <Leader>ee :e <C-R>=expand("%:p:h") . "/" <CR> nnoremap <Leader>EE :sp <C-R>=expand("%:p:h") . "/" <CR> " gt: next tab or buffer (source: http://j.mp/dotvimrc) " enhanced to support range (via v:count) fun! MyGotoNextTabOrBuffer(...) let c = a:0 ? a:1 : v:count exec (c ? c : '') . (tabpagenr('$') == 1 ? 'bn' : 'tabnext') endfun fun! MyGotoPrevTabOrBuffer() exec (v:count ? v:count : '') . (tabpagenr('$') == 1 ? 'bp' : 'tabprevious') endfun nnoremap <silent> <Plug>NextTabOrBuffer :<C-U>call MyGotoNextTabOrBuffer()<CR> nnoremap <silent> <Plug>PrevTabOrBuffer :<C-U>call MyGotoPrevTabOrBuffer()<CR> " Ctrl-Space: split into new tab. " Disables diff mode, which gets taken over from the old buffer. nnoremap <C-Space> :tab sp \| set nodiff<cr> nnoremap <A-Space> :tabnew<cr> " For terminal. nnoremap <C-@> :tab sp \| set nodiff<cr> " Opens a tab edit command with the path of the currently edited file filled in map <Leader>te :tabe <C-R>=expand("%:p:h") . "/" <CR> map <a-o> <C-W>o " Avoid this to be done accidentally (when zooming is meant). ":on" is more " explicit. map <C-W><C-o> <Nop> " does not work, even with lilyterm.. :/ " TODO: <C-1>..<C-0> for tabs; not possible; only certain C-sequences get " through to the terminal Vim " nmap <C-Insert> :tabnew<cr> " nmap <C-Del> :tabclose<cr> nmap <A-Del> :tabclose<cr> " nmap <C-1> 1gt<cr> " Prev/next tab. nmap <C-PageUp> <Plug>PrevTabOrBuffer nmap <C-PageDown> <Plug>NextTabOrBuffer map <A-,> <Plug>PrevTabOrBuffer map <A-.> <Plug>NextTabOrBuffer map <C-S-Tab> <Plug>PrevTabOrBuffer map <C-Tab> <Plug>NextTabOrBuffer " Switch to most recently used tab. " Source: http://stackoverflow.com/a/2120168/15690 fun! MyGotoMRUTab() if !exists('g:mrutab') let g:mrutab = 1 endif if tabpagenr('$') == 1 echomsg "There is only one tab!" return endif if g:mrutab > tabpagenr('$') || g:mrutab == tabpagenr() let g:mrutab = tabpagenr() > 1 ? tabpagenr()-1 : tabpagenr('$') endif exe "tabn ".g:mrutab endfun " Overrides Vim's gh command (start select-mode, but I don't use that). " It can be simulated using v<C-g> also. nnoremap <silent> gh :call MyGotoMRUTab()<CR> " nnoremap ° :call MyGotoMRUTab()<CR> " nnoremap <C-^> :call MyGotoMRUTab()<CR> augroup MyTL au! au TabLeave * let g:mrutab = tabpagenr() augroup END " Map <A-1> .. <A-9> to goto tab or buffer. for i in range(9) exec 'nmap <M-' .(i+1).'> :call MyGotoNextTabOrBuffer('.(i+1).')<cr>' endfor fun! MyGetNonDefaultServername() " Not for gvim in general (uses v:servername by default), and the global " server ("G"). let sname = v:servername if len(sname) if has('nvim') if sname !~# '^/tmp/nvim' let sname = substitute(fnamemodify(v:servername, ':t:r'), '^nvim-', '', '') return sname endif elseif sname !~# '\v^GVIM.*' " && sname =~# '\v^G\d*$' return sname endif endif return '' endfun fun! MyGetSessionName() " Use / auto-set g:MySessionName if !len(get(g:, "MySessionName", "")) if len(v:this_session) let g:MySessionName = fnamemodify(v:this_session, ':t:r') elseif len($TERM_INSTANCE_NAME) let g:MySessionName = substitute($TERM_INSTANCE_NAME, '^vim-', '', '') else return '' end endif return g:MySessionName endfun " titlestring handling, with tmux support {{{ " Set titlestring, used to set terminal title (pane title in tmux). set title " Setup titlestring on BufEnter, when v:servername is available. fun! MySetupTitleString() let title = '✐ ' let session_name = MyGetSessionName() if len(session_name) let title .= '['.session_name.'] ' else " Add non-default servername to titlestring. let sname = MyGetNonDefaultServername() if len(sname) let title .= '['.sname.'] ' endif endif " Call the function and use its result, rather than including it. " (for performance reasons). let title .= substitute( \ ShortenFilenameWithSuffix('%', 15).' ('.ShortenPath(getcwd()).')', \ '%', '%%', 'g') if len(s:my_context) let title .= ' {'.s:my_context.'}' endif " Easier to type/find than the unicode symbol prefix. let title .= ' - vim' " Append $_TERM_TITLE_SUFFIX (e.g. user@host) to title (set via zsh, used " with SSH). if len($_TERM_TITLE_SUFFIX) let title .= $_TERM_TITLE_SUFFIX endif " Setup tmux window name, see ~/.dotfiles/oh-my-zsh/lib/termsupport.zsh. if len($TMUX) \ && (!len($_tmux_name_reset) || $_tmux_name_reset != $TMUX . '_' . $TMUX_PANE) let tmux_auto_rename=systemlist('tmux show-window-options -t '.$TMUX_PANE.' -v automatic-rename 2>/dev/null') " || $(tmux show-window-options -t $TMUX_PANE | grep '^automatic-rename' | cut -f2 -d\ ) " echom string(tmux_auto_rename) if !len(tmux_auto_rename) || tmux_auto_rename[0] != "off" " echom "Resetting tmux name to 0." call system('tmux set-window-option -t '.$TMUX_PANE.' -q automatic-rename off') call system('tmux rename-window -t '.$TMUX_PANE.' 0') endif endif let &titlestring = title " Set icon text according to &titlestring (used for minimized windows). let &iconstring = '(v) '.&titlestring endfun augroup vimrc_title au! " XXX: might not get called with fugitive buffers (title is the (closed) fugitive buffer). autocmd BufEnter,BufWritePost * call MySetupTitleString() if exists('##TextChanged') autocmd TextChanged * call MySetupTitleString() endif augroup END " Make Vim set the window title according to &titlestring. if !has('gui_running') && empty(&t_ts) if len($TMUX) let &t_ts = "\e]2;" let &t_fs = "\007" elseif &term =~ "^screen.*" let &t_ts="\ek" let &t_fs="\e\\" endif endif fun! MySetSessionName(name) let g:MySessionName = a:name call MySetupTitleString() endfun "}}} " Inserts the path of the currently edited file into a command " Command mode: Ctrl+P " cmap <C-P> <C-R>=expand("%:p:h") . "/" <CR> " Change to current file's dir nnoremap <Leader>cd :lcd <C-R>=expand('%:p:h')<CR><CR> " yankstack, see also unite's history/yank {{{1 if &rtp =~ '\<yankstack\>' " Do not map s/S (used by vim-sneak). " let g:yankstack_yank_keys = ['c', 'C', 'd', 'D', 's', 'S', 'x', 'X', 'y', 'Y'] let g:yankstack_yank_keys = ['c', 'C', 'd', 'D', 'x', 'X', 'y', 'Y'] " Setup yankstack now to make yank/paste related mappings work. call yankstack#setup() endif " Command-line maps to act on the current search (with incsearch). {{{ " E.g. '?foo$m' will move the matched line to where search started. " Source: http://www.reddit.com/r/vim/comments/1yfzg2/does_anyone_actually_use_easymotion/cfkaxw5 " NOTE: with vim-oblique, '?' and '/' are mapped, and not in getcmdtype(). fun! MyCmdMapNotForColon(from, to, ...) let init = a:0 ? 0 : 1 if init exec printf('cnoremap <expr> %s MyCmdMapNotForColon("%s", "%s", 1)', \ a:from, a:from, a:to) return endif if index([':', '>', '@', '-', '='], getcmdtype()) == 0 return a:from endif return a:to endfun call MyCmdMapNotForColon('$d', "<CR>:delete<CR>``") call MyCmdMapNotForColon('$m', "<CR>:move''<CR>") call MyCmdMapNotForColon('$c', "<CR>:copy''<CR>") call MyCmdMapNotForColon('$t', "<CR>:t''<CR>") " synonym for :copy " Allow to quickly enter a single $. cnoremap $$ $ " }}} " sneak {{{1 " Overwrite yankstack with sneak maps. " Ref: https://github.com/maxbrunsfeld/vim-yankstack/issues/39 nmap s <Plug>Sneak_s nmap S <Plug>Sneak_S xmap s <Plug>Sneak_s xmap S <Plug>Sneak_S omap s <Plug>Sneak_s omap S <Plug>Sneak_S " Use streak mode, also for Sneak_f/Sneak_t. let g:sneak#streak=2 let g:sneak#s_next = 1 " clever-s let g:sneak#target_labels = "sfjktunbqz/SFKGHLTUNBRMQZ?" " Replace 'f' with inclusive 1-char Sneak. nmap f <Plug>Sneak_f nmap F <Plug>Sneak_F xmap f <Plug>Sneak_f xmap F <Plug>Sneak_F omap f <Plug>Sneak_f omap F <Plug>Sneak_F " Replace 't' with exclusive 1-char Sneak. nmap t <Plug>Sneak_t nmap T <Plug>Sneak_T xmap t <Plug>Sneak_t xmap T <Plug>Sneak_T omap t <Plug>Sneak_t omap T <Plug>Sneak_T " IDEA: just use 'f' for sneak, leaving 's' at its default. " nmap f <Plug>Sneak_s " nmap F <Plug>Sneak_S " xmap f <Plug>Sneak_s " xmap F <Plug>Sneak_S " omap f <Plug>Sneak_s " omap F <Plug>Sneak_S " }}}1 " GoldenView {{{1 let g:goldenview__enable_default_mapping = 0 let g:goldenview__enable_at_startup = 0 " 1. split to tiled windows nmap <silent> g<C-L> <Plug>GoldenViewSplit
blueyed/dotfiles
c952c671a1728c144b5d69268c06cea51157079c
Add terminfo/x/xterm-kitty
diff --git a/terminfo/x/xterm-kitty b/terminfo/x/xterm-kitty new file mode 100644 index 0000000..08d300e Binary files /dev/null and b/terminfo/x/xterm-kitty differ
blueyed/dotfiles
abe59a331eb0aeebccba55516ffbf885c577e8c6
Add timeit-shell
diff --git a/usr/bin/timeit-shell b/usr/bin/timeit-shell new file mode 100755 index 0000000..4b55ab8 --- /dev/null +++ b/usr/bin/timeit-shell @@ -0,0 +1,15 @@ +#!/usr/bin/python + +""" +Wrapper around Python's timeit to time a shell command. +""" + +import sys +import timeit + +timeit.main([ + '--setup', 'import subprocess', + '--', + 'subprocess.Popen(%r, stdout=subprocess.PIPE).communicate()' % ( + sys.argv[1:], + )])
blueyed/dotfiles
672e8b6a63b9bbc75a690f1bb061ebb129da88c6
vim: move gitcommit setup to ftplugin
diff --git a/usr/bin/vim-for-git b/usr/bin/vim-for-git deleted file mode 100755 index bf35ada..0000000 --- a/usr/bin/vim-for-git +++ /dev/null @@ -1,26 +0,0 @@ -#!/bin/sh - -# Wrapper meant to be set for GIT_EDITOR. -# This sets up the editor for git commit messages: -# It scrolls to "Changes" in the buffer, splits the window (resized to 10 lines). -# This allows for reviewing the diff (from `git commit -v`) while editing the commit message. - -FILE=$1 - -# TODO: allow for gvim, but make sure it's some "vim". -# EDITOR=$(git config --get core.editor) -# if [ -z $EDITOR ]; EDITOR=vim ; fi - -if [ "$(basename "$FILE")" = "COMMIT_EDITMSG" ]; then - # NOTE: there is also a FileType autocommand for "gitcommit" in ~/.vimrc. - # -c "set foldmethod=syntax foldlevel=1 nohlsearch nospell sw=2 scrolloff=0" \ - # -c "g/^# \(Changes not staged\|Untracked files\)/norm zc" \ - # -c "normal zt" \ - # -c "set spell spl=en,de" \ - $EDITOR \ - -c "exe max([5, min([10, (winheight(0) / 3)])]).'split'" \ - -c "normal gg" \ - -c "command! Q qa" "$@" -else - $EDITOR "$@" -fi diff --git a/vim/ftplugin/gitcommit.vim b/vim/ftplugin/gitcommit.vim new file mode 100644 index 0000000..4fcd499 --- /dev/null +++ b/vim/ftplugin/gitcommit.vim @@ -0,0 +1,20 @@ +" Setup windows for Git commit message editing. +" It scrolls to "Changes" in the buffer, splits the window etc. +" This allows for reviewing the diff (from `git commit -v`) while editing the +" commit message easily. +if get(b:, 'fugitive_type', '') !=# 'index' " Skip with fugitive :Gstatus + let b:my_auto_scrolloff=0 + setlocal foldmethod=syntax foldlevel=1 nohlsearch spell spl=de,en sw=2 scrolloff=0 + + augroup vimrc_gitcommit + autocmd BufWinEnter <buffer> + \ exe 'g/^# \(Changes not staged\|Untracked files\)/norm! zc' + \ | silent! exe '?^# Changes to be committed:' + \ | exe 'norm! zt' + \ | belowright exe max([5, min([10, (winheight(0) / 3)])]).'split' + \ | exe 'normal! gg' + \ | if has('vim_starting') | exe 'autocmd VimEnter * nested 2wincmd w' | endif + \ | exe 'augroup vimrc_gitcommit | exe "au!" | augroup END' + \ | map <buffer> Q :qall<CR> + augroup END +endif diff --git a/vimrc b/vimrc index 5bb2453..0309cd6 100644 --- a/vimrc +++ b/vimrc @@ -3208,819 +3208,803 @@ nnoremap <silent> <F8> :TagbarToggle<CR> nnoremap <silent> <Leader><F8> :TagbarOpenAutoClose<CR> " VimFiler {{{2 let g:vimfiler_as_default_explorer = 1 let g:vimfiler_ignore_filters = ['matcher_ignore_wildignore'] " Netrw {{{2 " Short-circuit detection, which might be even wrong. let g:netrw_browsex_viewer = 'open-in-running-browser' " NERDTree {{{2 " Show hidden files *except* the known temp files, system files & VCS files let NERDTreeHijackNetrw = 0 let NERDTreeShowHidden = 1 let NERDTreeIgnore = [] for suffix in split(&suffixes, ',') let NERDTreeIgnore += [ escape(suffix, '.~') . '$' ] endfor let NERDTreeIgnore += ['^\.bundle$', '^\.bzr$', '^\.git$', '^\.hg$', '^\.sass-cache$', '^\.svn$', '^\.$', '^\.\.$', '^Thumbs\.db$'] let NERDTreeIgnore += ['__pycache__', '.ropeproject'] " }}} " TODO " noremap <Up> gk " noremap <Down> gj " (Cursor keys should be consistent between insert and normal mode) " slow! " inoremap <Up> <C-O>:normal gk<CR> " inoremap <Down> <C-O>:normal gj<CR> " " j,k move by screen line instead of file line. " nnoremap j gj " nnoremap k gk nnoremap <Down> gj nnoremap <Up> gk " inoremap <Down> <C-o>gj " inoremap <Up> <C-o>gk " XXX: does not keep virtual column! Also adds undo points! " inoremap <expr> <Down> pumvisible() ? "\<C-n>" : "\<C-o>gj" " inoremap <expr> <Up> pumvisible() ? "\<C-p>" : "\<C-o>gk" " Make C-BS and C-Del work like they do in most text editors for the sake of muscle memory {{{2 imap <C-BS> <C-W> imap <C-Del> <C-O>dw imap <C-S-Del> <C-O>dW " Map delete to 'delete to black hole register' (experimental, might use " `d` instead) " Join lines, if on last column, delete otherwise (used in insert mode) " NOTE: de-activated: misbehaves with '""' at end of line (autoclose), " and deleting across lines works anyway. The registers also do not " get polluted.. do not remember why I came up with it... " function! MyDelAcrossEOL() " echomsg col(".") col("$") " if col(".") == col("$") " " XXX: found no way to use '_' register " call feedkeys("\<Down>\<Home>\<Backspace>") " else " normal! "_x " endif " return '' " endfunction " noremap <Del> "_<Del> " inoremap <Del> <C-R>=MyDelAcrossEOL()<cr> " vnoremap <Del> "_<Del> " " Vaporize delete without overwriting the default register. {{{1 " nnoremap vd "_d " xnoremap x "_d " nnoremap vD "_D " }}} " Replace without yank {{{ " Source: https://github.com/justinmk/config/blob/master/.vimrc#L743 func! s:replace_without_yank(type) let sel_save = &selection let l:col = col('.') let &selection = "inclusive" if a:type == 'line' silent normal! '[V']"_d elseif a:type == 'block' silent normal! `[`]"_d else silent normal! `[v`]"_d endif if col('.') == l:col "paste to the left. silent normal! P else "if the operation deleted the last column, then the cursor "gets bumped left (because its original position no longer exists), "so we need to paste to the right instead of the left. silent normal! p endif let &selection = sel_save endf nnoremap <silent> rr :<C-u>set opfunc=<sid>replace_without_yank<CR>g@ nnoremap <silent> rrr 0:<C-u>set opfunc=<sid>replace_without_yank<CR>g@$ " }}} map _ <Plug>(operator-replace) function! TabIsEmpty() return winnr('$') == 1 && WindowIsEmpty() endfunction " Is the current window considered to be empty? function! WindowIsEmpty() if &ft == 'startify' return 1 endif return len(expand('%')) == 0 && line2byte(line('$') + 1) <= 2 endfunction function! MyEditConfig(path, ...) let cmd = a:0 ? a:1 : (WindowIsEmpty() ? 'e' : 'vsplit') exec cmd a:path endfunction " edit vimrc shortcut nnoremap <leader>ec :call MyEditConfig(resolve($MYVIMRC))<cr> nnoremap <leader>Ec :call MyEditConfig(resolve($MYVIMRC), 'edit')<cr> " edit zshrc shortcut nnoremap <leader>ez :call MyEditConfig(resolve("~/.zshrc"))<cr> " edit .lvimrc shortcut (in repository root) nnoremap <leader>elv :call MyEditConfig(ProjectRootGuess().'/.lvimrc')<cr> nnoremap <leader>em :call MyEditConfig(ProjectRootGuess().'/Makefile')<cr> nnoremap <leader>et :call MyEditConfig(expand('~/TODO'))<cr> nnoremap <leader>ept :call MyEditConfig(ProjectRootGet().'/TODO')<cr> " Utility functions to create file commands " Source: https://github.com/carlhuda/janus/blob/master/gvimrc " function! s:CommandCabbr(abbreviation, expansion) " execute 'cabbrev ' . a:abbreviation . ' <c-r>=getcmdpos() == 1 && getcmdtype() == ":" ? "' . a:expansion . '" : "' . a:abbreviation . '"<CR>' " endfunction " Open URL nmap <leader>gw <Plug>(openbrowser-smart-search) vmap <leader>gw <Plug>(openbrowser-smart-search) " Remap CTRL-W_ using vim-maximizer (smarter and toggles). nnoremap <silent><c-w>_ :MaximizerToggle<CR> vnoremap <silent><F3> :MaximizerToggle<CR>gv inoremap <silent><F3> <C-o>:MaximizerToggle<CR> " vimdiff current vs git head (fugitive extension) {{{2 " Close any corresponding fugitive diff buffer. function! MyCloseDiff() if (&diff == 0 || getbufvar('#', '&diff') == 0) \ && (bufname('%') !~ '^fugitive:' && bufname('#') !~ '^fugitive:') echom "Not in diff view." return endif diffoff " safety net / required to workaround powerline issue " Close current buffer if alternate is not fugitive but current one is. if bufname('#') !~ '^fugitive:' && bufname('%') =~ '^fugitive:' if bufwinnr("#") == -1 " XXX: might not work reliable (old comment) b # bd # else bd endif else bd # endif endfunction " nnoremap <Leader>gd :Gdiff<cr> " Maps related to version control (Git). {{{1 " Toggle `:Gdiff`. nnoremap <silent> <Leader>gd :if !&diff \|\| winnr('$') == 1 \| FollowSymlink \| Gdiff \| else \| call MyCloseDiff() \| endif <cr> nnoremap <Leader>gDm :Gdiff master:%<cr> nnoremap <Leader>gDom :Gdiff origin/master:%<cr> nnoremap <Leader>gDs :Gdiff stash:%<cr> " nnoremap <Leader>gD :Git difftool % nnoremap <Leader>gb :Gblame<cr> nnoremap <Leader>gl :Glog<cr> nnoremap <Leader>gs :Gstatus<cr> " Shortcuts for committing. nnoremap <Leader>gc :Gcommit -v command! -nargs=1 Gcm Gcommit -m <q-args> " }}}1 " "wincmd p" might not work initially, although there are two windows. fun! MyWincmdPrevious() let w = winnr() wincmd p if winnr() == w wincmd w endif endfun " Diff this window with the previous one. command! DiffThese diffthis | call MyWincmdPrevious() | diffthis | wincmd p command! DiffOff Windo diffoff " Toggle highlighting of too long lines {{{2 function! ToggleTooLongHL() if exists('*matchadd') if ! exists("w:TooLongMatchNr") let last = (&tw <= 0 ? 80 : &tw) let w:TooLongMatchNr = matchadd('ErrorMsg', '.\%>' . (last+1) . 'v', 0) echo " Long Line Highlight" else call matchdelete(w:TooLongMatchNr) unlet w:TooLongMatchNr echo "No Long Line Highlight" endif endif endfunction " noremap <silent> <leader>sl :call ToggleTooLongHL()<cr> " Capture output of a:cmd into a new tab via redirection " source: http://vim.wikia.com/wiki/Capture_ex_command_output function! RedirCommand(cmd, newcmd) " Default to "message" for command if empty(a:cmd) | let cmd = 'message' | else | let cmd = a:cmd | endif redir => message silent execute cmd redir END exec a:newcmd silent put=message " NOTE: 'ycmblacklisted' filetype used with YCM blacklist. " Needs patch: https://github.com/Valloric/YouCompleteMe/pull/830 set nomodified ft=vim.ycmblacklisted norm! gg endfunction command! -nargs=* -complete=command Redir call RedirCommand(<q-args>, 'tabnew') " cnoreabbrev TM TabMessage command! -nargs=* -complete=command Redirbuf call RedirCommand(<q-args>, 'new') command! Maps Redir map " fun! Cabbrev(key, value) " exe printf('cabbrev <expr> %s (getcmdtype() == ":" && getcmdpos() <= %d) ? %s : %s', " \ a:key, 1+len(a:key), string(a:value), string(a:key)) " endfun " " IDEA: requires expansion of abbr. " call Cabbrev('/', '/\v') " call Cabbrev('?', '?\v') " call Cabbrev('s/', 's/\v') " call Cabbrev('%s/', '%s/\v') " Make Y consistent with C and D / copy selection to gui-clipboard. {{{2 nnoremap Y y$ " copy selection to gui-clipboard xnoremap Y "+y " Cycle history. cnoremap <c-j> <up> cnoremap <c-k> <down> " Move without arrow keys. {{{2 inoremap <m-h> <left> inoremap <m-l> <right> inoremap <m-j> <down> inoremap <m-k> <up> cnoremap <m-h> <left> cnoremap <m-l> <right> " Folding {{{2 if has("folding") set foldenable set foldmethod=marker " set foldmethod=syntax " let javaScript_fold=1 " JavaScript " javascript: au! FileType javascript syntax region foldBraces start=/{/ end=/}/ transparent fold keepend extend | setlocal foldmethod=syntax " let perl_fold=1 " Perl " let php_folding=1 " PHP " let r_syntax_folding=1 " R " let ruby_fold=1 " Ruby " let sh_fold_enabled=1 " sh " let vimsyn_folding='af' " Vim script " let xml_syntax_folding=1 " XML set foldlevel=1 set foldlevelstart=1 " set foldmethod=indent " set foldnestmax=2 " set foldtext=strpart(getline(v:foldstart),0,50).'\ ...\ '.substitute(getline(v:foldend),'^[\ #]*','','g').'\ ' " set foldcolumn=2 " <2-LeftMouse> Open fold, or select word or % match. nnoremap <expr> <2-LeftMouse> foldclosed(line('.')) == -1 ? "\<2-LeftMouse>" : 'zo' endif if has('eval') " Windo/Bufdo/Tabdo which do not change window, buffer or tab. {{{1 " Source: http://vim.wikia.com/wiki/Run_a_command_in_multiple_buffers#Restoring_position " Like windo but restore the current window. function! Windo(command) let curaltwin = winnr('#') ? winnr('#') : 1 let currwin = winnr() execute 'windo ' . a:command execute curaltwin . 'wincmd w' execute currwin . 'wincmd w' endfunction com! -nargs=+ -complete=command Windo call Windo(<q-args>) " Like bufdo but restore the current buffer. function! Bufdo(command) let currBuff = bufnr("%") execute 'bufdo ' . a:command execute 'buffer ' . currBuff endfunction com! -nargs=+ -complete=command Bufdo call Bufdo(<q-args>) " Like tabdo but restore the current tab. function! Tabdo(command) let currTab=tabpagenr() execute 'tabdo ' . a:command execute 'tabn ' . currTab endfunction com! -nargs=+ -complete=command Tabdo call Tabdo(<q-args>) " }}}1 " Maps for fold commands across windows. for k in ['i', 'm', 'M', 'n', 'N', 'r', 'R', 'v', 'x', 'X'] execute "nnoremap <silent> Z".k." :Windo normal z".k."<CR>" endfor endif if has('user_commands') " typos command! -bang Q q<bang> command! W w command! Wq wq command! Wqa wqa endif "{{{2 Abbreviations " <C-g>u adds break to undo chain, see i_CTRL-G_u inoreabbr cdata <![CDATA[]]><Left><Left><Left> inoreabbr sg Sehr geehrte Damen und Herren,<cr> inoreabbr sgh Sehr geehrter Herr<space> inoreabbr sgf Sehr geehrte Frau<space> inoreabbr mfg Mit freundlichen Grüßen<cr><C-g>u<C-r>=g:my_full_name<cr> inoreabbr LG Liebe Grüße,<cr>Daniel. inoreabbr VG Viele Grüße,<cr>Daniel. " iabbr sig -- <cr><C-r>=readfile(expand('~/.mail-signature')) " sign "checkmark" inoreabbr scm ✓ " date timestamp. inoreabbr <expr> _dts strftime('%a, %d %b %Y %H:%M:%S %z') inoreabbr <expr> _ds strftime('%a, %d %b %Y') inoreabbr <expr> _dt strftime('%Y-%m-%d') " date timestamp with fold markers. inoreabbr dtsf <C-r>=strftime('%a, %d %b %Y %H:%M:%S %z')<cr><space>{{{<cr><cr>}}}<up> " German/styled quotes. inoreabbr <silent> _" „“<Left> inoreabbr <silent> _' ‚‘<Left> inoreabbr <silent> _- –<space> "}}} " Ignore certain files for completion (used also by Command-T). " NOTE: different from suffixes: those get lower prio, but are not ignored! set wildignore+=*.o,*.obj,.git,.svn set wildignore+=*.png,*.jpg,*.jpeg,*.gif,*.mp3 set wildignore+=*.mp4,*.pdf set wildignore+=*.sw? set wildignore+=*.pyc set wildignore+=*/__pycache__/* " allow for tab-completion in vim, but ignore them with command-t let g:CommandTWildIgnore=&wildignore \ .',htdocs/asset/*' \ .',htdocs/media/*' \ .',**/static/_build/*' \ .',**/node_modules/*' \ .',**/build/*' \ .',**/cache/*' \ .',**/.tox/*' " \ .',**/bower_components/*' let g:vdebug_keymap = { \ "run" : "<S-F5>", \} command! VdebugStart python debugger.run() " LocalVimRC {{{ let g:localvimrc_sandbox = 0 " allow to adjust/set &path let g:localvimrc_persistent = 1 " 0=no, 1=uppercase, 2=always " let g:localvimrc_debug = 3 let g:localvimrc_persistence_file = s:vimsharedir . '/localvimrc_persistent' " Helper method for .lvimrc files to finish fun! MyLocalVimrcAlreadySourced(...) " let sfile = expand(a:sfile) let sfile = g:localvimrc_script let guard_key = expand(sfile).'_'.getftime(sfile) if exists('b:local_vimrc_sourced') if type(b:local_vimrc_sourced) != type({}) echomsg "warning: b:local_vimrc_sourced is not a dict!" let b:local_vimrc_sourced = {} endif if has_key(b:local_vimrc_sourced, guard_key) return 1 endif else let b:local_vimrc_sourced = {} endif let b:local_vimrc_sourced[guard_key] = 1 return 0 endfun " }}} " vim-session / session.vim {{{ " Do not autoload/autosave 'default' session " let g:session_autoload = 'no' let g:session_autosave = "yes" let g:session_default_name = '' let g:session_command_aliases = 1 let g:session_persist_globals = [ \ '&sessionoptions', \ 'g:tmru_file', \ 'g:neomru#file_mru_path', \ 'g:neomru#directory_mru_path', \ 'g:session_autosave', \ 'g:MySessionName'] " call add(g:session_persist_globals, 'g:session_autoload') if has('nvim') call add(g:session_persist_globals, '&shada') endif let g:session_persist_colors = 0 let s:my_context = '' fun! MySetContextVars(...) let context = a:0 ? a:1 : '' if len(context) if &verbose | echom "Setting context:" context | endif let suffix = '_' . context else let suffix = '' endif " Use separate MRU files store. let g:tmru_file = s:global_tmru_file . suffix let g:neomru#file_mru_path = s:vimsharedir . '/neomru/file' . suffix let g:neomru#directory_mru_path = s:vimsharedir . '/neomru/dir' . suffix " Use a separate shada file per session, derived from the main/current one. if has('shada') && len(suffix) && &shada !~ ',n' let shada_file = s:xdg_data_home.'/nvim/shada/session-'.fnamemodify(context, ':t').'.shada' let &shada .= ',n'.shada_file if !filereadable(shada_file) wshada rshada endif endif let s:my_context = context endfun " Wrapper for .lvimrc files. fun! MySetContextFromLvimrc(context) if !g:localvimrc_sourced_once && !len(s:my_context) let lvimrc_dir = fnamemodify(g:localvimrc_script, ':p:h') if getcwd()[0:len(lvimrc_dir)-1] == lvimrc_dir call MySetContextVars(a:context) endif endif endfun " Setup session options. This is meant to be called once per created session. " The vars then get stored in the session itself. fun! MySetupSessionOptions() if len(get(g:, 'MySessionName', '')) call MyWarningMsg('MySetupSessionOptions: session is already configured' \ .' (g:MySessionName: '.g:MySessionName.').') return endif let sess_name = MyGetSessionName() if !len(sess_name) call MyWarningMsg('MySetupSessionOptions: this does not appear to be a session.') return endif call MySetContextVars(sess_name) endfun augroup VimrcSetupContext au! " Check for already set context (might come from .lvimrc). au VimEnter * if !len(s:my_context) | call MySetContextVars() | endif augroup END " }}} " xmledit: do not enable for HTML (default) " interferes too much, see issue https://github.com/sukima/xmledit/issues/27 " let g:xmledit_enable_html = 1 " indent these tags for ft=html let g:html_indent_inctags = "body,html,head,p,tbody" " do not indent these let g:html_indent_autotags = "br,input,img" " Setup late autocommands {{{ if has('autocmd') augroup vimrc_late au! - " See also ~/.dotfiles/usr/bin/vim-for-git, which uses this setup and - " additionally splits the window. - fun! MySetupGitCommitMsg() - if bufname("%") == '.git/index' - " fugitive :Gstatus - return - endif - set foldmethod=syntax foldlevel=1 - set nohlsearch nospell sw=4 scrolloff=0 - silent! g/^# \(Changes not staged\|Untracked files\|Changes to be committed\|Changes not staged for commit\)/norm zc - normal! zt - set spell spl=en,de - endfun - au FileType gitcommit call MySetupGitCommitMsg() - - " Detect indent. au FileType mail,make,python let b:no_detect_indent=1 au BufReadPost * if exists(':DetectIndent') | \ if !exists('b:no_detect_indent') || !b:no_detect_indent | \ exec 'DetectIndent' | \ endif | endif au BufReadPost * if &bt == "quickfix" | set nowrap | endif " Check if the new file (with git-diff prefix removed) is readable and " edit that instead (copy'n'paste from shell). " (for git diff: `[abiw]`). au BufNewFile * nested let fn = expand('<afile>') | \ if !filereadable(fn) | \ for pat in ['^\S/', '^\S\ze/'] | \ let new_fn = substitute(fn, pat, '', '') | \ if fn !=# new_fn && filereadable(new_fn) | \ exec 'edit '.new_fn | \ bdelete # | \ redraw | \ echomsg 'Got unreadable file, editing '.new_fn.' instead.' | \ break | \ endif | \ endfor | \ endif " Display a warning when editing foo.css, but foo.{scss,sass} exists. au BufRead *.css if &modifiable \ && (glob(expand('<afile>:r').'.s[ca]ss', 1) != "" \ || glob(substitute(expand('<afile>'), 'css', 's[ac]ss', 'g')) != "") \ | echoerr "WARN: editing .css, but .scss/.sass exists!" \ | set nomodifiable readonly \ | endif " Vim help files: modifiable (easier to edit for typo fixes); buflisted " for easier switching to them. au FileType help setl modifiable buflisted augroup END endif " }}} " delimitMate let delimitMate_excluded_ft = "unite" " let g:delimitMate_balance_matchpairs = 1 " let g:delimitMate_expand_cr = 1 " let g:delimitMate_expand_space = 1 " au FileType c,perl,php let b:delimitMate_eol_marker = ";" " (pre-)Override S-Tab mapping " Orig: silent! imap <unique> <buffer> <expr> <S-Tab> pumvisible() ? "\<C-p>" : "<Plug>delimitMateS-Tab" " Ref: https://github.com/Raimondi/delimitMate/pull/148#issuecomment-29428335 " NOTE: mapped by SuperTab now. " imap <buffer> <expr> <S-Tab> pumvisible() ? "\<C-p>" : "<Plug>delimitMateS-Tab" if has('vim_starting') " only do this on startup, not when reloading .vimrc " Don't move when you use * " nnoremap <silent> * :let stay_star_view = winsaveview()<cr>*:call winrestview(stay_star_view)<cr> endif " Map alt sequences for terminal via Esc. " source: http://stackoverflow.com/a/10216459/15690 " NOTE: <Esc>O is used for special keys (e.g. OF (End)) " NOTE: drawback (with imap) - triggers timeout for Esc: use jk/kj, " or press it twice. " NOTE: Alt-<NR> mapped in tmux. TODO: change this?! if ! has('nvim') && ! has('gui_running') fun! MySetupAltMapping(c) " XXX: causes problems in macros: <Esc>a gets mapped to á. " Solution: use <C-c> / jk in macros. exec "set <A-".a:c.">=\e".a:c endfun for [c, n] in items({'a':'z', 'A':'N', 'P':'Z', '0':'9'}) while 1 call MySetupAltMapping(c) if c >= n break endif let c = nr2char(1+char2nr(c)) endw endfor " for c in [',', '.', '-', 'ö', 'ä', '#', 'ü', '+', '<'] for c in [',', '.', '-', '#', '+', '<'] call MySetupAltMapping(c) endfor endif " Fix (shifted, altered) function and special keys in tmux. {{{ " (requires `xterm-keys` option for tmux, works with screen). " Ref: http://unix.stackexchange.com/a/58469, http://superuser.com/a/402084/30216 " See also: https://github.com/nacitar/terminalkeys.vim/blob/master/plugin/terminalkeys.vim " With tmux' 'xterm-keys' option, we can make use of these. {{{ " Based on tmux's examples/xterm-keys.vim. " NOTE: using this always, with adjusted urxvt keysym. execute "set <xUp>=\e[1;*A" execute "set <xDown>=\e[1;*B" execute "set <xRight>=\e[1;*C" execute "set <xLeft>=\e[1;*D" " NOTE: xHome/xEnd used with real xterm " execute "set <xHome>=\e[1;*H" " execute "set <xEnd>=\e[1;*F" " also required for xterm hack with urxvt. execute "set <Insert>=\e[2;*~" execute "set <Delete>=\e[3;*~" execute "set <PageUp>=\e[5;*~" execute "set <PageDown>=\e[6;*~" " NOTE: breaks real xterm " execute "set <xF1>=\e[1;*P" " execute "set <xF2>=\e[1;*Q" " execute "set <xF3>=\e[1;*R" " execute "set <xF4>=\e[1;*S" execute "set <F5>=\e[15;*~" execute "set <F6>=\e[17;*~" execute "set <F7>=\e[18;*~" execute "set <F8>=\e[19;*~" execute "set <F9>=\e[20;*~" execute "set <F10>=\e[21;*~" execute "set <F11>=\e[23;*~" execute "set <F12>=\e[24;*~" " }}} " Change cursor shape for terminal mode. {{{1 " See also ~/.dotfiles/oh-my-zsh/themes/blueyed.zsh-theme. " Note: with neovim, this gets controlled via $NVIM_TUI_ENABLE_CURSOR_SHAPE. if has('nvim') let $NVIM_TUI_ENABLE_CURSOR_SHAPE = 1 elseif exists('&t_SI') " 'start insert' and 'exit insert'. if $_USE_XTERM_CURSOR_CODES == 1 " Reference: {{{ " P s = 0 → blinking block. " P s = 1 → blinking block (default). " P s = 2 → steady block. " P s = 3 → blinking underline. " P s = 4 → steady underline. " P s = 5 → blinking bar (xterm, urxvt). " P s = 6 → steady bar (xterm, urxvt). " Source: http://vim.wikia.com/wiki/Configuring_the_cursor " }}} let &t_SI = "\<Esc>[5 q" let &t_EI = "\<Esc>[1 q" " let &t_SI = "\<Esc>]12;purple\x7" " let &t_EI = "\<Esc>]12;blue\x7" " mac / iTerm?! " let &t_SI = "\<Esc>]50;CursorShape=1\x7" " let &t_EI = "\<Esc>]50;CursorShape=0\x7" elseif $KONSOLE_PROFILE_NAME =~ "^Solarized.*" let &t_EI = "\<Esc>]50;CursorShape=0;BlinkingCursorEnabled=1\x7" let &t_SI = "\<Esc>]50;CursorShape=1;BlinkingCursorEnabled=1\x7" elseif &t_Co > 1 && $TERM != "linux" " Fallback: change only the color of the cursor. let &t_SI = "\<Esc>]12;#0087ff\x7" let &t_EI = "\<Esc>]12;#5f8700\x7" endif endif " Wrap escape codes for tmux. " NOTE: wrapping it acts on the term, not just on the pane! " if len($TMUX) " let &t_SI = "\<Esc>Ptmux;\<Esc>".&t_SI."\<Esc>\\" " let &t_EI = "\<Esc>Ptmux;\<Esc>".&t_EI."\<Esc>\\" " endif " }}} " Delete all but the current buffer. {{{ " Source: http://vim.1045645.n5.nabble.com/Close-all-buffers-except-the-one-you-re-in-tp1183357p1183361.html com! -bar -bang BDOnly call s:BdOnly(<q-bang>) func! s:BdOnly(bang) let bdcmd = "bdelete". a:bang let bnr = bufnr("") if bnr > 1 call s:ExecCheckBdErrs("1,".(bnr-1). bdcmd) endif if bnr < bufnr("$") call s:ExecCheckBdErrs((bnr+1).",".bufnr("$"). bdcmd) endif endfunc func! s:ExecCheckBdErrs(bdrangecmd) try exec a:bdrangecmd catch /:E51[567]:/ " no buffers unloaded/deleted/wiped out: ignore catch echohl ErrorMsg echomsg matchstr(v:exception, ':\zsE.*') echohl none endtry endfunc " }}} " Automatic swapfile handling. augroup VimrcSwapfileHandling au! au SwapExists * call MyHandleSwapfile(expand('<afile>:p')) augroup END fun! MyHandleSwapfile(filename) " If swapfile is older than file itself, just get rid of it. if getftime(v:swapname) < getftime(a:filename) call MyWarningMsg('Old swapfile detected, and deleted.') call delete(v:swapname) let v:swapchoice = 'e' else call MyWarningMsg('Swapfile detected, opening read-only.') let v:swapchoice = 'o' endif endfun let g:quickfixsigns_protect_sign_rx = '^neomake_' " Python setup for NeoVim. {{{ " Defining it also skips auto-detecting it. if has("nvim") " Arch Linux, with python-neovim packages. if len(glob('/usr/lib/python2*/site-packages/neovim/__init__.py', 1)) let g:python_host_prog="/usr/bin/python2" endif if len(glob('/usr/lib/python3*/site-packages/neovim/__init__.py', 1)) let g:python3_host_prog="/usr/bin/python3" endif fun! s:get_python_from_pyenv(ver) if !len($PYENV_ROOT) return endif " XXX: Rather slow. " let ret=system('pyenv which python'.a:ver) " if !v:shell_error && len(ret) " return ret " endif " XXX: should be natural sort and/or look for */lib/python3.5/site-packages/neovim/__init__.py. let files = sort(glob($PYENV_ROOT."/versions/".a:ver.".*/bin/python", 1, 1), "n") if len(files) return files[-1] endif echohl WarningMsg | echomsg "Could not find Python" a:ver "through pyenv!" | echohl None endfun if !exists('g:python3_host_prog') " let g:python3_host_prog = "python3" let g:python3_host_prog=s:get_python_from_pyenv(3) if !len('g:python3_host_prog') echohl WarningMsg | echomsg "Could not find python3 for g:python3_host_prog!" | echohl None endif endif if !exists('g:python_host_prog') " Use the Python 2 version YCM was built with. if len($PYTHON_YCM) && filereadable($PYTHON_YCM) let g:python_host_prog=$PYTHON_YCM " Look for installed Python 2 with pyenv. else let g:python_host_prog=s:get_python_from_pyenv(2) endif if !len('g:python_host_prog') echohl WarningMsg | echomsg "Could not find python2 for g:python_host_prog!" | echohl None endif endif " Avoid loading python3 host: YCM uses Python2 anyway, so prefer it for " UltiSnips, too. if s:use_ycm && has('nvim') && len(get(g:, 'python_host_prog', '')) let g:UltiSnipsUsePythonVersion = 2 endif endif " }}} " Patch: https://code.google.com/p/vim/issues/detail?id=319 if exists('+belloff') set belloff+=showmatch endif " Local config (if any). {{{1 if filereadable(expand("~/.vimrc.local")) source ~/.vimrc.local endif " vim: fdm=marker foldlevel=0
blueyed/dotfiles
0e6518e28f2931f94d39dec1d3f91d4e3a7923f7
git: use EDITOR
diff --git a/config/git/config b/config/git/config index ba1d40b..6cb555c 100644 --- a/config/git/config +++ b/config/git/config @@ -1,218 +1,216 @@ # vim: ft=gitconfig [user] name = Daniel Hahler email = [email protected] [init] templatedir = ~/.config/git/template [alias] # NOTE: I am using full aliases for most of this, e.g. "ga" for "git add". amend = commit --amend -v # use "aliases" instead of "alias", which is used by hub; ref: https://github.com/defunkt/hub/issues/303 aliases = !git config --get-regexp '^alias\\.' | sed -e 's/^alias\\.//' -e 's/ / /' | sort cp = cherry-pick dd = !git difftool --no-prompt --tool=my-icdiff dsf = !git diff --color $@ | diff-so-fancy desc = describe --all --always dv = !git diff -w "$@" | vim -R - f = fetch # Used (verbatim/resolved) for internal dirty status in shell theme (✗). ls-untracked = ls-files --other --directory --exclude-standard m = merge mf = merge --ff-only ma = merge --abort mm = merge --no-edit mmm = merge -X theirs --no-edit # preview/temp merge mp = merge --no-commit rb = rebase -i @{u} rba = rebase --abort rbc = rebase --continue rbi = rebase --interactive rbs = rebase --skip rl = reflog @{now} rlf = reflog --pretty=reflog s = status st = status sm = submodule sta = stash --keep-index sts = stash show -p stp = stash pop stl = stash list --format=\"%gd: %ci - %gs\" up = !git fetch && git rebase showtrackedignored = ! cd \"${GIT_PREFIX}\" && untracked_list=$(git rev-parse --git-dir)/ignored-untracked.txt && git ls-files -o -i --exclude-standard >\"${untracked_list}\" && GIT_INDEX_FILE=\"\" git ls-files -o -i --exclude-standard | grep -Fvxf \"${untracked_list}\" && rm -rf \"${untracked_list}\" # Diff stash with working tree. # This is used to decide, if a stash can be savely dropped. stash-diff = !zsh -c 'bcompare =(git stash show -p --no-prefix) =(git diff --no-prefix)' cfg = !$EDITOR $(readlink -f ~/.gitconfig) # Based on http://haacked.com/archive/2014/07/28/github-flow-aliases/. # wipe: reset --hard with savepoint. wipe = "!f() { rev=$(git rev-parse ${1-HEAD}); \ git add -A && git commit --allow-empty -qm 'WIPE SAVEPOINT' \ && git reset $rev --hard; }; f" # Merge file contents from another branch. # Source: http://stackoverflow.com/a/24544974/15690 mergetool-file = "!sh -c 'git show $1:$2 > $2.theirs \ && git show $(git merge-base $1 $(git rev-parse HEAD)):$2 > $2.base \ && bcompare $2.theirs $2 $2.base $2 && { rm -f $2.theirs; rm -f $2.base; }' -" [browser "open-in-running-browser"] cmd = open-in-running-browser [web] browser = open-in-running-browser [color] diff = auto status = auto branch = auto ui = true [color "branch"] current = green # current = yellow reverse local = normal remote = blue [color "decorate"] # bold green by default. branch = green # bold red by default. remoteBranch = bold green # default: bold yellow. # tag = green # default: bold magenta. # stash = red # default: bold cyan. # HEAD = green bold # default: bold blue. # grafted = [color "diff"] meta = yellow bold commit = green bold frag = magenta bold old = red bold new = green bold whitespace = red reverse [color "diff-highlight"] # oldNormal = red bold # oldHighlight = red bold 52 # newNormal = green bold # newHighlight = green bold 22 [color "status"] added = yellow changed = green untracked = cyan [core] - # See also GIT_EDITOR. - editor = vim # use default.. # whitespace=fix,-indent-with-non-tab,trailing-space,cr-at-eol,blank-at-eol # -F: --quit-if-one-screen: Quit if entire file fits on first screen. # -X: --no-init: Don't use termcap init/deinit strings. # pager = less --no-init --quit-if-one-screen -+S pager = less -S --no-init --quit-if-one-screen # -+F/-+X to override LESS selectively?! (http://stackoverflow.com/a/18781512/15690) # pager = less -+F -+X [diff] tool = vimdiff guitool = bc3 mnemonicprefix = true compactionHeuristic = true [difftool "my-icdiff"] cmd = icdiff --line-numbers --head 5000 "$LOCAL" "$REMOTE" [difftool "bc3"] cmd = bcompare $LOCAL $REMOTE [difftool] prompt = false [difftool "vimdiff"] path = nvim [merge] tool = vimdiff # http://sjl.bitbucket.org/splice.vim/ # tool = splice stat = true ff = no # Insert common ancestor in conflict hunks. conflictstyle = diff3 [mergetool "splice"] cmd = "vim -f $BASE $LOCAL $REMOTE $MERGED -c 'SpliceInit'" trustExitCode = true [mergetool "bc3"] # Not required (anymore?)?! # cmd = bcompare $LOCAL $REMOTE $BASE $MERGED trustExitCode = true [merge "dpkg-mergechangelogs"] name = debian/changelog merge driver driver = dpkg-mergechangelogs -m %O %A %B %A # "git-meld": [treediff] tool = bc3 [treediff "bc3"] cmd = bcompare [log] abbrevCommit = true decorate = short [pretty] # reflog, with relative date (but for commits, not reflog entries!): reflog = %C(auto)%h %<|(17)%gd %<|(31)%C(blue)%cr%C(reset) %gs (%s) [push] # "simple" not available with Git 1.7.10 (Debian stable), "current" is similar. default = simple [interactive] # Requires perl-term-readkey (Arch) / libterm-readkey-perl (Debian). singlekey = true [url "[email protected]:"] insteadOf = github: [url "git://github.com/"] insteadOf = gitpub: [github] user = blueyed [diff "odf"] binary = true textconv = odt2txt [url "ssh://[email protected]/"] pushInsteadOf = git://github.com/ pushInsteadOf = https://github.com/ [diff-so-fancy] # changeHunkIndicators = false stripLeadingSymbols = false markEmptyLines = false [pager] dd = true dsf = true icdiff = true status = true diff = ~/.dotfiles/lib/diff-so-fancy/diff-so-fancy | $(git config core.pager) log = ~/.dotfiles/lib/diff-so-fancy/diff-so-fancy | $(git config core.pager) show = ~/.dotfiles/lib/diff-so-fancy/diff-so-fancy | $(git config core.pager) [sendemail] confirm = always [rerere] enabled = true [rebase] autosquash = 1 [grep] patternType = perl lineNumber = true # TODO: should be set for Tk/tcl globally probably?! [gui] fontui = -family \"Liberation Sans\" -size 10 -weight normal -slant roman -underline 0 -overstrike 0 fontdiff = -family \"Liberation Mono\" -size 8 -weight normal -slant roman -underline 0 -overstrike 0
blueyed/dotfiles
2cc6e23db5393cb7dda2cbd7467d26611e5260f8
ctags: look for local .ctags files
diff --git a/ctags b/ctags index f07efae..9cf3e7c 100644 --- a/ctags +++ b/ctags @@ -1,26 +1,30 @@ --fields=+ln --c-kinds=+p --c++-kinds=+p # Python: v are class members?! l are local vars. (with universal-ctags) # --python-kinds=-iv --langmap=php:.engine.inc.module.theme.install.php.php3.php4.php5.phtml --langmap=sh:+(zshrc).zsh-theme --langmap=vim:+.vader --exclude=.tox --exclude=build --exclude=.build* # Arch package dirs. --exclude=pkg --languages=-json # Fails with --append? # --tag-relative=yes # Look for shebangs/modelines. --guess-language-eagerly # Nix; source: https://github.com/NixOS/nixpkgs/blob/master/pkgs/development/tools/misc/ctags/wrapped.nix --langdef=NIX --langmap=NIX:.nix --regex-NIX=/(\S+)\s*=.*:/\1/f/ --regex-NIX=/^\s*(\S+)\s*=/\1/v/ + +# Look at .ctags for extra options. +# This can be used to ignore certain files per repo. +--options-maybe=./.ctags
blueyed/dotfiles
eaa4f4e8ee2768b421d13cca6fdc911efec77c8f
Fix usr/bin/open-in-running-browser
diff --git a/usr/bin/open-in-running-browser b/usr/bin/open-in-running-browser index 8c4f56f..b8bdeee 100755 --- a/usr/bin/open-in-running-browser +++ b/usr/bin/open-in-running-browser @@ -1,32 +1,32 @@ #!/bin/sh # Pass through all arguments to the first running program from a list. # Fall back to $default. # # When used as default browser, it will prefer a running instance of Chrome # instead of launching Firefox (default). default=qutebrowser browsers="$default firefox chromium google-chrome-stable google-chrome /opt/google/chrome/chrome" this_tty=$(get-tty) for browser in $browsers; do - for pid in $(pgrep -f "$browser"); do - pid_tty=$(get-tty $pid) + for pid in $(pgrep "$browser"); do + pid_tty=$(get-tty "$pid") if [ "$pid_tty" = "$this_tty" ]; then $browser "$@" & if [ "$(ps -o state= "$pid")" = T ]; then kill -CONT "$pid" fi if [ -n "$DESKTOP_STARTUP_ID" ] && hash awesome-client 2>/dev/null; then echo "awesome.emit_signal('spawn::completed', {id='$DESKTOP_STARTUP_ID'})" | awesome-client fi exit 0 fi done done exec $default "$@"
blueyed/dotfiles
04bdaef34de6a4c1d86ff3e84c69ac2d8ce85bc0
usr/bin/sh-setup-x-theme: rename var for config file
diff --git a/usr/bin/sh-setup-x-theme b/usr/bin/sh-setup-x-theme index 8b3fee7..6587fa8 100755 --- a/usr/bin/sh-setup-x-theme +++ b/usr/bin/sh-setup-x-theme @@ -1,268 +1,268 @@ #!/bin/sh # # Change X/xrdb theme between light/dark (solarized). # # This script's output is meant to be eval'd. # It is used from my Zsh theme and in ~/.xsessionrc. # See the theme_variant function for a wrapper arount it. # # $1: theme to use: auto/light/dark. # $2: "save" to save the value to the config file. # # MY_X_THEME_VARIANT: set to the effective variant: "light" or "dark". # # TODO: query urxvt's current bg and use it for dircolors. # see ~/bin/query-urxvt and ~/bin/xterm-bg. -X_THEME_VARIANT_CONFIG_FILE=~/.config/x-theme-variant +config_file=~/.config/x-theme-variant # set -x # date >>/tmp/debug-sh-setup-x-theme.log # exec 2>>/tmp/debug-sh-setup-x-theme.log debug() { if [ -n "$DEBUG" ]; then echo "$(date +%FT%T) [sh-setup-x-theme] $*" >&2 fi # echo "$(date +%FT%T) [sh-setup-x-theme:$$:$(ps -o cmd= $$)] $@" >> /tmp/debug-sh-setup-x-theme.log } get_variant_from_config() { if [ -n "$TMUX" ]; then tmux_variant="$(tmux show-env MY_X_THEME_VARIANT 2>/dev/null | cut -d= -f 2)" config_variant="$tmux_variant" debug "variant from tmux: $config_variant" fi if [ -z "$config_variant" ]; then - if [ -f $X_THEME_VARIANT_CONFIG_FILE ]; then - config_variant=$(cat $X_THEME_VARIANT_CONFIG_FILE) + if [ -f $config_file ]; then + config_variant=$(cat $config_file) debug "variant from cfg: $config_variant" else - debug "Config file ($X_THEME_VARIANT_CONFIG_FILE) does not exist." + debug "Config file ($config_file) does not exist." fi if [ -z "$config_variant" ]; then config_variant=auto debug "variant from fallback: $config_variant" fi fi } # Init once and export the value. # This gets used in Vim to auto-set the background, too. # Handle options, in this case it does not / should not get sourced. while [ "${1#-*}" != "$1" ]; do case "$1" in -d ) DEBUG=1 ;; -f ) FORCE=1 ;; -s ) SHELL_ONLY=1 ;; -q ) # Query/info. echo "Current theme variant: MY_X_THEME_VARIANT=$MY_X_THEME_VARIANT." echo "BASE16_THEME: $BASE16_THEME." get_variant_from_config if [ -n "$tmux_variant" ]; then echo "Theme from tmux: $config_variant." else echo "Theme from config: $config_variant." fi echo "Use 'auto', 'dark' or 'light' to change it." exit ;; *) echo "Unknown option: $1"; exit 1; ;; esac shift done debug "RUN: $0 $*" given_variant=$1 debug "Requested variant: $given_variant" # No argument provided: read config/env. if [ -z "$given_variant" ]; then get_variant_from_config given_variant="$config_variant" SAVE_VARIANT=0 else FORCE=1 if [ "$SHELL_ONLY" != 1 ]; then SAVE_VARIANT=1 fi fi variant="$given_variant" debug "given_variant: $given_variant" # Refresh terminal stuff (base16, dircolors) in a new urxvt instance. TTY="$(tty)" if [ "$FORCE" = 1 ] || [ "$_MY_X_THEME_VARIANT_TTY" != "$TTY" ]; then REFRESH_TERM=1 fi echo "export _MY_X_THEME_VARIANT_TTY=\$TTY" # Get auto-theme from get-daytime-period for "auto", # and validate value. case $variant in auto) dt_period="$(~/.dotfiles/usr/bin/get-daytime-period)" if [ "$dt_period" = 'Daytime' ]; then variant=light elif [ -n "$dt_period" ]; then variant=dark else echo "get-daytime-period failed. Using 'dark' variant." >&2 variant=dark fi debug "=> variant: $variant" ;; light|dark ) ;; * ) echo "Invalid variant: $variant" >&2; exit 64 esac # curbg="$(xrdb -query|sed -n -e '/^\*background:/ {p;q}' | tr -d '[:space:]' | cut -f2 -d:)" # if [[ $curbg == '#fdf6e3' ]]; then # if [[ $variant == "dark" ]]; then # # xrdb -DSOLARIZED_DARK ~/.Xresources # xrdb -merge ~/.dotfiles/lib/solarized-xresources/Xresources.dark # changed_xrdb=1 # fi # elif [[ $variant == "light" ]]; then # # xrdb -DSOLARIZED_LIGHT ~/.Xresources # xrdb -merge ~/.dotfiles/lib/solarized-xresources/Xresources.light # changed_xrdb=1 # fi if [ -n "$DISPLAY" ] && [ "$USER" != "root" ] && [ "$SHELL_ONLY" != 1 ] \ && [ -z "$TMUX" ] && hash xrdb 2>/dev/null; then # Query "mythemevariant" resource, used to hold the current state. # Unset by default in ~/.Xresources. cur_xrdb_theme="$(xrdb -query|sed -n -E -e '/mythemevariant:\t/ {s/.*:\t//p;q}')" debug "cur_xrdb_theme=$cur_xrdb_theme" if [ "$FORCE" = 1 ] || [ "$cur_xrdb_theme" != "$variant" ]; then if [ "$variant" = dark ]; then xrdb -DSOLARIZED_DARK -I"$HOME" -merge ~/.Xresources elif [ "$variant" = light ]; then xrdb -DSOLARIZED_LIGHT -I"$HOME" -merge ~/.Xresources fi echo "mythemevariant: $variant" | xrdb -merge echo "Changed X/xrdb theme variant to $variant." >&2 fi fi DIRCOLORS_FILE=~/.dotfiles/lib/LS_COLORS/LS_COLORS # Setup dircolors once. if [ -n "$DIRCOLORS_FILE" ] \ && ([ "$REFRESH_TERM" = 1 ] || [ "$DIRCOLORS_SETUP" != "$DIRCOLORS_FILE" ]); then debug "Setting up DIRCOLORS_FILE=$DIRCOLORS_FILE" debug "DIRCOLORS_SETUP=$DIRCOLORS_SETUP" if [ -n "$DIRCOLORS_SETUP" ]; then debug "Adjusting dircolors for variant=$variant." else debug "TODO: dircolors only during .xresources ($(basename "$0"))." fi # debug "running: dircolors -b $DIRCOLORS_FILE" echo "$(dircolors -b $DIRCOLORS_FILE);" echo "export DIRCOLORS_SETUP=$DIRCOLORS_FILE" fi # Used in ~/.vimrc. echo "export MY_X_THEME_VARIANT=$variant;" # Configure colors for fzf. if hash fzf 2>/dev/null; then if [ -z "$_FZF_DEFAULT_OPTS_BASE" ]; then echo "export _FZF_DEFAULT_OPTS_BASE=\"\$FZF_DEFAULT_OPTS\"" fi [ $variant = "light" ] && bg=21 || bg=18 echo "export FZF_DEFAULT_OPTS='$_FZF_DEFAULT_OPTS_BASE --color 16,bg+:$bg'" fi # Update tmux env, after sending escape codes eventually, which the # "tmux display" might prevent to work correctly (?!). (might be obsolete) # This also inits it initially. if [ -n "$TMUX" ]; then # && [ "$SHELL_ONLY" != 1 ]; then COLORS="$(tput colors)" if [ "$COLORS" -lt 16 ]; then debug "SKIP tmux: not enough colors ($COLORS are available (via 'tput colors'); TERM=$TERM)." else debug "tmux_variant: $tmux_variant" tmux_tmp_conf="$(mktemp)" if [ -z "$tmux_variant" ]; then echo "echo 'theme-variant: setting tmux env: $variant.'" tmux_session="$(tmux display-message -p '#S')" tmux_windows= for w in $(tmux list-windows -t "$tmux_session" -F '#{window_id}'); do sed -n "s/ -g//; /^set /p; /^if/p; s/^\s*setw /\0-t $w /p" "$HOME/.dotfiles/lib/tmux-colors-solarized/tmuxcolors-$variant.conf" >> "$tmux_tmp_conf" done else # echo "echo 'theme-variant: styling new tmux window ($variant).'" tmux_windows="" sed -n "s/ -g//; /^set /p; /^if/p; s/^\s*setw /\0$tmux_windows/p" "$HOME/.dotfiles/lib/tmux-colors-solarized/tmuxcolors-$variant.conf" > "$tmux_tmp_conf" fi echo "tmux set-env MY_X_THEME_VARIANT $variant" echo "tmux source $tmux_tmp_conf" echo "rm '$tmux_tmp_conf'" fi fi # Setup base16-shell. if [ "$REFRESH_TERM" = 1 ] || [ "${BASE16_THEME##*.}" != "$variant" ]; then if [ "${TERM%%-*}" = 'linux' ]; then echo "Skipping base16-shell with TERM=linux." >&2 else echo "base16_theme solarized.$variant" if [ -n "$TMUX" ]; then # shellcheck disable=SC2016 echo 'tmux set-environment BASE16_THEME "$BASE16_THEME"' fi fi fi if [ "$MY_X_THEME_VARIANT" != "$variant" ] || [ "$FORCE" = 1 ]; then if [ "${COLORTERM#rxvt}" != "$COLORTERM" ]; then if [ "$variant" = light ]; then escape_codes='\033]11;#fdf6e3\007 \033]10;#657b83\007 \033]12;#586e75\007 \033]13;#586e75\007 \033]708;#fdf6e3\007 \033]709;#fdf6e3\007' else escape_codes='\033]11;#002b36\007 \033]10;#839496\007 \033]12;#93a1a1\007 \033]13;#93a1a1\007 \033]708;#002b36\007 \033]709;#657b83\007' fi cat <<EOF _printf_for_tmux() { local i="\$1" if [ -n "\$TMUX" ]; then i="\\ePtmux;\\e\$i\\e\\\\" fi printf '%b' "\$i" } EOF for i in $escape_codes; do echo "_printf_for_tmux '$i'" done fi fi if [ "$SAVE_VARIANT" = 1 ]; then # Save given value. case $variant in auto) if [ -n "$TMUX" ]; then tmux set-env -u MY_X_THEME_VARIANT - elif [ -f "$X_THEME_VARIANT_CONFIG_FILE" ]; then - rm "$X_THEME_VARIANT_CONFIG_FILE" + elif [ -f "$config_file" ]; then + rm "$config_file" fi ;; light|dark) if [ -n "$TMUX" ]; then tmux set-env MY_X_THEME_VARIANT "$variant" echo "Saved variant=$1 in tmux." >&2 else - echo "$1" > "$X_THEME_VARIANT_CONFIG_FILE" + echo "$1" > "$config_file" echo "Saved variant=$1." >&2 fi ;; * ) echo "Invalid variant: $variant" >&2; exit 64 esac fi
blueyed/dotfiles
18ae76e74c4b0c419444b975b0237001f6259db1
revisit get-daytime-period (shellcheck, hide waiting msg)
diff --git a/usr/bin/get-daytime-period b/usr/bin/get-daytime-period index fb97b37..7c999c0 100755 --- a/usr/bin/get-daytime-period +++ b/usr/bin/get-daytime-period @@ -1,90 +1,90 @@ #!/bin/sh # # Get/print the daytime period ("Night", "Day), possibly from redshift # ("Night" / "Daytime" / "Transition"). # # This uses DEFAULT_LATLON by default, because the geoclue provider is too # fragile. The result is cached for 10 minutes. is_remote() { [ -n "$SSH_CONNECTION" ] && return # Container in OpenVZ? [ -r /proc/user_beancounters ] && ! [ -d /proc/bc ] } is_remote && USE_REDSHIFT=0 || USE_REDSHIFT=1 # Do not use geoclue by default, too slow and fragile. # TODO: provide a method to easily update the latlonfile. USE_GEOCLUE=0 GEOCLUE_TIMEOUT=2s CACHE_SECONDS=600 if [ "$USE_REDSHIFT" = 1 ] && ! hash redshift 2> /dev/null; then echo "redshift not found." >&2 USE_REDSHIFT=0 fi cachefile=/tmp/redshift-period ok_to_cache=1 get_period_by_hour() { hour=$(date +%H) if [ "$hour" -gt 8 ] && [ "$hour" -lt 20 ]; then - echo -n "Daytime" + printf "Daytime" else - echo -n "Night" + printf "Night" fi } # If not using `redshift`, just look at the current hour. if [ "$USE_REDSHIFT" = 0 ]; then get_period_by_hour exit fi if [ -e "$cachefile" ]; then - if [ `stat --format=%Y $cachefile` -gt $(( `date +%s` - $CACHE_SECONDS )) ]; then + if [ "$(stat --format=%Y $cachefile)" -gt $(( $(date +%s) - CACHE_SECONDS )) ]; then cat $cachefile exit fi fi # Try geoclue. if [ "$USE_GEOCLUE" = 1 ]; then geoclue_period=$(timeout $GEOCLUE_TIMEOUT redshift -l geoclue2 -p 2>/dev/null) timeout_ret=$? if [ "$timeout_ret" = 0 ]; then period=$(echo "$geoclue_period" | grep "^Period") else if [ "$timeout_ret" = 124 ]; then echo 'WARNING: redshift with geoclue timed out.' >&2 else echo "WARNING: redshift failed with exit code $timeout_ret." >&2 fi ok_to_cache=0 fi fi if [ -z "$period" ]; then # Default lat/lon when geoclue is not used. DEFAULT_LATLON="$(dotfiles-decrypt U2FsdGVkX19nvkwAQ0jDg1/aA1DNhQuSu3024+/3hruhmpNKhmm0ymufkCmmhrwf)" if [ -z "$DEFAULT_LATLON" ]; then - echo "ERROR: $(basename $0): DEFAULT_LATLON is not defined." >&2 + echo "ERROR: $(basename "$0"): DEFAULT_LATLON is not defined." >&2 exit 1 fi - period=$(redshift -l "$DEFAULT_LATLON" -p | grep "^Period") + period=$(redshift -l "$DEFAULT_LATLON" -p 2>/dev/null | grep "^Period") fi if [ -z "$period" ]; then echo "WARNING: failed to determine period using redshift." >&2 echo "Falling back to get_period_by_hour." >&2 get_period_by_hour exit fi -period=$(echo $period | cut -d\ -f2) +period="${period#Period: }" if [ "$ok_to_cache" = 1 ]; then - echo -n $period > $cachefile + printf '%s' "$period" > $cachefile fi -echo -n $period +printf '%s' "$period"
blueyed/dotfiles
8e831404ace21c4f7a474b7a873c8813c950403e
usr/bin/mktmpenv: use venv options
diff --git a/usr/bin/mktmpenv b/usr/bin/mktmpenv index e26b5b6..aabe3be 100755 --- a/usr/bin/mktmpenv +++ b/usr/bin/mktmpenv @@ -1,42 +1,43 @@ #!/bin/sh set -e # set -x # Make sure pyenv and pyenv-virtualenv is setup. eval "$(pyenv init -)" eval "$(pyenv virtualenv-init -)" venv_options= while [ "${1#-}" != "$1" ]; do venv_options="$venv_options $1" shift done if [ -n "$1" ]; then pyenv_version="$1" else pyenv_version=$(pyenv version-name | sed 's/:.*//') fi if [ -n "$2" ]; then venv_name="$2" else # Use -u (short for --dry-run) for compatibility (MacOS). venv_name=$(mktemp -u -d "tmp-${pyenv_version}-${PWD##*/}-XXXXXX") fi -pyenv virtualenv "${pyenv_version}" "${venv_name}" +# shellcheck disable=SC2086 +pyenv virtualenv $venv_options "${pyenv_version}" "${venv_name}" echo echo "Entering a new shell session with virtualenv '${venv_name}' (${pyenv_version})." echo "It will be removed when exiting (ctrl+d or 'exit')." echo "NOTE: to keep it just rename/move it while still in there." # export PYENV_DEBUG=1 pyenv activate --force "$venv_name" # NOTE: the shell will return the exit code from the last command, which might # have failed. $SHELL || true echo "Destroying temporary virtualenv '${venv_name}'." pyenv uninstall -f "${venv_name}"
blueyed/dotfiles
ea17941941c26505575a62ad6c6232e40aeb4922
vimrc: update ShortenPath
diff --git a/vimrc b/vimrc index 790ab31..5bb2453 100644 --- a/vimrc +++ b/vimrc @@ -1286,1051 +1286,1057 @@ let g:cursorcross_no_map_CR = 1 let g:cursorcross_no_map_BS = 1 let g:delimitMate_expand_cr = 0 let g:SuperTabCrMapping = 0 " Skip SuperTab CR map setup (skipped anyway for expr mapping) let g:cursorcross_mappings = 0 " No generic mappings for cursorcross. " Force delimitMate mapping (gets skipped if mapped already). fun! My_CR_map() " "<CR>" via delimitMateCR if len(maparg('<Plug>delimitMateCR', 'i')) let r = "\<Plug>delimitMateCR" else let r = "\<CR>" endif if len(maparg('<Plug>CursorCrossCR', 'i')) " requires vim 704 let r .= "\<Plug>CursorCrossCR" endif if len(maparg('<Plug>DiscretionaryEnd', 'i')) let r .= "\<Plug>DiscretionaryEnd" endif return r endfun imap <expr> <CR> My_CR_map() fun! My_BS_map() " "<BS>" via delimitMateBS if len(maparg('<Plug>delimitMateBS', 'i')) let r = "\<Plug>delimitMateBS" else let r = "\<BS>" endif if len(maparg('<Plug>CursorCrossBS', 'i')) " requires vim 704 let r .= "\<Plug>CursorCrossBS" endif return r endfun imap <expr> <BS> My_BS_map() " For endwise. imap <C-X><CR> <CR><Plug>AlwaysEnd " }}} " github-issues " Trigger API request(s) only when completion is used/invoked. let g:gissues_lazy_load = 1 " Add tags from $VIRTUAL_ENV if $VIRTUAL_ENV != "" let &tags = $VIRTUAL_ENV.'/tags,' . &tags endif " syntax mode setup let php_sql_query = 1 let php_htmlInStrings = 1 " let php_special_functions = 0 " let php_alt_comparisons = 0 " let php_alt_assignByReference = 0 " let PHP_outdentphpescape = 1 let g:PHP_autoformatcomment = 0 " do not set formatoptions/comments automatically (php-indent bundle / vim runtime) let g:php_noShortTags = 1 " always use Smarty comments in smarty files " NOTE: for {php} it's useful let g:tcommentGuessFileType_smarty = 0 endif if &t_Co == 8 " Allow color schemes to do bright colors without forcing bold. (vim-sensible) if $TERM !~# '^linux' set t_Co=16 endif " Fix t_Co: hack to enable 256 colors with e.g. "screen-bce" on CentOS 5.4; " COLORTERM=lilyterm used for LilyTerm (set TERM=xterm). " Do not match "screen" in Linux VT " if (&term[0:6] == "screen-" || len($COLORTERM)) " set t_Co=256 " endif endif " Local dirs"{{{1 set backupdir=~/.local/share/vim/backups if ! isdirectory(expand(&backupdir)) call mkdir( &backupdir, 'p', 0700 ) endif if 1 let s:xdg_cache_home = $XDG_CACHE_HOME if !len(s:xdg_cache_home) let s:xdg_cache_home = expand('~/.cache') endif let s:vimcachedir = s:xdg_cache_home . '/vim' let g:tlib_cache = s:vimcachedir . '/tlib' let s:xdg_config_home = $XDG_CONFIG_HOME if !len(s:xdg_config_home) let s:xdg_config_home = expand('~/.config') endif let s:vimconfigdir = s:xdg_config_home . '/vim' let g:session_directory = s:vimconfigdir . '/sessions' let g:startify_session_dir = g:session_directory let g:startify_change_to_dir = 0 let s:xdg_data_home = $XDG_DATA_HOME if !len(s:xdg_data_home) let s:xdg_data_home = expand('~/.local/share') endif let s:vimsharedir = s:xdg_data_home . '/vim' let &viewdir = s:vimsharedir . '/views' let g:yankring_history_dir = s:vimsharedir let g:yankring_max_history = 500 " let g:yankring_min_element_length = 2 " more that 1 breaks e.g. `xp` " Move yankring history from old location, if any.. let s:old_yankring = expand('~/yankring_history_v2.txt') if filereadable(s:old_yankring) execute '!mv -i '.s:old_yankring.' '.s:vimsharedir endif " Transfer any old (default) tmru files db to new (default) location. let g:tlib_persistent = s:vimsharedir let s:old_tmru_file = expand('~/.cache/vim/tlib/tmru/files') let s:global_tmru_file = s:vimsharedir.'/tmru/files' let s:new_tmru_file_dir = fnamemodify(s:global_tmru_file, ':h') if ! isdirectory(s:new_tmru_file_dir) call mkdir(s:new_tmru_file_dir, 'p', 0700) endif if filereadable(s:old_tmru_file) execute '!mv -i '.shellescape(s:old_tmru_file).' '.shellescape(s:global_tmru_file) " execute '!rm -r '.shellescape(g:tlib_cache) endif end let s:check_create_dirs = [s:vimcachedir, g:tlib_cache, s:vimconfigdir, g:session_directory, s:vimsharedir, &directory] if has('persistent_undo') let &undodir = s:vimsharedir . '/undo' set undofile call add(s:check_create_dirs, &undodir) endif for s:create_dir in s:check_create_dirs " Remove trailing slashes, especially for &directory. let s:create_dir = substitute(s:create_dir, '/\+$', '', '') if ! isdirectory(s:create_dir) if match(s:create_dir, ',') != -1 echohl WarningMsg | echom "WARN: not creating dir: ".s:create_dir | echohl None continue endif echom "Creating dir: ".s:create_dir call mkdir(s:create_dir, 'p', 0700 ) endif endfor " }}} if has("user_commands") " Themes " Airline: let g:airline#extensions#disable_rtp_load = 1 let g:airline_extensions_add = ['neomake'] let g:airline_powerline_fonts = 1 " to test let g:airline#extensions#branch#use_vcscommand = 1 let g:airline#extensions#branch#displayed_head_limit = 7 let g:airline#extensions#hunks#non_zero_only = 1 let g:airline#extensions#tabline#enabled = 1 let g:airline#extensions#tabline#show_buffers = 0 let g:airline#extensions#tabline#tab_nr_type = '[__tabnr__.%{len(tabpagebuflist(__tabnr__))}]' let g:airline#extensions#tmuxline#enabled = 1 let g:airline#extensions#whitespace#enabled = 0 let g:airline#extensions#tagbar#enabled = 0 let g:airline#extensions#tagbar#flags = 'f' " full hierarchy of tag (with scope), see tagbar-statusline " see airline-predefined-parts " let r += ['%{ShortenFilename(fnamemodify(bufname("%"), ":~:."), winwidth(0)-50)}'] " function! AirlineInit() " " let g:airline_section_a = airline#section#create(['mode', ' ', 'foo']) " " let g:airline_section_b = airline#section#create_left(['ffenc','file']) " " let g:airline_section_c = airline#section#create(['%{getcwd()}']) " endfunction " au VimEnter * call AirlineInit() " jedi-vim (besides YCM with jedi library) {{{1 " let g:jedi#force_py_version = 3 let g:jedi#auto_vim_configuration = 0 let g:jedi#goto_assignments_command = '' " dynamically done for ft=python. let g:jedi#goto_definitions_command = '' " dynamically done for ft=python. let g:jedi#rename_command = 'cR' let g:jedi#usages_command = 'gr' let g:jedi#completions_enabled = 1 " Unite/ref and pydoc are more useful. let g:jedi#documentation_command = '<Leader>_K' " Manually setup jedi's call signatures. let g:jedi#show_call_signatures = 1 if &rtp =~ '\<jedi\>' augroup JediSetup au! au FileType python call jedi#configure_call_signatures() augroup END endif let g:jedi#auto_close_doc = 1 " if g:jedi#auto_close_doc " " close preview if its still open after insert " autocmd InsertLeave <buffer> if pumvisible() == 0|pclose|endif " end " }}}1 endif " Enable syntax {{{1 " Switch syntax highlighting on, when the terminal has colors " Also switch on highlighting the last used search pattern. " if (&t_Co > 2 || has("gui_running")) && !exists("syntax_on") if (&t_Co > 2 || has("gui_running")) if !exists("syntax_on") syntax on " after 'filetype plugin indent on' (?!), but not on reload. endif set nohlsearch " Improved syntax handling of TODO etc. au Syntax * syn match MyTodo /\v<(FIXME|NOTE|TODO|OPTIMIZE|XXX):/ \ containedin=.*Comment,vimCommentTitle hi def link MyTodo Todo endif if 1 " has('eval') " Color scheme (after 'syntax on') {{{1 " Use light/dark background based on day/night period (according to " get-daytime-period (uses redshift)) fun! SetBgAccordingToShell(...) let variant = a:0 ? a:1 : "" if len(variant) && variant != "auto" let bg = variant elseif len($TMUX) let bg = system('tmux show-env MY_X_THEME_VARIANT') == "MY_X_THEME_VARIANT=light\n" ? 'light' : 'dark' elseif len($MY_X_THEME_VARIANT) let bg = $MY_X_THEME_VARIANT else " let daytime = system('get-daytime-period') let daytime_file = expand('/tmp/redshift-period') if filereadable(daytime_file) let daytime = readfile(daytime_file)[0] if daytime == 'Daytime' let bg = "light" else let bg = "dark" endif else let bg = "dark" endif endif if bg != &bg let &bg = bg let $FZF_DEFAULT_OPTS = '--color 16,bg+:' . (bg == 'dark' ? '18' : '21') doautocmd <nomodeline> ColorScheme endif endfun command! -nargs=? Autobg call SetBgAccordingToShell(<q-args>) fun! ToggleBg() let &bg = &bg == 'dark' ? 'light' : 'dark' endfun nnoremap <Leader>sb :call ToggleBg()<cr> " Colorscheme: prefer solarized with 16 colors (special palette). let g:solarized_hitrail=0 " using MyWhitespaceSetup instead. let g:solarized_menu=0 " Use corresponding theme from $BASE16_THEME, if set up in the shell. " BASE16_THEME should be in sudoer's env_keep for "sudo vi". if len($BASE16_THEME) let base16colorspace=&t_Co if $BASE16_THEME =~ '^solarized' let s:use_colorscheme = 'solarized' let g:solarized_base16=1 let g:airline_theme = 'solarized' else let s:use_colorscheme = 'base16-'.substitute($BASE16_THEME, '\.\(dark\|light\)$', '', '') endif let g:solarized_termtrans=1 elseif has('gui_running') let s:use_colorscheme = "solarized" let g:solarized_termcolors=256 else " Check for dumb terminal. if ($TERM !~ '256color' ) let s:use_colorscheme = "default" else let s:use_colorscheme = "solarized" let g:solarized_termcolors=256 endif endif " Airline: do not use powerline symbols with linux/screen terminal. " NOTE: xterm-256color gets setup for tmux/screen with $DISPLAY. if (index(["linux", "screen"], $TERM) != -1) let g:airline_powerline_fonts = 0 endif fun! s:MySetColorscheme() " Set s:use_colorscheme, called through GUIEnter for gvim. try exec 'NeoBundleSource colorscheme-'.s:use_colorscheme exec 'colorscheme' s:use_colorscheme catch echom "Failed to load colorscheme: " v:exception endtry endfun if has('vim_starting') call SetBgAccordingToShell($MY_X_THEME_VARIANT) endif if has('gui_running') au GUIEnter * nested call s:MySetColorscheme() else call s:MySetColorscheme() endif endif " Only do this part when compiled with support for autocommands. if has("autocmd") " Autocommands {{{1 " Put these in an autocmd group, so that we can delete them easily. augroup vimrcEx au! " Handle large files, based on LargeFile plugin. let g:LargeFile = 5 " 5mb autocmd BufWinEnter * if get(b:, 'LargeFile_mode') || line2byte(line("$") + 1) > 1000000 \ | echom "vimrc: handling large file." \ | set syntax=off \ | let &ft = &ft.".ycmblacklisted" \ | endif " Enable soft-wrapping for text files au FileType text,markdown,html,xhtml,eruby,vim setlocal wrap linebreak nolist au FileType mail,markdown,gitcommit setlocal spell au FileType json setlocal equalprg=json_pp " XXX: only works for whole files " au FileType css setlocal equalprg=csstidy\ -\ --silent=true\ --template=default " For all text files set 'textwidth' to 78 characters. " au FileType text setlocal textwidth=78 " Follow symlinks when opening a file {{{ " NOTE: this happens with directory symlinks anyway (due to Vim's chdir/getcwd " magic when getting filenames). " Sources: " - https://github.com/tpope/vim-fugitive/issues/147#issuecomment-7572351 " - http://www.reddit.com/r/vim/comments/yhsn6/is_it_possible_to_work_around_the_symlink_bug/c5w91qw function! MyFollowSymlink(...) if exists('w:no_resolve_symlink') && w:no_resolve_symlink return endif if &ft == 'help' return endif let fname = a:0 ? a:1 : expand('%') if fname =~ '^\w\+:/' " Do not mess with 'fugitive://' etc. return endif let fname = simplify(fname) let resolvedfile = resolve(fname) if resolvedfile == fname return endif let resolvedfile = fnameescape(resolvedfile) let sshm = &shm set shortmess+=A " silence ATTENTION message about swap file (would get displayed twice) redraw " Redraw now, to avoid hit-enter prompt. exec 'file ' . resolvedfile let &shm=sshm unlet! b:git_dir call fugitive#detect(resolvedfile) if &modifiable " Only display a note when editing a file, especially not for `:help`. redraw " Redraw now, to avoid hit-enter prompt. echomsg 'Resolved symlink: =>' resolvedfile endif endfunction command! -bar FollowSymlink call MyFollowSymlink() command! ToggleFollowSymlink let w:no_resolve_symlink = !get(w:, 'no_resolve_symlink', 0) | echo "w:no_resolve_symlink =>" w:no_resolve_symlink au BufReadPost * nested call MyFollowSymlink(expand('%')) " Automatically load .vimrc source when saved au BufWritePost $MYVIMRC,~/.dotfiles/vimrc,$MYVIMRC.local source $MYVIMRC au BufWritePost $MYGVIMRC,~/.dotfiles/gvimrc source $MYGVIMRC " if (has("gui_running")) " au FocusLost * stopinsert " endif " autocommands for fugitive {{{2 " Source: http://vimcasts.org/episodes/fugitive-vim-browsing-the-git-object-database/ au User Fugitive \ if fugitive#buffer().type() =~# '^\%(tree\|blob\)' | \ nnoremap <buffer> .. :edit %:h<CR> | \ endif au BufReadPost fugitive://* set bufhidden=delete " Expand tabs for Debian changelog. This is probably not the correct way. au BufNewFile,BufRead */debian/changelog,changelog.dch set expandtab " Ignore certain files with vim-stay. au BufNewFile,BufRead */.git/addp-hunk-edit.diff let b:stay_ignore = 1 " Python " irrelevant, using python-pep8-indent " let g:pyindent_continue = '&sw * 1' " let g:pyindent_open_paren = '&sw * 1' " let g:pyindent_nested_paren = '&sw' " python-mode let g:pymode_options = 0 " do not change relativenumber let g:pymode_indent = 0 " use vim-python-pep8-indent (upstream of pymode) let g:pymode_lint = 0 " prefer syntastic; pymode has problems when PyLint was invoked already before VirtualEnvActivate..!?! let g:pymode_virtualenv = 0 " use virtualenv plugin (required for pylint?!) let g:pymode_doc = 0 " use pydoc let g:pymode_rope_completion = 0 " use YouCompleteMe instead (python-jedi) let g:pymode_syntax_space_errors = 0 " using MyWhitespaceSetup let g:pymode_trim_whitespaces = 0 let g:pymode_debug = 0 let g:pymode_rope = 0 let g:pydoc_window_lines=0.5 " use 50% height let g:pydoc_perform_mappings=0 " let python_space_error_highlight = 1 " using MyWhitespaceSetup " C au FileType C setlocal formatoptions-=c formatoptions-=o formatoptions-=r fu! Select_c_style() if search('^\t', 'n', 150) setlocal shiftwidth=8 noexpandtab el setlocal shiftwidth=4 expandtab en endf au FileType c call Select_c_style() au FileType make setlocal noexpandtab " Disable highlighting of markdownError (Ref: https://github.com/tpope/vim-markdown/issues/79). autocmd FileType markdown hi link markdownError NONE augroup END " Trailing whitespace highlighting {{{2 " Map to toogle EOLWS syntax highlighting noremap <silent> <leader>se :let g:MyAuGroupEOLWSactive = (synIDattr(synIDtrans(hlID("EOLWS")), "bg", "cterm") == -1)<cr> \:call MyAuGroupEOLWS(mode())<cr> let g:MyAuGroupEOLWSactive = 0 function! MyAuGroupEOLWS(mode) if g:MyAuGroupEOLWSactive && &buftype == '' hi EOLWS ctermbg=red guibg=red syn clear EOLWS " match whitespace not preceded by a backslash if a:mode == "i" syn match EOLWS excludenl /[\\]\@<!\s\+\%#\@!$/ containedin=ALL else syn match EOLWS excludenl /[\\]\@<!\s\+$\| \+\ze\t/ containedin=ALLBUT,gitcommitDiff | endif else syn clear EOLWS hi clear EOLWS endif endfunction augroup vimrcExEOLWS au! " highlight EOLWS ctermbg=red guibg=red " based on solarizedTrailingSpace highlight EOLWS term=underline cterm=underline ctermfg=1 au InsertEnter * call MyAuGroupEOLWS("i") " highlight trailing whitespace, space before tab and tab not at the " beginning of the line (except in comments), only for normal buffers: au InsertLeave,BufWinEnter * call MyAuGroupEOLWS("n") " fails with gitcommit: filetype | syn match EOLWS excludenl /[^\t]\zs\t\+/ containedin=ALLBUT,gitcommitComment " add this for Python (via python_highlight_all?!): " au FileType python " \ if g:MyAuGroupEOLWSactive | " \ syn match EOLWS excludenl /^\t\+/ containedin=ALL | " \ endif augroup END "}}} " automatically save and reload viminfo across Vim instances " Source: http://vimhelp.appspot.com/vim_faq.txt.html#faq-17.3 augroup viminfo_onfocus au! " au FocusLost * wviminfo " au FocusGained * rviminfo augroup end endif " has("autocmd") }}} " Shorten a given (absolute) file path, via external `shorten_path` script. " This mainly shortens entries from Zsh's `hash -d` list. let s:_cache_shorten_path = {} let s:_has_functional_shorten_path = 1 -fun! ShortenPath(path, ...) - if ! len(a:path) || ! s:_has_functional_shorten_path +let s:shorten_path_exe = executable('shorten_path') + \ ? 'shorten_path' + \ : filereadable(expand("$HOME/.dotfiles/usr/bin/shorten_path")) + \ ? expand("$HOME/.dotfiles/usr/bin/shorten_path") + \ : expand("/home/$SUDO_USER/.dotfiles/usr/bin/shorten_path") +function! ShortenPath(path, ...) + if !len(a:path) || !s:_has_functional_shorten_path return a:path endif let base = a:0 ? a:1 : "" let annotate = a:0 > 1 ? a:2 : 0 let cache_key = base . ":" . a:path . ":" . annotate - if ! exists('s:_cache_shorten_path[cache_key]') - let shorten_path = executable('shorten_path') - \ ? 'shorten_path' - \ : filereadable(expand("$HOME/.dotfiles/usr/bin/shorten_path")) - \ ? expand("$HOME/.dotfiles/usr/bin/shorten_path") - \ : expand("/home/$SUDO_USER/.dotfiles/usr/bin/shorten_path") + if !exists('s:_cache_shorten_path[cache_key]') + let shorten_path = [s:shorten_path_exe] if annotate - let shorten_path .= ' -a' + let shorten_path += ['-a'] endif - let cmd = shorten_path.' '.shellescape(a:path).' '.shellescape(base) - let s:_cache_shorten_path[cache_key] = system(cmd.' 2>/dev/null') + let cmd = shorten_path + [a:path, base] + let output = s:systemlist(cmd) + let lastline = empty(output) ? '' : output[-1] + let s:_cache_shorten_path[cache_key] = lastline if v:shell_error try let tmpfile = tempname() - call system(cmd.' 2>'.tmpfile) + let system_cmd = join(map(copy(cmd), 'fnameescape(v:val)')) + call system(system_cmd.' 2>'.tmpfile) if v:shell_error == 127 let s:_has_functional_shorten_path = 0 endif - throw "There was a problem running shorten_path: " - \ . join(readfile(tmpfile), "\n") . ' ('.v:shell_error.')' + echohl ErrorMsg + echom printf('There was a problem running %s: %s (%d)', + \ cmd, join(readfile(tmpfile), "\n"), v:shell_error) + echohl None return a:path finally call delete(tmpfile) endtry endif endif return s:_cache_shorten_path[cache_key] endfun function! My_get_qfloclist_type(bufnr) let isLoc = getbufvar(a:bufnr, 'isLoc', -1) " via vim-qf. if isLoc != -1 return isLoc ? 'll' : 'qf' endif " A hacky way to distinguish qf from loclist windows/buffers. " https://github.com/vim-airline/vim-airline/blob/83b6dd11a8829bbd934576e76bfbda6559ed49e1/autoload/airline/extensions/quickfix.vim#L27-L43. " Changes: " - Caching! " - Match opening square bracket at least. Apart from that it could be " localized. " if &ft !=# 'qf' " return '' " endif let type = getbufvar(a:bufnr, 'my_qfloclist_type', '') if type != '' return type endif redir => buffers silent ls - redir END let type = 'unknown' for buf in split(buffers, '\n') if match(buf, '\v^\s*'.a:bufnr.'\s\S+\s+"\[') > -1 if match(buf, '\cQuickfix') > -1 let type = 'qf' break else let type = 'll' break endif endif endfor call setbufvar(a:bufnr, 'my_qfloclist_type', type) return type endfunction " Shorten a given filename by truncating path segments. let g:_cache_shorten_filename = {} let g:_cache_shorten_filename_git = {} function! ShortenString(s, maxlen) if len(a:s) <= a:maxlen return a:s endif return a:s[0:a:maxlen-1] . '…' endfunction function! ShortenFilename(...) " {{{ " Args: bufname ('%' for default), maxlength, cwd let cwd = a:0 > 2 ? a:3 : getcwd() " Maxlen from a:2 (used for cache key) and caching. let maxlen = a:0>1 ? a:2 : max([10, winwidth(0)-50]) " get bufname from a:1, defaulting to bufname('%') {{{ if a:0 && type(a:1) == type('') && a:1 !=# '%' let bufname = expand(a:1) " tilde-expansion. else if !a:0 || a:1 == '%' let bufnr = bufnr('%') else let bufnr = a:1 endif let bufname = bufname(bufnr) let ft = getbufvar(bufnr, '&filetype') if !len(bufname) if ft == 'qf' let type = My_get_qfloclist_type(bufnr) " XXX: uses current window. Also not available after ":tab split". let qf_title = get(w:, 'quickfix_title', '') if qf_title != '' return ShortenString('['.type.'] '.qf_title, maxlen) elseif type == 'll' let alt_name = expand('#') " For location lists the alternate file is the corresponding buffer " and the quickfix list does not have an alternate buffer " (but not always)!?! if len(alt_name) return '[loc] '.ShortenFilename(alt_name, maxlen-5) endif return '[loc]' endif return '[qf]' else let bt = getbufvar(bufnr, '&buftype') if bt != '' && ft != '' " Use &ft for name (e.g. with 'startify' and quickfix windows). " if &ft == 'qf' " let alt_name = expand('#') " if len(alt_name) " return '[loc] '.ShortenFilename(alt_name) " else " return '[qf]' " endif let alt_name = expand('#') if len(alt_name) return '['.&ft.'] '.ShortenFilename(expand('#')) else return '['.&ft.']' endif else " TODO: get Vim's original "[No Name]" somehow return '[No Name]' endif endif end if ft ==# 'help' return '[?] '.fnamemodify(bufname, ':t') endif if bufname =~# '^__' return bufname endif " '^\[ref-\w\+:.*\]$' if bufname =~# '^\[.*\]$' return bufname endif endif " }}} " {{{ fugitive if bufname =~# '^fugitive:///' let [gitdir, fug_path] = split(bufname, '//')[1:2] " Caching based on bufname and timestamp of gitdir. let git_ftime = getftime(gitdir) if exists('g:_cache_shorten_filename_git[bufname]') \ && g:_cache_shorten_filename_git[bufname][0] == git_ftime let [commit_name, fug_type, fug_path] \ = g:_cache_shorten_filename_git[bufname][1:-1] else let fug_buffer = fugitive#buffer(bufname) let fug_type = fug_buffer.type() " if fug_path =~# '^\x\{7,40\}\>' let commit = matchstr(fug_path, '\v\w*') if len(commit) > 1 let git_argv = ['git', '--git-dir='.gitdir] let commit = systemlist(git_argv + ['rev-parse', '--short', commit])[0] let commit_name = systemlist(git_argv + ['name-rev', '--name-only', commit])[0] if commit_name !=# 'undefined' " Remove current branch name (master~4 => ~4). let HEAD = get(systemlist(git_argv + ['symbolic-ref', '--quiet', '--short', 'HEAD']), 0, '') let len_HEAD = len(HEAD) if len_HEAD > len(commit_name) && commit_name[0:len_HEAD-1] == HEAD let commit_name = commit_name[len_HEAD:-1] endif " let commit .= '('.commit_name.')' let commit_name .= '('.commit.')' else let commit_name = commit endif else let commit_name = commit endif " endif if fug_type !=# 'commit' let fug_path = substitute(fug_path, '\v\w*/', '', '') if len(fug_path) let fug_path = ShortenFilename(fug_buffer.repo().tree(fug_path)) endif else let fug_path = 'NOT_USED' endif " Set cache. let g:_cache_shorten_filename_git[bufname] \ = [git_ftime, commit_name, fug_type, fug_path] endif if fug_type ==# 'blob' return 'λ:' . commit_name . ':' . fug_path elseif fug_type ==# 'file' return 'λ:' . fug_path . '@' . commit_name elseif fug_type ==# 'commit' " elseif fug_path =~# '^\x\{7,40\}\>' let work_tree = fugitive#buffer(bufname).repo().tree() if cwd[0:len(work_tree)-1] == work_tree let rel_work_tree = '' else let rel_work_tree = ShortenPath(fnamemodify(work_tree.'/', ':.')) endif return 'λ:' . rel_work_tree . '@' . commit_name endif throw "fug_type: ".fug_type." not handled: ".fug_path endif " }}} " Check for cache (avoiding fnamemodify): {{{ let cache_key = bufname.'::'.cwd.'::'.maxlen if has_key(g:_cache_shorten_filename, cache_key) return g:_cache_shorten_filename[cache_key] endif " Make path relative first, which might not work with the result from " `shorten_path`. let rel_path = fnamemodify(bufname, ":.") let bufname = ShortenPath(rel_path, cwd, 1) " }}} " Loop over all segments/parts, to mark symlinks. " XXX: symlinks get resolved currently anyway!? " NOTE: consider using another method like http://stackoverflow.com/questions/13165941/how-to-truncate-long-file-path-in-vim-powerline-statusline let maxlen_of_parts = 7 " including slash/dot let maxlen_of_subparts = 1 " split at hypen/underscore; including split let s:PS = exists('+shellslash') ? (&shellslash ? '/' : '\') : "/" let parts = split(bufname, '\ze['.escape(s:PS, '\').']') let i = 0 let n = len(parts) let wholepath = '' " used for symlink check while i < n let wholepath .= parts[i] " Shorten part, if necessary: " TODO: use pathshorten(fnamemodify(path, ':~')) as fallback?! if i < n-1 && len(bufname) > maxlen && len(parts[i]) > maxlen_of_parts " Let's see if there are dots or hyphens to truncate at, e.g. " 'vim-pkg-debian' => 'v-p-d…' let w = split(parts[i], '\ze[_-]') if len(w) > 1 let parts[i] = '' for j in w if len(j) > maxlen_of_subparts-1 let parts[i] .= j[0:max([maxlen_of_subparts-2, 1])] "."…" else let parts[i] .= j endif endfor else let parts[i] = parts[i][0:max([maxlen_of_parts-2, 1])].'…' endif endif let i += 1 endwhile let r = join(parts, '') if len(r) > maxlen " echom len(r) maxlen let i = 0 let n -= 1 while i < n && len(join(parts, '')) > maxlen if i > 0 || parts[i][0] != '~' let j = 0 let parts[i] = matchstr(parts[i], '.\{-}\w') " if i == 0 && parts[i][0] != '/' " let parts[i] = parts[i][0] " else " let parts[i] = matchstr(parts[i], 1) " endif endif let i += 1 endwhile let r = join(parts, '') endif let g:_cache_shorten_filename[cache_key] = r " echom "ShortenFilename" r return r endfunction "}}} " Shorten filename, and append suffix(es), e.g. for modified buffers. {{{2 fun! ShortenFilenameWithSuffix(...) let r = call('ShortenFilename', a:000) if &modified let r .= ',+' endif return r endfun " }}} " Opens an edit command with the path of the currently edited file filled in " Normal mode: <Leader>e nnoremap <Leader>ee :e <C-R>=expand("%:p:h") . "/" <CR> nnoremap <Leader>EE :sp <C-R>=expand("%:p:h") . "/" <CR> " gt: next tab or buffer (source: http://j.mp/dotvimrc) " enhanced to support range (via v:count) fun! MyGotoNextTabOrBuffer(...) let c = a:0 ? a:1 : v:count exec (c ? c : '') . (tabpagenr('$') == 1 ? 'bn' : 'tabnext') endfun fun! MyGotoPrevTabOrBuffer() exec (v:count ? v:count : '') . (tabpagenr('$') == 1 ? 'bp' : 'tabprevious') endfun nnoremap <silent> <Plug>NextTabOrBuffer :<C-U>call MyGotoNextTabOrBuffer()<CR> nnoremap <silent> <Plug>PrevTabOrBuffer :<C-U>call MyGotoPrevTabOrBuffer()<CR> " Ctrl-Space: split into new tab. " Disables diff mode, which gets taken over from the old buffer. nnoremap <C-Space> :tab sp \| set nodiff<cr> nnoremap <A-Space> :tabnew<cr> " For terminal. nnoremap <C-@> :tab sp \| set nodiff<cr> " Opens a tab edit command with the path of the currently edited file filled in map <Leader>te :tabe <C-R>=expand("%:p:h") . "/" <CR> map <a-o> <C-W>o " Avoid this to be done accidentally (when zooming is meant). ":on" is more " explicit. map <C-W><C-o> <Nop> " does not work, even with lilyterm.. :/ " TODO: <C-1>..<C-0> for tabs; not possible; only certain C-sequences get " through to the terminal Vim " nmap <C-Insert> :tabnew<cr> " nmap <C-Del> :tabclose<cr> nmap <A-Del> :tabclose<cr> " nmap <C-1> 1gt<cr> " Prev/next tab. nmap <C-PageUp> <Plug>PrevTabOrBuffer nmap <C-PageDown> <Plug>NextTabOrBuffer map <A-,> <Plug>PrevTabOrBuffer map <A-.> <Plug>NextTabOrBuffer map <C-S-Tab> <Plug>PrevTabOrBuffer map <C-Tab> <Plug>NextTabOrBuffer " Switch to most recently used tab. " Source: http://stackoverflow.com/a/2120168/15690 fun! MyGotoMRUTab() if !exists('g:mrutab') let g:mrutab = 1 endif if tabpagenr('$') == 1 echomsg "There is only one tab!" return endif if g:mrutab > tabpagenr('$') || g:mrutab == tabpagenr() let g:mrutab = tabpagenr() > 1 ? tabpagenr()-1 : tabpagenr('$') endif exe "tabn ".g:mrutab endfun " Overrides Vim's gh command (start select-mode, but I don't use that). " It can be simulated using v<C-g> also. nnoremap <silent> gh :call MyGotoMRUTab()<CR> " nnoremap ° :call MyGotoMRUTab()<CR> " nnoremap <C-^> :call MyGotoMRUTab()<CR> augroup MyTL au! au TabLeave * let g:mrutab = tabpagenr() augroup END " Map <A-1> .. <A-9> to goto tab or buffer. for i in range(9) exec 'nmap <M-' .(i+1).'> :call MyGotoNextTabOrBuffer('.(i+1).')<cr>' endfor fun! MyGetNonDefaultServername() " Not for gvim in general (uses v:servername by default), and the global " server ("G"). let sname = v:servername if len(sname) if has('nvim') if sname !~# '^/tmp/nvim' let sname = substitute(fnamemodify(v:servername, ':t:r'), '^nvim-', '', '') return sname endif elseif sname !~# '\v^GVIM.*' " && sname =~# '\v^G\d*$' return sname endif endif return '' endfun fun! MyGetSessionName() " Use / auto-set g:MySessionName if !len(get(g:, "MySessionName", "")) if len(v:this_session) let g:MySessionName = fnamemodify(v:this_session, ':t:r') elseif len($TERM_INSTANCE_NAME) let g:MySessionName = substitute($TERM_INSTANCE_NAME, '^vim-', '', '') else return '' end endif return g:MySessionName endfun " titlestring handling, with tmux support {{{ " Set titlestring, used to set terminal title (pane title in tmux). set title " Setup titlestring on BufEnter, when v:servername is available. fun! MySetupTitleString() let title = '✐ ' let session_name = MyGetSessionName() if len(session_name) let title .= '['.session_name.'] ' else " Add non-default servername to titlestring. let sname = MyGetNonDefaultServername() if len(sname) let title .= '['.sname.'] ' endif endif " Call the function and use its result, rather than including it. " (for performance reasons). let title .= substitute( \ ShortenFilenameWithSuffix('%', 15).' ('.ShortenPath(getcwd()).')', \ '%', '%%', 'g') if len(s:my_context) let title .= ' {'.s:my_context.'}' endif " Easier to type/find than the unicode symbol prefix. let title .= ' - vim' " Append $_TERM_TITLE_SUFFIX (e.g. user@host) to title (set via zsh, used " with SSH). if len($_TERM_TITLE_SUFFIX) let title .= $_TERM_TITLE_SUFFIX endif " Setup tmux window name, see ~/.dotfiles/oh-my-zsh/lib/termsupport.zsh. if len($TMUX) \ && (!len($_tmux_name_reset) || $_tmux_name_reset != $TMUX . '_' . $TMUX_PANE) let tmux_auto_rename=systemlist('tmux show-window-options -t '.$TMUX_PANE.' -v automatic-rename 2>/dev/null') " || $(tmux show-window-options -t $TMUX_PANE | grep '^automatic-rename' | cut -f2 -d\ ) " echom string(tmux_auto_rename) if !len(tmux_auto_rename) || tmux_auto_rename[0] != "off" " echom "Resetting tmux name to 0." call system('tmux set-window-option -t '.$TMUX_PANE.' -q automatic-rename off') call system('tmux rename-window -t '.$TMUX_PANE.' 0') endif endif let &titlestring = title " Set icon text according to &titlestring (used for minimized windows). let &iconstring = '(v) '.&titlestring endfun augroup vimrc_title au! " XXX: might not get called with fugitive buffers (title is the (closed) fugitive buffer). autocmd BufEnter,BufWritePost * call MySetupTitleString() if exists('##TextChanged') autocmd TextChanged * call MySetupTitleString() endif augroup END " Make Vim set the window title according to &titlestring. if !has('gui_running') && empty(&t_ts) if len($TMUX) let &t_ts = "\e]2;" let &t_fs = "\007" elseif &term =~ "^screen.*" let &t_ts="\ek" let &t_fs="\e\\" endif endif fun! MySetSessionName(name) let g:MySessionName = a:name call MySetupTitleString() endfun "}}} " Inserts the path of the currently edited file into a command " Command mode: Ctrl+P " cmap <C-P> <C-R>=expand("%:p:h") . "/" <CR> " Change to current file's dir nnoremap <Leader>cd :lcd <C-R>=expand('%:p:h')<CR><CR> " yankstack, see also unite's history/yank {{{1 if &rtp =~ '\<yankstack\>' " Do not map s/S (used by vim-sneak). " let g:yankstack_yank_keys = ['c', 'C', 'd', 'D', 's', 'S', 'x', 'X', 'y', 'Y'] let g:yankstack_yank_keys = ['c', 'C', 'd', 'D', 'x', 'X', 'y', 'Y'] " Setup yankstack now to make yank/paste related mappings work. call yankstack#setup() endif " Command-line maps to act on the current search (with incsearch). {{{ " E.g. '?foo$m' will move the matched line to where search started. " Source: http://www.reddit.com/r/vim/comments/1yfzg2/does_anyone_actually_use_easymotion/cfkaxw5 " NOTE: with vim-oblique, '?' and '/' are mapped, and not in getcmdtype(). fun! MyCmdMapNotForColon(from, to, ...) let init = a:0 ? 0 : 1 if init exec printf('cnoremap <expr> %s MyCmdMapNotForColon("%s", "%s", 1)', \ a:from, a:from, a:to) return endif if index([':', '>', '@', '-', '='], getcmdtype()) == 0 return a:from endif return a:to endfun call MyCmdMapNotForColon('$d', "<CR>:delete<CR>``") call MyCmdMapNotForColon('$m', "<CR>:move''<CR>") call MyCmdMapNotForColon('$c', "<CR>:copy''<CR>") call MyCmdMapNotForColon('$t', "<CR>:t''<CR>") " synonym for :copy " Allow to quickly enter a single $. cnoremap $$ $ " }}}
blueyed/dotfiles
d42e5b7da0c6f1225e9338195fafc0d13274d4b0
vim: add vim/after/ftplugin/qf.vim
diff --git a/vim/after/ftplugin/qf.vim b/vim/after/ftplugin/qf.vim new file mode 100644 index 0000000..b2d9325 --- /dev/null +++ b/vim/after/ftplugin/qf.vim @@ -0,0 +1,114 @@ +" Generic wrapper, should replace s:MyQuickfixCR +function! s:with_equalalways(cmd) + try + let winid = win_getid() + catch + let winid = -1 + endtry + + try + exe a:cmd + catch /:E36:/ + if !&equalalways + set equalalways + try + exe a:cmd + finally + set noequalalways + endtry + endif + endtry + + if winid != -1 + " Used in MyQuitWindow(). + let w:my_prev_winid = winid + endif +endfunction + +function! s:open_in_prev_win() + " does not contain line number + let cfile = expand('<cfile>') + let f = findfile(cfile) + if !len(f) + echom 'Could not find file at cursor ('.cfile.')' + return + endif + + " Delegate to vim-fetch. Could need better API + " (https://github.com/kopischke/vim-fetch/issues/13). + let f = expand('<cWORD>') + wincmd p + silent exe 'e' f +endfunction + +nmap <buffer> o :call <SID>open_in_prev_win()<cr> +nmap <buffer> gf :call <SID>with_equalalways('wincmd F')<cr> +nmap <buffer> gF :call <SID>with_equalalways('wincmd gF')<cr> +nmap <buffer> <c-w><cr> :call <SID>with_equalalways('call feedkeys("<Bslash><lt>c-w><Bslash><lt>cr>", "nx")')<cr> + +" nmap <buffer> gf try :wincmd p \| norm gF<cr> +" nmap <buffer> gF :tab sp \| norm gF<cr> + +" Workaround for https://github.com/vim/vim/issues/908. +" NOTE: could use s:with_equalalways maybe, but needs to save and execute +" the previous CR mapping. +let s:cr_map = ':call <SID>MyQuickfixCR()<cr>' +let s:cr_map_match = ':call <SNR>\d\+_MyQuickfixCR()<CR>' +if !exists('*s:MyQuickfixCR') + " prevent E127: Cannot redefine function %s: It is in use" (likely when using this function triggers a new qf list (e.g. via Neomake)) +function! s:MyQuickfixCR() + let bufnr = bufnr('%') + " if !bufexists(bufnr) + " " Might happen with jedi-vim's goto-window, which closes itself on + " " WinLeave. + " return + " endif + let prev_map = "\<Plug>MyQuickfixCRPre" + + " Remove our mapping. + exe 'nunmap <buffer> <cr>' + try + call feedkeys(prev_map, 'x') + catch /:E36:/ + set equalalways + try + call feedkeys(prev_map, 'x') + finally + set noequalalways + endtry + finally + if !bufexists(bufnr) + " Might happen with jedi-vim's goto-window, which closes itself on + " WinLeave. + return + endif + if bufnr('%') == bufnr + exe 'nmap <buffer> <cr> '.s:cr_map + " call SetupMyQuickfixCR() + " map <buffer> <cr> :call MyQuickfixCR()<cr> + else + " Setup autocmd to re-setup our mapping. + augroup myquickfixcr + exe 'au! * <buffer'.bufnr.'>' + " au! WinEnter <buffer> call SetupMyQuickfixCR() + exe 'au! WinEnter <buffer='.bufnr.'> exe "nmap <buffer> <cr> ".s:cr_map | au! myquickfixcr' + augroup END + endif + endtry +endfunction +endif + +function! SetupMyQuickfixCR() + if maparg('<cr>', 'n') =~# s:cr_map_match + " Already setup, don't do it twice. + return + endif + let prev_map = maparg('<cr>', 'n') + if !len(prev_map) + let prev_map = "\<CR>" + endif + exe 'nmap <buffer> <Plug>MyQuickfixCRPre '.prev_map + exe 'nmap <buffer> <cr> '.s:cr_map + exe 'nmap <buffer> ,xy '.s:cr_map +endfunction +call SetupMyQuickfixCR()
blueyed/dotfiles
82fd24e45a6edfbd7117b6d6a0d5fd1b45bb9de2
vimrc: rename QuitIfOnlyControlWinLeft, use nested
diff --git a/vimrc b/vimrc index 282176f..790ab31 100644 --- a/vimrc +++ b/vimrc @@ -2349,1042 +2349,1043 @@ omap S <Plug>Sneak_S let g:sneak#streak=2 let g:sneak#s_next = 1 " clever-s let g:sneak#target_labels = "sfjktunbqz/SFKGHLTUNBRMQZ?" " Replace 'f' with inclusive 1-char Sneak. nmap f <Plug>Sneak_f nmap F <Plug>Sneak_F xmap f <Plug>Sneak_f xmap F <Plug>Sneak_F omap f <Plug>Sneak_f omap F <Plug>Sneak_F " Replace 't' with exclusive 1-char Sneak. nmap t <Plug>Sneak_t nmap T <Plug>Sneak_T xmap t <Plug>Sneak_t xmap T <Plug>Sneak_T omap t <Plug>Sneak_t omap T <Plug>Sneak_T " IDEA: just use 'f' for sneak, leaving 's' at its default. " nmap f <Plug>Sneak_s " nmap F <Plug>Sneak_S " xmap f <Plug>Sneak_s " xmap F <Plug>Sneak_S " omap f <Plug>Sneak_s " omap F <Plug>Sneak_S " }}}1 " GoldenView {{{1 let g:goldenview__enable_default_mapping = 0 let g:goldenview__enable_at_startup = 0 " 1. split to tiled windows nmap <silent> g<C-L> <Plug>GoldenViewSplit " " 2. quickly switch current window with the main pane " " and toggle back nmap <silent> <F9> <Plug>GoldenViewSwitchMain nmap <silent> <S-F9> <Plug>GoldenViewSwitchToggle " " 3. jump to next and previous window nmap <silent> <C-N> <Plug>GoldenViewNext nmap <silent> <C-P> <Plug>GoldenViewPrevious " }}} " Duplicate a selection in visual mode vmap D y'>p " Press Shift+P while in visual mode to replace the selection without " overwriting the default register vmap P p :call setreg('"', getreg('0')) <CR> " This is an alternative that also works in block mode, but the deleted " text is lost and it only works for putting the current register. "vnoremap p "_dp " imap <C-L> <Space>=><Space> " Toggle settings (see also vim-unimpaired). " No pastetoggle: use `yo`/`yO` from unimpaired. Triggers also Neovim issue #6716. " set pastetoggle=<leader>sp nnoremap <leader>sc :ColorToggle<cr> nnoremap <leader>sq :QuickfixsignsToggle<cr> nnoremap <leader>si :IndentGuidesToggle<cr> " Toggle mouse. nnoremap <leader>sm :exec 'set mouse='.(&mouse == 'a' ? '' : 'a')<cr>:set mouse?<cr> " OLD: Ack/Ag setup, handled via ag plugin {{{ " Use Ack instead of Grep when available " if executable("ack") " set grepprg=ack\ -H\ --nogroup\ --nocolor\ --ignore-dir=tmp\ --ignore-dir=coverage " elseif executable("ack-grep") " set grepprg=ack-grep\ -H\ --nogroup\ --nocolor\ --ignore-dir=tmp\ --ignore-dir=coverage " else " this is for Windows/cygwin and to add -H " '$*' is not passed to the shell, but used by Vim set grepprg=grep\ -nH\ $*\ /dev/null " endif if executable("ag") let g:ackprg = 'ag --nogroup --nocolor --column' " command alias, http://stackoverflow.com/a/3879737/15690 " if re-used, use a function " cnoreabbrev <expr> Ag ((getcmdtype() is# ':' && getcmdline() is# 'Ag')?('Ack'):('Ag')) endif " 1}}} " Automatic line numbers {{{ " NOTE: relativenumber might slow Vim down: https://code.google.com/p/vim/issues/detail?id=311 set norelativenumber fun! MyAutoSetNumberSettings(...) if get(w:, 'my_default_number_manually_set') return endif let s:my_auto_number_ignore_OptionSet = 1 if a:0 exec 'setl' a:1 elseif &ft =~# 'qf\|cram\|vader' setl number elseif index(['nofile', 'terminal'], &buftype) != -1 \ || index(['help', 'fugitiveblame', 'fzf'], &ft) != -1 \ || bufname("%") =~ '^__' setl nonumber elseif winwidth(".") > 90 setl number else setl nonumber endif unlet s:my_auto_number_ignore_OptionSet endfun fun! MySetDefaultNumberSettingsSet() if !exists('s:my_auto_number_ignore_OptionSet') " echom "Manually set:" expand("<amatch>").":" v:option_old "=>" v:option_new let w:my_auto_number_manually_set = 1 endif endfun augroup vimrc_number_setup au! au VimResized,FileType,BufWinEnter * call MyAutoSetNumberSettings() if exists('##OptionSet') au OptionSet number,relativenumber call MySetDefaultNumberSettingsSet() endif au CmdwinEnter * call MyAutoSetNumberSettings('number norelativenumber') augroup END fun! MyOnVimResized() noautocmd WindoNodelay call MyAutoSetNumberSettings() QfResizeWindows endfun nnoremap <silent> <c-w>= :wincmd =<cr>:call MyOnVimResized()<cr> fun! MyWindoNoDelay(range, command) " 100ms by default! let s = g:ArgsAndMore_AfterCommand let g:ArgsAndMore_AfterCommand = '' call ArgsAndMore#Windo('', a:command) let g:ArgsAndMore_AfterCommand = s endfun command! -nargs=1 -complete=command WindoNodelay call MyWindoNoDelay('', <q-args>) augroup vimrc_on_resize au! au VimResized * WindoNodelay call MyOnVimResized() augroup END let &showbreak = '↪ ' set cpoptions+=n " Use line column for wrapped text / &showbreak. function! CycleLineNr() " states: [start] => norelative/number => relative/number (=> relative/nonumber) => nonumber/norelative if exists('+relativenumber') if &relativenumber " if &number " set relativenumber nonumber " else set norelativenumber nonumber " endif else if &number set number relativenumber if !&number " Older Vim. set relativenumber endif else " init: set norelativenumber number endif endif " if &number | set relativenumber | elseif &relativenumber | set norelativenumber | else | set number | endif else set number! endif call SetNumberWidth() endfunction function! SetNumberWidth() " NOTE: 'numberwidth' will get expanded by Vim automatically to fit the last line if &number if has('float') let &l:numberwidth = float2nr(ceil(log10(line('$')))) endif elseif exists('+relativenumber') && &relativenumber set numberwidth=2 endif endfun nnoremap <leader>sa :call CycleLineNr()<CR> " Toggle numbers, but with relativenumber turned on fun! ToggleLineNr() if &number if exists('+relativenumber') set norelativenumber endif set nonumber else if exists('+relativenumber') set relativenumber endif set number endif endfun " map according to unimpaired, mnemonic "a on the left, like numbers". nnoremap coa :call ToggleLineNr()<cr> " Allow cursor to move anywhere in all modes. nnoremap cov :set <C-R>=empty(&virtualedit) ? 'virtualedit=all' : 'virtualedit='<CR><CR> "}}} " Completion options. " Do not use longest, but make Ctrl-P work directly. set completeopt=menuone " set completeopt+=preview " experimental set wildmode=list:longest,list:full " set complete+=kspell " complete from spell checking " set dictionary+=spell " very useful (via C-X C-K), but requires ':set spell' once " NOTE: gets handled dynamically via cursorcross plugin. " set cursorline " highlight CursorLine guibg=lightblue ctermbg=lightgray " via http://www.reddit.com/r/programming/comments/7yk4i/vim_settings_per_directory/c07rk9d " :au! BufRead,BufNewFile *path/to/project/*.* setlocal noet " Maps for jk and kj to act as Esc (idempotent in normal mode). " NOTE: jk moves to the right after Esc, leaving the cursor at the current position. fun! MyRightWithoutError() if col(".") < len(getline(".")) normal! l endif endfun inoremap <silent> jk <esc>:call MyRightWithoutError()<cr> " cno jk <c-c> ino kj <esc> " cno kj <c-c> ino jh <esc> " Improve the Esc key: good for `i`, does not work for `a`. " Source: http://vim.wikia.com/wiki/Avoid_the_escape_key#Improving_the_Esc_key " inoremap <Esc> <Esc>`^ " close tags (useful for html) " NOTE: not required/used; avoid imap for leader. " imap <Leader>/ </<C-X><C-O> nnoremap <Leader>a :Ag<space> nnoremap <Leader>A :Ag!<space> " Make those behave like ci' , ci" nnoremap ci( f(ci( nnoremap ci{ f{ci{ nnoremap ci[ f[ci[ " NOTE: occupies `c`. " vnoremap ci( f(ci( " vnoremap ci{ f{ci{ " vnoremap ci[ f[ci[ " 'goto buffer'; NOTE: overwritten with Unite currently. nnoremap gb :ls<CR>:b function! MyIfToVarDump() normal yyP s/\mif\>/var_dump/ s/\m\s*\(&&\|||\)\s*/, /ge s/\m{\s*$/; die();/ endfunction " Toggle fold under cursor. {{{ fun! MyToggleFold() if !&foldenable echom "Folds are not enabled." endif let level = foldlevel('.') echom "Current foldlevel:" level if level == 0 return endif if foldclosed('.') > 0 " Open recursively norm! zA else " Close only one level. norm! za endif endfun nnoremap <Leader><space> :call MyToggleFold()<cr> vnoremap <Leader><space> zf " }}} " Easily switch between different fold methods {{{ " Source: https://github.com/pydave/daveconfig/blob/master/multi/vim/.vim/bundle/foldtoggle/plugin/foldtoggle.vim nnoremap <Leader>sf :call ToggleFold()<CR> function! ToggleFold() if !exists("b:fold_toggle_options") " By default, use the main three. I rarely use custom expressions or " manual and diff is just for diffing. let b:fold_toggle_options = ["syntax", "indent", "marker"] if len(&foldexpr) let b:fold_toggle_options += ["expr"] endif endif " Find the current setting in the list let i = match(b:fold_toggle_options, &foldmethod) " Advance to the next setting let i = (i + 1) % len(b:fold_toggle_options) let old_method = &l:foldmethod let &l:foldmethod = b:fold_toggle_options[i] echom 'foldmethod: ' . old_method . " => " . &l:foldmethod endfunction function! FoldParagraphs() setlocal foldmethod=expr setlocal fde=getline(v:lnum)=~'^\\s*$'&&getline(v:lnum+1)=~'\\S'?'<1':1 endfunction command! FoldParagraphs call FoldParagraphs() " }}} " Sort Python imports. command! -range=% -nargs=* Isort :<line1>,<line2>! isort --lines 79 <args> - " Map S-Insert to insert the "*" register literally. if has('gui') " nmap <S-Insert> <C-R><C-o>* " map! <S-Insert> <C-R><C-o>* nmap <S-Insert> <MiddleMouse> map! <S-Insert> <MiddleMouse> endif " swap previously selected text with currently selected one (via http://vim.wikia.com/wiki/Swapping_characters,_words_and_lines#Visual-mode_swapping) vnoremap <C-X> <Esc>`.``gvP``P " Easy indentation in visual mode " This keeps the visual selection active after indenting. " Usually the visual selection is lost after you indent it. "vmap > >gv "vmap < <gv " Make `<leader>gp` select the last pasted text " (http://vim.wikia.com/wiki/Selecting_your_pasted_text). nnoremap <expr> <leader>gp '`[' . strpart(getregtype(), 0, 1) . '`]' " select last inserted text " nnoremap gV `[v`] nmap gV <leader>gp if 1 " has('eval') {{{1 " Strip trailing whitespace {{{2 function! StripWhitespace(line1, line2, ...) let s_report = &report let &report=0 let pattern = a:0 ? a:1 : '[\\]\@<!\s\+$' if exists('*winsaveview') let oldview = winsaveview() else let save_cursor = getpos(".") endif exe 'keepjumps keeppatterns '.a:line1.','.a:line2.'substitute/'.pattern.'//e' if exists('oldview') if oldview != winsaveview() redraw echohl WarningMsg | echomsg 'Trimmed whitespace.' | echohl None endif call winrestview(oldview) else call setpos('.', save_cursor) endif let &report = s_report endfunction command! -range=% -nargs=0 -bar Untrail keepjumps call StripWhitespace(<line1>,<line2>) " Untrail, for pastes from tmux (containing border). command! -range=% -nargs=0 -bar UntrailSpecial keepjumps call StripWhitespace(<line1>,<line2>,'[\\]\@<!\s\+│\?$') nnoremap <leader>st :Untrail<CR> " Source/execute current line/selection/operator-pending. {{{ " This uses a temporary file instead of "exec", which does not handle " statements after "endfunction". fun! SourceViaFile() range let tmpfile = tempname() call writefile(getbufline(bufnr('%'), a:firstline, a:lastline), tmpfile) exe "source" tmpfile if &verbose echom "Sourced ".(a:lastline - a:firstline + 1)." lines." endif endfun command! -range SourceThis <line1>,<line2>call SourceViaFile() map <Leader>< <Plug>(operator-source) nnoremap <Leader><< :call SourceViaFile()<cr> if &rtp =~ '\<operator-user\>' call operator#user#define('source', 'Op_source_via_file') " call operator#user#define_ex_command('source', 'SourceThis') function! Op_source_via_file(motion_wiseness) " execute (line("']") - line("'[") + 1) 'wincmd' '_' '[,']call SourceViaFile() endfunction endif " }}} " Shortcut for <C-r>= in cmdline. fun! RR(...) return call(ProjectRootGuess, a:000) endfun command! RR ProjectRootLCD command! RRR ProjectRootCD " Follow symlink and lcd to root. fun! MyLCDToProjectRoot() let oldcwd = getcwd() FollowSymlink ProjectRootLCD if oldcwd != getcwd() echom "lcd:" oldcwd "=>" getcwd() endif endfun nnoremap <silent> <Leader>fr :call MyLCDToProjectRoot()<cr> " Toggle pattern (typically a char) at the end of line(s). {{{2 function! MyToggleLastChar(pat) let view = winsaveview() try keepjumps keeppatterns exe 's/\([^'.escape(a:pat,'/').']\)$\|^$/\1'.escape(a:pat,'/').'/' catch /^Vim\%((\a\+)\)\=:E486: Pattern not found/ keepjumps keeppatterns exe 's/'.escape(a:pat, '/').'$//' finally call winrestview(view) endtry endfunction if has('vim_starting') noremap <unique> <Leader>,; :call MyToggleLastChar(';')<cr> noremap <unique> <Leader>,: :call MyToggleLastChar(':')<cr> noremap <unique> <Leader>,, :call MyToggleLastChar(',')<cr> noremap <unique> <Leader>,. :call MyToggleLastChar('.')<cr> noremap <unique> <Leader>,qa :call MyToggleLastChar(' # noqa')<cr> endif " use 'en_us' also to work around matchit considering 'en' as 'endif' set spl=de,en_us " Toggle spellang: de => en => de,en fun! MyToggleSpellLang() if &spl == 'de,en' set spl=en elseif &spl == 'en' set spl=de else set spl=de,en endif echo "Set spl to ".&spl endfun nnoremap <Leader>ss :call MyToggleSpellLang()<cr> " Grep in the current (potential unsaved) buffer {{{2 " NOTE: obsolete with Unite. command! -nargs=1 GrepCurrentBuffer call GrepCurrentBuffer('<args>') fun! GrepCurrentBuffer(q) let save_cursor = getpos(".") let save_errorformat = &errorformat try set errorformat=%f:%l:%m cexpr [] exe 'g/'.escape(a:q, '/').'/caddexpr expand("%") . ":" . line(".") . ":" . getline(".")' cw finally call setpos('.', save_cursor) let &errorformat = save_errorformat endtry endfunction " nnoremap <leader><space> :GrepCurrentBuffer <C-r><C-w><cr> " Commands to disable (and re-enable) all other tests in the current file. {{{2 command! DisableOtherTests call DisableOtherTests() fun! DisableOtherTests() let save_cursor = getpos(".") try %s/function test_/function ttest_/ call setpos('.', save_cursor) call search('function ttest_', 'b') normal wx finally call setpos('.', save_cursor) endtry endfun command! EnableAllTests call EnableAllTests() fun! EnableAllTests() let save_cursor = getpos(".") try %s/function ttest_/function test_/ finally call setpos('.', save_cursor) endtry endfun " Twiddle case of chars / visual selection. {{{2 " source http://vim.wikia.com/wiki/Switching_case_of_characters function! TwiddleCase(str) if a:str ==# toupper(a:str) let result = tolower(a:str) elseif a:str ==# tolower(a:str) let result = substitute(a:str,'\(\<\w\+\>\)', '\u\1', 'g') else let result = toupper(a:str) endif return result endfunction vnoremap ~ ygv"=TwiddleCase(@")<CR>Pgv " }}}2 " Exit if the last window is a controlling one (NERDTree, qf). {{{2 -function! s:CloseIfOnlyControlWinLeft() +" Note: vim-qf has something similar (but simpler). +function! s:QuitIfOnlyControlWinLeft() if winnr("$") != 1 return endif " Alt Source: https://github.com/scrooloose/nerdtree/issues/21#issuecomment-3348390 " autocmd bufenter * if (winnr("$") == 1 && exists("b:NERDTreeType") && b:NERDTreeType == "primary") | q | endif if (exists("t:NERDTreeBufName") && bufwinnr(t:NERDTreeBufName) != -1) \ || &buftype == 'quickfix' " NOTE: problematic with Unite's directory, when opening a file: " :Unite from startify, then quitting Unite quits Vim; also with TMRU from " startify. " \ || &ft == 'startify' q endif endfunction -augroup CloseIfOnlyControlWinLeft +augroup my_QuitIfOnlyControlWinLeft au! - au BufEnter * call s:CloseIfOnlyControlWinLeft() + au BufEnter * nested call s:QuitIfOnlyControlWinLeft() augroup END " }}}2 " Check for file modifications automatically " (current buffer only) " Use :NoAutoChecktime to disable it (uses b:autochecktime) fun! MyAutoCheckTime() " only check timestamp for normal files if &buftype != '' | return | endif if ! exists('b:autochecktime') || b:autochecktime checktime % let b:autochecktime = 1 endif endfun augroup MyAutoChecktime au! " NOTE: nested is required for Neovim to trigger FileChangedShellPost " autocommand with :checktime. au FocusGained,BufEnter,CursorHold,InsertEnter * nested call MyAutoCheckTime() augroup END command! NoAutoChecktime let b:autochecktime=0 command! ToggleAutoChecktime let b:autochecktime=!get(b:, 'autochecktime', 0) | echom "b:autochecktime:" b:autochecktime " vcscommand: only used as lib for detection (e.g. with airline). {{{1 " Setup b:VCSCommandVCSType. function! SetupVCSType() try call VCSCommandGetVCSType(bufnr('%')) catch /No suitable plugin/ endtry endfunction " do not call it automatically for now: vcscommands behaves weird (changing " dirs), and slows simple scrolling (?) down (that might be quickfixsigns " though) if exists("*VCSCommandVCSType") "au BufRead * call SetupVCSType() endif let g:VCSCommandDisableMappings = 1 " }}}1 " Open Windows explorer and select current file if executable('explorer.exe') command! Winexplorer :!start explorer.exe /e,/select,"%:p:gs?/?\\?" endif " do not pick last item automatically (non-global: g:tmru_world.tlib_pick_last_item) let g:tlib_pick_last_item = 1 let g:tlib_inputlist_match = 'cnf' let g:tmruSize = 2000 let g:tmru_resolve_method = '' " empty: ask, 'read' or 'write'. let g:tlib#cache#purge_days = 365 let g:tmru_world = {} let g:tmru_world.cache_var = 'g:tmru_cache' let g:tmru#drop = 0 " do not `:drop` to files in existing windows. XXX: should use/follow &switchbuf maybe?! XXX: not documented " Easytags let g:easytags_on_cursorhold = 0 " disturbing, at least on work machine let g:easytags_cmd = 'ctags' let g:easytags_suppress_ctags_warning = 1 " let g:easytags_dynamic_files = 1 let g:easytags_resolve_links = 1 let g:easytags_async = 1 let g:detectindent_preferred_indent = 2 " used for sw and ts if only tabs let g:detectindent_preferred_expandtab = 1 let g:detectindent_min_indent = 2 let g:detectindent_max_indent = 4 let g:detectindent_max_lines_to_analyse = 100 " command-t plugin {{{ let g:CommandTMaxFiles=50000 let g:CommandTMaxHeight=20 " NOTE: find finder does not skip g:CommandTWildIgnore for scanning! " let g:CommandTFileScanner='find' if has("autocmd") && exists(":CommandTFlush") && has("ruby") " this is required for Command-T to pickup the setting(s) au VimEnter * CommandTFlush endif if (has("gui_running")) " use Alt-T in GUI mode map <A-t> :CommandT<CR> endif map <leader>tt :CommandT<CR> map <leader>t. :execute "CommandT ".expand("%:p:h")<cr> map <leader>t :CommandT<space> map <leader>tb :CommandTBuffer<CR> " }}} " Setup completefunc / base completion. {{{ " (used as fallback (manual)). " au FileType python set completefunc=eclim#python#complete#CodeComplete if !s:use_ycm && has("autocmd") && exists("+omnifunc") augroup vimrc_base_omnifunc au! if &rtp =~ '\<eclim\>' au FileType * if index( \ ["php", "javascript", "css", "python", "xml", "java", "html"], &ft) != -1 | \ let cf="eclim#".&ft."#complete#CodeComplete" | \ exec 'setlocal omnifunc='.cf | \ endif " function! eclim#php#complete#CodeComplete(findstart, base) " function! eclim#javascript#complete#CodeComplete(findstart, base) " function! eclim#css#complete#CodeComplete(findstart, base) " function! eclim#python#complete#CodeComplete(findstart, base) " {{{ " function! eclim#xml#complete#CodeComplete(findstart, base) " function! eclim#java#complete#CodeComplete(findstart, base) " {{{ " function! eclim#java#ant#complete#CodeComplete(findstart, base) " function! eclim#html#complete#CodeComplete(findstart, base) else au FileType css setlocal omnifunc=csscomplete#CompleteCSS au FileType html,markdown setlocal omnifunc=htmlcomplete#CompleteTags au FileType javascript setlocal omnifunc=javascriptcomplete#CompleteJS au FileType python setlocal omnifunc=pythoncomplete#Complete au FileType xml setlocal omnifunc=xmlcomplete#CompleteTags "au FileType ruby setlocal omnifunc=rubycomplete#Complete endif au FileType htmldjango set omnifunc=htmldjangocomplete#CompleteDjango " Use syntaxcomplete, if there is no better omnifunc. autocmd Filetype * \ if &omnifunc == "" | \ setlocal omnifunc=syntaxcomplete#Complete | \ endif augroup END endif " }}} " supertab.vim {{{ if &rtp =~ '\<supertab\>' " "context" appears to trigger path/file lookup?! " let g:SuperTabDefaultCompletionType = 'context' " let g:SuperTabContextDefaultCompletionType = "<c-p>" " let g:SuperTabContextTextFileTypeExclusions = " \ ['htmldjango', 'htmljinja', 'javascript', 'sql'] " auto select the first result when using 'longest' "let g:SuperTabLongestHighlight = 1 " triggers bug with single match (https://github.com/ervandew/supertab/commit/e026bebf1b7113319fc7831bc72d0fb6e49bd087#commitcomment-297471) " let g:SuperTabLongestEnhanced = 1 " involves mappings; requires " completeopt =~ longest let g:SuperTabClosePreviewOnPopupClose = 1 let g:SuperTabNoCompleteAfter = ['^', '\s'] " map <c-space> to <c-p> completion (useful when supertab 'context' " defaults to something else). " imap <nul> <c-r>=SuperTabAlternateCompletion("\<lt>c-p>")<cr> " Setup completion with SuperTab: default to omnifunc (YouCompleteMe), " then completefunc. if s:use_ycm " Call YouCompleteMe always (semantic). " Let &completefunc untouched (eclim). " Use autocommand to override any other automatic setting from filetypes. " Use SuperTab chaining to fallback to "<C-p>". " autocmd FileType * " \ let g:ycm_set_omnifunc = 0 | " \ set omnifunc=youcompleteme#OmniComplete " let g:SuperTabDefaultCompletionType = "<c-x><c-o>" fun! CompleteViaSuperTab(findstart, base) let old = g:ycm_min_num_of_chars_for_completion " 0 would trigger/force semantic completion (results in everything after " a dot also). let g:ycm_min_num_of_chars_for_completion = 1 let r = youcompleteme#Complete(a:findstart, a:base) let g:ycm_min_num_of_chars_for_completion = old return r endfun " completefunc is used by SuperTab's chaining. " let ycm_set_completefunc = 0 autocmd FileType * \ call SuperTabChain("CompleteViaSuperTab", "<c-p>") | \ call SuperTabSetDefaultCompletionType("<c-x><c-u>") | " Let SuperTab trigger YCM always. " call SuperTabChain('youcompleteme#OmniComplete', "<c-p>") | " let g:SuperTabChain = ['youcompleteme#Complete', "<c-p>"] " set completefunc=SuperTabCodeComplete " let g:SuperTabDefaultCompletionType = "<c-x><c-u>" " autocmd FileType * " \ call SuperTabChain('youcompleteme#Complete', "<c-p>") | " \ call SuperTabSetDefaultCompletionType("<c-x><c-u>") | else let g:SuperTabDefaultCompletionType = "<c-p>" autocmd FileType * \ if &omnifunc != '' | \ call SuperTabChain(&omnifunc, "<c-p>") | \ call SuperTabSetDefaultCompletionType("<c-x><c-u>") | \ elseif &completefunc != '' | \ call SuperTabChain(&completefunc, "<c-p>") | \ call SuperTabSetDefaultCompletionType("<c-x><c-u>") | \ endif endif endif " }}} let g:LustyExplorerSuppressRubyWarning = 1 " suppress warning when vim-ruby is not installed let g:EclimLargeFileEnabled = 0 let g:EclimCompletionMethod = 'completefunc' " Default, picked up via SuperTab. " let g:EclimLogLevel = 6 " if exists(":EclimEnable") " au VimEnter * EclimEnable " endif let g:EclimShowCurrentError = 0 " can be really slow, when used with PHP omnicompletion. I am using Syntastic anyway. let g:EclimSignLevel = 0 let g:EclimLocateFileNonProjectScope = 'ag' " Disable eclim's validation, prefer Syntastic. " NOTE: patch pending to do so automatically (in eclim). " does not work as expected, ref: https://github.com/ervandew/eclim/issues/199 let g:EclimFileTypeValidate = 0 " Disable HTML indenting via eclim, ref: https://github.com/ervandew/eclim/issues/332. let g:EclimHtmlIndentDisabled = 1 let g:EclimHtmldjangoIndentDisabled = 1 " lua {{{ let g:lua_check_syntax = 0 " done via syntastic let g:lua_define_omnifunc = 0 " must be enabled also (g:lua_complete_omni=1, but crashes Vim!) let g:lua_complete_keywords = 0 " interferes with YouCompleteMe let g:lua_complete_globals = 0 " interferes with YouCompleteMe? let g:lua_complete_library = 0 " interferes with YouCompleteMe let g:lua_complete_dynamic = 0 " interferes with YouCompleteMe let g:lua_complete_omni = 0 " Disabled by default. Likely to crash Vim! let g:lua_define_completion_mappings = 0 " }}} " Prepend <leader> to visualctrlg mappings. let g:visualctrg_no_default_keymappings = 1 silent! vmap <unique> <Leader><C-g> <Plug>(visualctrlg-briefly) silent! vmap <unique> <Leader>g<C-g> <Plug>(visualctrlg-verbosely) " Toggle quickfix window, using <Leader>qq. {{{2 " Based on: http://vim.wikia.com/wiki/Toggle_to_open_or_close_the_quickfix_window nnoremap <Leader>qq :QFix<CR> nnoremap <Leader>cc :QFix<CR> command! -bang -nargs=? QFix call QFixToggle(<bang>0) function! QFixToggle(forced) if exists("t:qfix_buf") && bufwinnr(t:qfix_buf) != -1 && a:forced == 0 cclose else copen let t:qfix_buf = bufnr("%") endif endfunction " Used to track manual opening of the quickfix, e.g. via `:copen`. augroup QFixToggle au! au BufWinEnter quickfix let g:qfix_buf = bufnr("%") augroup END " 2}}} fun! MyHandleWinClose(event) if get(t:, '_win_count', 0) > winnr('$') " NOTE: '<nomodeline>' prevents the modelines to get applied, even if " there are no autocommands being executed! " That would cause folds to collaps after closing another window and " coming back to e.g. this vimrc. doautocmd <nomodeline> User MyAfterWinClose endif let t:_win_count = winnr('$') endfun augroup vimrc_user au! for e in ['BufWinEnter', 'WinEnter', 'BufDelete', 'BufWinLeave'] exec 'au' e '* call MyHandleWinClose("'.e.'")' endfor augroup END endif " 1}}} eval guard " Mappings {{{1 " Save. nnoremap <silent> <C-s> :up<CR>:if &diff \| diffupdate \| endif<cr> imap <C-s> <Esc><C-s> " Swap n_CTRL-Z and n_CTRL-Y (qwertz layout; CTRL-Z should be next to CTRL-U). nnoremap <C-z> <C-y> nnoremap <C-y> <C-z> " map! <C-Z> <C-O>:stop<C-M> " zi: insert one char " map zi i$<ESC>r " defined in php-doc.vim " nnoremap <Leader>d :call PhpDocSingle()<CR> nnoremap <Leader>n :NERDTree<space> nnoremap <Leader>n. :execute "NERDTree ".expand("%:p:h")<cr> nnoremap <Leader>nb :NERDTreeFromBookmark<space> nnoremap <Leader>nn :NERDTreeToggle<cr> nnoremap <Leader>no :NERDTreeToggle<space> nnoremap <Leader>nf :NERDTreeFind<cr> nnoremap <Leader>nc :NERDTreeClose<cr> nnoremap <S-F1> :tab<Space>:help<Space> " ':tag {ident}' - difficult on german keyboard layout and not working in gvim/win32 nnoremap <F2> g<C-]> " expand abbr (insert mode and command line) noremap! <F2> <C-]> nnoremap <F3> :if exists('g:tmru#world')<cr>:let g:tmru#world.restore_from_cache = []<cr>:endif<cr>:TRecentlyUsedFiles<cr> nnoremap <S-F3> :if exists('g:tmru#world')<cr>:let g:tmru#world.restore_from_cache = ['filter']<cr>:endif<cr>:TRecentlyUsedFiles<cr> " XXX: mapping does not work (autoclose?!) " noremap <F3> :CtrlPMRUFiles fun! MyF5() if &diff diffupdate else e endif endfun noremap <F5> :call MyF5()<cr> " noremap <F11> :YRShow<cr> " if has('gui_running') " map <silent> <F11> :call system("wmctrl -ir " . v:windowid . " -b toggle,fullscreen")<CR> " imap <silent> <F11> <Esc><F11>a " endif " }}} " tagbar plugin nnoremap <silent> <F8> :TagbarToggle<CR> nnoremap <silent> <Leader><F8> :TagbarOpenAutoClose<CR> " VimFiler {{{2 let g:vimfiler_as_default_explorer = 1 let g:vimfiler_ignore_filters = ['matcher_ignore_wildignore'] " Netrw {{{2 " Short-circuit detection, which might be even wrong. let g:netrw_browsex_viewer = 'open-in-running-browser' " NERDTree {{{2 " Show hidden files *except* the known temp files, system files & VCS files let NERDTreeHijackNetrw = 0 let NERDTreeShowHidden = 1 let NERDTreeIgnore = [] for suffix in split(&suffixes, ',') let NERDTreeIgnore += [ escape(suffix, '.~') . '$' ] endfor let NERDTreeIgnore += ['^\.bundle$', '^\.bzr$', '^\.git$', '^\.hg$', '^\.sass-cache$', '^\.svn$', '^\.$', '^\.\.$', '^Thumbs\.db$'] let NERDTreeIgnore += ['__pycache__', '.ropeproject'] " }}} " TODO " noremap <Up> gk " noremap <Down> gj " (Cursor keys should be consistent between insert and normal mode) " slow! " inoremap <Up> <C-O>:normal gk<CR> " inoremap <Down> <C-O>:normal gj<CR> " " j,k move by screen line instead of file line. " nnoremap j gj " nnoremap k gk nnoremap <Down> gj nnoremap <Up> gk " inoremap <Down> <C-o>gj " inoremap <Up> <C-o>gk " XXX: does not keep virtual column! Also adds undo points! " inoremap <expr> <Down> pumvisible() ? "\<C-n>" : "\<C-o>gj" " inoremap <expr> <Up> pumvisible() ? "\<C-p>" : "\<C-o>gk" " Make C-BS and C-Del work like they do in most text editors for the sake of muscle memory {{{2 imap <C-BS> <C-W> imap <C-Del> <C-O>dw imap <C-S-Del> <C-O>dW " Map delete to 'delete to black hole register' (experimental, might use " `d` instead) " Join lines, if on last column, delete otherwise (used in insert mode) " NOTE: de-activated: misbehaves with '""' at end of line (autoclose), " and deleting across lines works anyway. The registers also do not " get polluted.. do not remember why I came up with it... " function! MyDelAcrossEOL() " echomsg col(".") col("$") " if col(".") == col("$") " " XXX: found no way to use '_' register " call feedkeys("\<Down>\<Home>\<Backspace>") " else " normal! "_x " endif " return '' " endfunction " noremap <Del> "_<Del> " inoremap <Del> <C-R>=MyDelAcrossEOL()<cr> " vnoremap <Del> "_<Del> " " Vaporize delete without overwriting the default register. {{{1 " nnoremap vd "_d " xnoremap x "_d " nnoremap vD "_D " }}} " Replace without yank {{{ " Source: https://github.com/justinmk/config/blob/master/.vimrc#L743 func! s:replace_without_yank(type) let sel_save = &selection let l:col = col('.') let &selection = "inclusive" if a:type == 'line' silent normal! '[V']"_d elseif a:type == 'block' silent normal! `[`]"_d else silent normal! `[v`]"_d endif if col('.') == l:col "paste to the left. silent normal! P else "if the operation deleted the last column, then the cursor "gets bumped left (because its original position no longer exists), "so we need to paste to the right instead of the left. silent normal! p endif let &selection = sel_save endf nnoremap <silent> rr :<C-u>set opfunc=<sid>replace_without_yank<CR>g@ nnoremap <silent> rrr 0:<C-u>set opfunc=<sid>replace_without_yank<CR>g@$ " }}} map _ <Plug>(operator-replace) function! TabIsEmpty() return winnr('$') == 1 && WindowIsEmpty() endfunction " Is the current window considered to be empty? function! WindowIsEmpty() if &ft == 'startify' return 1 endif return len(expand('%')) == 0 && line2byte(line('$') + 1) <= 2 endfunction function! MyEditConfig(path, ...) let cmd = a:0 ? a:1 : (WindowIsEmpty() ? 'e' : 'vsplit') exec cmd a:path endfunction " edit vimrc shortcut nnoremap <leader>ec :call MyEditConfig(resolve($MYVIMRC))<cr> nnoremap <leader>Ec :call MyEditConfig(resolve($MYVIMRC), 'edit')<cr> " edit zshrc shortcut nnoremap <leader>ez :call MyEditConfig(resolve("~/.zshrc"))<cr> " edit .lvimrc shortcut (in repository root) nnoremap <leader>elv :call MyEditConfig(ProjectRootGuess().'/.lvimrc')<cr> nnoremap <leader>em :call MyEditConfig(ProjectRootGuess().'/Makefile')<cr> nnoremap <leader>et :call MyEditConfig(expand('~/TODO'))<cr> nnoremap <leader>ept :call MyEditConfig(ProjectRootGet().'/TODO')<cr> " Utility functions to create file commands " Source: https://github.com/carlhuda/janus/blob/master/gvimrc " function! s:CommandCabbr(abbreviation, expansion) " execute 'cabbrev ' . a:abbreviation . ' <c-r>=getcmdpos() == 1 && getcmdtype() == ":" ? "' . a:expansion . '" : "' . a:abbreviation . '"<CR>' " endfunction " Open URL nmap <leader>gw <Plug>(openbrowser-smart-search) vmap <leader>gw <Plug>(openbrowser-smart-search) " Remap CTRL-W_ using vim-maximizer (smarter and toggles). nnoremap <silent><c-w>_ :MaximizerToggle<CR> vnoremap <silent><F3> :MaximizerToggle<CR>gv inoremap <silent><F3> <C-o>:MaximizerToggle<CR> " vimdiff current vs git head (fugitive extension) {{{2 " Close any corresponding fugitive diff buffer. function! MyCloseDiff() if (&diff == 0 || getbufvar('#', '&diff') == 0) \ && (bufname('%') !~ '^fugitive:' && bufname('#') !~ '^fugitive:') echom "Not in diff view." return endif diffoff " safety net / required to workaround powerline issue " Close current buffer if alternate is not fugitive but current one is. if bufname('#') !~ '^fugitive:' && bufname('%') =~ '^fugitive:' if bufwinnr("#") == -1 " XXX: might not work reliable (old comment) b # bd # else bd endif else bd # endif endfunction " nnoremap <Leader>gd :Gdiff<cr> " Maps related to version control (Git). {{{1 " Toggle `:Gdiff`. nnoremap <silent> <Leader>gd :if !&diff \|\| winnr('$') == 1 \| FollowSymlink \| Gdiff \| else \| call MyCloseDiff() \| endif <cr> nnoremap <Leader>gDm :Gdiff master:%<cr> nnoremap <Leader>gDom :Gdiff origin/master:%<cr> nnoremap <Leader>gDs :Gdiff stash:%<cr> " nnoremap <Leader>gD :Git difftool % nnoremap <Leader>gb :Gblame<cr> nnoremap <Leader>gl :Glog<cr> nnoremap <Leader>gs :Gstatus<cr> " Shortcuts for committing. nnoremap <Leader>gc :Gcommit -v command! -nargs=1 Gcm Gcommit -m <q-args> " }}}1
blueyed/dotfiles
dee0365d77605d9f42039e369efbea47d5c0d43d
tmux: improve select-pane mappings
diff --git a/tmux.conf b/tmux.conf index c9ef9ac..5d79123 100644 --- a/tmux.conf +++ b/tmux.conf @@ -1,212 +1,212 @@ # This file holds common settings between tmux and byobu-tmux. # It gets sourced by ~/.tmux.conf and ~/.byobu/.tmux.conf. # # TODO: select windows using alt-NR (again)?! - but used in Vim, too. # Use new tmux-256color terminfo, also provided in ~/.dotfiles/terminfo (via FAQ). set -g default-terminal "tmux-256color" # Use xterm keycodes for Shift-F1 etc (for Vim). set-window-option -g xterm-keys on # Set utf8 options only for tmux < 2.2. if '[ "#{utf8}" ]' 'set -g utf8 on; set -g status-utf8 on; set -g mouse-utf8 on' '' # Do not use a login shell. set -g default-command "exec $SHELL" # Disable terminal capabilities for alternate screen, to make is scrollable in # the outer terminal emulator (via S-PageUp/S-PageDown). # Enable S-PageUp/S-PageDown. # (see byobu bug https://bugs.launchpad.net/byobu/+bug/1258537 and # http://superuser.com/a/326592/30216) # NOTE: disabled, because it fails to restore the screen after "attach", when tmux exists # ("make test" in vim-diminactive). # set -ga terminal-overrides ",xterm*:smcup@:rmcup@" # Setup defaults from xterm* also for urxvt (minus Ms for set-selection). # Asked about this on the mailing list (rejected): https://sourceforge.net/p/tmux/mailman/message/33169870/ set -ga terminal-overrides ",rxvt*:XT:Cs=\\E]12;%p1%s\\007:Cr=\\E]112\\007:Ss=\\E[%p1%d q:Se=\\E[2 q" # Toggle mouse mode. bind M-m run "tmux-toggle-mouse on" bind M-M run "tmux-toggle-mouse off" # Improved mouse-wheel/page-up handling ("More like old tmux"). # Based on https://bbs.archlinux.org/viewtopic.php?pid=1572580#p1572580. # NOTE on auto-PPage: `less -X` does not use alternate-screen. Therefore # this also looks for "less" in pane's ps list # (based on has_vim from vim-tmux-navigator). has_less="ps -o state= -o comm= -t '#{pane_tty}' \ | grep -qE '^[^TXZ ]+ +(\S+\/)?less$'" # Test for tmux 2.1+ by checking for a new variable. is_tmux21='[ "#{pid}" ]' if "$is_tmux21" '\ bind -n PPage if-shell -F "#{alternate_on}" "send-keys PPage" "if \"$has_less\" \"send-keys PPage\" \"copy-mode -e; send-keys PPage\"" ;\ bind -t vi-copy PPage page-up ;\ bind -t vi-copy NPage page-down ;\ bind -t emacs-copy PPage page-up ;\ bind -t emacs-copy NPage page-down ;\ bind -n WheelUpPane if-shell -F -t = "#{mouse_any_flag}" "send-keys -M" "if -Ft= \"#{pane_in_mode}\" \"send-keys -M\" \"select-pane -t=; copy-mode -e; send-keys -M\"" ;\ bind -n WheelDownPane select-pane -t= \; send-keys -M ;\ bind -t vi-copy WheelUpPane halfpage-up ;\ bind -t vi-copy WheelDownPane halfpage-down ;\ bind -t emacs-copy WheelUpPane halfpage-up ;\ bind -t emacs-copy WheelDownPane halfpage-down' # Use C-a as prefix. # Via http://robots.thoughtbot.com/post/2641409235/a-tmux-crash-course unbind C-b set -g prefix C-a bind a send-prefix # set -g prefix2 ^ # bind ^ send-prefix -2 # bind C-a send-prefix # bind C-A send-prefix \; send-prefix # bind -n C-^ send-keys C-^ # Reload config: unset/reset options that are appended to. # Unsetting global config vars is fixed in Git for tmux 2.1. # set -gu update-environment # set -gu terminal-overrides _tmux_conf=~/.tmux.conf bind R source-file $_tmux_conf \; display "Reloaded!" bind C-a last-window bind -r Tab select-pane -t :.+ bind -r S-Tab select-pane -t :.- # via http://jasonwryan.com/blog/2011/06/07/copy-and-paste-in-tmux/ unbind [ bind Escape copy-mode # unbind p bind P paste-buffer bind-key -t vi-copy 'v' begin-selection # Yank to tmux buffer and X11 selection. bind-key -t vi-copy 'y' copy-pipe "xsel -i --primary" # tmux buffer <-> clipboard interaction bind C-c run "tmux show-buffer | xsel -i --clipboard" \; display 'Copied..' bind C-v run "tmux set-buffer -- \"$(xsel -o --clipboard)\"; tmux paste-buffer" set-option -g display-time 4000 set-option -g display-panes-time 4000 # time for repeating of a hotkey bound using the -r flag without having to type the prefix again; default: 500 set-option -g repeat-time 1000 # Resize the window to the size of the smallest session for which it is the # current window, rather than the smallest session to which it is attached. set -g aggressive-resize on set -g history-limit 50000 # Terminal emulator window title set -g set-titles on # Use hostname (@#h) in set-titles-string with SSH. if-shell 'test -n "$SSH_CONNECTION"' 'set -g set-titles-string "[tmux: #S:#I.#P @#h] #T"' 'set -g set-titles-string "[tmux: #S:#I.#P] #T"' # Config for vim-like movements; based on https://github.com/sdball/dotfiles/blob/master/.tmux.conf bind h select-pane -L bind j select-pane -D bind k select-pane -U bind l select-pane -R # Do not allow for repeating (-r, default; distracts with shell history). bind-key Up select-pane -U # Vim movement keys for moving windows. bind -r C-H select-window -t :- bind -r C-L select-window -t :+ # Use 1 as base for windows/panes. set -g base-index 1 set -g pane-base-index 1 # Resize panes with meta-h/j/k/l (repeats). bind -r M-h resize-pane -L 6 bind -r M-j resize-pane -D 5 bind -r M-k resize-pane -U 5 bind -r M-l resize-pane -R 5 # Swap panes with Shift-h/j/k/l. bind H swap-window -t -1 bind L swap-window -t +1 bind J swap-pane -D bind K swap-pane -U # vi mode setw -g mode-keys vi # vim movement keys for switching panes # Emacs key bindings in tmux command prompt (prefix + :) are better than # vi keys, even for vim users. set -g status-keys emacs # Focus events enabled for terminals that support them. set -g focus-events on # # enable maximizing panes # NOTE: `resize-pane -Z` is available with tmux 1.8 (bound to "z") # bind S-Up new-window -d -n tmp \; swap-pane -s tmp.0 \; select-window -t tmp # bind S-Down last-window \; swap-pane -s tmp.0 \; kill-window -t tmp # Activity Monitoring # b/B: set/unset bell bind b setw monitor-activity on bind B setw monitor-activity off set -g visual-activity on # Removed in 992ef70 (after 1.9a). # set -g visual-content on set -g visual-bell off # default # Sets urgent flag for window manager. set -g bell-action any # default?! set -g bell-on-alert on # Do not make Esc+key behave like Alt-key. set -s escape-time 0 # Smart pane switching with awareness of Vim splits. # See: https://github.com/christoomey/vim-tmux-navigator is_vim="ps -o state= -o comm= -t '#{pane_tty}' \ | grep -iqE '^[^TXZ ]+ +(\\S+\\/)?g?(view|n?vim?x?)(diff)?$'" -bind-key -n C-h if-shell "$is_vim" "send-keys C-h" "select-pane -L" -bind-key -n C-j if-shell "$is_vim" "send-keys C-j" "select-pane -D" -bind-key -n C-k if-shell "$is_vim" "send-keys C-k" "select-pane -U" -bind-key -n C-l if-shell "$is_vim" "send-keys C-l" "select-pane -R" -bind-key -n C-\ if-shell "$is_vim" "send-keys C-\\" "select-pane -l" +bind-key -r h if-shell "$is_vim" "send-keys C-h" "select-pane -L" +bind-key -r j if-shell "$is_vim" "send-keys C-j" "select-pane -D" +bind-key -r k if-shell "$is_vim" "send-keys C-k" "select-pane -U" +bind-key -r l if-shell "$is_vim" "send-keys C-l" "select-pane -R" +bind-key ^ select-pane -l # restore original C-l bind C-l send-keys 'C-l' # Colors, via seebi/tmux-colors-solarized. if '[ "$MY_X_THEME_VARIANT" = "light" ]' 'source $HOME/.dotfiles/lib/tmux-colors-solarized/tmuxcolors-light.conf' 'source $HOME/.dotfiles/lib/tmux-colors-solarized/tmuxcolors-dark.conf' set -ga update-environment " MY_X_THEME_VARIANT" # Window status formats, using #W or #T conditionally (via zsh renaming). # Uses reverse attribute if the prefix key has been pressed. set -g status-left '#{?client_prefix,#[underscore],}#S:#{?client_prefix,,#[underscore]}' set -g window-status-format "#I#F #{=20:?window_name,[#W],#T}" set -g window-status-current-format "#I#F #{=50:?window_name,[#W],#T}" set -g status-right "" set -g -a window-status-activity-style italics set -g -a window-status-style noitalics # Automatic rename on by default, indicates that the window name can be set to # 0 via zsh, and gets turned off then (via ~/.oh-my-zsh/lib/termsupport.zsh). setw -g automatic-rename on # Make window name "empty" (for the test in window-status-format). # NOTE: done via zsh once per shell/window. # rename-window 0 # tmuxstart; like tmuxinator/teamocil, but more inception-like bind S command-prompt -p "Make/attach session:" "new-window 'tmuxstart \'%%\''" # Disable rate-limiting which might cause not all text to get added to the # scrollback buffer. Ref: http://sourceforge.net/p/tmux/tickets/62/ if-shell 'tmux show -g -w | grep -q c0-change-trigger' \ "set -g c0-change-trigger 0" "" # Source ~/.tmux.local.conf if it exists. if '[ -e ~/.tmux.local.conf ]' 'source ~/.tmux.local.conf'
blueyed/dotfiles
a4785b07c6bdf8c931084ce162e18d5e14f1c560
vimrc: update/sync
diff --git a/vimrc b/vimrc index e67de60..282176f 100644 --- a/vimrc +++ b/vimrc @@ -1,543 +1,557 @@ +" NOTE: this is not in sync currently with my local config currently. +" E.g. I am using vim-plug since a while since Neobundle. scriptencoding utf-8 +" Hack for left-over Vader Log commands. +com! -nargs=+ Log call neomake#utils#DebugMessage(type(<args>) == 1 ? <args> : string(<args>)) +com! -nargs=* Assert echo if 1 " has('eval') / `let` may not be available. " Profiling. {{{ - " Start profiling. Optional arg: logfile path. + " Start profiling. Optional args: logfile-path, copy-to-@*. fun! ProfileStart(...) if a:0 && a:1 != 1 - let profile_file = a:1 + let g:profile_file = a:1 else - let profile_file = '/tmp/vim.'.getpid().'.'.reltimestr(reltime())[-4:].'profile.txt' - echom "Profiling into" profile_file - let @* = profile_file + let g:profile_file = '/tmp/vim.'.getpid().'.'.reltimestr(reltime())[-4:].'profile.txt' + echom "Profiling into" g:profile_file + if a:0 < 2 || a:2 + let @* = g:profile_file + endif endif - exec 'profile start '.profile_file + exec 'profile start '.g:profile_file profile! file ** profile func * endfun if len(get(g:, 'profile', '')) call ProfileStart(g:profile) endif if 0 - call ProfileStart() + call ProfileStart(1, 0) endif " }}} - fun! MyWarningMsg(msg) - redraw + fun! MyWarningMsg(msg, ...) + let redraw = a:0 ? a:1 : !has('vim_starting') + if redraw | redraw | endif echohl WarningMsg | echom a:msg | echohl None endfun + " Use both , and Space as leader, but not for imap. + let mapleader = "," + nmap <space> <Leader> + vmap <space> <Leader> + nmap <space><space> <C-d> + " Try to init neobundle. try set rtp+=~/.vim/bundle/neobundle let s:bundles_path = expand('~/.vim/neobundles') call neobundle#begin(s:bundles_path) let s:use_neobundle = 1 catch echom "NeoBundle not found!" echom "Error:" v:exception let s:use_neobundle = 0 let s:bundles_path = expand('~/.vim/bundles') endtry let s:has_ycm = len(glob(s:bundles_path.'/YouCompleteMe/third_party/ycmd/ycm_core.*')) let s:use_ycm = s:has_ycm " Light(er) setup? if exists('MyRcProfile') if MyRcProfile ==# 'email' " Used with External Editor addon for Thunderbird (~/bin/gvim-email). fun! MySetupForEmail() if exists('b:did_setup_spl_email') return endif let b:did_setup_spl_email=1 let l:cursor = getcurpos() if !search('\v%<5l^(To:|Cc:|Bcc:).*\@(\.de)@!', 'n') " Only german recipients. set spl=de endif call setpos('.', l:cursor) endfun augroup VimRcEmail au! " Not for help windows. au FileType * if &bt == '' | call MySetupForEmail() | endif augroup END let MyRcProfile = 'light' endif else let MyRcProfile = 'default' endif if s:use_neobundle " {{{ filetype off let g:neobundle#enable_name_conversion = 1 " Use normalized names. let g:neobundle#default_options = { \ 'manual': { 'base': '~/.vim/bundle', 'type': 'nosync' }, \ 'colors': { 'script_type' : 'colors' } } " Cache file: use it from tmp/tmpfs. {{{ " This helps in case the default location might not be writable (r/o " bind-mount), and should be good for performance in general (apart from " the first run after reboot). let s:vim_cache = '/tmp/vim-cache-' . $USER if !isdirectory(s:vim_cache) call mkdir(s:vim_cache, "", 0700) endif " NOTE: helptags will still be rebuild always / not cached. " Would require to overwrite neobundle#get_rtp_dir. " https://github.com/Shougo/neobundle.vim/issues/504. let s:cache_key = '_rc'.g:MyRcProfile.'_tmux'.executable("tmux") \ .'_deoplete'.get(s:, 'use_deoplete', 0) \ .'_nvim'.has('nvim') \ .'_ruby'.has('ruby') " Remove any previous cache files. let s:neobundle_default_cache_file = neobundle#commands#get_default_cache_file() let g:neobundle#cache_file = s:neobundle_default_cache_file . s:cache_key if filereadable(s:neobundle_default_cache_file) call delete(s:neobundle_default_cache_file) endif if filereadable(g:neobundle#cache_file) call delete(g:neobundle#cache_file) endif let g:neobundle#cache_file = s:vim_cache.'/neobundle.cache'.s:cache_key " }}} if neobundle#load_cache($MYVIMRC) " NeoBundles list - here be dragons! {{{ fun! MyNeoBundleWrapper(cmd_args, default, light) let lazy = g:MyRcProfile == "light" ? a:light : a:default if lazy == -1 return endif if lazy exec 'NeoBundleLazy ' . a:cmd_args else exec 'NeoBundle ' . a:cmd_args endif endfun com! -nargs=+ MyNeoBundle call MyNeoBundleWrapper(<q-args>, 1, 1) com! -nargs=+ MyNeoBundleLazy call MyNeoBundleWrapper(<q-args>, 1, 1) com! -nargs=+ MyNeoBundleNeverLazy call MyNeoBundleWrapper(<q-args>, 0, 0) com! -nargs=+ MyNeoBundleNoLazyForDefault call MyNeoBundleWrapper(<q-args>, 0, 1) com! -nargs=+ MyNeoBundleNoLazyNotForLight call MyNeoBundleWrapper(<q-args>, 0, -1) if s:use_ycm MyNeoBundleNoLazyForDefault 'blueyed/YouCompleteMe' , { \ 'build': { \ 'unix': './install.sh --clang-completer --system-libclang' \ .' || ./install.sh --clang-completer', \ }, \ 'augroup': 'youcompletemeStart', \ 'autoload': { 'filetypes': ['c', 'vim'], 'commands': 'YcmCompleter' } \ } endif MyNeoBundleLazy 'davidhalter/jedi-vim', '', { \ 'directory': 'jedi', \ 'autoload': { 'filetypes': ['python'], 'commands': ['Pyimport'] }} " Generate NeoBundle statements from .gitmodules. " (migration from pathogen to neobundle). " while read p url; do \ " echo "NeoBundle '${url#*://github.com/}', { 'directory': '${${p##*/}%.url}' }"; \ " done < <(git config -f .gitmodules --get-regexp 'submodule.vim/bundle/\S+.(url)' | sort) MyNeoBundle 'tpope/vim-abolish' MyNeoBundle 'mileszs/ack.vim' MyNeoBundle 'tpope/vim-afterimage' MyNeoBundleNoLazyForDefault 'ervandew/ag' MyNeoBundleNoLazyForDefault 'gabesoft/vim-ags' MyNeoBundleNoLazyForDefault 'blueyed/vim-airline' MyNeoBundleNoLazyForDefault 'vim-airline/vim-airline-themes' MyNeoBundle 'vim-scripts/bufexplorer.zip', { 'name': 'bufexplorer' } MyNeoBundleNoLazyForDefault 'qpkorr/vim-bufkill' MyNeoBundle 'vim-scripts/cmdline-completion', { \ 'autoload': {'mappings': [['c', '<Plug>CmdlineCompletion']]}} MyNeoBundle 'kchmck/vim-coffee-script' MyNeoBundle 'chrisbra/colorizer' \, { 'autoload': { 'commands': ['ColorToggle'] } } MyNeoBundle 'chrisbra/vim-diff-enhanced' \, { 'autoload': { 'commands': ['CustomDiff', 'PatienceDiff'] } } MyNeoBundle 'chrisbra/vim-zsh', { \ 'autoload': {'filetypes': ['zsh']} } " MyNeoBundle 'lilydjwg/colorizer' MyNeoBundle 'JulesWang/css.vim' MyNeoBundleNoLazyForDefault 'ctrlpvim/ctrlp.vim' MyNeoBundleNoLazyForDefault 'JazzCore/ctrlp-cmatcher' MyNeoBundle 'mtth/cursorcross.vim' \, { 'autoload': { 'insert': 1, 'filetypes': 'all' } } MyNeoBundleLazy 'tpope/vim-endwise', { \ 'autoload': {'filetypes': ['lua','elixir','ruby','sh','zsh','vb','vbnet','aspvbs','vim','c','cpp','xdefaults','objc','matlab']} } MyNeoBundle 'blueyed/cyclecolor' MyNeoBundleLazy 'Raimondi/delimitMate' \, { 'autoload': { 'insert': 1, 'filetypes': 'all' }} " MyNeoBundleNeverLazy 'cohama/lexima.vim' " MyNeoBundleNoLazyForDefault 'raymond-w-ko/detectindent' MyNeoBundleNoLazyForDefault 'roryokane/detectindent' MyNeoBundleNoLazyForDefault 'tpope/vim-dispatch' MyNeoBundleNoLazyForDefault 'radenling/vim-dispatch-neovim' MyNeoBundle 'jmcomets/vim-pony', { 'directory': 'django-pony' } MyNeoBundle 'xolox/vim-easytags', { \ 'autoload': { 'commands': ['UpdateTags'] }, \ 'depends': [['xolox/vim-misc', {'name': 'vim-misc'}]]} MyNeoBundleNoLazyForDefault 'tpope/vim-eunuch' MyNeoBundleNoLazyForDefault 'tommcdo/vim-exchange' MyNeoBundle 'int3/vim-extradite' MyNeoBundle 'jmcantrell/vim-fatrat' MyNeoBundleNoLazyForDefault 'kopischke/vim-fetch' MyNeoBundleNoLazyForDefault 'kopischke/vim-stay' MyNeoBundle 'thinca/vim-fontzoom' MyNeoBundleNoLazyForDefault 'idanarye/vim-merginal' MyNeoBundle 'mkomitee/vim-gf-python' MyNeoBundle 'mattn/gist-vim', { \ 'depends': [['mattn/webapi-vim']]} MyNeoBundle 'jaxbot/github-issues.vim' MyNeoBundle 'gregsexton/gitv' MyNeoBundleNeverLazy 'jamessan/vim-gnupg' MyNeoBundle 'google/maktaba' MyNeoBundle 'blueyed/grep.vim' MyNeoBundle 'mbbill/undotree', { \ 'autoload': {'command_prefix': 'Undotree'}} MyNeoBundle 'tpope/vim-haml' MyNeoBundle 'nathanaelkane/vim-indent-guides' " MyNeoBundle 'ivanov/vim-ipython' " MyNeoBundle 'johndgiese/vipy' MyNeoBundle 'vim-scripts/keepcase.vim' " NOTE: sets eventsignore+=FileType globally.. use a own snippet instead. " NOTE: new patch from author. MyNeoBundleNoLazyForDefault 'vim-scripts/LargeFile' " MyNeoBundleNoLazyForDefault 'mhinz/vim-hugefile' " MyNeoBundle 'groenewege/vim-less' MyNeoBundleNoLazyForDefault 'embear/vim-localvimrc' MyNeoBundle 'xolox/vim-lua-ftplugin', { \ 'autoload': {'filetypes': 'lua'}, \ 'depends': [['xolox/vim-misc', {'name': 'vim-misc'}]]} MyNeoBundle 'raymond-w-ko/vim-lua-indent', { \ 'autoload': {'filetypes': 'lua'}} if has('ruby') MyNeoBundleNoLazyForDefault 'sjbach/lusty' endif MyNeoBundle 'vim-scripts/mail.tgz', { 'name': 'mail', 'directory': 'mail_tgz' } MyNeoBundle 'tpope/vim-markdown' MyNeoBundle 'nelstrom/vim-markdown-folding' \, {'autoload': {'filetypes': 'markdown'}} MyNeoBundle 'Shougo/neomru.vim' MyNeoBundleLazy 'blueyed/nerdtree', { \ 'augroup' : 'NERDTreeHijackNetrw' } MyNeoBundle 'blueyed/nginx.vim' MyNeoBundleLazy 'tyru/open-browser.vim', { \ 'autoload': { 'mappings': '<Plug>(openbrowser' } } MyNeoBundle 'kana/vim-operator-replace' MyNeoBundleNoLazyForDefault 'kana/vim-operator-user' MyNeoBundle 'vim-scripts/pac.vim' MyNeoBundle 'mattn/pastebin-vim' MyNeoBundle 'shawncplus/phpcomplete.vim' MyNeoBundle '2072/PHP-Indenting-for-VIm', { 'name': 'php-indent' } MyNeoBundle 'greyblake/vim-preview' MyNeoBundleNoLazyForDefault 'tpope/vim-projectionist' MyNeoBundleNoLazyForDefault 'dbakker/vim-projectroot' " MyNeoBundle 'dbakker/vim-projectroot', { " \ 'autoload': {'commands': 'ProjectRootGuess'}} MyNeoBundle 'fs111/pydoc.vim' \ , {'autoload': {'filetypes': ['python']} } MyNeoBundle 'alfredodeza/pytest.vim' MyNeoBundle '5long/pytest-vim-compiler' \ , {'autoload': {'filetypes': ['python']} } MyNeoBundle 'hynek/vim-python-pep8-indent' \ , {'autoload': {'filetypes': ['python']} } " MyNeoBundle 'Chiel92/vim-autoformat' " \ , {'autoload': {'filetypes': ['python']} } MyNeoBundleNoLazyForDefault 'tomtom/quickfixsigns_vim' MyNeoBundleNoLazyForDefault 't9md/vim-quickhl' MyNeoBundle 'aaronbieber/vim-quicktask' MyNeoBundle 'tpope/vim-ragtag' \ , {'autoload': {'filetypes': ['html', 'smarty', 'php', 'htmldjango']} } MyNeoBundle 'tpope/vim-rails' MyNeoBundle 'vim-scripts/Rainbow-Parenthsis-Bundle' MyNeoBundle 'thinca/vim-ref' MyNeoBundle 'tpope/vim-repeat' MyNeoBundle 'inkarkat/runVimTests' " MyNeoBundleLazy 'tpope/vim-scriptease', { " \ 'autoload': {'mappings': 'zS', 'filetypes': 'vim', 'commands': ['Runtime']} } MyNeoBundleNoLazyForDefault 'tpope/vim-scriptease' MyNeoBundle 'xolox/vim-session', { \ 'autoload': {'commands': ['SessionOpen', 'OpenSession']} \, 'depends': [['xolox/vim-misc', {'name': 'vim-misc'}]] \, 'augroup': 'PluginSession' } " For PHP: " MyNeoBundle 'blueyed/smarty.vim', { " \ 'autoload': {'filetypes': 'smarty'}} MyNeoBundleNeverLazy 'justinmk/vim-sneak' MyNeoBundle 'rstacruz/sparkup' \ , {'autoload': {'filetypes': ['html', 'htmldjango', 'smarty']}} MyNeoBundle 'tpope/vim-speeddating' MyNeoBundle 'AndrewRadev/splitjoin.vim' MyNeoBundleNoLazyForDefault 'AndrewRadev/undoquit.vim' MyNeoBundleNoLazyForDefault 'EinfachToll/DidYouMean' MyNeoBundleNoLazyForDefault 'mhinz/vim-startify' " After startify: https://github.com/mhinz/vim-startify/issues/33 " NeoBundle does not keep the order in the cache though.. :/ MyNeoBundleNoLazyForDefault 'tpope/vim-fugitive' \, {'augroup': 'fugitive'} MyNeoBundleNoLazyForDefault 'chrisbra/sudoedit.vim', { \ 'autoload': {'commands': ['SudoWrite', 'SudoRead']} } MyNeoBundleNoLazyForDefault 'ervandew/supertab' MyNeoBundleNoLazyForDefault 'tpope/vim-surround' MyNeoBundle 'kurkale6ka/vim-swap' MyNeoBundleNoLazyForDefault "neomake/neomake" MyNeoBundle 'vim-scripts/syntaxattr.vim' if executable("tmux") MyNeoBundle 'Keithbsmiley/tmux.vim', { \ 'name': 'syntax-tmux', \ 'autoload': {'filetypes': ['tmux']} } MyNeoBundleNoLazyForDefault 'blueyed/vim-tmux-navigator' MyNeoBundleNoLazyForDefault 'tmux-plugins/vim-tmux-focus-events' MyNeoBundleNoLazyForDefault 'wellle/tmux-complete.vim' endif " Dependency " MyNeoBundle 'godlygeek/tabular' MyNeoBundle 'junegunn/vim-easy-align' \ ,{ 'autoload': {'commands': ['EasyAlign', 'LiveEasyAlign']} } MyNeoBundle 'majutsushi/tagbar' \ ,{ 'autoload': {'commands': ['TagbarToggle']} } MyNeoBundle 'tpope/vim-tbone' MyNeoBundleNoLazyForDefault 'tomtom/tcomment_vim' " MyNeoBundle 'kana/vim-textobj-user' MyNeoBundleNoLazyForDefault 'kana/vim-textobj-function' \ ,{'depends': 'kana/vim-textobj-user'} MyNeoBundleNoLazyForDefault 'kana/vim-textobj-indent' \ ,{'depends': 'kana/vim-textobj-user'} MyNeoBundleNoLazyForDefault 'mattn/vim-textobj-url' \ ,{'depends': 'kana/vim-textobj-user'} MyNeoBundle 'bps/vim-textobj-python' \ ,{'depends': 'kana/vim-textobj-user', \ 'autoload': {'filetypes': 'python'}} MyNeoBundleNoLazyForDefault 'inkarkat/argtextobj.vim', \ {'depends': ['tpope/vim-repeat', 'vim-scripts/ingo-library']} MyNeoBundleNoLazyForDefault 'vim-scripts/ArgsAndMore', \ {'depends': ['vim-scripts/ingo-library']} " MyNeoBundle 'kana/vim-textobj-django-template', 'fix' MyNeoBundle 'mjbrownie/django-template-textobjects' \ , {'autoload': {'filetypes': ['htmldjango']} } MyNeoBundle 'vim-scripts/parameter-text-objects' " paulhybryant/vim-textobj-path " ap/ip (next path w/o basename), aP/iP (prev) " kana/vim-textobj-syntax " ay/iy MyNeoBundle 'tomtom/tinykeymap_vim' MyNeoBundle 'tomtom/tmarks_vim' MyNeoBundleNoLazyForDefault 'tomtom/tmru_vim', { 'depends': \ [['tomtom/tlib_vim', { 'directory': 'tlib' }]]} MyNeoBundle 'vim-scripts/tracwiki' MyNeoBundle 'tomtom/ttagecho_vim' " UltiSnips cannot be set as lazy (https://github.com/Shougo/neobundle.vim/issues/335). MyNeoBundleNoLazyForDefault 'SirVer/ultisnips' " MyNeoBundle 'honza/vim-snippets' MyNeoBundleNoLazyForDefault 'blueyed/vim-snippets' MyNeoBundleNeverLazy 'tpope/vim-unimpaired' MyNeoBundle 'Shougo/unite-outline' MyNeoBundleNoLazyForDefault 'Shougo/unite.vim' MyNeoBundle 'vim-scripts/vcscommand.vim' MyNeoBundleLazy 'joonty/vdebug', { \ 'autoload': { 'commands': 'VdebugStart' }} MyNeoBundle 'vim-scripts/viewoutput' MyNeoBundleNoLazyForDefault 'Shougo/vimfiler.vim' MyNeoBundle 'xolox/vim-misc', { 'name': 'vim-misc' } MyNeoBundle 'tpope/vim-capslock' MyNeoBundle 'sjl/splice.vim' " Sophisticated mergetool. " Enhanced omnifunc for ft=vim. MyNeoBundle 'c9s/vimomni.vim' MyNeoBundle 'inkarkat/VimTAP', { 'name': 'VimTAP' } " Try VimFiler instead; vinegar maps "." (https://github.com/tpope/vim-repeat/issues/19#issuecomment-59454216). " MyNeoBundle 'tpope/vim-vinegar' MyNeoBundle 'jmcantrell/vim-virtualenv' \, { 'autoload': {'commands': 'VirtualEnvActivate'} } MyNeoBundle 'tyru/visualctrlg.vim' MyNeoBundle 'nelstrom/vim-visual-star-search' MyNeoBundle 'mattn/webapi-vim' MyNeoBundle 'gcmt/wildfire.vim' MyNeoBundle 'sukima/xmledit' " Expensive on startup, not used much " (autoload issue: https://github.com/actionshrimp/vim-xpath/issues/7). MyNeoBundleLazy 'actionshrimp/vim-xpath', { \ 'autoload': {'commands': ['XPathSearchPrompt']}} MyNeoBundle 'guns/xterm-color-table.vim' MyNeoBundleNoLazyForDefault 'maxbrunsfeld/vim-yankstack' MyNeoBundle 'klen/python-mode' " MyNeoBundle 'chrisbra/Recover.vim' MyNeoBundleNoLazyForDefault 'blueyed/vim-diminactive' MyNeoBundleNoLazyForDefault 'blueyed/vim-smartinclude' " Previously disabled plugins: MyNeoBundle 'MarcWeber/vim-addon-nix' \, {'name': 'nix', 'autoload': {'filetypes': ['nix']} \, 'depends': [ \ ['MarcWeber/vim-addon-mw-utils', { 'directory': 'mw-utils' }], \ ['MarcWeber/vim-addon-actions', { 'directory': 'actions' }], \ ['MarcWeber/vim-addon-completion', { 'directory': 'completion' }], \ ['MarcWeber/vim-addon-goto-thing-at-cursor', { 'directory': 'goto-thing-at-cursor' }], \ ['MarcWeber/vim-addon-errorformats', { 'directory': 'errorformats' }], \ ]} MyNeoBundleLazy 'szw/vim-maximizer' \ , {'autoload': {'commands': 'MaximizerToggle'}} " Colorschemes. " MyNeoBundle 'vim-scripts/Atom', '', 'colors', { 'name': 'colorscheme-atom' } MyNeoBundleNeverLazy 'chriskempson/base16-vim', '', 'colors', { 'name': 'colorscheme-base16' } " MyNeoBundle 'rking/vim-detailed', '', 'colors', { 'name': 'colorscheme-detailed' } " MyNeoBundle 'nanotech/jellybeans.vim', '', 'colors', { 'name': 'colorscheme-jellybeans' } " MyNeoBundle 'tpope/vim-vividchalk', '', 'colors', { 'name': 'colorscheme-vividchalk' } " MyNeoBundle 'nielsmadan/harlequin', '', 'colors', { 'name': 'colorscheme-harlequin' } " MyNeoBundle 'gmarik/ingretu', '', 'colors', { 'name': 'colorscheme-ingretu' } " MyNeoBundle 'vim-scripts/molokai', '', 'colors', { 'name': 'colorscheme-molokai' } " MyNeoBundle 'vim-scripts/tir_black', '', 'colors', { 'name': 'colorscheme-tir_black' } " MyNeoBundle 'blueyed/xoria256.vim', '', 'colors', { 'name': 'colorscheme-xoria256' } " MyNeoBundle 'vim-scripts/xterm16.vim', '', 'colors', { 'name': 'colorscheme-xterm16' } " MyNeoBundle 'vim-scripts/Zenburn', '', 'colors', { 'name': 'colorscheme-zenburn' } " MyNeoBundle 'whatyouhide/vim-gotham', '', 'colors', { 'name': 'colorscheme-gotham' } " EXPERIMENTAL " MyNeoBundle 'atweiden/vim-betterdigraphs', { 'directory': 'betterdigraphs' } MyNeoBundle 'chrisbra/unicode.vim', { 'type__depth': 1 } MyNeoBundle 'xolox/vim-colorscheme-switcher' MyNeoBundle 't9md/vim-choosewin' MyNeoBundleNeverLazy 'junegunn/vim-oblique/', { 'depends': \ [['junegunn/vim-pseudocl']]} MyNeoBundleNoLazyForDefault 'Konfekt/fastfold' MyNeoBundleNoLazyNotForLight 'junegunn/vader.vim', { \ 'autoload': {'commands': 'Vader'} } MyNeoBundleNoLazyForDefault 'ryanoasis/vim-webdevicons' MyNeoBundle 'mjbrownie/vim-htmldjango_omnicomplete' \ , {'autoload': {'filetypes': ['htmldjango']} } MyNeoBundle 'othree/html5.vim' \ , {'autoload': {'filetypes': ['html', 'htmldjango']} } MyNeoBundleLazy 'lambdalisue/vim-pyenv' " \ , {'depends': ['blueyed/YouCompleteMe'] " \ , 'autoload': {'filetypes': ['python', 'htmldjango']} } " Problems with <a-d> (which is ä), and I prefer <a-hjkl>. " MyNeoBundleNoLazyForDefault 'tpope/vim-rsi' MyNeoBundleNoLazyForDefault 'junegunn/fzf.vim' MyNeoBundleLazy 'chase/vim-ansible-yaml' \ , {'autoload': {'filetypes': ['yaml', 'ansible']} } " MyNeoBundleLazy 'mrk21/yaml-vim' " \ , {'autoload': {'filetypes': ['yaml', 'ansible']} } " Manual bundles. MyNeoBundleLazy 'eclim', '', 'manual' " \ , {'autoload': {'filetypes': ['htmldjango']} } " MyNeoBundle 'neobundle', '', 'manual' " NeoBundleFetch "Shougo/neobundle.vim", { " \ 'default': 'manual', " \ 'directory': 'neobundle', } MyNeoBundleNeverLazy 'blueyed/vim-colors-solarized', { 'name': 'colorscheme-solarized' } " }}} NeoBundleSaveCache endif call neobundle#end() filetype plugin indent on " Use shallow copies by default. let g:neobundle#types#git#clone_depth = 10 NeoBundleCheck " Setup a command alias, source: http://stackoverflow.com/a/3879737/15690 fun! SetupCommandAlias(from, to) exec 'cnoreabbrev <expr> '.a:from \ .' ((getcmdtype() is# ":" && getcmdline() is# "'.a:from.'")' \ .'? ("'.a:to.'") : ("'.a:from.'"))' endfun call SetupCommandAlias('NBS', 'NeoBundleSource') if !has('vim_starting') " Call on_source hook when reloading .vimrc. call neobundle#call_hook('on_source') endif endif endif " Settings {{{1 set hidden if &encoding != 'utf-8' " Skip this on resourcing with Neovim (E905). set encoding=utf-8 endif " Prefer unix fileformat " set fileformat=unix set fileformats=unix,dos set noequalalways " do not auto-resize windows when opening/closing them! set backspace=indent,eol,start " allow backspacing over everything in insert mode set confirm " ask for confirmation by default (instead of silently failing) set nosplitright splitbelow set diffopt+=vertical set diffopt+=context:1000000 " don't fold set history=1000 set ruler " show the cursor position all the time set showcmd " display incomplete commands set incsearch " do incremental searching set nowrapscan " do not wrap around when searching. set writebackup " keep a backup while writing the file (default on) set backupcopy=yes " important to keep the file descriptor (inotify) if 1 " has('eval'), and can create the dir dynamically. set directory=~/tmp/vim/swapfiles// " // => use full path of original file set backup " enable backup (default off), if 'backupdir' can be created dynamically. endif set noautoread " Enabled by default in Neovim; I like to get notified/confirm it. set nowrap if has("virtualedit") set virtualedit+=block endif set autoindent " always set autoindenting on (fallback after 'indentexpr')
blueyed/dotfiles
25a3c93227cfe67d0b495627c9c1eac3e2f9aa19
vimrc: fixup: remove echom
diff --git a/vimrc b/vimrc index 855a654..e67de60 100644 --- a/vimrc +++ b/vimrc @@ -3218,788 +3218,788 @@ let NERDTreeIgnore += ['__pycache__', '.ropeproject'] " nnoremap j gj " nnoremap k gk nnoremap <Down> gj nnoremap <Up> gk " inoremap <Down> <C-o>gj " inoremap <Up> <C-o>gk " XXX: does not keep virtual column! Also adds undo points! " inoremap <expr> <Down> pumvisible() ? "\<C-n>" : "\<C-o>gj" " inoremap <expr> <Up> pumvisible() ? "\<C-p>" : "\<C-o>gk" " Make C-BS and C-Del work like they do in most text editors for the sake of muscle memory {{{2 imap <C-BS> <C-W> imap <C-Del> <C-O>dw imap <C-S-Del> <C-O>dW " Map delete to 'delete to black hole register' (experimental, might use " `d` instead) " Join lines, if on last column, delete otherwise (used in insert mode) " NOTE: de-activated: misbehaves with '""' at end of line (autoclose), " and deleting across lines works anyway. The registers also do not " get polluted.. do not remember why I came up with it... " function! MyDelAcrossEOL() " echomsg col(".") col("$") " if col(".") == col("$") " " XXX: found no way to use '_' register " call feedkeys("\<Down>\<Home>\<Backspace>") " else " normal! "_x " endif " return '' " endfunction " noremap <Del> "_<Del> " inoremap <Del> <C-R>=MyDelAcrossEOL()<cr> " vnoremap <Del> "_<Del> " " Vaporize delete without overwriting the default register. {{{1 " nnoremap vd "_d " xnoremap x "_d " nnoremap vD "_D " }}} " Replace without yank {{{ " Source: https://github.com/justinmk/config/blob/master/.vimrc#L743 func! s:replace_without_yank(type) let sel_save = &selection let l:col = col('.') let &selection = "inclusive" if a:type == 'line' silent normal! '[V']"_d elseif a:type == 'block' silent normal! `[`]"_d else silent normal! `[v`]"_d endif if col('.') == l:col "paste to the left. silent normal! P else "if the operation deleted the last column, then the cursor "gets bumped left (because its original position no longer exists), "so we need to paste to the right instead of the left. silent normal! p endif let &selection = sel_save endf nnoremap <silent> rr :<C-u>set opfunc=<sid>replace_without_yank<CR>g@ nnoremap <silent> rrr 0:<C-u>set opfunc=<sid>replace_without_yank<CR>g@$ " }}} map _ <Plug>(operator-replace) function! TabIsEmpty() return winnr('$') == 1 && WindowIsEmpty() endfunction " Is the current window considered to be empty? function! WindowIsEmpty() if &ft == 'startify' return 1 endif return len(expand('%')) == 0 && line2byte(line('$') + 1) <= 2 endfunction function! MyEditConfig(path, ...) let cmd = a:0 ? a:1 : (WindowIsEmpty() ? 'e' : 'vsplit') exec cmd a:path endfunction " edit vimrc shortcut nnoremap <leader>ec :call MyEditConfig(resolve($MYVIMRC))<cr> nnoremap <leader>Ec :call MyEditConfig(resolve($MYVIMRC), 'edit')<cr> " edit zshrc shortcut nnoremap <leader>ez :call MyEditConfig(resolve("~/.zshrc"))<cr> " edit .lvimrc shortcut (in repository root) nnoremap <leader>elv :call MyEditConfig(ProjectRootGuess().'/.lvimrc')<cr> nnoremap <leader>em :call MyEditConfig(ProjectRootGuess().'/Makefile')<cr> nnoremap <leader>et :call MyEditConfig(expand('~/TODO'))<cr> nnoremap <leader>ept :call MyEditConfig(ProjectRootGet().'/TODO')<cr> " Utility functions to create file commands " Source: https://github.com/carlhuda/janus/blob/master/gvimrc " function! s:CommandCabbr(abbreviation, expansion) " execute 'cabbrev ' . a:abbreviation . ' <c-r>=getcmdpos() == 1 && getcmdtype() == ":" ? "' . a:expansion . '" : "' . a:abbreviation . '"<CR>' " endfunction " Open URL nmap <leader>gw <Plug>(openbrowser-smart-search) vmap <leader>gw <Plug>(openbrowser-smart-search) " Remap CTRL-W_ using vim-maximizer (smarter and toggles). nnoremap <silent><c-w>_ :MaximizerToggle<CR> vnoremap <silent><F3> :MaximizerToggle<CR>gv inoremap <silent><F3> <C-o>:MaximizerToggle<CR> " vimdiff current vs git head (fugitive extension) {{{2 " Close any corresponding fugitive diff buffer. function! MyCloseDiff() if (&diff == 0 || getbufvar('#', '&diff') == 0) \ && (bufname('%') !~ '^fugitive:' && bufname('#') !~ '^fugitive:') echom "Not in diff view." return endif diffoff " safety net / required to workaround powerline issue " Close current buffer if alternate is not fugitive but current one is. if bufname('#') !~ '^fugitive:' && bufname('%') =~ '^fugitive:' if bufwinnr("#") == -1 " XXX: might not work reliable (old comment) b # bd # else bd endif else bd # endif endfunction " nnoremap <Leader>gd :Gdiff<cr> " Maps related to version control (Git). {{{1 " Toggle `:Gdiff`. nnoremap <silent> <Leader>gd :if !&diff \|\| winnr('$') == 1 \| FollowSymlink \| Gdiff \| else \| call MyCloseDiff() \| endif <cr> nnoremap <Leader>gDm :Gdiff master:%<cr> nnoremap <Leader>gDom :Gdiff origin/master:%<cr> nnoremap <Leader>gDs :Gdiff stash:%<cr> " nnoremap <Leader>gD :Git difftool % nnoremap <Leader>gb :Gblame<cr> nnoremap <Leader>gl :Glog<cr> nnoremap <Leader>gs :Gstatus<cr> " Shortcuts for committing. nnoremap <Leader>gc :Gcommit -v command! -nargs=1 Gcm Gcommit -m <q-args> " }}}1 " "wincmd p" might not work initially, although there are two windows. fun! MyWincmdPrevious() let w = winnr() wincmd p if winnr() == w wincmd w endif endfun " Diff this window with the previous one. command! DiffThese diffthis | call MyWincmdPrevious() | diffthis | wincmd p command! DiffOff Windo diffoff " Toggle highlighting of too long lines {{{2 function! ToggleTooLongHL() if exists('*matchadd') if ! exists("w:TooLongMatchNr") let last = (&tw <= 0 ? 80 : &tw) let w:TooLongMatchNr = matchadd('ErrorMsg', '.\%>' . (last+1) . 'v', 0) echo " Long Line Highlight" else call matchdelete(w:TooLongMatchNr) unlet w:TooLongMatchNr echo "No Long Line Highlight" endif endif endfunction " noremap <silent> <leader>sl :call ToggleTooLongHL()<cr> " Capture output of a:cmd into a new tab via redirection " source: http://vim.wikia.com/wiki/Capture_ex_command_output function! RedirCommand(cmd, newcmd) " Default to "message" for command if empty(a:cmd) | let cmd = 'message' | else | let cmd = a:cmd | endif redir => message silent execute cmd redir END exec a:newcmd silent put=message " NOTE: 'ycmblacklisted' filetype used with YCM blacklist. " Needs patch: https://github.com/Valloric/YouCompleteMe/pull/830 set nomodified ft=vim.ycmblacklisted norm! gg endfunction command! -nargs=* -complete=command Redir call RedirCommand(<q-args>, 'tabnew') " cnoreabbrev TM TabMessage command! -nargs=* -complete=command Redirbuf call RedirCommand(<q-args>, 'new') command! Maps Redir map " fun! Cabbrev(key, value) " exe printf('cabbrev <expr> %s (getcmdtype() == ":" && getcmdpos() <= %d) ? %s : %s', " \ a:key, 1+len(a:key), string(a:value), string(a:key)) " endfun " " IDEA: requires expansion of abbr. " call Cabbrev('/', '/\v') " call Cabbrev('?', '?\v') " call Cabbrev('s/', 's/\v') " call Cabbrev('%s/', '%s/\v') " Make Y consistent with C and D / copy selection to gui-clipboard. {{{2 nnoremap Y y$ " copy selection to gui-clipboard xnoremap Y "+y " Cycle history. cnoremap <c-j> <up> cnoremap <c-k> <down> " Move without arrow keys. {{{2 inoremap <m-h> <left> inoremap <m-l> <right> inoremap <m-j> <down> inoremap <m-k> <up> cnoremap <m-h> <left> cnoremap <m-l> <right> " Folding {{{2 if has("folding") set foldenable set foldmethod=marker " set foldmethod=syntax " let javaScript_fold=1 " JavaScript " javascript: au! FileType javascript syntax region foldBraces start=/{/ end=/}/ transparent fold keepend extend | setlocal foldmethod=syntax " let perl_fold=1 " Perl " let php_folding=1 " PHP " let r_syntax_folding=1 " R " let ruby_fold=1 " Ruby " let sh_fold_enabled=1 " sh " let vimsyn_folding='af' " Vim script " let xml_syntax_folding=1 " XML set foldlevel=1 set foldlevelstart=1 " set foldmethod=indent " set foldnestmax=2 " set foldtext=strpart(getline(v:foldstart),0,50).'\ ...\ '.substitute(getline(v:foldend),'^[\ #]*','','g').'\ ' " set foldcolumn=2 " <2-LeftMouse> Open fold, or select word or % match. nnoremap <expr> <2-LeftMouse> foldclosed(line('.')) == -1 ? "\<2-LeftMouse>" : 'zo' endif if has('eval') " Windo/Bufdo/Tabdo which do not change window, buffer or tab. {{{1 " Source: http://vim.wikia.com/wiki/Run_a_command_in_multiple_buffers#Restoring_position " Like windo but restore the current window. function! Windo(command) let curaltwin = winnr('#') ? winnr('#') : 1 let currwin = winnr() execute 'windo ' . a:command execute curaltwin . 'wincmd w' execute currwin . 'wincmd w' endfunction com! -nargs=+ -complete=command Windo call Windo(<q-args>) " Like bufdo but restore the current buffer. function! Bufdo(command) let currBuff = bufnr("%") execute 'bufdo ' . a:command execute 'buffer ' . currBuff endfunction com! -nargs=+ -complete=command Bufdo call Bufdo(<q-args>) " Like tabdo but restore the current tab. function! Tabdo(command) let currTab=tabpagenr() execute 'tabdo ' . a:command execute 'tabn ' . currTab endfunction com! -nargs=+ -complete=command Tabdo call Tabdo(<q-args>) " }}}1 " Maps for fold commands across windows. for k in ['i', 'm', 'M', 'n', 'N', 'r', 'R', 'v', 'x', 'X'] execute "nnoremap <silent> Z".k." :Windo normal z".k."<CR>" endfor endif if has('user_commands') " typos command! -bang Q q<bang> command! W w command! Wq wq command! Wqa wqa endif "{{{2 Abbreviations " <C-g>u adds break to undo chain, see i_CTRL-G_u inoreabbr cdata <![CDATA[]]><Left><Left><Left> inoreabbr sg Sehr geehrte Damen und Herren,<cr> inoreabbr sgh Sehr geehrter Herr<space> inoreabbr sgf Sehr geehrte Frau<space> inoreabbr mfg Mit freundlichen Grüßen<cr><C-g>u<C-r>=g:my_full_name<cr> inoreabbr LG Liebe Grüße,<cr>Daniel. inoreabbr VG Viele Grüße,<cr>Daniel. " iabbr sig -- <cr><C-r>=readfile(expand('~/.mail-signature')) " sign "checkmark" inoreabbr scm ✓ " date timestamp. inoreabbr <expr> _dts strftime('%a, %d %b %Y %H:%M:%S %z') inoreabbr <expr> _ds strftime('%a, %d %b %Y') inoreabbr <expr> _dt strftime('%Y-%m-%d') " date timestamp with fold markers. inoreabbr dtsf <C-r>=strftime('%a, %d %b %Y %H:%M:%S %z')<cr><space>{{{<cr><cr>}}}<up> " German/styled quotes. inoreabbr <silent> _" „“<Left> inoreabbr <silent> _' ‚‘<Left> inoreabbr <silent> _- –<space> "}}} " Ignore certain files for completion (used also by Command-T). " NOTE: different from suffixes: those get lower prio, but are not ignored! set wildignore+=*.o,*.obj,.git,.svn set wildignore+=*.png,*.jpg,*.jpeg,*.gif,*.mp3 set wildignore+=*.mp4,*.pdf set wildignore+=*.sw? set wildignore+=*.pyc set wildignore+=*/__pycache__/* " allow for tab-completion in vim, but ignore them with command-t let g:CommandTWildIgnore=&wildignore \ .',htdocs/asset/*' \ .',htdocs/media/*' \ .',**/static/_build/*' \ .',**/node_modules/*' \ .',**/build/*' \ .',**/cache/*' \ .',**/.tox/*' " \ .',**/bower_components/*' let g:vdebug_keymap = { \ "run" : "<S-F5>", \} command! VdebugStart python debugger.run() " LocalVimRC {{{ let g:localvimrc_sandbox = 0 " allow to adjust/set &path let g:localvimrc_persistent = 1 " 0=no, 1=uppercase, 2=always " let g:localvimrc_debug = 3 let g:localvimrc_persistence_file = s:vimsharedir . '/localvimrc_persistent' " Helper method for .lvimrc files to finish fun! MyLocalVimrcAlreadySourced(...) " let sfile = expand(a:sfile) let sfile = g:localvimrc_script let guard_key = expand(sfile).'_'.getftime(sfile) if exists('b:local_vimrc_sourced') if type(b:local_vimrc_sourced) != type({}) echomsg "warning: b:local_vimrc_sourced is not a dict!" let b:local_vimrc_sourced = {} endif if has_key(b:local_vimrc_sourced, guard_key) return 1 endif else let b:local_vimrc_sourced = {} endif let b:local_vimrc_sourced[guard_key] = 1 return 0 endfun " }}} " vim-session / session.vim {{{ " Do not autoload/autosave 'default' session " let g:session_autoload = 'no' let g:session_autosave = "yes" let g:session_default_name = '' let g:session_command_aliases = 1 let g:session_persist_globals = [ \ '&sessionoptions', \ 'g:tmru_file', \ 'g:neomru#file_mru_path', \ 'g:neomru#directory_mru_path', \ 'g:session_autosave', \ 'g:MySessionName'] " call add(g:session_persist_globals, 'g:session_autoload') if has('nvim') call add(g:session_persist_globals, '&shada') endif let g:session_persist_colors = 0 let s:my_context = '' fun! MySetContextVars(...) let context = a:0 ? a:1 : '' if len(context) if &verbose | echom "Setting context:" context | endif let suffix = '_' . context else let suffix = '' endif " Use separate MRU files store. let g:tmru_file = s:global_tmru_file . suffix let g:neomru#file_mru_path = s:vimsharedir . '/neomru/file' . suffix let g:neomru#directory_mru_path = s:vimsharedir . '/neomru/dir' . suffix " Use a separate shada file per session, derived from the main/current one. if has('shada') && len(suffix) && &shada !~ ',n' let shada_file = s:xdg_data_home.'/nvim/shada/session-'.fnamemodify(context, ':t').'.shada' let &shada .= ',n'.shada_file if !filereadable(shada_file) wshada rshada endif endif let s:my_context = context endfun " Wrapper for .lvimrc files. fun! MySetContextFromLvimrc(context) if !g:localvimrc_sourced_once && !len(s:my_context) let lvimrc_dir = fnamemodify(g:localvimrc_script, ':p:h') if getcwd()[0:len(lvimrc_dir)-1] == lvimrc_dir call MySetContextVars(a:context) endif endif endfun " Setup session options. This is meant to be called once per created session. " The vars then get stored in the session itself. fun! MySetupSessionOptions() if len(get(g:, 'MySessionName', '')) call MyWarningMsg('MySetupSessionOptions: session is already configured' \ .' (g:MySessionName: '.g:MySessionName.').') return endif let sess_name = MyGetSessionName() if !len(sess_name) call MyWarningMsg('MySetupSessionOptions: this does not appear to be a session.') return endif call MySetContextVars(sess_name) endfun augroup VimrcSetupContext au! " Check for already set context (might come from .lvimrc). au VimEnter * if !len(s:my_context) | call MySetContextVars() | endif augroup END " }}} " xmledit: do not enable for HTML (default) " interferes too much, see issue https://github.com/sukima/xmledit/issues/27 " let g:xmledit_enable_html = 1 " indent these tags for ft=html let g:html_indent_inctags = "body,html,head,p,tbody" " do not indent these let g:html_indent_autotags = "br,input,img" " Setup late autocommands {{{ if has('autocmd') augroup vimrc_late au! " See also ~/.dotfiles/usr/bin/vim-for-git, which uses this setup and " additionally splits the window. fun! MySetupGitCommitMsg() if bufname("%") == '.git/index' " fugitive :Gstatus return endif set foldmethod=syntax foldlevel=1 set nohlsearch nospell sw=4 scrolloff=0 silent! g/^# \(Changes not staged\|Untracked files\|Changes to be committed\|Changes not staged for commit\)/norm zc normal! zt set spell spl=en,de endfun au FileType gitcommit call MySetupGitCommitMsg() " Detect indent. au FileType mail,make,python let b:no_detect_indent=1 au BufReadPost * if exists(':DetectIndent') | \ if !exists('b:no_detect_indent') || !b:no_detect_indent | \ exec 'DetectIndent' | \ endif | endif au BufReadPost * if &bt == "quickfix" | set nowrap | endif " Check if the new file (with git-diff prefix removed) is readable and " edit that instead (copy'n'paste from shell). " (for git diff: `[abiw]`). au BufNewFile * nested let fn = expand('<afile>') | \ if !filereadable(fn) | \ for pat in ['^\S/', '^\S\ze/'] | - \ let new_fn = substitute(fn, pat, '', '') | echom new_fn | + \ let new_fn = substitute(fn, pat, '', '') | \ if fn !=# new_fn && filereadable(new_fn) | \ exec 'edit '.new_fn | \ bdelete # | \ redraw | \ echomsg 'Got unreadable file, editing '.new_fn.' instead.' | \ break | \ endif | \ endfor | \ endif " Display a warning when editing foo.css, but foo.{scss,sass} exists. au BufRead *.css if &modifiable \ && (glob(expand('<afile>:r').'.s[ca]ss', 1) != "" \ || glob(substitute(expand('<afile>'), 'css', 's[ac]ss', 'g')) != "") \ | echoerr "WARN: editing .css, but .scss/.sass exists!" \ | set nomodifiable readonly \ | endif " Vim help files: modifiable (easier to edit for typo fixes); buflisted " for easier switching to them. au FileType help setl modifiable buflisted augroup END endif " }}} " delimitMate let delimitMate_excluded_ft = "unite" " let g:delimitMate_balance_matchpairs = 1 " let g:delimitMate_expand_cr = 1 " let g:delimitMate_expand_space = 1 " au FileType c,perl,php let b:delimitMate_eol_marker = ";" " (pre-)Override S-Tab mapping " Orig: silent! imap <unique> <buffer> <expr> <S-Tab> pumvisible() ? "\<C-p>" : "<Plug>delimitMateS-Tab" " Ref: https://github.com/Raimondi/delimitMate/pull/148#issuecomment-29428335 " NOTE: mapped by SuperTab now. " imap <buffer> <expr> <S-Tab> pumvisible() ? "\<C-p>" : "<Plug>delimitMateS-Tab" if has('vim_starting') " only do this on startup, not when reloading .vimrc " Don't move when you use * " nnoremap <silent> * :let stay_star_view = winsaveview()<cr>*:call winrestview(stay_star_view)<cr> endif " Map alt sequences for terminal via Esc. " source: http://stackoverflow.com/a/10216459/15690 " NOTE: <Esc>O is used for special keys (e.g. OF (End)) " NOTE: drawback (with imap) - triggers timeout for Esc: use jk/kj, " or press it twice. " NOTE: Alt-<NR> mapped in tmux. TODO: change this?! if ! has('nvim') && ! has('gui_running') fun! MySetupAltMapping(c) " XXX: causes problems in macros: <Esc>a gets mapped to á. " Solution: use <C-c> / jk in macros. exec "set <A-".a:c.">=\e".a:c endfun for [c, n] in items({'a':'z', 'A':'N', 'P':'Z', '0':'9'}) while 1 call MySetupAltMapping(c) if c >= n break endif let c = nr2char(1+char2nr(c)) endw endfor " for c in [',', '.', '-', 'ö', 'ä', '#', 'ü', '+', '<'] for c in [',', '.', '-', '#', '+', '<'] call MySetupAltMapping(c) endfor endif " Fix (shifted, altered) function and special keys in tmux. {{{ " (requires `xterm-keys` option for tmux, works with screen). " Ref: http://unix.stackexchange.com/a/58469, http://superuser.com/a/402084/30216 " See also: https://github.com/nacitar/terminalkeys.vim/blob/master/plugin/terminalkeys.vim " With tmux' 'xterm-keys' option, we can make use of these. {{{ " Based on tmux's examples/xterm-keys.vim. " NOTE: using this always, with adjusted urxvt keysym. execute "set <xUp>=\e[1;*A" execute "set <xDown>=\e[1;*B" execute "set <xRight>=\e[1;*C" execute "set <xLeft>=\e[1;*D" " NOTE: xHome/xEnd used with real xterm " execute "set <xHome>=\e[1;*H" " execute "set <xEnd>=\e[1;*F" " also required for xterm hack with urxvt. execute "set <Insert>=\e[2;*~" execute "set <Delete>=\e[3;*~" execute "set <PageUp>=\e[5;*~" execute "set <PageDown>=\e[6;*~" " NOTE: breaks real xterm " execute "set <xF1>=\e[1;*P" " execute "set <xF2>=\e[1;*Q" " execute "set <xF3>=\e[1;*R" " execute "set <xF4>=\e[1;*S" execute "set <F5>=\e[15;*~" execute "set <F6>=\e[17;*~" execute "set <F7>=\e[18;*~" execute "set <F8>=\e[19;*~" execute "set <F9>=\e[20;*~" execute "set <F10>=\e[21;*~" execute "set <F11>=\e[23;*~" execute "set <F12>=\e[24;*~" " }}} " Change cursor shape for terminal mode. {{{1 " See also ~/.dotfiles/oh-my-zsh/themes/blueyed.zsh-theme. " Note: with neovim, this gets controlled via $NVIM_TUI_ENABLE_CURSOR_SHAPE. if has('nvim') let $NVIM_TUI_ENABLE_CURSOR_SHAPE = 1 elseif exists('&t_SI') " 'start insert' and 'exit insert'. if $_USE_XTERM_CURSOR_CODES == 1 " Reference: {{{ " P s = 0 → blinking block. " P s = 1 → blinking block (default). " P s = 2 → steady block. " P s = 3 → blinking underline. " P s = 4 → steady underline. " P s = 5 → blinking bar (xterm, urxvt). " P s = 6 → steady bar (xterm, urxvt). " Source: http://vim.wikia.com/wiki/Configuring_the_cursor " }}} let &t_SI = "\<Esc>[5 q" let &t_EI = "\<Esc>[1 q" " let &t_SI = "\<Esc>]12;purple\x7" " let &t_EI = "\<Esc>]12;blue\x7" " mac / iTerm?! " let &t_SI = "\<Esc>]50;CursorShape=1\x7" " let &t_EI = "\<Esc>]50;CursorShape=0\x7" elseif $KONSOLE_PROFILE_NAME =~ "^Solarized.*" let &t_EI = "\<Esc>]50;CursorShape=0;BlinkingCursorEnabled=1\x7" let &t_SI = "\<Esc>]50;CursorShape=1;BlinkingCursorEnabled=1\x7" elseif &t_Co > 1 && $TERM != "linux" " Fallback: change only the color of the cursor. let &t_SI = "\<Esc>]12;#0087ff\x7" let &t_EI = "\<Esc>]12;#5f8700\x7" endif endif " Wrap escape codes for tmux. " NOTE: wrapping it acts on the term, not just on the pane! " if len($TMUX) " let &t_SI = "\<Esc>Ptmux;\<Esc>".&t_SI."\<Esc>\\" " let &t_EI = "\<Esc>Ptmux;\<Esc>".&t_EI."\<Esc>\\" " endif " }}} " Delete all but the current buffer. {{{ " Source: http://vim.1045645.n5.nabble.com/Close-all-buffers-except-the-one-you-re-in-tp1183357p1183361.html com! -bar -bang BDOnly call s:BdOnly(<q-bang>) func! s:BdOnly(bang) let bdcmd = "bdelete". a:bang let bnr = bufnr("") if bnr > 1 call s:ExecCheckBdErrs("1,".(bnr-1). bdcmd) endif if bnr < bufnr("$") call s:ExecCheckBdErrs((bnr+1).",".bufnr("$"). bdcmd) endif endfunc func! s:ExecCheckBdErrs(bdrangecmd) try exec a:bdrangecmd catch /:E51[567]:/ " no buffers unloaded/deleted/wiped out: ignore catch echohl ErrorMsg echomsg matchstr(v:exception, ':\zsE.*') echohl none endtry endfunc " }}} " Automatic swapfile handling. augroup VimrcSwapfileHandling au! au SwapExists * call MyHandleSwapfile(expand('<afile>:p')) augroup END fun! MyHandleSwapfile(filename) " If swapfile is older than file itself, just get rid of it. if getftime(v:swapname) < getftime(a:filename) call MyWarningMsg('Old swapfile detected, and deleted.') call delete(v:swapname) let v:swapchoice = 'e' else call MyWarningMsg('Swapfile detected, opening read-only.') let v:swapchoice = 'o' endif endfun let g:quickfixsigns_protect_sign_rx = '^neomake_' " Python setup for NeoVim. {{{ " Defining it also skips auto-detecting it. if has("nvim") " Arch Linux, with python-neovim packages. if len(glob('/usr/lib/python2*/site-packages/neovim/__init__.py', 1)) let g:python_host_prog="/usr/bin/python2" endif if len(glob('/usr/lib/python3*/site-packages/neovim/__init__.py', 1)) let g:python3_host_prog="/usr/bin/python3" endif fun! s:get_python_from_pyenv(ver) if !len($PYENV_ROOT) return endif " XXX: Rather slow. " let ret=system('pyenv which python'.a:ver) " if !v:shell_error && len(ret) " return ret " endif " XXX: should be natural sort and/or look for */lib/python3.5/site-packages/neovim/__init__.py. let files = sort(glob($PYENV_ROOT."/versions/".a:ver.".*/bin/python", 1, 1), "n") if len(files) return files[-1] endif echohl WarningMsg | echomsg "Could not find Python" a:ver "through pyenv!" | echohl None endfun if !exists('g:python3_host_prog') " let g:python3_host_prog = "python3" let g:python3_host_prog=s:get_python_from_pyenv(3) if !len('g:python3_host_prog') echohl WarningMsg | echomsg "Could not find python3 for g:python3_host_prog!" | echohl None endif endif if !exists('g:python_host_prog') " Use the Python 2 version YCM was built with. if len($PYTHON_YCM) && filereadable($PYTHON_YCM) let g:python_host_prog=$PYTHON_YCM " Look for installed Python 2 with pyenv. else let g:python_host_prog=s:get_python_from_pyenv(2) endif if !len('g:python_host_prog') echohl WarningMsg | echomsg "Could not find python2 for g:python_host_prog!" | echohl None endif endif " Avoid loading python3 host: YCM uses Python2 anyway, so prefer it for " UltiSnips, too. if s:use_ycm && has('nvim') && len(get(g:, 'python_host_prog', '')) let g:UltiSnipsUsePythonVersion = 2 endif endif " }}} " Patch: https://code.google.com/p/vim/issues/detail?id=319 if exists('+belloff') set belloff+=showmatch endif " Local config (if any). {{{1 if filereadable(expand("~/.vimrc.local")) source ~/.vimrc.local endif " vim: fdm=marker foldlevel=0
blueyed/dotfiles
f4a4e35f29caf1341b613b1043b6279cf3bae4f4
vimrc: improve BufNewFile handler for unreadable files
diff --git a/vimrc b/vimrc index 9338656..855a654 100644 --- a/vimrc +++ b/vimrc @@ -3215,779 +3215,791 @@ let NERDTreeIgnore += ['__pycache__', '.ropeproject'] " inoremap <Down> <C-O>:normal gj<CR> " " j,k move by screen line instead of file line. " nnoremap j gj " nnoremap k gk nnoremap <Down> gj nnoremap <Up> gk " inoremap <Down> <C-o>gj " inoremap <Up> <C-o>gk " XXX: does not keep virtual column! Also adds undo points! " inoremap <expr> <Down> pumvisible() ? "\<C-n>" : "\<C-o>gj" " inoremap <expr> <Up> pumvisible() ? "\<C-p>" : "\<C-o>gk" " Make C-BS and C-Del work like they do in most text editors for the sake of muscle memory {{{2 imap <C-BS> <C-W> imap <C-Del> <C-O>dw imap <C-S-Del> <C-O>dW " Map delete to 'delete to black hole register' (experimental, might use " `d` instead) " Join lines, if on last column, delete otherwise (used in insert mode) " NOTE: de-activated: misbehaves with '""' at end of line (autoclose), " and deleting across lines works anyway. The registers also do not " get polluted.. do not remember why I came up with it... " function! MyDelAcrossEOL() " echomsg col(".") col("$") " if col(".") == col("$") " " XXX: found no way to use '_' register " call feedkeys("\<Down>\<Home>\<Backspace>") " else " normal! "_x " endif " return '' " endfunction " noremap <Del> "_<Del> " inoremap <Del> <C-R>=MyDelAcrossEOL()<cr> " vnoremap <Del> "_<Del> " " Vaporize delete without overwriting the default register. {{{1 " nnoremap vd "_d " xnoremap x "_d " nnoremap vD "_D " }}} " Replace without yank {{{ " Source: https://github.com/justinmk/config/blob/master/.vimrc#L743 func! s:replace_without_yank(type) let sel_save = &selection let l:col = col('.') let &selection = "inclusive" if a:type == 'line' silent normal! '[V']"_d elseif a:type == 'block' silent normal! `[`]"_d else silent normal! `[v`]"_d endif if col('.') == l:col "paste to the left. silent normal! P else "if the operation deleted the last column, then the cursor "gets bumped left (because its original position no longer exists), "so we need to paste to the right instead of the left. silent normal! p endif let &selection = sel_save endf nnoremap <silent> rr :<C-u>set opfunc=<sid>replace_without_yank<CR>g@ nnoremap <silent> rrr 0:<C-u>set opfunc=<sid>replace_without_yank<CR>g@$ " }}} map _ <Plug>(operator-replace) function! TabIsEmpty() return winnr('$') == 1 && WindowIsEmpty() endfunction " Is the current window considered to be empty? function! WindowIsEmpty() if &ft == 'startify' return 1 endif return len(expand('%')) == 0 && line2byte(line('$') + 1) <= 2 endfunction function! MyEditConfig(path, ...) let cmd = a:0 ? a:1 : (WindowIsEmpty() ? 'e' : 'vsplit') exec cmd a:path endfunction " edit vimrc shortcut nnoremap <leader>ec :call MyEditConfig(resolve($MYVIMRC))<cr> nnoremap <leader>Ec :call MyEditConfig(resolve($MYVIMRC), 'edit')<cr> " edit zshrc shortcut nnoremap <leader>ez :call MyEditConfig(resolve("~/.zshrc"))<cr> " edit .lvimrc shortcut (in repository root) nnoremap <leader>elv :call MyEditConfig(ProjectRootGuess().'/.lvimrc')<cr> nnoremap <leader>em :call MyEditConfig(ProjectRootGuess().'/Makefile')<cr> nnoremap <leader>et :call MyEditConfig(expand('~/TODO'))<cr> nnoremap <leader>ept :call MyEditConfig(ProjectRootGet().'/TODO')<cr> " Utility functions to create file commands " Source: https://github.com/carlhuda/janus/blob/master/gvimrc " function! s:CommandCabbr(abbreviation, expansion) " execute 'cabbrev ' . a:abbreviation . ' <c-r>=getcmdpos() == 1 && getcmdtype() == ":" ? "' . a:expansion . '" : "' . a:abbreviation . '"<CR>' " endfunction " Open URL nmap <leader>gw <Plug>(openbrowser-smart-search) vmap <leader>gw <Plug>(openbrowser-smart-search) " Remap CTRL-W_ using vim-maximizer (smarter and toggles). nnoremap <silent><c-w>_ :MaximizerToggle<CR> vnoremap <silent><F3> :MaximizerToggle<CR>gv inoremap <silent><F3> <C-o>:MaximizerToggle<CR> " vimdiff current vs git head (fugitive extension) {{{2 " Close any corresponding fugitive diff buffer. function! MyCloseDiff() if (&diff == 0 || getbufvar('#', '&diff') == 0) \ && (bufname('%') !~ '^fugitive:' && bufname('#') !~ '^fugitive:') echom "Not in diff view." return endif diffoff " safety net / required to workaround powerline issue " Close current buffer if alternate is not fugitive but current one is. if bufname('#') !~ '^fugitive:' && bufname('%') =~ '^fugitive:' if bufwinnr("#") == -1 " XXX: might not work reliable (old comment) b # bd # else bd endif else bd # endif endfunction " nnoremap <Leader>gd :Gdiff<cr> " Maps related to version control (Git). {{{1 " Toggle `:Gdiff`. nnoremap <silent> <Leader>gd :if !&diff \|\| winnr('$') == 1 \| FollowSymlink \| Gdiff \| else \| call MyCloseDiff() \| endif <cr> nnoremap <Leader>gDm :Gdiff master:%<cr> nnoremap <Leader>gDom :Gdiff origin/master:%<cr> nnoremap <Leader>gDs :Gdiff stash:%<cr> " nnoremap <Leader>gD :Git difftool % nnoremap <Leader>gb :Gblame<cr> nnoremap <Leader>gl :Glog<cr> nnoremap <Leader>gs :Gstatus<cr> " Shortcuts for committing. nnoremap <Leader>gc :Gcommit -v command! -nargs=1 Gcm Gcommit -m <q-args> " }}}1 " "wincmd p" might not work initially, although there are two windows. fun! MyWincmdPrevious() let w = winnr() wincmd p if winnr() == w wincmd w endif endfun " Diff this window with the previous one. command! DiffThese diffthis | call MyWincmdPrevious() | diffthis | wincmd p command! DiffOff Windo diffoff " Toggle highlighting of too long lines {{{2 function! ToggleTooLongHL() if exists('*matchadd') if ! exists("w:TooLongMatchNr") let last = (&tw <= 0 ? 80 : &tw) let w:TooLongMatchNr = matchadd('ErrorMsg', '.\%>' . (last+1) . 'v', 0) echo " Long Line Highlight" else call matchdelete(w:TooLongMatchNr) unlet w:TooLongMatchNr echo "No Long Line Highlight" endif endif endfunction " noremap <silent> <leader>sl :call ToggleTooLongHL()<cr> " Capture output of a:cmd into a new tab via redirection " source: http://vim.wikia.com/wiki/Capture_ex_command_output function! RedirCommand(cmd, newcmd) " Default to "message" for command if empty(a:cmd) | let cmd = 'message' | else | let cmd = a:cmd | endif redir => message silent execute cmd redir END exec a:newcmd silent put=message " NOTE: 'ycmblacklisted' filetype used with YCM blacklist. " Needs patch: https://github.com/Valloric/YouCompleteMe/pull/830 set nomodified ft=vim.ycmblacklisted norm! gg endfunction command! -nargs=* -complete=command Redir call RedirCommand(<q-args>, 'tabnew') " cnoreabbrev TM TabMessage command! -nargs=* -complete=command Redirbuf call RedirCommand(<q-args>, 'new') command! Maps Redir map " fun! Cabbrev(key, value) " exe printf('cabbrev <expr> %s (getcmdtype() == ":" && getcmdpos() <= %d) ? %s : %s', " \ a:key, 1+len(a:key), string(a:value), string(a:key)) " endfun " " IDEA: requires expansion of abbr. " call Cabbrev('/', '/\v') " call Cabbrev('?', '?\v') " call Cabbrev('s/', 's/\v') " call Cabbrev('%s/', '%s/\v') " Make Y consistent with C and D / copy selection to gui-clipboard. {{{2 nnoremap Y y$ " copy selection to gui-clipboard xnoremap Y "+y " Cycle history. cnoremap <c-j> <up> cnoremap <c-k> <down> " Move without arrow keys. {{{2 inoremap <m-h> <left> inoremap <m-l> <right> inoremap <m-j> <down> inoremap <m-k> <up> cnoremap <m-h> <left> cnoremap <m-l> <right> " Folding {{{2 if has("folding") set foldenable set foldmethod=marker " set foldmethod=syntax " let javaScript_fold=1 " JavaScript " javascript: au! FileType javascript syntax region foldBraces start=/{/ end=/}/ transparent fold keepend extend | setlocal foldmethod=syntax " let perl_fold=1 " Perl " let php_folding=1 " PHP " let r_syntax_folding=1 " R " let ruby_fold=1 " Ruby " let sh_fold_enabled=1 " sh " let vimsyn_folding='af' " Vim script " let xml_syntax_folding=1 " XML set foldlevel=1 set foldlevelstart=1 " set foldmethod=indent " set foldnestmax=2 " set foldtext=strpart(getline(v:foldstart),0,50).'\ ...\ '.substitute(getline(v:foldend),'^[\ #]*','','g').'\ ' " set foldcolumn=2 " <2-LeftMouse> Open fold, or select word or % match. nnoremap <expr> <2-LeftMouse> foldclosed(line('.')) == -1 ? "\<2-LeftMouse>" : 'zo' endif if has('eval') " Windo/Bufdo/Tabdo which do not change window, buffer or tab. {{{1 " Source: http://vim.wikia.com/wiki/Run_a_command_in_multiple_buffers#Restoring_position " Like windo but restore the current window. function! Windo(command) let curaltwin = winnr('#') ? winnr('#') : 1 let currwin = winnr() execute 'windo ' . a:command execute curaltwin . 'wincmd w' execute currwin . 'wincmd w' endfunction com! -nargs=+ -complete=command Windo call Windo(<q-args>) " Like bufdo but restore the current buffer. function! Bufdo(command) let currBuff = bufnr("%") execute 'bufdo ' . a:command execute 'buffer ' . currBuff endfunction com! -nargs=+ -complete=command Bufdo call Bufdo(<q-args>) " Like tabdo but restore the current tab. function! Tabdo(command) let currTab=tabpagenr() execute 'tabdo ' . a:command execute 'tabn ' . currTab endfunction com! -nargs=+ -complete=command Tabdo call Tabdo(<q-args>) " }}}1 " Maps for fold commands across windows. for k in ['i', 'm', 'M', 'n', 'N', 'r', 'R', 'v', 'x', 'X'] execute "nnoremap <silent> Z".k." :Windo normal z".k."<CR>" endfor endif if has('user_commands') " typos command! -bang Q q<bang> command! W w command! Wq wq command! Wqa wqa endif "{{{2 Abbreviations " <C-g>u adds break to undo chain, see i_CTRL-G_u inoreabbr cdata <![CDATA[]]><Left><Left><Left> inoreabbr sg Sehr geehrte Damen und Herren,<cr> inoreabbr sgh Sehr geehrter Herr<space> inoreabbr sgf Sehr geehrte Frau<space> inoreabbr mfg Mit freundlichen Grüßen<cr><C-g>u<C-r>=g:my_full_name<cr> inoreabbr LG Liebe Grüße,<cr>Daniel. inoreabbr VG Viele Grüße,<cr>Daniel. " iabbr sig -- <cr><C-r>=readfile(expand('~/.mail-signature')) " sign "checkmark" inoreabbr scm ✓ " date timestamp. inoreabbr <expr> _dts strftime('%a, %d %b %Y %H:%M:%S %z') inoreabbr <expr> _ds strftime('%a, %d %b %Y') inoreabbr <expr> _dt strftime('%Y-%m-%d') " date timestamp with fold markers. inoreabbr dtsf <C-r>=strftime('%a, %d %b %Y %H:%M:%S %z')<cr><space>{{{<cr><cr>}}}<up> " German/styled quotes. inoreabbr <silent> _" „“<Left> inoreabbr <silent> _' ‚‘<Left> inoreabbr <silent> _- –<space> "}}} " Ignore certain files for completion (used also by Command-T). " NOTE: different from suffixes: those get lower prio, but are not ignored! set wildignore+=*.o,*.obj,.git,.svn set wildignore+=*.png,*.jpg,*.jpeg,*.gif,*.mp3 set wildignore+=*.mp4,*.pdf set wildignore+=*.sw? set wildignore+=*.pyc set wildignore+=*/__pycache__/* " allow for tab-completion in vim, but ignore them with command-t let g:CommandTWildIgnore=&wildignore \ .',htdocs/asset/*' \ .',htdocs/media/*' \ .',**/static/_build/*' \ .',**/node_modules/*' \ .',**/build/*' \ .',**/cache/*' \ .',**/.tox/*' " \ .',**/bower_components/*' let g:vdebug_keymap = { \ "run" : "<S-F5>", \} command! VdebugStart python debugger.run() " LocalVimRC {{{ let g:localvimrc_sandbox = 0 " allow to adjust/set &path let g:localvimrc_persistent = 1 " 0=no, 1=uppercase, 2=always " let g:localvimrc_debug = 3 let g:localvimrc_persistence_file = s:vimsharedir . '/localvimrc_persistent' " Helper method for .lvimrc files to finish fun! MyLocalVimrcAlreadySourced(...) " let sfile = expand(a:sfile) let sfile = g:localvimrc_script let guard_key = expand(sfile).'_'.getftime(sfile) if exists('b:local_vimrc_sourced') if type(b:local_vimrc_sourced) != type({}) echomsg "warning: b:local_vimrc_sourced is not a dict!" let b:local_vimrc_sourced = {} endif if has_key(b:local_vimrc_sourced, guard_key) return 1 endif else let b:local_vimrc_sourced = {} endif let b:local_vimrc_sourced[guard_key] = 1 return 0 endfun " }}} " vim-session / session.vim {{{ " Do not autoload/autosave 'default' session " let g:session_autoload = 'no' let g:session_autosave = "yes" let g:session_default_name = '' let g:session_command_aliases = 1 let g:session_persist_globals = [ \ '&sessionoptions', \ 'g:tmru_file', \ 'g:neomru#file_mru_path', \ 'g:neomru#directory_mru_path', \ 'g:session_autosave', \ 'g:MySessionName'] " call add(g:session_persist_globals, 'g:session_autoload') if has('nvim') call add(g:session_persist_globals, '&shada') endif let g:session_persist_colors = 0 let s:my_context = '' fun! MySetContextVars(...) let context = a:0 ? a:1 : '' if len(context) if &verbose | echom "Setting context:" context | endif let suffix = '_' . context else let suffix = '' endif " Use separate MRU files store. let g:tmru_file = s:global_tmru_file . suffix let g:neomru#file_mru_path = s:vimsharedir . '/neomru/file' . suffix let g:neomru#directory_mru_path = s:vimsharedir . '/neomru/dir' . suffix " Use a separate shada file per session, derived from the main/current one. if has('shada') && len(suffix) && &shada !~ ',n' let shada_file = s:xdg_data_home.'/nvim/shada/session-'.fnamemodify(context, ':t').'.shada' let &shada .= ',n'.shada_file if !filereadable(shada_file) wshada rshada endif endif let s:my_context = context endfun " Wrapper for .lvimrc files. fun! MySetContextFromLvimrc(context) if !g:localvimrc_sourced_once && !len(s:my_context) let lvimrc_dir = fnamemodify(g:localvimrc_script, ':p:h') if getcwd()[0:len(lvimrc_dir)-1] == lvimrc_dir call MySetContextVars(a:context) endif endif endfun " Setup session options. This is meant to be called once per created session. " The vars then get stored in the session itself. fun! MySetupSessionOptions() if len(get(g:, 'MySessionName', '')) call MyWarningMsg('MySetupSessionOptions: session is already configured' \ .' (g:MySessionName: '.g:MySessionName.').') return endif let sess_name = MyGetSessionName() if !len(sess_name) call MyWarningMsg('MySetupSessionOptions: this does not appear to be a session.') return endif call MySetContextVars(sess_name) endfun augroup VimrcSetupContext au! " Check for already set context (might come from .lvimrc). au VimEnter * if !len(s:my_context) | call MySetContextVars() | endif augroup END " }}} " xmledit: do not enable for HTML (default) " interferes too much, see issue https://github.com/sukima/xmledit/issues/27 " let g:xmledit_enable_html = 1 " indent these tags for ft=html let g:html_indent_inctags = "body,html,head,p,tbody" " do not indent these let g:html_indent_autotags = "br,input,img" " Setup late autocommands {{{ if has('autocmd') augroup vimrc_late au! " See also ~/.dotfiles/usr/bin/vim-for-git, which uses this setup and " additionally splits the window. fun! MySetupGitCommitMsg() if bufname("%") == '.git/index' " fugitive :Gstatus return endif set foldmethod=syntax foldlevel=1 set nohlsearch nospell sw=4 scrolloff=0 silent! g/^# \(Changes not staged\|Untracked files\|Changes to be committed\|Changes not staged for commit\)/norm zc normal! zt set spell spl=en,de endfun au FileType gitcommit call MySetupGitCommitMsg() " Detect indent. au FileType mail,make,python let b:no_detect_indent=1 au BufReadPost * if exists(':DetectIndent') | \ if !exists('b:no_detect_indent') || !b:no_detect_indent | \ exec 'DetectIndent' | \ endif | endif au BufReadPost * if &bt == "quickfix" | set nowrap | endif " Check if the new file (with git-diff prefix removed) is readable and " edit that instead (copy'n'paste from shell). " (for git diff: `[abiw]`). - au BufNewFile * nested let s:fn = expand('<afile>') | if ! filereadable(s:fn) | let s:fn = substitute(s:fn, '^\S\{-}/', '', '') | if filereadable(s:fn) | echomsg 'Editing' s:fn 'instead' | exec 'e '.s:fn.' | bd#' | endif | endif + au BufNewFile * nested let fn = expand('<afile>') | + \ if !filereadable(fn) | + \ for pat in ['^\S/', '^\S\ze/'] | + \ let new_fn = substitute(fn, pat, '', '') | echom new_fn | + \ if fn !=# new_fn && filereadable(new_fn) | + \ exec 'edit '.new_fn | + \ bdelete # | + \ redraw | + \ echomsg 'Got unreadable file, editing '.new_fn.' instead.' | + \ break | + \ endif | + \ endfor | + \ endif " Display a warning when editing foo.css, but foo.{scss,sass} exists. au BufRead *.css if &modifiable \ && (glob(expand('<afile>:r').'.s[ca]ss', 1) != "" \ || glob(substitute(expand('<afile>'), 'css', 's[ac]ss', 'g')) != "") \ | echoerr "WARN: editing .css, but .scss/.sass exists!" \ | set nomodifiable readonly \ | endif " Vim help files: modifiable (easier to edit for typo fixes); buflisted " for easier switching to them. au FileType help setl modifiable buflisted augroup END endif " }}} " delimitMate let delimitMate_excluded_ft = "unite" " let g:delimitMate_balance_matchpairs = 1 " let g:delimitMate_expand_cr = 1 " let g:delimitMate_expand_space = 1 " au FileType c,perl,php let b:delimitMate_eol_marker = ";" " (pre-)Override S-Tab mapping " Orig: silent! imap <unique> <buffer> <expr> <S-Tab> pumvisible() ? "\<C-p>" : "<Plug>delimitMateS-Tab" " Ref: https://github.com/Raimondi/delimitMate/pull/148#issuecomment-29428335 " NOTE: mapped by SuperTab now. " imap <buffer> <expr> <S-Tab> pumvisible() ? "\<C-p>" : "<Plug>delimitMateS-Tab" if has('vim_starting') " only do this on startup, not when reloading .vimrc " Don't move when you use * " nnoremap <silent> * :let stay_star_view = winsaveview()<cr>*:call winrestview(stay_star_view)<cr> endif " Map alt sequences for terminal via Esc. " source: http://stackoverflow.com/a/10216459/15690 " NOTE: <Esc>O is used for special keys (e.g. OF (End)) " NOTE: drawback (with imap) - triggers timeout for Esc: use jk/kj, " or press it twice. " NOTE: Alt-<NR> mapped in tmux. TODO: change this?! if ! has('nvim') && ! has('gui_running') fun! MySetupAltMapping(c) " XXX: causes problems in macros: <Esc>a gets mapped to á. " Solution: use <C-c> / jk in macros. exec "set <A-".a:c.">=\e".a:c endfun for [c, n] in items({'a':'z', 'A':'N', 'P':'Z', '0':'9'}) while 1 call MySetupAltMapping(c) if c >= n break endif let c = nr2char(1+char2nr(c)) endw endfor " for c in [',', '.', '-', 'ö', 'ä', '#', 'ü', '+', '<'] for c in [',', '.', '-', '#', '+', '<'] call MySetupAltMapping(c) endfor endif " Fix (shifted, altered) function and special keys in tmux. {{{ " (requires `xterm-keys` option for tmux, works with screen). " Ref: http://unix.stackexchange.com/a/58469, http://superuser.com/a/402084/30216 " See also: https://github.com/nacitar/terminalkeys.vim/blob/master/plugin/terminalkeys.vim " With tmux' 'xterm-keys' option, we can make use of these. {{{ " Based on tmux's examples/xterm-keys.vim. " NOTE: using this always, with adjusted urxvt keysym. execute "set <xUp>=\e[1;*A" execute "set <xDown>=\e[1;*B" execute "set <xRight>=\e[1;*C" execute "set <xLeft>=\e[1;*D" " NOTE: xHome/xEnd used with real xterm " execute "set <xHome>=\e[1;*H" " execute "set <xEnd>=\e[1;*F" " also required for xterm hack with urxvt. execute "set <Insert>=\e[2;*~" execute "set <Delete>=\e[3;*~" execute "set <PageUp>=\e[5;*~" execute "set <PageDown>=\e[6;*~" " NOTE: breaks real xterm " execute "set <xF1>=\e[1;*P" " execute "set <xF2>=\e[1;*Q" " execute "set <xF3>=\e[1;*R" " execute "set <xF4>=\e[1;*S" execute "set <F5>=\e[15;*~" execute "set <F6>=\e[17;*~" execute "set <F7>=\e[18;*~" execute "set <F8>=\e[19;*~" execute "set <F9>=\e[20;*~" execute "set <F10>=\e[21;*~" execute "set <F11>=\e[23;*~" execute "set <F12>=\e[24;*~" " }}} " Change cursor shape for terminal mode. {{{1 " See also ~/.dotfiles/oh-my-zsh/themes/blueyed.zsh-theme. " Note: with neovim, this gets controlled via $NVIM_TUI_ENABLE_CURSOR_SHAPE. if has('nvim') let $NVIM_TUI_ENABLE_CURSOR_SHAPE = 1 elseif exists('&t_SI') " 'start insert' and 'exit insert'. if $_USE_XTERM_CURSOR_CODES == 1 " Reference: {{{ " P s = 0 → blinking block. " P s = 1 → blinking block (default). " P s = 2 → steady block. " P s = 3 → blinking underline. " P s = 4 → steady underline. " P s = 5 → blinking bar (xterm, urxvt). " P s = 6 → steady bar (xterm, urxvt). " Source: http://vim.wikia.com/wiki/Configuring_the_cursor " }}} let &t_SI = "\<Esc>[5 q" let &t_EI = "\<Esc>[1 q" " let &t_SI = "\<Esc>]12;purple\x7" " let &t_EI = "\<Esc>]12;blue\x7" " mac / iTerm?! " let &t_SI = "\<Esc>]50;CursorShape=1\x7" " let &t_EI = "\<Esc>]50;CursorShape=0\x7" elseif $KONSOLE_PROFILE_NAME =~ "^Solarized.*" let &t_EI = "\<Esc>]50;CursorShape=0;BlinkingCursorEnabled=1\x7" let &t_SI = "\<Esc>]50;CursorShape=1;BlinkingCursorEnabled=1\x7" elseif &t_Co > 1 && $TERM != "linux" " Fallback: change only the color of the cursor. let &t_SI = "\<Esc>]12;#0087ff\x7" let &t_EI = "\<Esc>]12;#5f8700\x7" endif endif " Wrap escape codes for tmux. " NOTE: wrapping it acts on the term, not just on the pane! " if len($TMUX) " let &t_SI = "\<Esc>Ptmux;\<Esc>".&t_SI."\<Esc>\\" " let &t_EI = "\<Esc>Ptmux;\<Esc>".&t_EI."\<Esc>\\" " endif " }}} " Delete all but the current buffer. {{{ " Source: http://vim.1045645.n5.nabble.com/Close-all-buffers-except-the-one-you-re-in-tp1183357p1183361.html com! -bar -bang BDOnly call s:BdOnly(<q-bang>) func! s:BdOnly(bang) let bdcmd = "bdelete". a:bang let bnr = bufnr("") if bnr > 1 call s:ExecCheckBdErrs("1,".(bnr-1). bdcmd) endif if bnr < bufnr("$") call s:ExecCheckBdErrs((bnr+1).",".bufnr("$"). bdcmd) endif endfunc func! s:ExecCheckBdErrs(bdrangecmd) try exec a:bdrangecmd catch /:E51[567]:/ " no buffers unloaded/deleted/wiped out: ignore catch echohl ErrorMsg echomsg matchstr(v:exception, ':\zsE.*') echohl none endtry endfunc " }}} " Automatic swapfile handling. augroup VimrcSwapfileHandling au! au SwapExists * call MyHandleSwapfile(expand('<afile>:p')) augroup END fun! MyHandleSwapfile(filename) " If swapfile is older than file itself, just get rid of it. if getftime(v:swapname) < getftime(a:filename) call MyWarningMsg('Old swapfile detected, and deleted.') call delete(v:swapname) let v:swapchoice = 'e' else call MyWarningMsg('Swapfile detected, opening read-only.') let v:swapchoice = 'o' endif endfun let g:quickfixsigns_protect_sign_rx = '^neomake_' " Python setup for NeoVim. {{{ " Defining it also skips auto-detecting it. if has("nvim") " Arch Linux, with python-neovim packages. if len(glob('/usr/lib/python2*/site-packages/neovim/__init__.py', 1)) let g:python_host_prog="/usr/bin/python2" endif if len(glob('/usr/lib/python3*/site-packages/neovim/__init__.py', 1)) let g:python3_host_prog="/usr/bin/python3" endif fun! s:get_python_from_pyenv(ver) if !len($PYENV_ROOT) return endif " XXX: Rather slow. " let ret=system('pyenv which python'.a:ver) " if !v:shell_error && len(ret) " return ret " endif " XXX: should be natural sort and/or look for */lib/python3.5/site-packages/neovim/__init__.py. let files = sort(glob($PYENV_ROOT."/versions/".a:ver.".*/bin/python", 1, 1), "n") if len(files) return files[-1] endif echohl WarningMsg | echomsg "Could not find Python" a:ver "through pyenv!" | echohl None endfun if !exists('g:python3_host_prog') " let g:python3_host_prog = "python3" let g:python3_host_prog=s:get_python_from_pyenv(3) if !len('g:python3_host_prog') echohl WarningMsg | echomsg "Could not find python3 for g:python3_host_prog!" | echohl None endif endif if !exists('g:python_host_prog') " Use the Python 2 version YCM was built with. if len($PYTHON_YCM) && filereadable($PYTHON_YCM) let g:python_host_prog=$PYTHON_YCM " Look for installed Python 2 with pyenv. else let g:python_host_prog=s:get_python_from_pyenv(2) endif if !len('g:python_host_prog') echohl WarningMsg | echomsg "Could not find python2 for g:python_host_prog!" | echohl None endif endif " Avoid loading python3 host: YCM uses Python2 anyway, so prefer it for " UltiSnips, too. if s:use_ycm && has('nvim') && len(get(g:, 'python_host_prog', '')) let g:UltiSnipsUsePythonVersion = 2 endif endif " }}} " Patch: https://code.google.com/p/vim/issues/detail?id=319 if exists('+belloff') set belloff+=showmatch endif " Local config (if any). {{{1 if filereadable(expand("~/.vimrc.local")) source ~/.vimrc.local endif " vim: fdm=marker foldlevel=0
blueyed/dotfiles
efa2c894137c7d17b4f8215b85286327296f559f
Add config/python/pythonrc.py
diff --git a/config/python/pythonrc.py b/config/python/pythonrc.py new file mode 100644 index 0000000..24ea2fa --- /dev/null +++ b/config/python/pythonrc.py @@ -0,0 +1,60 @@ +""" +Used as PYTHONSTARTUP file. + +Based on the example in Doc/library/readline.rst. + +# The default behavior is enable tab-completion and to use +# :file:`~/.python_history` as the history save file. To disable it, delete +# (or override) the :data:`sys.__interactivehook__` attribute in your +# :mod:`sitecustomize` or :mod:`usercustomize` module or your +# :envvar:`PYTHONSTARTUP` file. +""" + +import atexit +import os +import readline + +default_histfile = os.path.join( + os.path.expanduser('~'), '.local', 'share', 'python_history') + + +def get_histfile(test): + """Use history file based on project / start_filename, if it exists. + + Also used in ~/.pdbrc.py. + """ + prev, test = None, os.path.abspath(test) + while prev != test: + fname = os.path.join(test, '.python_history') + if os.path.isfile(fname): + return fname + prev, test = test, os.path.abspath(os.path.join(test, + os.pardir)) + return default_histfile + + +histfile = get_histfile(os.getcwd()) +# print('Using histfile {} (via {})'.format(histfile, __file__)) +print('Using histfile {} (via pythonrc)'.format(histfile)) + +try: + readline.read_history_file(histfile) + h_len = readline.get_history_length() +except FileNotFoundError: + open(histfile, 'wb').close() + h_len = 0 + + +def save(prev_h_len, histfile): + """Save the history file on exit.""" + readline.set_history_length(1000) + + if hasattr(readline, 'append_history_file'): + new_h_len = readline.get_history_length() + # py 3.5+ + readline.append_history_file(new_h_len - prev_h_len, histfile) + else: + readline.write_history_file(histfile) + + +atexit.register(save, h_len, histfile)
praekelt/django-googlesearch
12a77b9f391e472a1a2c8dbefc348bdcceece806
Amend licence to Consulting
diff --git a/LICENSE b/LICENSE index a429a1f..bce1513 100644 --- a/LICENSE +++ b/LICENSE @@ -1,24 +1,24 @@ -Copyright (c) Praekelt Foundation +Copyright (c) Praekelt Consulting All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - * Neither the name of Praekelt Foundation nor the + * Neither the name of Praekelt Consulting nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL PRAEKELT FOUNDATION BE LIABLE FOR ANY +DISCLAIMED. IN NO EVENT SHALL PRAEKELT CONSULTING BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
praekelt/django-googlesearch
fa21c4a23aceab4d3b1b69fba6f73cc741c9d47e
Prep for release
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 79fbc94..28f0bd6 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -1,20 +1,24 @@ Changelog ========= +0.2 +--- +#. Django 1.6 compatibility. + 0.1.2 ----- #. Refer to correct template tag in help text. Thanks grafyte. 0.1 --- #. Refactor to use a linked custom search engine as described at http://www.google.com/cse/docs/cref.html. 0.0.6 ----- #. Packaging and test setup cleanup. 0.0.5 ----- #. Refactor to not use django-preferences. #. Documentation. diff --git a/setup.py b/setup.py index da9d3ca..e033f0a 100644 --- a/setup.py +++ b/setup.py @@ -1,31 +1,31 @@ from setuptools import setup, find_packages setup( name='django-googlesearch', - version='0.1.2', + version='0.2', description='Django Google linked custom search engine app.', long_description = open('README.rst', 'r').read() + open('AUTHORS.rst', 'r').read() + open('CHANGELOG.rst', 'r').read(), author='Praekelt Foundation', author_email='[email protected]', license='BSD', url='http://github.com/praekelt/django-googlesearch', packages = find_packages(), include_package_data=True, install_requires = [ 'Django', ], test_suite="setuptest.setuptest.SetupTestSuite", tests_require=[ 'django-setuptest>=0.1.2', ], classifiers = [ "Programming Language :: Python", "License :: OSI Approved :: BSD License", "Development Status :: 4 - Beta", "Operating System :: OS Independent", "Framework :: Django", "Intended Audience :: Developers", "Topic :: Internet :: WWW/HTTP :: Dynamic Content", ], zip_safe=False, )
praekelt/django-googlesearch
36f4e79818a76de45a6ffe7a7d947a73f3dc2000
Fix urls
diff --git a/googlesearch/urls.py b/googlesearch/urls.py index 5c69f86..39a56f8 100644 --- a/googlesearch/urls.py +++ b/googlesearch/urls.py @@ -1,19 +1,20 @@ -from django.conf.urls.defaults import patterns, url +from django.conf.urls import patterns, url +from django.views.generic.base import TemplateView + urlpatterns = patterns( '', url( - r'^results/$', - 'django.views.generic.simple.direct_to_template', - {'template': 'googlesearch/results.html'}, + r'^results/$', + TemplateView.as_view(template_name='googlesearch/results.html'), name='googlesearch-results' ), url( - r'^cref-cse\.xml/$', - 'googlesearch.views.cref_cse', + r'^cref-cse\.xml/$', + 'googlesearch.views.cref_cse', {}, name='googlesearch-cref-cse' ), )
praekelt/django-googlesearch
01b5dc65c36a93be5f8cd8fd014d39dc53d0a4a0
Prep for release
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 99c2794..79fbc94 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -1,20 +1,20 @@ Changelog ========= -0.1.1 +0.1.2 ----- #. Refer to correct template tag in help text. Thanks grafyte. 0.1 --- #. Refactor to use a linked custom search engine as described at http://www.google.com/cse/docs/cref.html. 0.0.6 ----- #. Packaging and test setup cleanup. 0.0.5 ----- #. Refactor to not use django-preferences. #. Documentation. diff --git a/setup.py b/setup.py index 0fb3fcb..da9d3ca 100644 --- a/setup.py +++ b/setup.py @@ -1,31 +1,31 @@ from setuptools import setup, find_packages setup( name='django-googlesearch', - version='0.1.1', + version='0.1.2', description='Django Google linked custom search engine app.', long_description = open('README.rst', 'r').read() + open('AUTHORS.rst', 'r').read() + open('CHANGELOG.rst', 'r').read(), author='Praekelt Foundation', author_email='[email protected]', license='BSD', url='http://github.com/praekelt/django-googlesearch', packages = find_packages(), include_package_data=True, install_requires = [ 'Django', ], test_suite="setuptest.setuptest.SetupTestSuite", tests_require=[ 'django-setuptest>=0.1.2', ], classifiers = [ "Programming Language :: Python", "License :: OSI Approved :: BSD License", "Development Status :: 4 - Beta", "Operating System :: OS Independent", "Framework :: Django", "Intended Audience :: Developers", "Topic :: Internet :: WWW/HTTP :: Dynamic Content", ], zip_safe=False, )
praekelt/django-googlesearch
9d363edca19a7db281f5463b3f28235eb24dfb7e
Prep for release
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 2627c83..99c2794 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -1,20 +1,20 @@ Changelog ========= -next ----- +0.1.1 +----- #. Refer to correct template tag in help text. Thanks grafyte. 0.1 --- #. Refactor to use a linked custom search engine as described at http://www.google.com/cse/docs/cref.html. 0.0.6 ----- #. Packaging and test setup cleanup. 0.0.5 ----- #. Refactor to not use django-preferences. #. Documentation. diff --git a/setup.py b/setup.py index 6d3f5fe..0fb3fcb 100644 --- a/setup.py +++ b/setup.py @@ -1,31 +1,31 @@ from setuptools import setup, find_packages setup( name='django-googlesearch', - version='0.1', + version='0.1.1', description='Django Google linked custom search engine app.', long_description = open('README.rst', 'r').read() + open('AUTHORS.rst', 'r').read() + open('CHANGELOG.rst', 'r').read(), author='Praekelt Foundation', author_email='[email protected]', license='BSD', url='http://github.com/praekelt/django-googlesearch', packages = find_packages(), include_package_data=True, install_requires = [ 'Django', ], test_suite="setuptest.setuptest.SetupTestSuite", tests_require=[ 'django-setuptest>=0.1.2', ], classifiers = [ "Programming Language :: Python", "License :: OSI Approved :: BSD License", "Development Status :: 4 - Beta", "Operating System :: OS Independent", "Framework :: Django", "Intended Audience :: Developers", "Topic :: Internet :: WWW/HTTP :: Dynamic Content", ], zip_safe=False, )
praekelt/django-googlesearch
991c3df69e2084dda886bcd1dc328a7d59fdb380
Refer to correct template tag
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 7646796..2627c83 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -1,16 +1,20 @@ Changelog ========= +next +---- +#. Refer to correct template tag in help text. Thanks grafyte. + 0.1 --- #. Refactor to use a linked custom search engine as described at http://www.google.com/cse/docs/cref.html. 0.0.6 ----- #. Packaging and test setup cleanup. 0.0.5 ----- #. Refactor to not use django-preferences. #. Documentation. diff --git a/README.rst b/README.rst index d47b162..7306559 100644 --- a/README.rst +++ b/README.rst @@ -1,55 +1,55 @@ Django Google Search ==================== **Django Google custom search engine app.** Provides a simple tag rendering a Google Custom Search Engine input field and a view displaying search results. The product is an implementation of http://www.google.com/cse/docs/cref.html. The custom search engine definition is stored on your site, not by Google. This allows you to define a search engine in version controlled code. .. contents:: Contents :depth: 5 Installation ------------ #. Install or add ``django-googlesearch`` to your Python path. #. Add ``googlesearch`` to your ``INSTALLED_APPS`` setting. #. Add googlesearch url include to your project's ``urls.py`` file:: (r'^search/', include('googlesearch.urls')), #. Optionally add ``"django.core.context_processors.request",`` to your ``TEMPLATE_CONTEXT_PROCESSORS`` setting, i.e.:: TEMPLATE_CONTEXT_PROCESSORS = ( "django.core.context_processors.request", ...other processors... ) We need a ``request`` object when rendering the search input field and results to be able to display the search query value. This is optional and is not required for operation but is highly recommended. Usage ----- -Once installed you can add a Google search box to your templates by using the ``googlesearch_input`` template tag, i.e.:: +Once installed you can add a Google search box to your templates by using the ``googlesearch_form`` template tag, i.e.:: {% load googlesearch_inclusion_tags %} ...some html... - {% googlesearch_input %} + {% googlesearch_form %} ...some more html... By default search results are displayed through the view with URL named ``googlesearch-results``, as defined in ``googlesearch.urls``. You can create your own URL named ``googlesearch-results`` and include the ``googlesearch_results`` template tag in its template to display results, i.e.:: {% load googlesearch_inclusion_tags %} ...some html... {% googlesearch_results %} ...some more html...
praekelt/django-googlesearch
0d599a6521eb288c8af7861dab48432690d7eadc
Prep for release
diff --git a/setup.py b/setup.py index 0be4513..6d3f5fe 100644 --- a/setup.py +++ b/setup.py @@ -1,31 +1,31 @@ from setuptools import setup, find_packages setup( name='django-googlesearch', version='0.1', description='Django Google linked custom search engine app.', long_description = open('README.rst', 'r').read() + open('AUTHORS.rst', 'r').read() + open('CHANGELOG.rst', 'r').read(), author='Praekelt Foundation', author_email='[email protected]', license='BSD', url='http://github.com/praekelt/django-googlesearch', packages = find_packages(), include_package_data=True, install_requires = [ 'Django', ], - test_suite="setuptest.SetupTestSuite", + test_suite="setuptest.setuptest.SetupTestSuite", tests_require=[ - 'django-setuptest>=0.0.6', + 'django-setuptest>=0.1.2', ], classifiers = [ "Programming Language :: Python", "License :: OSI Approved :: BSD License", "Development Status :: 4 - Beta", "Operating System :: OS Independent", "Framework :: Django", "Intended Audience :: Developers", "Topic :: Internet :: WWW/HTTP :: Dynamic Content", ], zip_safe=False, )
praekelt/django-googlesearch
6e45b03fdb0e09d9a7209aeaba527a95b9f6de3f
Prep for release
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 639d8b8..7646796 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -1,16 +1,16 @@ Changelog ========= -next ----- +0.1 +--- #. Refactor to use a linked custom search engine as described at http://www.google.com/cse/docs/cref.html. 0.0.6 ----- #. Packaging and test setup cleanup. 0.0.5 ----- #. Refactor to not use django-preferences. #. Documentation. diff --git a/setup.py b/setup.py index 84ad172..0be4513 100644 --- a/setup.py +++ b/setup.py @@ -1,31 +1,31 @@ from setuptools import setup, find_packages setup( name='django-googlesearch', - version='0.0.6', - description='Django Google custom search engine app.', + version='0.1', + description='Django Google linked custom search engine app.', long_description = open('README.rst', 'r').read() + open('AUTHORS.rst', 'r').read() + open('CHANGELOG.rst', 'r').read(), author='Praekelt Foundation', author_email='[email protected]', license='BSD', url='http://github.com/praekelt/django-googlesearch', packages = find_packages(), include_package_data=True, install_requires = [ 'Django', ], test_suite="setuptest.SetupTestSuite", tests_require=[ 'django-setuptest>=0.0.6', ], classifiers = [ "Programming Language :: Python", "License :: OSI Approved :: BSD License", "Development Status :: 4 - Beta", "Operating System :: OS Independent", "Framework :: Django", "Intended Audience :: Developers", "Topic :: Internet :: WWW/HTTP :: Dynamic Content", ], zip_safe=False, )
praekelt/django-googlesearch
662aeed3175e0f97304dd622993a7558171841fb
Clean up xml
diff --git a/googlesearch/templates/googlesearch/cref_cse.xml b/googlesearch/templates/googlesearch/cref_cse.xml index 26a4fd5..d5659f2 100644 --- a/googlesearch/templates/googlesearch/cref_cse.xml +++ b/googlesearch/templates/googlesearch/cref_cse.xml @@ -1,27 +1,26 @@ <?xml version="1.0" encoding="UTF-8" ?> <GoogleCustomizations> <CustomSearchEngine> - <Title>Solar Energy</Title> - <!--<Description>A Google Custom Search Engine that only includes solar energy sites</Description> - --> + <Title>Search</Title> + <!--<Description></Description>--> <Context> <BackgroundLabels> <Label name="django_googlesearch" mode="FILTER" /> </BackgroundLabels> </Context> <!-- <LookAndFeel nonprofit="true"> <Colors url="#FF6600" background="#FFFF33" border="#FF6600" title="#FF3300" text="#000000" visited="#663399" light="#FF0077"/> </LookAndFeel> --> </CustomSearchEngine> <Annotations> <Annotation about="http{% if request.is_secure %}s{%endif %}://{{ request.META.HTTP_HOST }}/*"> <Label name="django_googlesearch"/> </Annotation> </Annotations> </GoogleCustomizations>
praekelt/django-googlesearch
be8fab03eed9363652efd1c7eca7da863c0a028b
Refactor to use a linked custom search engine
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 8811c47..639d8b8 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -1,12 +1,16 @@ Changelog ========= +next +---- +#. Refactor to use a linked custom search engine as described at http://www.google.com/cse/docs/cref.html. + 0.0.6 ----- #. Packaging and test setup cleanup. 0.0.5 ----- #. Refactor to not use django-preferences. #. Documentation. diff --git a/README.rst b/README.rst index 8174a0d..d99055b 100644 --- a/README.rst +++ b/README.rst @@ -1,57 +1,57 @@ Django Google Search ==================== **Django Google custom search engine app.** -Provides a simple tag rendering a Google Custom Search Engine input field and a view displaying search results. +Provides a simple tag rendering a Google Custom Search Engine input field and a view displaying search results. http://www.google.com/cse/docs/cref.html. .. contents:: Contents :depth: 5 Installation ------------ #. Install or add ``django-googlesearch`` to your Python path. #. Add ``googlesearch`` to your ``INSTALLED_APPS`` setting. #. Add a ``GOOGLE_SEARCH_PARTNER_ID`` setting to your project's ``settings.py`` file. This setting specifies the Google Custom Search Engine ID to use when rendering the Google search box, as provided by Google, i.e.:: GOOGLE_SEARCH_PARTNER_ID = 'partner-pub-329847239847234:xcvx-3kasd' #. Add googlesearch url include to your project's ``urls.py`` file:: (r'^search/', include('googlesearch.urls')), #. Optionally add ``"django.core.context_processors.request",`` to your ``TEMPLATE_CONTEXT_PROCESSORS`` setting, i.e.:: TEMPLATE_CONTEXT_PROCESSORS = ( "django.core.context_processors.request", ...other processors... ) We need a ``request`` object when rendering the search input field and results to be able to display the search query value. This is optional and is not required for operation but is highly recommended. Usage ----- Once installed you can add a Google search box to your templates by using the ``googlesearch_input`` template tag, i.e.:: {% load googlesearch_inclusion_tags %} ...some html... {% googlesearch_input %} ...some more html... By default search results are displayed through the view with URL named ``googlesearch_results``, as defined in ``googlesearch.urls``. You can create your own URL named ``googlesearch_results`` and include the ``googlesearch_results`` template tag in its template to display results, i.e.:: {% load googlesearch_inclusion_tags %} ...some html... {% googlesearch_results %} ...some more html... diff --git a/googlesearch/templates/googlesearch/cref_cse.xml b/googlesearch/templates/googlesearch/cref_cse.xml index 36fc976..26a4fd5 100644 --- a/googlesearch/templates/googlesearch/cref_cse.xml +++ b/googlesearch/templates/googlesearch/cref_cse.xml @@ -1,39 +1,27 @@ <?xml version="1.0" encoding="UTF-8" ?> <GoogleCustomizations> + <CustomSearchEngine> <Title>Solar Energy</Title> - <Description>A Google Custom Search Engine that only includes solar energy sites</Description> + <!--<Description>A Google Custom Search Engine that only includes solar energy sites</Description> + --> <Context> <BackgroundLabels> - <Label name="solar_example" mode="FILTER" /> + <Label name="django_googlesearch" mode="FILTER" /> </BackgroundLabels> - </Context> + <!-- <LookAndFeel nonprofit="true"> - <!-- In the spirit of solar, this search engine has a yellow background with orange titles --> <Colors url="#FF6600" background="#FFFF33" border="#FF6600" title="#FF3300" text="#000000" visited="#663399" light="#FF0077"/> </LookAndFeel> + --> </CustomSearchEngine> - <!-- The Annotations section. This example illustrates the 3 different ways of specifying annotations --> - - <!-- Link to a XML annotations files --> - - <Include type="Annotations" href="http://guha.com/cref_anno.xml"/> - - <!-- Use a tool provided by Google (or anyone else) to automatically generate a set of annotations. This will grabs all the links from http://dmoz.org/Science/Technology/Energy/Renewable/Solar/ and assign the label solar_example to those links. You can add as many &label= parameters as you want. --> - <Include type="Annotations" href="http://www.google.com/cse/tools/makeannotations?url=http://dmoz.org/Science/Technology/Energy/Renewable/Solar/&amp;label=solar_example" /> - - <!-- You need not include files to add annotations. Adding them inline as shown here will work as well --> - <Annotations> - <Annotation about="http://www.solarenergy.org/*"> - <Label name="solar_example"/> - </Annotation> - - <Annotation about="http://www.solarfacts.net/*"> - <Label name="solar_example"/> - </Annotation> - </Annotations> + <Annotations> + <Annotation about="http{% if request.is_secure %}s{%endif %}://{{ request.META.HTTP_HOST }}/*"> + <Label name="django_googlesearch"/> + </Annotation> + </Annotations> </GoogleCustomizations> diff --git a/googlesearch/templates/googlesearch/inclusion_tags/form.html b/googlesearch/templates/googlesearch/inclusion_tags/form.html index b802a1c..4cb2b4f 100644 --- a/googlesearch/templates/googlesearch/inclusion_tags/form.html +++ b/googlesearch/templates/googlesearch/inclusion_tags/form.html @@ -1,14 +1,11 @@ {% load i18n %} <div class="googlesearch-form-inclusion"> <form id="cref" action="{% url googlesearch-results %}"> - <!--<input type="hidden" name="cref" value="{% url googlesearch-cref-cse %}" /> - --> - <input type="hidden" name="cref" value="http://www.guha.com/cref_cse.xml"" /> - + <input type="hidden" name="cref" value="http{% if request.is_secure %}s{%endif %}://{{ request.META.HTTP_HOST }}{% url googlesearch-cref-cse %}" /> <input type="hidden" name="cof" value="FORID:9" /> <input type="text" name="q" /> <input type="submit" name="sa" value="{% trans "Search" %}" /> </form> <script type="text/javascript" src="http://www.google.com/cse/brand?form=cref"></script> </div> diff --git a/googlesearch/urls.py b/googlesearch/urls.py index ab7732a..5c69f86 100644 --- a/googlesearch/urls.py +++ b/googlesearch/urls.py @@ -1,19 +1,19 @@ from django.conf.urls.defaults import patterns, url urlpatterns = patterns( '', url( r'^results/$', 'django.views.generic.simple.direct_to_template', {'template': 'googlesearch/results.html'}, name='googlesearch-results' ), url( r'^cref-cse\.xml/$', - 'django.views.generic.simple.direct_to_template', - {'template': 'googlesearch/cref_cse.xml'}, + 'googlesearch.views.cref_cse', + {}, name='googlesearch-cref-cse' ), ) diff --git a/googlesearch/views.py b/googlesearch/views.py new file mode 100644 index 0000000..865eb06 --- /dev/null +++ b/googlesearch/views.py @@ -0,0 +1,9 @@ +from django.http import HttpResponse +from django.template import RequestContext, loader + + +def cref_cse(request): + return HttpResponse( + loader.render_to_string('googlesearch/cref_cse.xml', {}, context_instance=RequestContext(request)), + mimetype = 'text/xml' + )
praekelt/django-googlesearch
99156e53c7f2cefe400e6e50891103ff7e2d48eb
Refactor to use linked CSE
diff --git a/googlesearch/templates/googlesearch/cref_cse.xml b/googlesearch/templates/googlesearch/cref_cse.xml new file mode 100644 index 0000000..36fc976 --- /dev/null +++ b/googlesearch/templates/googlesearch/cref_cse.xml @@ -0,0 +1,39 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<GoogleCustomizations> + <CustomSearchEngine> + <Title>Solar Energy</Title> + <Description>A Google Custom Search Engine that only includes solar energy sites</Description> + <Context> + <BackgroundLabels> + <Label name="solar_example" mode="FILTER" /> + </BackgroundLabels> + + </Context> + <LookAndFeel nonprofit="true"> + <!-- In the spirit of solar, this search engine has a yellow background with orange titles --> + <Colors url="#FF6600" background="#FFFF33" border="#FF6600" title="#FF3300" text="#000000" visited="#663399" light="#FF0077"/> + </LookAndFeel> + </CustomSearchEngine> + + <!-- The Annotations section. This example illustrates the 3 different ways of specifying annotations --> + + <!-- Link to a XML annotations files --> + + <Include type="Annotations" href="http://guha.com/cref_anno.xml"/> + + <!-- Use a tool provided by Google (or anyone else) to automatically generate a set of annotations. This will grabs all the links from http://dmoz.org/Science/Technology/Energy/Renewable/Solar/ and assign the label solar_example to those links. You can add as many &label= parameters as you want. --> + <Include type="Annotations" href="http://www.google.com/cse/tools/makeannotations?url=http://dmoz.org/Science/Technology/Energy/Renewable/Solar/&amp;label=solar_example" /> + + <!-- You need not include files to add annotations. Adding them inline as shown here will work as well --> + <Annotations> + <Annotation about="http://www.solarenergy.org/*"> + <Label name="solar_example"/> + </Annotation> + + <Annotation about="http://www.solarfacts.net/*"> + <Label name="solar_example"/> + </Annotation> + </Annotations> + +</GoogleCustomizations> + diff --git a/googlesearch/templates/googlesearch/googlesearch_results.html b/googlesearch/templates/googlesearch/googlesearch_results.html deleted file mode 100644 index dabbbf3..0000000 --- a/googlesearch/templates/googlesearch/googlesearch_results.html +++ /dev/null @@ -1,18 +0,0 @@ -{% extends "base.html" %} -{% load googlesearch_inclusion_tags %} - -{% block content %} - <div class="page section_user"> - <div class="title"> - <h1>{{ title }}</h1> - </div><!--/title--> - - <div class="generic"> - <h2>You searched for <strong>{{ request.GET.q }}</strong></h2> - <div class="rich"> - {% googlesearch_results %} - </div> - </div><!--/generic--> - - </div><!--/page--> -{% endblock %} diff --git a/googlesearch/templates/googlesearch/inclusion_tags/form.html b/googlesearch/templates/googlesearch/inclusion_tags/form.html new file mode 100644 index 0000000..b802a1c --- /dev/null +++ b/googlesearch/templates/googlesearch/inclusion_tags/form.html @@ -0,0 +1,14 @@ +{% load i18n %} + +<div class="googlesearch-form-inclusion"> + <form id="cref" action="{% url googlesearch-results %}"> + <!--<input type="hidden" name="cref" value="{% url googlesearch-cref-cse %}" /> + --> + <input type="hidden" name="cref" value="http://www.guha.com/cref_cse.xml"" /> + + <input type="hidden" name="cof" value="FORID:9" /> + <input type="text" name="q" /> + <input type="submit" name="sa" value="{% trans "Search" %}" /> + </form> + <script type="text/javascript" src="http://www.google.com/cse/brand?form=cref"></script> +</div> diff --git a/googlesearch/templates/googlesearch/inclusion_tags/googlesearch_input.html b/googlesearch/templates/googlesearch/inclusion_tags/googlesearch_input.html deleted file mode 100644 index c2cbb63..0000000 --- a/googlesearch/templates/googlesearch/inclusion_tags/googlesearch_input.html +++ /dev/null @@ -1,12 +0,0 @@ -{% if google_search_partner_id %} - <form id="frmSearch" action="{% url googlesearch_results %}" id="cref_iframe" class="search"> - <p> - <input name="cx" value="{{ google_search_partner_id }}" type="hidden"> - <input name="cof" value="FORID:11" type="hidden"> - <input name="ie" value="ISO-8859-1" type="hidden"> - <input type="text" name="q" value="{% if request.GET.q %}{{ request.GET.q }}{% else %}Search{% endif %}" class="search_txt" onfocus="if (this.value == '{% if request.GET.q %}{{ request.GET.q }}{% else %}Search{% endif %}') {this.value = '';}" onblur="if (this.value == '') {this.value = '{% if request.GET.q %}{{ request.GET.q }}{% else %}Search{% endif %}';}" /> - <input type="submit" name="submit" value="" class="search_btn" /> - </p> - </form><!--/search--> - <script type="text/javascript" src="http://www.google.com/coop/cse/brand?form=cref_iframe"></script> -{% endif %} diff --git a/googlesearch/templates/googlesearch/inclusion_tags/googlesearch_results.html b/googlesearch/templates/googlesearch/inclusion_tags/results.html similarity index 86% rename from googlesearch/templates/googlesearch/inclusion_tags/googlesearch_results.html rename to googlesearch/templates/googlesearch/inclusion_tags/results.html index d1d9463..4054119 100644 --- a/googlesearch/templates/googlesearch/inclusion_tags/googlesearch_results.html +++ b/googlesearch/templates/googlesearch/inclusion_tags/results.html @@ -1,8 +1,8 @@ -<div id="cse-search-results" style="width: 600px;"></div> +<div id="cse-search-results"></div> <script type="text/javascript"> var googleSearchIframeName = "cse-search-results"; var googleSearchFormName = "cse-search-box"; var googleSearchFrameWidth = 600; var googleSearchDomain = "www.google.com"; var googleSearchPath = "/cse"; </script><script type="text/javascript" src="http://www.google.com/afsonline/show_afs_search.js"></script> diff --git a/googlesearch/templates/googlesearch/results.html b/googlesearch/templates/googlesearch/results.html new file mode 100644 index 0000000..bb3296f --- /dev/null +++ b/googlesearch/templates/googlesearch/results.html @@ -0,0 +1,16 @@ +{% extends "base.html" %} +{% load i18n googlesearch_inclusion_tags %} + +{% block content %} + <div class="googlesearch-results"> + + <div class="title">{% trans "Search results" %}</div> + + <!-- {{ request.GET.q }} --> + + <div class="results"> + {% googlesearch_results %} + </div> + + </div> +{% endblock %} diff --git a/googlesearch/templatetags/googlesearch_inclusion_tags.py b/googlesearch/templatetags/googlesearch_inclusion_tags.py index 4184d64..bf3c113 100644 --- a/googlesearch/templatetags/googlesearch_inclusion_tags.py +++ b/googlesearch/templatetags/googlesearch_inclusion_tags.py @@ -1,17 +1,17 @@ from django import template -from django.conf import settings + register = template.Library() [email protected]_tag('googlesearch/inclusion_tags/googlesearch_input.html', takes_context=True) -def googlesearch_input(context): - context.update({ - 'google_search_partner_id': settings.GOOGLE_SEARCH_PARTNER_ID - }) [email protected]_tag('googlesearch/inclusion_tags/form.html', takes_context=True) +def googlesearch_form(context): + #context.update({ + # 'google_search_partner_id': settings.GOOGLE_SEARCH_PARTNER_ID + #}) return context [email protected]_tag('googlesearch/inclusion_tags/googlesearch_results.html') [email protected]_tag('googlesearch/inclusion_tags/results.html') def googlesearch_results(): return {} diff --git a/googlesearch/urls.py b/googlesearch/urls.py index 2fe2dc8..ab7732a 100644 --- a/googlesearch/urls.py +++ b/googlesearch/urls.py @@ -1,8 +1,19 @@ from django.conf.urls.defaults import patterns, url urlpatterns = patterns( - 'django.views.generic.simple', - url(r'^results/$', 'direct_to_template', {'template': \ - 'googlesearch/googlesearch_results.html', 'extra_context': \ - {'title': 'Search Results'}}, name='googlesearch_results'), + '', + + url( + r'^results/$', + 'django.views.generic.simple.direct_to_template', + {'template': 'googlesearch/results.html'}, + name='googlesearch-results' + ), + + url( + r'^cref-cse\.xml/$', + 'django.views.generic.simple.direct_to_template', + {'template': 'googlesearch/cref_cse.xml'}, + name='googlesearch-cref-cse' + ), )
praekelt/django-googlesearch
f775d2ecee56958e43610bcfa85ba090cff3dd84
Prep for release
diff --git a/AUTHORS.rst b/AUTHORS.rst index 53f9b3c..9a5b5bb 100644 --- a/AUTHORS.rst +++ b/AUTHORS.rst @@ -1,7 +1,8 @@ Authors ======= Praekelt Foundation ------------------- * Shaun Sephton +* Hedley Roos diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 6cb77bd..8811c47 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -1,8 +1,12 @@ Changelog ========= -0.0.5 (2011-08-11) ------------------- +0.0.6 +----- +#. Packaging and test setup cleanup. + +0.0.5 +----- #. Refactor to not use django-preferences. #. Documentation. diff --git a/setup.py b/setup.py index e671cac..84ad172 100644 --- a/setup.py +++ b/setup.py @@ -1,28 +1,31 @@ from setuptools import setup, find_packages setup( name='django-googlesearch', - version='0.0.5', + version='0.0.6', description='Django Google custom search engine app.', long_description = open('README.rst', 'r').read() + open('AUTHORS.rst', 'r').read() + open('CHANGELOG.rst', 'r').read(), author='Praekelt Foundation', author_email='[email protected]', license='BSD', url='http://github.com/praekelt/django-googlesearch', packages = find_packages(), include_package_data=True, + install_requires = [ + 'Django', + ], test_suite="setuptest.SetupTestSuite", tests_require=[ 'django-setuptest>=0.0.6', ], classifiers = [ "Programming Language :: Python", "License :: OSI Approved :: BSD License", "Development Status :: 4 - Beta", "Operating System :: OS Independent", "Framework :: Django", "Intended Audience :: Developers", "Topic :: Internet :: WWW/HTTP :: Dynamic Content", ], zip_safe=False, )
praekelt/django-googlesearch
e5224bb40ff4869f11e106e60faa63634a1ddf15
Fixing template tags' inclusion template names/paths.
diff --git a/googlesearch/templatetags/googlesearch_inclusion_tags.py b/googlesearch/templatetags/googlesearch_inclusion_tags.py index 145b369..4184d64 100644 --- a/googlesearch/templatetags/googlesearch_inclusion_tags.py +++ b/googlesearch/templatetags/googlesearch_inclusion_tags.py @@ -1,19 +1,17 @@ from django import template from django.conf import settings register = template.Library() [email protected]_tag('googlesearch/inclusion_tags/googlesearch_input.html',\ - takes_context=True) [email protected]_tag('googlesearch/inclusion_tags/googlesearch_input.html', takes_context=True) def googlesearch_input(context): context.update({ 'google_search_partner_id': settings.GOOGLE_SEARCH_PARTNER_ID }) return context [email protected]_tag('googlesearch/inclusion_tags/\ - googlesearch_results.html') [email protected]_tag('googlesearch/inclusion_tags/googlesearch_results.html') def googlesearch_results(): return {}
praekelt/django-googlesearch
dc0173afd398758d547f6ace2f9517e4f032bd50
use latest setuptest
diff --git a/setup.py b/setup.py index 45546e0..e671cac 100644 --- a/setup.py +++ b/setup.py @@ -1,34 +1,28 @@ from setuptools import setup, find_packages -from setuptools.command.test import test - -def run_tests(self): - from setuptest.runtests import runtests - return runtests(self) -test.run_tests = run_tests setup( name='django-googlesearch', version='0.0.5', description='Django Google custom search engine app.', long_description = open('README.rst', 'r').read() + open('AUTHORS.rst', 'r').read() + open('CHANGELOG.rst', 'r').read(), author='Praekelt Foundation', author_email='[email protected]', license='BSD', url='http://github.com/praekelt/django-googlesearch', packages = find_packages(), include_package_data=True, - test_suite="googlesearch.tests", + test_suite="setuptest.SetupTestSuite", tests_require=[ - 'django-setuptest', + 'django-setuptest>=0.0.6', ], classifiers = [ "Programming Language :: Python", "License :: OSI Approved :: BSD License", "Development Status :: 4 - Beta", "Operating System :: OS Independent", "Framework :: Django", "Intended Audience :: Developers", "Topic :: Internet :: WWW/HTTP :: Dynamic Content", ], zip_safe=False, )
praekelt/django-googlesearch
e62562bd41120fe7cd2a0fed36c2c6e59f7a7907
added testrunner
diff --git a/googlesearch/models.py b/googlesearch/models.py new file mode 100644 index 0000000..e69de29 diff --git a/googlesearch/tests.py b/googlesearch/tests.py new file mode 100644 index 0000000..83f9709 --- /dev/null +++ b/googlesearch/tests.py @@ -0,0 +1,6 @@ +import unittest + + +class TestCase(unittest.TestCase): + def test_something(self): + raise NotImplementedError('Test not implemented. Bad developer!') diff --git a/setup.py b/setup.py index e30ca98..45546e0 100644 --- a/setup.py +++ b/setup.py @@ -1,24 +1,34 @@ from setuptools import setup, find_packages +from setuptools.command.test import test + +def run_tests(self): + from setuptest.runtests import runtests + return runtests(self) +test.run_tests = run_tests setup( name='django-googlesearch', version='0.0.5', description='Django Google custom search engine app.', long_description = open('README.rst', 'r').read() + open('AUTHORS.rst', 'r').read() + open('CHANGELOG.rst', 'r').read(), author='Praekelt Foundation', author_email='[email protected]', license='BSD', url='http://github.com/praekelt/django-googlesearch', packages = find_packages(), include_package_data=True, + test_suite="googlesearch.tests", + tests_require=[ + 'django-setuptest', + ], classifiers = [ "Programming Language :: Python", "License :: OSI Approved :: BSD License", "Development Status :: 4 - Beta", "Operating System :: OS Independent", "Framework :: Django", "Intended Audience :: Developers", "Topic :: Internet :: WWW/HTTP :: Dynamic Content", ], zip_safe=False, ) diff --git a/test_settings.py b/test_settings.py new file mode 100644 index 0000000..ffa0a9c --- /dev/null +++ b/test_settings.py @@ -0,0 +1,5 @@ +DATABASE_ENGINE = 'sqlite3' + +INSTALLED_APPS = [ + 'googlesearch', +]
praekelt/django-googlesearch
34b1a2d9834a6a23e80d51611b0e07d7a038a332
prepare v0.0.5 release
diff --git a/setup.py b/setup.py index 8906416..e30ca98 100644 --- a/setup.py +++ b/setup.py @@ -1,24 +1,24 @@ from setuptools import setup, find_packages setup( name='django-googlesearch', version='0.0.5', description='Django Google custom search engine app.', - long_description = open('README.rst', 'r').read(), + long_description = open('README.rst', 'r').read() + open('AUTHORS.rst', 'r').read() + open('CHANGELOG.rst', 'r').read(), author='Praekelt Foundation', author_email='[email protected]', license='BSD', url='http://github.com/praekelt/django-googlesearch', packages = find_packages(), include_package_data=True, classifiers = [ "Programming Language :: Python", "License :: OSI Approved :: BSD License", "Development Status :: 4 - Beta", "Operating System :: OS Independent", "Framework :: Django", "Intended Audience :: Developers", "Topic :: Internet :: WWW/HTTP :: Dynamic Content", ], zip_safe=False, )
praekelt/django-googlesearch
39b4544eed5b13fd15475df7dd7374181a96c198
prepare v0.0.5 release
diff --git a/AUTHORS b/AUTHORS deleted file mode 100644 index 1ea9e2b..0000000 --- a/AUTHORS +++ /dev/null @@ -1,3 +0,0 @@ -Praekelt Foundation -=================== -* Shaun Sephton diff --git a/AUTHORS.rst b/AUTHORS.rst new file mode 100644 index 0000000..53f9b3c --- /dev/null +++ b/AUTHORS.rst @@ -0,0 +1,7 @@ +Authors +======= + +Praekelt Foundation +------------------- +* Shaun Sephton + diff --git a/CHANGELOG.rst b/CHANGELOG.rst new file mode 100644 index 0000000..6cb77bd --- /dev/null +++ b/CHANGELOG.rst @@ -0,0 +1,8 @@ +Changelog +========= + +0.0.5 (2011-08-11) +------------------ +#. Refactor to not use django-preferences. +#. Documentation. + diff --git a/MANIFEST.in b/MANIFEST.in index 66104d2..518301d 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,5 +1,6 @@ -include AUTHORS +include AUTHORS.rst +include CHANGELOG.rst include LICENSE include README.rst recursive-include googlesearch/templates * recursive-include googlesearch/templatetags * diff --git a/setup.py b/setup.py index 9a49e95..8906416 100644 --- a/setup.py +++ b/setup.py @@ -1,24 +1,24 @@ from setuptools import setup, find_packages setup( name='django-googlesearch', - version='0.0.4', + version='0.0.5', description='Django Google custom search engine app.', long_description = open('README.rst', 'r').read(), author='Praekelt Foundation', author_email='[email protected]', license='BSD', url='http://github.com/praekelt/django-googlesearch', packages = find_packages(), include_package_data=True, classifiers = [ "Programming Language :: Python", "License :: OSI Approved :: BSD License", "Development Status :: 4 - Beta", "Operating System :: OS Independent", "Framework :: Django", "Intended Audience :: Developers", "Topic :: Internet :: WWW/HTTP :: Dynamic Content", ], zip_safe=False, )
praekelt/django-googlesearch
a269e1dd1be0769e984b907ea3b91efd1404ae11
request note
diff --git a/README.rst b/README.rst index 532950f..8174a0d 100644 --- a/README.rst +++ b/README.rst @@ -1,55 +1,57 @@ Django Google Search ==================== **Django Google custom search engine app.** Provides a simple tag rendering a Google Custom Search Engine input field and a view displaying search results. .. contents:: Contents :depth: 5 Installation ------------ #. Install or add ``django-googlesearch`` to your Python path. #. Add ``googlesearch`` to your ``INSTALLED_APPS`` setting. #. Add a ``GOOGLE_SEARCH_PARTNER_ID`` setting to your project's ``settings.py`` file. This setting specifies the Google Custom Search Engine ID to use when rendering the Google search box, as provided by Google, i.e.:: GOOGLE_SEARCH_PARTNER_ID = 'partner-pub-329847239847234:xcvx-3kasd' #. Add googlesearch url include to your project's ``urls.py`` file:: (r'^search/', include('googlesearch.urls')), #. Optionally add ``"django.core.context_processors.request",`` to your ``TEMPLATE_CONTEXT_PROCESSORS`` setting, i.e.:: TEMPLATE_CONTEXT_PROCESSORS = ( "django.core.context_processors.request", ...other processors... ) + We need a ``request`` object when rendering the search input field and results to be able to display the search query value. This is optional and is not required for operation but is highly recommended. + Usage ----- Once installed you can add a Google search box to your templates by using the ``googlesearch_input`` template tag, i.e.:: {% load googlesearch_inclusion_tags %} ...some html... {% googlesearch_input %} ...some more html... By default search results are displayed through the view with URL named ``googlesearch_results``, as defined in ``googlesearch.urls``. You can create your own URL named ``googlesearch_results`` and include the ``googlesearch_results`` template tag in its template to display results, i.e.:: {% load googlesearch_inclusion_tags %} ...some html... {% googlesearch_results %} ...some more html...
praekelt/django-googlesearch
7be28cd9f513e8c9156d985c0c32b168d582d83b
doc byline
diff --git a/README.rst b/README.rst index a47faea..898c5bd 100644 --- a/README.rst +++ b/README.rst @@ -1,30 +1,32 @@ Django Google Search ==================== **Django Google custom search engine app.** +Provides a simple tag rendering a Google Custom Search Engine input field and a view displaying search results. + .. contents:: Contents :depth: 5 Installation ------------ #. Install or add ``django-googlesearch`` to your Python path. #. Add ``googlesearch`` to your ``INSTALLED_APPS`` setting. #. Add a ``GOOGLE_SEARCH_PARTNER_ID`` setting to your project's ``settings.py`` file. This setting specifies the Google Custom Search Engine ID to use when rendering the Google search box, as provided by Google, i.e.:: GOOGLE_SEARCH_PARTNER_ID = 'partner-pub-329847239847234:xcvx-3kasd' #. Add googlesearch url include to your project's ``urls.py`` file:: (r'^search/', include('googlesearch.urls')), #. Optionally add ``"django.core.context_processors.request",`` to your ``TEMPLATE_CONTEXT_PROCESSORS`` setting, i.e.:: TEMPLATE_CONTEXT_PROCESSORS = ( - ...other processors... "django.core.context_processors.request", + ...other processors... )
praekelt/django-googlesearch
c85986b535802aa02348858ea78f6776f0f35fe5
refactor to drop use of preferences
diff --git a/README.rst b/README.rst index fdd2633..a47faea 100644 --- a/README.rst +++ b/README.rst @@ -1,15 +1,30 @@ Django Google Search ==================== **Django Google custom search engine app.** .. contents:: Contents :depth: 5 Installation ------------ -#. Install ``django-preferences`` as described `here <http://pypi.python.org/pypi/django-preferences#id6>`_. - #. Install or add ``django-googlesearch`` to your Python path. #. Add ``googlesearch`` to your ``INSTALLED_APPS`` setting. + +#. Add a ``GOOGLE_SEARCH_PARTNER_ID`` setting to your project's ``settings.py`` file. This setting specifies the Google Custom Search Engine ID to use when rendering the Google search box, as provided by Google, i.e.:: + + GOOGLE_SEARCH_PARTNER_ID = 'partner-pub-329847239847234:xcvx-3kasd' + +#. Add googlesearch url include to your project's ``urls.py`` file:: + + (r'^search/', include('googlesearch.urls')), + +#. Optionally add ``"django.core.context_processors.request",`` to your ``TEMPLATE_CONTEXT_PROCESSORS`` setting, i.e.:: + + TEMPLATE_CONTEXT_PROCESSORS = ( + ...other processors... + "django.core.context_processors.request", + ) + + diff --git a/googlesearch/admin.py b/googlesearch/admin.py deleted file mode 100644 index 3c7fe5b..0000000 --- a/googlesearch/admin.py +++ /dev/null @@ -1,5 +0,0 @@ -from django.contrib import admin - -from googlesearch.models import GoogleSearchPreferences - -admin.site.register(GoogleSearchPreferences) diff --git a/googlesearch/models.py b/googlesearch/models.py deleted file mode 100644 index f5cd347..0000000 --- a/googlesearch/models.py +++ /dev/null @@ -1,17 +0,0 @@ -from django.db import models - -from preferences.models import Preferences - -class GoogleSearchPreferences(Preferences): - __module__ = 'preferences.models' - - partner_id = models.CharField( - max_length=128, - help_text="Google custom search partner ID, i.e. partner-pub-324234324:dsfhk3dskf.", - blank=True, - null=True, - ) - - class Meta(): - verbose_name = "Google search preferences" - verbose_name_plural = "Google search preferences" diff --git a/googlesearch/templates/googlesearch/inclusion_tags/googlesearch_input.html b/googlesearch/templates/googlesearch/inclusion_tags/googlesearch_input.html index 5e26f33..c2cbb63 100644 --- a/googlesearch/templates/googlesearch/inclusion_tags/googlesearch_input.html +++ b/googlesearch/templates/googlesearch/inclusion_tags/googlesearch_input.html @@ -1,12 +1,12 @@ -{% if preferences.GoogleSearchPreferences.partner_id %} +{% if google_search_partner_id %} <form id="frmSearch" action="{% url googlesearch_results %}" id="cref_iframe" class="search"> <p> - <input name="cx" value="{{ preferences.GoogleSearchPreferences.partner_id }}" type="hidden"> + <input name="cx" value="{{ google_search_partner_id }}" type="hidden"> <input name="cof" value="FORID:11" type="hidden"> <input name="ie" value="ISO-8859-1" type="hidden"> <input type="text" name="q" value="{% if request.GET.q %}{{ request.GET.q }}{% else %}Search{% endif %}" class="search_txt" onfocus="if (this.value == '{% if request.GET.q %}{{ request.GET.q }}{% else %}Search{% endif %}') {this.value = '';}" onblur="if (this.value == '') {this.value = '{% if request.GET.q %}{{ request.GET.q }}{% else %}Search{% endif %}';}" /> <input type="submit" name="submit" value="" class="search_btn" /> </p> </form><!--/search--> <script type="text/javascript" src="http://www.google.com/coop/cse/brand?form=cref_iframe"></script> {% endif %} diff --git a/googlesearch/templatetags/googlesearch_inclusion_tags.py b/googlesearch/templatetags/googlesearch_inclusion_tags.py index 5a81b97..bf46129 100644 --- a/googlesearch/templatetags/googlesearch_inclusion_tags.py +++ b/googlesearch/templatetags/googlesearch_inclusion_tags.py @@ -1,13 +1,15 @@ from django import template - -from preferences import preferences +from django.conf import settings register = template.Library() @register.inclusion_tag('googlesearch/inclusion_tags/googlesearch_input.html', takes_context=True) def googlesearch_input(context): + context.update({ + 'google_search_partner_id': settings.GOOGLE_SEARCH_PARTNER_ID + }) return context @register.inclusion_tag('googlesearch/inclusion_tags/googlesearch_results.html') def googlesearch_results(): return {} diff --git a/setup.py b/setup.py index 51ed665..9a49e95 100644 --- a/setup.py +++ b/setup.py @@ -1,27 +1,24 @@ from setuptools import setup, find_packages setup( name='django-googlesearch', version='0.0.4', description='Django Google custom search engine app.', long_description = open('README.rst', 'r').read(), author='Praekelt Foundation', author_email='[email protected]', license='BSD', url='http://github.com/praekelt/django-googlesearch', packages = find_packages(), - install_requires = [ - 'django-preferences', - ], include_package_data=True, classifiers = [ "Programming Language :: Python", "License :: OSI Approved :: BSD License", "Development Status :: 4 - Beta", "Operating System :: OS Independent", "Framework :: Django", "Intended Audience :: Developers", "Topic :: Internet :: WWW/HTTP :: Dynamic Content", ], zip_safe=False, )
praekelt/django-googlesearch
98829d15856cad8a492723684ae9c43d5c97da67
started on docs
diff --git a/README.rst b/README.rst index e69de29..fdd2633 100644 --- a/README.rst +++ b/README.rst @@ -0,0 +1,15 @@ +Django Google Search +==================== +**Django Google custom search engine app.** + +.. contents:: Contents + :depth: 5 + +Installation +------------ + +#. Install ``django-preferences`` as described `here <http://pypi.python.org/pypi/django-preferences#id6>`_. + +#. Install or add ``django-googlesearch`` to your Python path. + +#. Add ``googlesearch`` to your ``INSTALLED_APPS`` setting.
praekelt/django-googlesearch
1443782e5332aa56c2509270e9cc8af4e12bf089
version bump, not zip safe
diff --git a/setup.py b/setup.py index 2dafb84..51ed665 100644 --- a/setup.py +++ b/setup.py @@ -1,26 +1,27 @@ from setuptools import setup, find_packages setup( name='django-googlesearch', - version='0.0.3', + version='0.0.4', description='Django Google custom search engine app.', long_description = open('README.rst', 'r').read(), author='Praekelt Foundation', author_email='[email protected]', license='BSD', url='http://github.com/praekelt/django-googlesearch', packages = find_packages(), install_requires = [ 'django-preferences', ], include_package_data=True, classifiers = [ "Programming Language :: Python", "License :: OSI Approved :: BSD License", "Development Status :: 4 - Beta", "Operating System :: OS Independent", "Framework :: Django", "Intended Audience :: Developers", "Topic :: Internet :: WWW/HTTP :: Dynamic Content", ], + zip_safe=False, )
praekelt/django-googlesearch
e8cf1cf67d322611ce86c29f9aa0d285c2832e66
version bump
diff --git a/setup.py b/setup.py index 6c58cd8..2dafb84 100644 --- a/setup.py +++ b/setup.py @@ -1,26 +1,26 @@ from setuptools import setup, find_packages setup( name='django-googlesearch', - version='0.0.2', + version='0.0.3', description='Django Google custom search engine app.', long_description = open('README.rst', 'r').read(), author='Praekelt Foundation', author_email='[email protected]', license='BSD', url='http://github.com/praekelt/django-googlesearch', packages = find_packages(), install_requires = [ 'django-preferences', ], include_package_data=True, classifiers = [ "Programming Language :: Python", "License :: OSI Approved :: BSD License", "Development Status :: 4 - Beta", "Operating System :: OS Independent", "Framework :: Django", "Intended Audience :: Developers", "Topic :: Internet :: WWW/HTTP :: Dynamic Content", ], )
praekelt/django-googlesearch
6eb877244833d43d34bd433f0d83f723ddf4fd0b
not override prefs
diff --git a/googlesearch/templates/googlesearch/inclusion_tags/googlesearch_input.html b/googlesearch/templates/googlesearch/inclusion_tags/googlesearch_input.html index 025460d..5e26f33 100644 --- a/googlesearch/templates/googlesearch/inclusion_tags/googlesearch_input.html +++ b/googlesearch/templates/googlesearch/inclusion_tags/googlesearch_input.html @@ -1,12 +1,12 @@ -{% if preferences.partner_id %} +{% if preferences.GoogleSearchPreferences.partner_id %} <form id="frmSearch" action="{% url googlesearch_results %}" id="cref_iframe" class="search"> <p> - <input name="cx" value="{{ preferences.partner_id }}" type="hidden"> + <input name="cx" value="{{ preferences.GoogleSearchPreferences.partner_id }}" type="hidden"> <input name="cof" value="FORID:11" type="hidden"> <input name="ie" value="ISO-8859-1" type="hidden"> <input type="text" name="q" value="{% if request.GET.q %}{{ request.GET.q }}{% else %}Search{% endif %}" class="search_txt" onfocus="if (this.value == '{% if request.GET.q %}{{ request.GET.q }}{% else %}Search{% endif %}') {this.value = '';}" onblur="if (this.value == '') {this.value = '{% if request.GET.q %}{{ request.GET.q }}{% else %}Search{% endif %}';}" /> <input type="submit" name="submit" value="" class="search_btn" /> </p> </form><!--/search--> <script type="text/javascript" src="http://www.google.com/coop/cse/brand?form=cref_iframe"></script> {% endif %} diff --git a/googlesearch/templatetags/googlesearch_inclusion_tags.py b/googlesearch/templatetags/googlesearch_inclusion_tags.py index 23fc45c..5a81b97 100644 --- a/googlesearch/templatetags/googlesearch_inclusion_tags.py +++ b/googlesearch/templatetags/googlesearch_inclusion_tags.py @@ -1,16 +1,13 @@ from django import template from preferences import preferences register = template.Library() @register.inclusion_tag('googlesearch/inclusion_tags/googlesearch_input.html', takes_context=True) def googlesearch_input(context): - context.update({ - 'preferences': preferences.GoogleSearchPreferences - }) return context @register.inclusion_tag('googlesearch/inclusion_tags/googlesearch_results.html') def googlesearch_results(): return {}
praekelt/django-googlesearch
05d7d5808b4e36a276922f40120e4fc82821f558
corrected includes
diff --git a/MANIFEST.in b/MANIFEST.in index 2b76c6b..66104d2 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,5 +1,5 @@ include AUTHORS include LICENSE include README.rst -recursive-include gallery/templates * -recursive-include gallery/templatetags * +recursive-include googlesearch/templates * +recursive-include googlesearch/templatetags *
praekelt/django-googlesearch
af4132483bc764677c0e224b7ff0ddc38e5ab428
include templates
diff --git a/MANIFEST.in b/MANIFEST.in index 7c985df..2b76c6b 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,3 +1,5 @@ include AUTHORS include LICENSE include README.rst +recursive-include gallery/templates * +recursive-include gallery/templatetags *
praekelt/django-googlesearch
331c0c41ebf3eac1be99ebd3211d9ae7ecfed303
copy correction
diff --git a/LICENSE b/LICENSE index 438baa2..a429a1f 100644 --- a/LICENSE +++ b/LICENSE @@ -1,24 +1,24 @@ Copyright (c) Praekelt Foundation All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Praekelt Foundation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL PRAKELT FOUNDATION BE LIABLE FOR ANY +DISCLAIMED. IN NO EVENT SHALL PRAEKELT FOUNDATION BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
praekelt/django-googlesearch
dac625a393b0e5897145e92100d9c9654f90dc79
correct import
diff --git a/googlesearch/admin.py b/googlesearch/admin.py index b9396cc..3c7fe5b 100644 --- a/googlesearch/admin.py +++ b/googlesearch/admin.py @@ -1,5 +1,5 @@ from django.contrib import admin -from googlesearch.models import GoogleSearchOptions +from googlesearch.models import GoogleSearchPreferences -admin.site.register(GoogleSearchOptions) +admin.site.register(GoogleSearchPreferences)
praekelt/django-googlesearch
c209fb7102d632fa9e0cfc28feee806c65484006
remed Jono
diff --git a/AUTHORS b/AUTHORS index 21e79f4..1ea9e2b 100644 --- a/AUTHORS +++ b/AUTHORS @@ -1,4 +1,3 @@ Praekelt Foundation =================== * Shaun Sephton -* Jonathan Bydendyk
praekelt/django-googlesearch
d0404a23bd9a6e20387b71cb2ec48e5069c64b54
version bump
diff --git a/setup.py b/setup.py index 2b6ce93..6c58cd8 100644 --- a/setup.py +++ b/setup.py @@ -1,26 +1,26 @@ from setuptools import setup, find_packages setup( name='django-googlesearch', - version='0.0.1', + version='0.0.2', description='Django Google custom search engine app.', long_description = open('README.rst', 'r').read(), author='Praekelt Foundation', author_email='[email protected]', license='BSD', url='http://github.com/praekelt/django-googlesearch', packages = find_packages(), install_requires = [ 'django-preferences', ], include_package_data=True, classifiers = [ "Programming Language :: Python", "License :: OSI Approved :: BSD License", "Development Status :: 4 - Beta", "Operating System :: OS Independent", "Framework :: Django", "Intended Audience :: Developers", "Topic :: Internet :: WWW/HTTP :: Dynamic Content", ], )
praekelt/django-googlesearch
dc8496e468de3ca4340ba13893b579d20e2f4ac4
preferences rename
diff --git a/googlesearch/models.py b/googlesearch/models.py index 44136c7..f5cd347 100644 --- a/googlesearch/models.py +++ b/googlesearch/models.py @@ -1,17 +1,17 @@ from django.db import models -from options.models import Options +from preferences.models import Preferences -class GoogleSearchOptions(Options): - __module__ = 'options.models' +class GoogleSearchPreferences(Preferences): + __module__ = 'preferences.models' partner_id = models.CharField( max_length=128, help_text="Google custom search partner ID, i.e. partner-pub-324234324:dsfhk3dskf.", blank=True, null=True, ) class Meta(): - verbose_name = "Google search options" - verbose_name_plural = "Google search options" + verbose_name = "Google search preferences" + verbose_name_plural = "Google search preferences" diff --git a/googlesearch/templates/googlesearch/inclusion_tags/googlesearch_input.html b/googlesearch/templates/googlesearch/inclusion_tags/googlesearch_input.html index 4b35494..025460d 100644 --- a/googlesearch/templates/googlesearch/inclusion_tags/googlesearch_input.html +++ b/googlesearch/templates/googlesearch/inclusion_tags/googlesearch_input.html @@ -1,12 +1,12 @@ -{% if options.partner_id %} +{% if preferences.partner_id %} <form id="frmSearch" action="{% url googlesearch_results %}" id="cref_iframe" class="search"> <p> - <input name="cx" value="{{ options.partner_id }}" type="hidden"> + <input name="cx" value="{{ preferences.partner_id }}" type="hidden"> <input name="cof" value="FORID:11" type="hidden"> <input name="ie" value="ISO-8859-1" type="hidden"> <input type="text" name="q" value="{% if request.GET.q %}{{ request.GET.q }}{% else %}Search{% endif %}" class="search_txt" onfocus="if (this.value == '{% if request.GET.q %}{{ request.GET.q }}{% else %}Search{% endif %}') {this.value = '';}" onblur="if (this.value == '') {this.value = '{% if request.GET.q %}{{ request.GET.q }}{% else %}Search{% endif %}';}" /> <input type="submit" name="submit" value="" class="search_btn" /> </p> </form><!--/search--> <script type="text/javascript" src="http://www.google.com/coop/cse/brand?form=cref_iframe"></script> {% endif %} diff --git a/googlesearch/templatetags/googlesearch_inclusion_tags.py b/googlesearch/templatetags/googlesearch_inclusion_tags.py index 9ce6696..23fc45c 100644 --- a/googlesearch/templatetags/googlesearch_inclusion_tags.py +++ b/googlesearch/templatetags/googlesearch_inclusion_tags.py @@ -1,16 +1,16 @@ from django import template -from options import options +from preferences import preferences register = template.Library() @register.inclusion_tag('googlesearch/inclusion_tags/googlesearch_input.html', takes_context=True) def googlesearch_input(context): context.update({ - 'options': options.GoogleSearchOptions + 'preferences': preferences.GoogleSearchPreferences }) return context @register.inclusion_tag('googlesearch/inclusion_tags/googlesearch_results.html') def googlesearch_results(): return {} diff --git a/setup.py b/setup.py index b8a5142..2b6ce93 100644 --- a/setup.py +++ b/setup.py @@ -1,23 +1,26 @@ from setuptools import setup, find_packages setup( name='django-googlesearch', version='0.0.1', description='Django Google custom search engine app.', long_description = open('README.rst', 'r').read(), author='Praekelt Foundation', author_email='[email protected]', license='BSD', url='http://github.com/praekelt/django-googlesearch', packages = find_packages(), + install_requires = [ + 'django-preferences', + ], include_package_data=True, classifiers = [ "Programming Language :: Python", "License :: OSI Approved :: BSD License", "Development Status :: 4 - Beta", "Operating System :: OS Independent", "Framework :: Django", "Intended Audience :: Developers", "Topic :: Internet :: WWW/HTTP :: Dynamic Content", ], )
praekelt/django-googlesearch
c145d484149e39350eefe9e1bb13046b163c4437
polish
diff --git a/setup.py b/setup.py index 4dfcd43..b8a5142 100644 --- a/setup.py +++ b/setup.py @@ -1,12 +1,23 @@ from setuptools import setup, find_packages setup( name='django-googlesearch', - version='dev', + version='0.0.1', description='Django Google custom search engine app.', - author='Praekelt Consulting', + long_description = open('README.rst', 'r').read(), + author='Praekelt Foundation', author_email='[email protected]', - url='https://github.com/praekelt/django-googlesearch', + license='BSD', + url='http://github.com/praekelt/django-googlesearch', packages = find_packages(), include_package_data=True, + classifiers = [ + "Programming Language :: Python", + "License :: OSI Approved :: BSD License", + "Development Status :: 4 - Beta", + "Operating System :: OS Independent", + "Framework :: Django", + "Intended Audience :: Developers", + "Topic :: Internet :: WWW/HTTP :: Dynamic Content", + ], )
Aequilibrium/GSMS
0575ed4f0f09ec828d9dd696e06ca4fbfb13a003
Loop update
diff --git a/gsms.kdevelop.pcs b/gsms.kdevelop.pcs index 1404f7e..0699672 100644 Binary files a/gsms.kdevelop.pcs and b/gsms.kdevelop.pcs differ diff --git a/gsms.kdevses b/gsms.kdevses index c3a94e2..711cf16 100644 --- a/gsms.kdevses +++ b/gsms.kdevses @@ -1,49 +1,55 @@ <?xml version = '1.0' encoding = 'UTF-8'?> <!DOCTYPE KDevPrjSession> <KDevPrjSession> - <DocsAndViews NumberOfDocuments="8" > + <DocsAndViews NumberOfDocuments="10" > <Doc0 NumberOfViews="1" URL="file:///home/t28a/sandbox/gsms/src/config/Hull.h" > <View0 Encoding="" Type="Source" /> </Doc0> <Doc1 NumberOfViews="1" URL="file:///home/t28a/sandbox/gsms/src/config/Hull.cpp" > <View0 Encoding="" Type="Source" /> </Doc1> <Doc2 NumberOfViews="1" URL="file:///home/t28a/sandbox/gsms/src/config/GSMS.h" > - <View0 Encoding="" Type="Source" /> + <View0 Encoding="" line="0" Type="Source" /> </Doc2> <Doc3 NumberOfViews="1" URL="file:///home/t28a/sandbox/gsms/src/config/GSMS.cpp" > <View0 Encoding="" Type="Source" /> </Doc3> <Doc4 NumberOfViews="1" URL="file:///home/t28a/sandbox/gsms/src/geometry/Geometry.h" > <View0 Encoding="" Type="Source" /> </Doc4> <Doc5 NumberOfViews="1" URL="file:///home/t28a/sandbox/gsms/src/geometry/Geometry.cpp" > <View0 Encoding="" Type="Source" /> </Doc5> <Doc6 NumberOfViews="1" URL="file:///home/t28a/sandbox/gsms/src/generator/Source.cpp" > <View0 Encoding="" Type="Source" /> </Doc6> <Doc7 NumberOfViews="1" URL="file:///home/t28a/sandbox/gsms/src/main.cpp" > - <View0 Encoding="" line="29" Type="Source" /> + <View0 Encoding="" line="30" Type="Source" /> </Doc7> + <Doc8 NumberOfViews="1" URL="file:///home/t28a/sandbox/gsms/src/generator/Source.h" > + <View0 Encoding="" line="142" Type="Source" /> + </Doc8> + <Doc9 NumberOfViews="1" URL="file:///home/t28a/sandbox/gsms/src/config/Job.h" > + <View0 Encoding="" line="31" Type="Source" /> + </Doc9> </DocsAndViews> <pluginList> <kdevdebugger> <breakpointList/> <showInternalCommands value="0" /> </kdevdebugger> <kdevastyle> <Extensions ext="*.cpp *.h *.hpp,*.c *.h,*.cxx *.hxx,*.c++ *.h++,*.cc *.hh,*.C *.H,*.diff ,*.inl,*.java,*.moc,*.patch,*.tlh,*.xpm" /> <AStyle IndentPreprocessors="0" FillCount="4" PadParenthesesOut="1" IndentNamespaces="1" IndentLabels="1" Fill="Tabs" MaxStatement="40" Brackets="Break" MinConditional="-1" IndentBrackets="0" PadParenthesesUn="1" BlockBreak="0" KeepStatements="1" KeepBlocks="1" BlockIfElse="0" IndentSwitches="1" PadOperators="0" FStyle="UserDefined" IndentCases="0" FillEmptyLines="0" BracketsCloseHeaders="0" BlockBreakAll="0" PadParenthesesIn="1" IndentClasses="1" IndentBlocks="0" FillForce="0" /> </kdevastyle> <kdevbookmarks> <bookmarks/> </kdevbookmarks> <kdevvalgrind> <executable path="" params="" /> <valgrind path="" params="" /> <calltree path="" params="" /> <kcachegrind path="" /> </kdevvalgrind> </pluginList> </KDevPrjSession> diff --git a/src/config/.deps/DetectorConfig.Plo b/src/config/.deps/DetectorConfig.Plo index 54a9338..10a40c9 100644 --- a/src/config/.deps/DetectorConfig.Plo +++ b/src/config/.deps/DetectorConfig.Plo @@ -534,1026 +534,1027 @@ DetectorConfig.lo: DetectorConfig.cpp DetectorConfig.h Config.h \ /usr/include/boost/memory_order.hpp \ /usr/include/boost/serialization/shared_ptr_132.hpp \ /usr/include/boost/serialization/detail/shared_ptr_132.hpp \ /usr/include/boost/serialization/detail/shared_count_132.hpp \ /usr/include/boost/detail/lightweight_mutex.hpp \ /usr/include/boost/smart_ptr/detail/lightweight_mutex.hpp \ /usr/include/boost/smart_ptr/detail/lwm_pthreads.hpp \ ../../src/typedefs.h ../../src/config/Exception.h \ /usr/include/geant/G4VPhysicalVolume.hh /usr/include/geant/geomdefs.hh \ /usr/include/geant/globals.hh /usr/include/geant/G4RotationMatrix.hh \ /usr/include/geant/G4ThreeVector.hh \ /usr/include/CLHEP/Vector/ThreeVector.h /usr/include/CLHEP/Vector/defs.h \ /usr/include/CLHEP/Vector/ThreeVector.icc \ /usr/include/CLHEP/Vector/Rotation.h \ /usr/include/CLHEP/Vector/RotationInterfaces.h \ /usr/include/CLHEP/Vector/LorentzVector.h \ /usr/include/CLHEP/Vector/LorentzVector.icc \ /usr/include/CLHEP/Vector/ZMxpv.h /usr/include/CLHEP/Vector/AxisAngle.h \ /usr/include/CLHEP/Vector/AxisAngle.icc \ /usr/include/CLHEP/Vector/RotationInterfaces.icc \ /usr/include/CLHEP/Vector/RotationX.h \ /usr/include/CLHEP/Vector/RotationX.icc \ /usr/include/CLHEP/Vector/RotationY.h \ /usr/include/CLHEP/Vector/RotationY.icc \ /usr/include/CLHEP/Vector/RotationZ.h \ /usr/include/CLHEP/Vector/RotationZ.icc \ /usr/include/CLHEP/Vector/Rotation.icc \ /usr/include/geant/G4VPhysicalVolume.icc /usr/include/sys/stat.h \ /usr/include/bits/stat.h GSMS.h Mask.h \ /usr/include/geant/G4AssemblyVolume.hh \ /usr/include/geant/G4Transform3D.hh \ /usr/include/CLHEP/Geometry/Transform3D.h \ /usr/include/CLHEP/Geometry/defs.h \ /usr/include/CLHEP/Geometry/Transform3D.icc \ /usr/include/CLHEP/Geometry/Point3D.h \ /usr/include/CLHEP/Geometry/BasicVector3D.h \ /usr/include/CLHEP/Geometry/Vector3D.h \ /usr/include/CLHEP/Geometry/Normal3D.h \ /usr/include/geant/G4AssemblyTriplet.hh \ /usr/include/geant/G4AssemblyTriplet.icc \ /usr/include/geant/G4AssemblyVolume.icc GlobalConfig.h Job.h \ ../../src/config/Config.h ../../src/generator/Source.h \ /usr/include/geant/G4ThreeVector.hh \ /usr/include/geant/G4SingleParticleSource.hh \ /usr/include/geant/G4VPrimaryGenerator.hh \ /usr/include/geant/G4ParticleMomentum.hh \ /usr/include/geant/G4ParticleDefinition.hh \ /usr/include/geant/G4ParticleDefinition.icc \ /usr/include/geant/G4SPSPosDistribution.hh \ /usr/include/geant/G4Navigator.hh \ /usr/include/geant/G4AffineTransform.hh \ /usr/include/geant/G4AffineTransform.icc \ /usr/include/geant/G4LogicalVolume.hh /usr/include/geant/G4Region.hh \ /usr/include/geant/G4Region.icc /usr/include/geant/G4VPhysicalVolume.hh \ /usr/include/geant/G4LogicalVolume.icc /usr/include/geant/G4GRSVolume.hh \ /usr/include/geant/G4VTouchable.hh /usr/include/geant/G4VTouchable.icc \ /usr/include/geant/G4GRSVolume.icc /usr/include/geant/G4GRSSolid.hh \ /usr/include/geant/G4GRSSolid.icc \ /usr/include/geant/G4TouchableHandle.hh \ /usr/include/geant/G4ReferenceCountedHandle.hh \ /usr/include/geant/G4Allocator.hh /usr/include/geant/G4AllocatorPool.hh \ /usr/include/geant/G4TouchableHistoryHandle.hh \ /usr/include/geant/G4TouchableHistory.hh \ /usr/include/geant/G4NavigationHistory.hh \ /usr/include/geant/G4NavigationLevel.hh \ /usr/include/geant/G4NavigationLevelRep.hh \ /usr/include/geant/G4NavigationLevelRep.icc \ /usr/include/geant/G4NavigationLevel.icc \ /usr/include/geant/G4NavigationHistory.icc \ /usr/include/geant/G4TouchableHistory.icc \ /usr/include/geant/G4NormalNavigation.hh /usr/include/geant/G4VSolid.hh \ /usr/include/geant/G4VSolid.icc \ /usr/include/geant/G4AuxiliaryNavServices.hh \ /usr/include/geant/G4AuxiliaryNavServices.icc \ /usr/include/geant/G4NormalNavigation.icc \ /usr/include/geant/G4VoxelNavigation.hh \ /usr/include/geant/G4BlockingList.hh \ /usr/include/geant/G4BlockingList.icc \ /usr/include/geant/G4SmartVoxelProxy.hh \ /usr/include/geant/G4SmartVoxelProxy.icc \ /usr/include/geant/G4SmartVoxelNode.hh \ /usr/include/geant/G4SmartVoxelNode.icc \ /usr/include/geant/G4SmartVoxelHeader.hh \ /usr/include/geant/G4SmartVoxelHeader.icc \ /usr/include/geant/G4VoxelNavigation.icc \ /usr/include/geant/G4ParameterisedNavigation.hh \ /usr/include/geant/G4VPVParameterisation.hh \ /usr/include/geant/G4VVolumeMaterialScanner.hh \ /usr/include/geant/G4ParameterisedNavigation.icc \ /usr/include/geant/G4ReplicaNavigation.hh \ /usr/include/geant/G4ReplicaNavigation.icc \ /usr/include/geant/G4RegularNavigation.hh \ /usr/include/geant/G4Navigator.icc \ /usr/include/geant/G4SPSRandomGenerator.hh \ /usr/include/geant/G4PhysicsOrderedFreeVector.hh \ /usr/include/geant/G4PhysicsVector.hh \ /usr/include/geant/G4PhysicsVectorType.hh \ /usr/include/geant/G4PhysicsVector.icc \ /usr/include/geant/G4PhysicsOrderedFreeVector.icc \ /usr/include/geant/G4DataInterpolation.hh \ /usr/include/geant/G4SPSAngDistribution.hh \ /usr/include/geant/G4SPSEneDistribution.hh \ /usr/include/geant/G4GeneralParticleSource.hh \ /usr/include/geant/G4Event.hh /usr/include/geant/G4PrimaryVertex.hh \ /usr/include/geant/G4PrimaryParticle.hh \ /usr/include/geant/G4HCofThisEvent.hh \ /usr/include/geant/G4VHitsCollection.hh \ /usr/include/geant/G4DCofThisEvent.hh \ /usr/include/geant/G4VDigiCollection.hh \ /usr/include/geant/G4TrajectoryContainer.hh \ /usr/include/geant/G4VTrajectory.hh \ /usr/include/geant/G4VUserEventInformation.hh \ /usr/include/geant/G4SingleParticleSource.hh \ /usr/include/geant/G4GeneralParticleSourceMessenger.hh \ /usr/include/geant/G4UImessenger.hh ../../src/config/Exposition.h \ ../../src/config/Waypoint.h Hull.h SceneConfig.h \ /usr/include/geant/G4LogicalVolume.hh /usr/include/geant/G4RunManager.hh \ /usr/include/geant/G4RunManagerKernel.hh \ /usr/include/geant/G4EventManager.hh /usr/include/geant/evmandefs.hh \ /usr/include/geant/trajectoryControl.hh \ /usr/include/geant/G4StackManager.hh \ /usr/include/geant/G4UserStackingAction.hh \ /usr/include/geant/G4ClassificationOfNewTrack.hh \ /usr/include/geant/G4StackedTrack.hh /usr/include/geant/G4Track.hh \ /usr/include/geant/G4DynamicParticle.hh \ /usr/include/geant/G4LorentzVector.hh \ /usr/include/geant/G4ElectronOccupancy.hh \ /usr/include/geant/G4DynamicParticle.icc \ /usr/include/geant/G4TrackStatus.hh \ /usr/include/geant/G4VUserTrackInformation.hh \ /usr/include/geant/G4Material.hh /usr/include/geant/G4Element.hh \ /usr/include/geant/G4Isotope.hh /usr/include/geant/G4AtomicShells.hh \ /usr/include/geant/G4IonisParamElm.hh \ /usr/include/geant/G4IsotopeVector.hh \ /usr/include/geant/G4ElementTable.hh \ /usr/include/geant/G4MaterialPropertiesTable.hh \ /usr/include/geant/G4MaterialPropertyVector.hh \ /usr/include/geant/G4MPVEntry.hh /usr/include/geant/G4IonisParamMat.hh \ /usr/include/geant/G4SandiaTable.hh /usr/include/geant/G4OrderedTable.hh \ /usr/include/geant/G4DataVector.hh /usr/include/geant/G4DataVector.icc \ /usr/include/geant/G4ElementVector.hh \ /usr/include/geant/G4MaterialTable.hh /usr/include/geant/G4Step.hh \ /usr/include/geant/G4StepPoint.hh \ /usr/include/geant/G4SteppingControl.hh \ /usr/include/geant/G4StepStatus.hh /usr/include/geant/G4StepPoint.icc \ /usr/include/geant/G4TrackVector.hh /usr/include/geant/G4Step.icc \ /usr/include/geant/G4Track.icc /usr/include/geant/G4TrackStack.hh \ /usr/include/geant/G4PrimaryTransformer.hh \ /usr/include/geant/G4ParticleTable.hh \ /usr/include/geant/G4ParticleTableIterator.hh \ /usr/include/geant/G4ParticleTable.icc \ /usr/include/geant/G4TrackingManager.hh \ /usr/include/geant/G4SteppingManager.hh /usr/include/geant/Randomize.hh \ /usr/include/CLHEP/Random/Randomize.h /usr/include/CLHEP/Random/defs.h \ /usr/include/CLHEP/Random/DRand48Engine.h \ /usr/include/CLHEP/Random/RandomEngine.h \ /usr/include/CLHEP/Random/RandomEngine.icc \ /usr/include/CLHEP/Random/DualRand.h \ /usr/include/CLHEP/Random/Hurd160Engine.h \ /usr/include/CLHEP/Random/Hurd288Engine.h \ /usr/include/CLHEP/Random/JamesRandom.h \ /usr/include/CLHEP/Random/MTwistEngine.h \ /usr/include/CLHEP/Random/RandEngine.h \ /usr/include/CLHEP/Random/RanecuEngine.h \ /usr/include/CLHEP/Random/RanluxEngine.h \ /usr/include/CLHEP/Random/Ranlux64Engine.h \ /usr/include/CLHEP/Random/RanshiEngine.h \ /usr/include/CLHEP/Random/TripleRand.h \ /usr/include/CLHEP/Random/RandBinomial.h \ /usr/include/CLHEP/Random/Random.h /usr/include/CLHEP/Random/Random.icc \ /usr/include/CLHEP/Random/RandBinomial.icc \ /usr/include/CLHEP/Random/RandBreitWigner.h \ /usr/include/CLHEP/Random/RandFlat.h \ /usr/include/CLHEP/Random/RandFlat.icc \ /usr/include/CLHEP/Random/RandBreitWigner.icc \ /usr/include/CLHEP/Random/RandChiSquare.h \ /usr/include/CLHEP/Random/RandChiSquare.icc \ /usr/include/CLHEP/Random/RandExponential.h \ /usr/include/CLHEP/Random/RandExponential.icc \ /usr/include/CLHEP/Random/RandBit.h \ /usr/include/CLHEP/Random/RandBit.icc \ /usr/include/CLHEP/Random/RandGamma.h \ /usr/include/CLHEP/Random/RandGamma.icc \ /usr/include/CLHEP/Random/RandGauss.h \ /usr/include/CLHEP/Random/RandGauss.icc \ /usr/include/CLHEP/Random/RandGaussQ.h \ /usr/include/CLHEP/Random/RandGaussQ.icc \ /usr/include/CLHEP/Random/RandGaussT.h /usr/include/CLHEP/Random/Stat.h \ /usr/include/CLHEP/Random/RandGaussT.icc \ /usr/include/CLHEP/Random/RandGeneral.h \ /usr/include/CLHEP/Random/RandGeneral.icc \ /usr/include/CLHEP/Random/RandLandau.h \ /usr/include/CLHEP/Random/RandLandau.icc \ /usr/include/CLHEP/Random/RandPoissonQ.h \ /usr/include/CLHEP/Random/RandPoisson.h \ /usr/include/CLHEP/Random/RandPoisson.icc \ /usr/include/CLHEP/Random/RandPoissonQ.icc \ /usr/include/CLHEP/Random/RandPoissonT.h \ /usr/include/CLHEP/Random/RandPoissonT.icc \ /usr/include/CLHEP/Random/RandStudentT.h \ /usr/include/CLHEP/Random/RandStudentT.icc \ /usr/include/geant/G4ProcessManager.hh /usr/include/geant/G4VProcess.hh \ /usr/include/geant/G4PhysicsTable.hh \ /usr/include/geant/G4PhysicsTable.icc \ /usr/include/geant/G4VParticleChange.hh \ /usr/include/geant/G4TrackFastVector.hh \ /usr/include/geant/G4FastVector.hh \ /usr/include/geant/G4VParticleChange.icc \ /usr/include/geant/G4ForceCondition.hh \ /usr/include/geant/G4GPILSelection.hh \ /usr/include/geant/G4ParticleChange.hh \ /usr/include/geant/G4ParticleChange.icc \ /usr/include/geant/G4ProcessType.hh \ /usr/include/geant/G4ProcessVector.hh \ /usr/include/geant/G4ProcessVector.icc \ /usr/include/geant/G4ProcessManager.icc \ /usr/include/geant/G4ProcessAttribute.hh \ /usr/include/geant/G4UserSteppingAction.hh \ /usr/include/geant/G4VSteppingVerbose.hh \ /usr/include/geant/G4TrackingMessenger.hh \ /usr/include/geant/G4UserTrackingAction.hh \ ../../src/physics/PhysicsList.h /usr/include/geant/G4VUserPhysicsList.hh \ /usr/include/geant/G4ProductionCutsTable.hh \ /usr/include/geant/G4MaterialCutsCouple.hh \ /usr/include/geant/G4ProductionCuts.hh \ /usr/include/geant/G4MCCIndexConversionTable.hh \ ../../src/physics/Scintillation.h /usr/include/geant/G4Scintillation.hh \ /usr/include/geant/G4Poisson.hh \ /usr/include/geant/G4VRestDiscreteProcess.hh \ /usr/include/geant/G4OpticalPhoton.hh \ /usr/include/geant/G4EmSaturation.hh ../../src/geometry/Geometry.h \ /usr/include/geant/G4VUserDetectorConstruction.hh \ /usr/include/geant/G4OpBoundaryProcess.hh \ /usr/include/geant/G4RandomTools.hh \ /usr/include/geant/G4RandomDirection.hh \ /usr/include/geant/G4VDiscreteProcess.hh \ /usr/include/geant/G4LogicalBorderSurface.hh \ /usr/include/geant/G4LogicalSurface.hh \ /usr/include/geant/G4LogicalSurface.icc \ /usr/include/geant/G4LogicalBorderSurface.icc \ /usr/include/geant/G4LogicalSkinSurface.hh \ /usr/include/geant/G4LogicalSkinSurface.icc \ /usr/include/geant/G4OpticalSurface.hh \ /usr/include/geant/G4SurfaceProperty.hh \ /usr/include/geant/G4TransportationManager.hh \ /usr/include/geant/G4SafetyHelper.hh \ /usr/include/geant/G4TransportationManager.icc \ /usr/include/geant/G4LogicalBorderSurface.hh \ ../../src/generator/Generator.h \ /usr/include/geant/G4VUserPrimaryGeneratorAction.hh \ ../../src/generator/SourceLib.h \ /usr/include/boost/iostreams/filtering_streambuf.hpp \ /usr/include/boost/iostreams/chain.hpp \ /usr/include/boost/iostreams/constants.hpp \ /usr/include/boost/iostreams/detail/ios.hpp \ /usr/include/boost/iostreams/detail/config/wide_streams.hpp \ /usr/include/boost/iostreams/detail/access_control.hpp \ /usr/include/boost/iostreams/detail/select.hpp \ /usr/include/boost/iostreams/detail/char_traits.hpp \ /usr/include/boost/iostreams/detail/push.hpp \ /usr/include/boost/iostreams/categories.hpp \ /usr/include/boost/iostreams/detail/adapter/range_adapter.hpp \ /usr/include/boost/iostreams/detail/error.hpp \ /usr/include/boost/iostreams/positioning.hpp \ /usr/include/boost/integer_traits.hpp \ /usr/include/boost/iostreams/detail/config/codecvt.hpp \ /usr/include/boost/iostreams/detail/config/fpos.hpp \ /usr/include/boost/iostreams/detail/config/disable_warnings.hpp \ /usr/include/boost/iostreams/detail/config/enable_warnings.hpp \ /usr/include/boost/type_traits/is_convertible.hpp \ /usr/include/boost/type_traits/add_reference.hpp \ /usr/include/boost/type_traits/ice.hpp \ /usr/include/boost/type_traits/detail/ice_eq.hpp \ /usr/include/boost/utility/enable_if.hpp \ /usr/include/boost/iostreams/detail/enable_if_stream.hpp \ /usr/include/boost/iostreams/traits_fwd.hpp \ /usr/include/boost/iostreams/pipeline.hpp \ /usr/include/boost/iostreams/detail/template_params.hpp \ /usr/include/boost/preprocessor/control/expr_if.hpp \ /usr/include/boost/preprocessor/repetition/enum_params.hpp \ /usr/include/boost/iostreams/traits.hpp \ /usr/include/boost/iostreams/detail/bool_trait_def.hpp \ /usr/include/boost/iostreams/detail/is_iterator_range.hpp \ /usr/include/boost/iostreams/detail/select_by_size.hpp \ /usr/include/boost/preprocessor/iteration/local.hpp \ /usr/include/boost/preprocessor/slot/slot.hpp \ /usr/include/boost/preprocessor/slot/detail/def.hpp \ /usr/include/boost/preprocessor/iteration/detail/local.hpp \ /usr/include/boost/iostreams/detail/wrap_unwrap.hpp \ /usr/include/boost/ref.hpp /usr/include/boost/utility/addressof.hpp \ /usr/include/boost/range/iterator_range.hpp \ /usr/include/boost/iterator/iterator_traits.hpp \ /usr/include/boost/range/functions.hpp \ /usr/include/boost/range/begin.hpp /usr/include/boost/range/config.hpp \ /usr/include/boost/range/iterator.hpp \ /usr/include/boost/range/mutable_iterator.hpp \ /usr/include/boost/range/const_iterator.hpp \ /usr/include/boost/range/end.hpp \ /usr/include/boost/range/detail/implementation_help.hpp \ /usr/include/boost/range/detail/common.hpp \ /usr/include/boost/range/detail/sfinae.hpp \ /usr/include/boost/range/size.hpp \ /usr/include/boost/range/difference_type.hpp \ /usr/include/boost/range/distance.hpp /usr/include/boost/range/empty.hpp \ /usr/include/boost/range/rbegin.hpp \ /usr/include/boost/range/reverse_iterator.hpp \ /usr/include/boost/iterator/reverse_iterator.hpp \ /usr/include/boost/utility.hpp \ /usr/include/boost/utility/base_from_member.hpp \ /usr/include/boost/preprocessor/repetition/enum_binary_params.hpp \ /usr/include/boost/preprocessor/repetition/repeat_from_to.hpp \ /usr/include/boost/utility/binary.hpp \ /usr/include/boost/preprocessor/control/deduce_d.hpp \ /usr/include/boost/preprocessor/seq/cat.hpp \ /usr/include/boost/preprocessor/seq/fold_left.hpp \ /usr/include/boost/preprocessor/seq/seq.hpp \ /usr/include/boost/preprocessor/seq/elem.hpp \ /usr/include/boost/preprocessor/seq/size.hpp \ /usr/include/boost/preprocessor/seq/transform.hpp \ /usr/include/boost/preprocessor/arithmetic/mod.hpp \ /usr/include/boost/preprocessor/arithmetic/detail/div_base.hpp \ /usr/include/boost/next_prior.hpp \ /usr/include/boost/iterator/iterator_adaptor.hpp \ /usr/include/boost/iterator/iterator_categories.hpp \ /usr/include/boost/iterator/detail/config_def.hpp \ /usr/include/boost/iterator/detail/config_undef.hpp \ /usr/include/boost/iterator/iterator_facade.hpp \ /usr/include/boost/iterator/interoperable.hpp \ /usr/include/boost/iterator/detail/facade_iterator_category.hpp \ /usr/include/boost/detail/indirect_traits.hpp \ /usr/include/boost/type_traits/is_function.hpp \ /usr/include/boost/type_traits/detail/false_result.hpp \ /usr/include/boost/type_traits/detail/is_function_ptr_helper.hpp \ /usr/include/boost/iterator/detail/enable_if.hpp \ /usr/include/boost/implicit_cast.hpp \ /usr/include/boost/type_traits/add_const.hpp \ /usr/include/boost/type_traits/add_pointer.hpp \ /usr/include/boost/range/rend.hpp \ /usr/include/boost/range/value_type.hpp \ /usr/include/boost/iostreams/detail/push_params.hpp \ /usr/include/boost/iostreams/detail/resolve.hpp \ /usr/include/boost/detail/is_incrementable.hpp \ /usr/include/boost/iostreams/detail/adapter/mode_adapter.hpp \ /usr/include/boost/iostreams/operations.hpp \ /usr/include/boost/iostreams/operations_fwd.hpp \ /usr/include/boost/iostreams/close.hpp \ /usr/include/boost/iostreams/flush.hpp \ /usr/include/boost/iostreams/detail/dispatch.hpp \ /usr/include/boost/iostreams/detail/streambuf.hpp \ /usr/include/boost/iostreams/detail/adapter/non_blocking_adapter.hpp \ /usr/include/boost/iostreams/read.hpp \ /usr/include/boost/iostreams/char_traits.hpp \ /usr/include/boost/iostreams/seek.hpp \ /usr/include/boost/iostreams/write.hpp \ /usr/include/boost/iostreams/imbue.hpp \ /usr/include/boost/iostreams/input_sequence.hpp \ /usr/include/boost/iostreams/optimal_buffer_size.hpp \ /usr/include/boost/iostreams/output_sequence.hpp \ /usr/include/boost/iostreams/detail/adapter/output_iterator_adapter.hpp \ /usr/include/boost/iostreams/detail/config/gcc.hpp \ /usr/include/boost/iostreams/detail/config/overload_resolution.hpp \ /usr/include/boost/iostreams/detail/is_dereferenceable.hpp \ /usr/include/boost/iostreams/device/array.hpp \ /usr/include/boost/iostreams/device/null.hpp \ /usr/include/boost/iostreams/stream_buffer.hpp \ /usr/include/boost/iostreams/detail/forward.hpp \ /usr/include/boost/iostreams/detail/config/limits.hpp \ /usr/include/boost/iostreams/detail/streambuf/direct_streambuf.hpp \ /usr/include/boost/iostreams/detail/execute.hpp \ /usr/include/boost/utility/result_of.hpp /usr/include/boost/type.hpp \ /usr/include/boost/preprocessor.hpp \ /usr/include/boost/preprocessor/library.hpp \ /usr/include/boost/preprocessor/arithmetic.hpp \ /usr/include/boost/preprocessor/arithmetic/div.hpp \ /usr/include/boost/preprocessor/arithmetic/mul.hpp \ /usr/include/boost/preprocessor/array.hpp \ /usr/include/boost/preprocessor/array/data.hpp \ /usr/include/boost/preprocessor/array/elem.hpp \ /usr/include/boost/preprocessor/array/size.hpp \ /usr/include/boost/preprocessor/array/insert.hpp \ /usr/include/boost/preprocessor/array/push_back.hpp \ /usr/include/boost/preprocessor/array/pop_back.hpp \ /usr/include/boost/preprocessor/repetition/enum.hpp \ /usr/include/boost/preprocessor/repetition/deduce_z.hpp \ /usr/include/boost/preprocessor/array/pop_front.hpp \ /usr/include/boost/preprocessor/array/push_front.hpp \ /usr/include/boost/preprocessor/array/remove.hpp \ /usr/include/boost/preprocessor/array/replace.hpp \ /usr/include/boost/preprocessor/array/reverse.hpp \ /usr/include/boost/preprocessor/tuple/reverse.hpp \ /usr/include/boost/preprocessor/comparison.hpp \ /usr/include/boost/preprocessor/comparison/equal.hpp \ /usr/include/boost/preprocessor/comparison/greater_equal.hpp \ /usr/include/boost/preprocessor/config/limits.hpp \ /usr/include/boost/preprocessor/control.hpp \ /usr/include/boost/preprocessor/debug.hpp \ /usr/include/boost/preprocessor/debug/assert.hpp \ /usr/include/boost/preprocessor/debug/line.hpp \ /usr/include/boost/preprocessor/iteration/iterate.hpp \ /usr/include/boost/preprocessor/facilities.hpp \ /usr/include/boost/preprocessor/facilities/apply.hpp \ /usr/include/boost/preprocessor/detail/is_unary.hpp \ /usr/include/boost/preprocessor/facilities/expand.hpp \ /usr/include/boost/preprocessor/facilities/intercept.hpp \ /usr/include/boost/preprocessor/iteration.hpp \ /usr/include/boost/preprocessor/iteration/self.hpp \ /usr/include/boost/preprocessor/list.hpp \ /usr/include/boost/preprocessor/list/at.hpp \ /usr/include/boost/preprocessor/list/rest_n.hpp \ /usr/include/boost/preprocessor/list/cat.hpp \ /usr/include/boost/preprocessor/list/enum.hpp \ /usr/include/boost/preprocessor/list/filter.hpp \ /usr/include/boost/preprocessor/list/first_n.hpp \ /usr/include/boost/preprocessor/list/for_each.hpp \ /usr/include/boost/preprocessor/list/for_each_product.hpp \ /usr/include/boost/preprocessor/list/to_tuple.hpp \ /usr/include/boost/preprocessor/list/size.hpp \ /usr/include/boost/preprocessor/logical.hpp \ /usr/include/boost/preprocessor/logical/bitnor.hpp \ /usr/include/boost/preprocessor/logical/bitor.hpp \ /usr/include/boost/preprocessor/logical/bitxor.hpp \ /usr/include/boost/preprocessor/logical/nor.hpp \ /usr/include/boost/preprocessor/logical/or.hpp \ /usr/include/boost/preprocessor/logical/xor.hpp \ /usr/include/boost/preprocessor/punctuation.hpp \ /usr/include/boost/preprocessor/punctuation/paren.hpp \ /usr/include/boost/preprocessor/punctuation/paren_if.hpp \ /usr/include/boost/preprocessor/repetition.hpp \ /usr/include/boost/preprocessor/repetition/deduce_r.hpp \ /usr/include/boost/preprocessor/repetition/enum_params_with_a_default.hpp \ /usr/include/boost/preprocessor/repetition/enum_params_with_defaults.hpp \ /usr/include/boost/preprocessor/repetition/enum_shifted.hpp \ /usr/include/boost/preprocessor/repetition/enum_shifted_binary_params.hpp \ /usr/include/boost/preprocessor/repetition/enum_shifted_params.hpp \ /usr/include/boost/preprocessor/repetition/enum_trailing.hpp \ /usr/include/boost/preprocessor/repetition/enum_trailing_binary_params.hpp \ /usr/include/boost/preprocessor/repetition/enum_trailing_params.hpp \ /usr/include/boost/preprocessor/selection.hpp \ /usr/include/boost/preprocessor/selection/max.hpp \ /usr/include/boost/preprocessor/selection/min.hpp \ /usr/include/boost/preprocessor/seq.hpp \ /usr/include/boost/preprocessor/seq/enum.hpp \ /usr/include/boost/preprocessor/seq/filter.hpp \ /usr/include/boost/preprocessor/seq/first_n.hpp \ /usr/include/boost/preprocessor/seq/detail/split.hpp \ /usr/include/boost/preprocessor/seq/fold_right.hpp \ /usr/include/boost/preprocessor/seq/reverse.hpp \ /usr/include/boost/preprocessor/seq/for_each.hpp \ /usr/include/boost/preprocessor/seq/for_each_i.hpp \ /usr/include/boost/preprocessor/seq/for_each_product.hpp \ /usr/include/boost/preprocessor/seq/insert.hpp \ /usr/include/boost/preprocessor/seq/rest_n.hpp \ /usr/include/boost/preprocessor/seq/pop_back.hpp \ /usr/include/boost/preprocessor/seq/pop_front.hpp \ /usr/include/boost/preprocessor/seq/push_back.hpp \ /usr/include/boost/preprocessor/seq/push_front.hpp \ /usr/include/boost/preprocessor/seq/remove.hpp \ /usr/include/boost/preprocessor/seq/replace.hpp \ /usr/include/boost/preprocessor/seq/subseq.hpp \ /usr/include/boost/preprocessor/seq/to_array.hpp \ /usr/include/boost/preprocessor/seq/to_tuple.hpp \ /usr/include/boost/preprocessor/slot.hpp \ /usr/include/boost/preprocessor/tuple.hpp \ /usr/include/boost/preprocessor/tuple/to_seq.hpp \ /usr/include/boost/preprocessor/iteration/detail/iter/forward1.hpp \ /usr/include/boost/preprocessor/iteration/detail/bounds/lower1.hpp \ /usr/include/boost/preprocessor/slot/detail/shared.hpp \ /usr/include/boost/preprocessor/iteration/detail/bounds/upper1.hpp \ /usr/include/boost/utility/detail/result_of_iterate.hpp \ /usr/include/boost/iostreams/detail/functional.hpp \ /usr/include/boost/iostreams/detail/optional.hpp \ /usr/include/boost/type_traits/aligned_storage.hpp \ /usr/include/boost/iostreams/detail/streambuf/linked_streambuf.hpp \ /usr/include/boost/iostreams/detail/streambuf/indirect_streambuf.hpp \ /usr/include/boost/iostreams/detail/adapter/concept_adapter.hpp \ /usr/include/boost/iostreams/concepts.hpp \ /usr/include/boost/iostreams/detail/default_arg.hpp \ /usr/include/boost/iostreams/detail/call_traits.hpp \ /usr/include/boost/iostreams/detail/buffer.hpp \ /usr/include/boost/iostreams/checked_operations.hpp \ /usr/include/boost/iostreams/get.hpp \ /usr/include/boost/iostreams/put.hpp \ /usr/include/boost/iostreams/detail/double_object.hpp \ /usr/include/boost/call_traits.hpp \ /usr/include/boost/detail/call_traits.hpp \ /usr/include/boost/iostreams/detail/streambuf/chainbuf.hpp \ /usr/include/boost/iostreams/detail/translate_int_type.hpp \ /usr/include/boost/iostreams/copy.hpp /usr/include/boost/bind.hpp \ /usr/include/boost/bind/bind.hpp /usr/include/boost/mem_fn.hpp \ /usr/include/boost/bind/mem_fn.hpp /usr/include/boost/get_pointer.hpp \ /usr/include/boost/bind/mem_fn_template.hpp \ /usr/include/boost/bind/mem_fn_cc.hpp \ /usr/include/boost/is_placeholder.hpp /usr/include/boost/bind/arg.hpp \ /usr/include/boost/visit_each.hpp /usr/include/boost/bind/storage.hpp \ /usr/include/boost/bind/bind_template.hpp \ /usr/include/boost/bind/bind_cc.hpp \ /usr/include/boost/bind/bind_mf_cc.hpp \ /usr/include/boost/bind/bind_mf2_cc.hpp \ /usr/include/boost/bind/placeholders.hpp \ /usr/include/boost/iostreams/filter/gzip.hpp \ /usr/include/boost/iostreams/device/back_inserter.hpp \ /usr/include/boost/iostreams/filter/zlib.hpp \ /usr/include/boost/iostreams/detail/config/auto_link.hpp \ /usr/include/boost/iostreams/detail/config/dyn_link.hpp \ /usr/include/boost/iostreams/detail/config/zlib.hpp \ /usr/include/boost/iostreams/filter/symmetric.hpp \ ../../src/detector/Detector.h /usr/include/geant/G4VSensitiveDetector.hh \ /usr/include/geant/G4VHit.hh /usr/include/geant/G4VReadOutGeometry.hh \ /usr/include/geant/G4SensitiveVolumeList.hh \ /usr/include/geant/G4CollectionNameVector.hh \ /usr/include/geant/G4VSDFilter.hh ../../src/detector/DetectorHit.h \ /usr/include/geant/G4VHit.hh /usr/include/geant/G4THitsCollection.hh \ - /usr/include/geant/G4Allocator.hh /usr/include/geant/G4Tubs.hh \ - /usr/include/geant/G4CSGSolid.hh /usr/include/geant/G4Tubs.icc \ + /usr/include/geant/G4Allocator.hh /usr/include/geant/G4Box.hh \ + /usr/include/geant/G4CSGSolid.hh /usr/include/geant/G4Box.icc \ + /usr/include/geant/G4Tubs.hh /usr/include/geant/G4Tubs.icc \ /usr/include/geant/G4Sphere.hh /usr/include/geant/G4Sphere.icc \ /usr/include/geant/G4PVPlacement.hh \ /usr/include/geant/G4VisAttributes.hh /usr/include/geant/G4Colour.hh \ /usr/include/geant/G4Color.hh /usr/include/geant/G4VisAttributes.icc \ /usr/include/geant/G4SDManager.hh /usr/include/geant/G4SDStructure.hh \ /usr/include/geant/G4VSensitiveDetector.hh \ /usr/include/geant/G4HCtable.hh /usr/include/geant/G4SDParticleFilter.hh \ /usr/include/geant/G4VPrimitiveScorer.hh \ /usr/include/geant/G4MultiFunctionalDetector.hh \ /usr/include/geant/G4PSEnergyDeposit.hh \ /usr/include/geant/G4VPrimitiveScorer.hh \ /usr/include/geant/G4THitsMap.hh /usr/include/geant/G4THitsCollection.hh \ /usr/include/geant/G4PSNofSecondary.hh \ /usr/include/geant/G4PSMinKinEAtGeneration.hh \ /usr/include/geant/G4PSTrackLength.hh /usr/include/geant/G4PSNofStep.hh DetectorConfig.h: Config.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/string: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/i686-pc-linux-gnu/bits/c++config.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/i686-pc-linux-gnu/bits/os_defines.h: /usr/include/features.h: /usr/include/sys/cdefs.h: /usr/include/bits/wordsize.h: /usr/include/gnu/stubs.h: /usr/include/gnu/stubs-32.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/i686-pc-linux-gnu/bits/cpu_defines.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/bits/stringfwd.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/bits/char_traits.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/bits/stl_algobase.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/cstddef: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/stddef.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/bits/functexcept.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/exception_defines.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/bits/cpp_type_traits.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/ext/type_traits.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/ext/numeric_traits.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/bits/stl_pair.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/bits/move.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/bits/concept_check.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/bits/stl_iterator_base_types.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/bits/stl_iterator_base_funcs.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/bits/stl_iterator.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/debug/debug.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/bits/postypes.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/cwchar: /usr/include/wchar.h: /usr/include/stdio.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/stdarg.h: /usr/include/bits/wchar.h: /usr/include/xlocale.h: /usr/include/bits/wchar2.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/bits/allocator.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/i686-pc-linux-gnu/bits/c++allocator.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/ext/new_allocator.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/new: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/exception: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/bits/localefwd.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/i686-pc-linux-gnu/bits/c++locale.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/clocale: /usr/include/locale.h: /usr/include/bits/locale.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/iosfwd: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/cctype: /usr/include/ctype.h: /usr/include/bits/types.h: /usr/include/bits/typesizes.h: /usr/include/endian.h: /usr/include/bits/endian.h: /usr/include/bits/byteswap.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/bits/ostream_insert.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/cxxabi-forced.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/bits/stl_function.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/backward/binders.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/bits/basic_string.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/ext/atomicity.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/i686-pc-linux-gnu/bits/gthr.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/i686-pc-linux-gnu/bits/gthr-default.h: /usr/include/pthread.h: /usr/include/sched.h: /usr/include/time.h: /usr/include/bits/sched.h: /usr/include/bits/time.h: /usr/include/signal.h: /usr/include/bits/sigset.h: /usr/include/bits/pthreadtypes.h: /usr/include/bits/setjmp.h: /usr/include/unistd.h: /usr/include/bits/posix_opt.h: /usr/include/bits/environments.h: /usr/include/bits/confname.h: /usr/include/getopt.h: /usr/include/bits/unistd.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/i686-pc-linux-gnu/bits/atomic_word.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/initializer_list: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/bits/basic_string.tcc: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/iomanip: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/bits/ios_base.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/bits/locale_classes.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/bits/locale_classes.tcc: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/iostream: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/ostream: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/ios: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/streambuf: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/bits/streambuf.tcc: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/bits/basic_ios.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/bits/locale_facets.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/cwctype: /usr/include/wctype.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/i686-pc-linux-gnu/bits/ctype_base.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/bits/streambuf_iterator.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/i686-pc-linux-gnu/bits/ctype_inline.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/bits/locale_facets.tcc: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/bits/basic_ios.tcc: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/bits/ostream.tcc: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/istream: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/bits/istream.tcc: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/fstream: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/bits/codecvt.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/cstdio: /usr/include/libio.h: /usr/include/_G_config.h: /usr/include/bits/stdio_lim.h: /usr/include/bits/sys_errlist.h: /usr/include/bits/stdio.h: /usr/include/bits/stdio2.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/i686-pc-linux-gnu/bits/basic_file.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/i686-pc-linux-gnu/bits/c++io.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/bits/fstream.tcc: /usr/include/geant/globals.hh: /usr/include/geant/G4ios.hh: /usr/include/geant/G4Types.hh: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/complex: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/cmath: /usr/include/math.h: /usr/include/bits/huge_val.h: /usr/include/bits/huge_valf.h: /usr/include/bits/huge_vall.h: /usr/include/bits/inf.h: /usr/include/bits/nan.h: /usr/include/bits/mathdef.h: /usr/include/bits/mathcalls.h: /usr/include/bits/mathinline.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/bits/cmath.tcc: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/sstream: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/bits/sstream.tcc: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/algorithm: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/bits/stl_algo.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/cstdlib: /usr/include/stdlib.h: /usr/include/bits/waitflags.h: /usr/include/bits/waitstatus.h: /usr/include/sys/types.h: /usr/include/sys/select.h: /usr/include/bits/select.h: /usr/include/sys/sysmacros.h: /usr/include/alloca.h: /usr/include/bits/stdlib.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/bits/algorithmfwd.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/bits/stl_heap.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/bits/stl_tempbuf.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/bits/stl_construct.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/bits/stl_uninitialized.h: /usr/include/geant/G4String.hh: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/cstring: /usr/include/string.h: /usr/include/bits/string3.h: /usr/include/geant/G4String.icc: /usr/include/geant/templates.hh: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/limits: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/climits: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include-fixed/limits.h: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include-fixed/syslimits.h: /usr/include/limits.h: /usr/include/bits/posix1_lim.h: /usr/include/bits/local_lim.h: /usr/include/linux/limits.h: /usr/include/bits/posix2_lim.h: /usr/include/bits/xopen_lim.h: /usr/include/geant/G4PhysicalConstants.hh: /usr/include/CLHEP/Units/PhysicalConstants.h: /usr/include/CLHEP/Units/defs.h: /usr/include/CLHEP/Units/SystemOfUnits.h: /usr/include/geant/G4SystemOfUnits.hh: /usr/include/geant/G4ExceptionSeverity.hh: /usr/include/geant/G4ios.hh: /usr/include/boost/serialization/version.hpp: /usr/include/boost/config.hpp: /usr/include/boost/config/user.hpp: /usr/include/boost/config/select_compiler_config.hpp: /usr/include/boost/config/compiler/gcc.hpp: /usr/include/boost/config/select_stdlib_config.hpp: /usr/include/boost/config/no_tr1/utility.hpp: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/utility: /usr/lib/gcc/i686-pc-linux-gnu/4.4.1/include/g++-v4/bits/stl_relops.h: /usr/include/boost/config/stdlib/libstdcpp3.hpp: /usr/include/boost/config/select_platform_config.hpp: /usr/include/boost/config/platform/linux.hpp: /usr/include/boost/config/posix_features.hpp: /usr/include/boost/config/suffix.hpp: /usr/include/boost/mpl/int.hpp: /usr/include/boost/mpl/int_fwd.hpp: /usr/include/boost/mpl/aux_/adl_barrier.hpp: /usr/include/boost/mpl/aux_/config/adl.hpp: /usr/include/boost/mpl/aux_/config/msvc.hpp: /usr/include/boost/mpl/aux_/config/intel.hpp: /usr/include/boost/mpl/aux_/config/gcc.hpp: /usr/include/boost/mpl/aux_/config/workaround.hpp: /usr/include/boost/detail/workaround.hpp: /usr/include/boost/mpl/aux_/nttp_decl.hpp: /usr/include/boost/mpl/aux_/config/nttp.hpp: /usr/include/boost/mpl/aux_/integral_wrapper.hpp: /usr/include/boost/mpl/integral_c_tag.hpp: /usr/include/boost/mpl/aux_/config/static_constant.hpp: /usr/include/boost/mpl/aux_/static_cast.hpp: /usr/include/boost/preprocessor/cat.hpp: /usr/include/boost/preprocessor/config/config.hpp: /usr/include/boost/mpl/eval_if.hpp: /usr/include/boost/mpl/if.hpp: /usr/include/boost/mpl/aux_/value_wknd.hpp: /usr/include/boost/mpl/aux_/config/integral.hpp: /usr/include/boost/mpl/aux_/config/eti.hpp: /usr/include/boost/mpl/aux_/na_spec.hpp: /usr/include/boost/mpl/lambda_fwd.hpp: /usr/include/boost/mpl/void_fwd.hpp: /usr/include/boost/mpl/aux_/na.hpp: /usr/include/boost/mpl/bool.hpp: /usr/include/boost/mpl/bool_fwd.hpp: /usr/include/boost/mpl/aux_/na_fwd.hpp: /usr/include/boost/mpl/aux_/config/ctps.hpp: /usr/include/boost/mpl/aux_/config/lambda.hpp: /usr/include/boost/mpl/aux_/config/ttp.hpp: /usr/include/boost/mpl/aux_/lambda_arity_param.hpp: /usr/include/boost/mpl/aux_/template_arity_fwd.hpp: /usr/include/boost/mpl/aux_/arity.hpp: /usr/include/boost/mpl/aux_/config/dtp.hpp: /usr/include/boost/mpl/aux_/preprocessor/params.hpp: /usr/include/boost/mpl/aux_/config/preprocessor.hpp: /usr/include/boost/preprocessor/comma_if.hpp: /usr/include/boost/preprocessor/punctuation/comma_if.hpp: /usr/include/boost/preprocessor/control/if.hpp: /usr/include/boost/preprocessor/control/iif.hpp: /usr/include/boost/preprocessor/logical/bool.hpp: /usr/include/boost/preprocessor/facilities/empty.hpp: /usr/include/boost/preprocessor/punctuation/comma.hpp: /usr/include/boost/preprocessor/repeat.hpp: /usr/include/boost/preprocessor/repetition/repeat.hpp: /usr/include/boost/preprocessor/debug/error.hpp: /usr/include/boost/preprocessor/detail/auto_rec.hpp: /usr/include/boost/preprocessor/tuple/eat.hpp: /usr/include/boost/preprocessor/inc.hpp: /usr/include/boost/preprocessor/arithmetic/inc.hpp: /usr/include/boost/mpl/aux_/preprocessor/enum.hpp: /usr/include/boost/mpl/aux_/preprocessor/def_params_tail.hpp: /usr/include/boost/mpl/limits/arity.hpp: /usr/include/boost/preprocessor/logical/and.hpp: /usr/include/boost/preprocessor/logical/bitand.hpp: /usr/include/boost/preprocessor/identity.hpp: /usr/include/boost/preprocessor/facilities/identity.hpp: /usr/include/boost/preprocessor/empty.hpp: /usr/include/boost/preprocessor/arithmetic/add.hpp: /usr/include/boost/preprocessor/arithmetic/dec.hpp: /usr/include/boost/preprocessor/control/while.hpp: /usr/include/boost/preprocessor/list/fold_left.hpp: @@ -2868,561 +2869,565 @@ SceneConfig.h: /usr/include/boost/type_traits/add_reference.hpp: /usr/include/boost/type_traits/ice.hpp: /usr/include/boost/type_traits/detail/ice_eq.hpp: /usr/include/boost/utility/enable_if.hpp: /usr/include/boost/iostreams/detail/enable_if_stream.hpp: /usr/include/boost/iostreams/traits_fwd.hpp: /usr/include/boost/iostreams/pipeline.hpp: /usr/include/boost/iostreams/detail/template_params.hpp: /usr/include/boost/preprocessor/control/expr_if.hpp: /usr/include/boost/preprocessor/repetition/enum_params.hpp: /usr/include/boost/iostreams/traits.hpp: /usr/include/boost/iostreams/detail/bool_trait_def.hpp: /usr/include/boost/iostreams/detail/is_iterator_range.hpp: /usr/include/boost/iostreams/detail/select_by_size.hpp: /usr/include/boost/preprocessor/iteration/local.hpp: /usr/include/boost/preprocessor/slot/slot.hpp: /usr/include/boost/preprocessor/slot/detail/def.hpp: /usr/include/boost/preprocessor/iteration/detail/local.hpp: /usr/include/boost/iostreams/detail/wrap_unwrap.hpp: /usr/include/boost/ref.hpp: /usr/include/boost/utility/addressof.hpp: /usr/include/boost/range/iterator_range.hpp: /usr/include/boost/iterator/iterator_traits.hpp: /usr/include/boost/range/functions.hpp: /usr/include/boost/range/begin.hpp: /usr/include/boost/range/config.hpp: /usr/include/boost/range/iterator.hpp: /usr/include/boost/range/mutable_iterator.hpp: /usr/include/boost/range/const_iterator.hpp: /usr/include/boost/range/end.hpp: /usr/include/boost/range/detail/implementation_help.hpp: /usr/include/boost/range/detail/common.hpp: /usr/include/boost/range/detail/sfinae.hpp: /usr/include/boost/range/size.hpp: /usr/include/boost/range/difference_type.hpp: /usr/include/boost/range/distance.hpp: /usr/include/boost/range/empty.hpp: /usr/include/boost/range/rbegin.hpp: /usr/include/boost/range/reverse_iterator.hpp: /usr/include/boost/iterator/reverse_iterator.hpp: /usr/include/boost/utility.hpp: /usr/include/boost/utility/base_from_member.hpp: /usr/include/boost/preprocessor/repetition/enum_binary_params.hpp: /usr/include/boost/preprocessor/repetition/repeat_from_to.hpp: /usr/include/boost/utility/binary.hpp: /usr/include/boost/preprocessor/control/deduce_d.hpp: /usr/include/boost/preprocessor/seq/cat.hpp: /usr/include/boost/preprocessor/seq/fold_left.hpp: /usr/include/boost/preprocessor/seq/seq.hpp: /usr/include/boost/preprocessor/seq/elem.hpp: /usr/include/boost/preprocessor/seq/size.hpp: /usr/include/boost/preprocessor/seq/transform.hpp: /usr/include/boost/preprocessor/arithmetic/mod.hpp: /usr/include/boost/preprocessor/arithmetic/detail/div_base.hpp: /usr/include/boost/next_prior.hpp: /usr/include/boost/iterator/iterator_adaptor.hpp: /usr/include/boost/iterator/iterator_categories.hpp: /usr/include/boost/iterator/detail/config_def.hpp: /usr/include/boost/iterator/detail/config_undef.hpp: /usr/include/boost/iterator/iterator_facade.hpp: /usr/include/boost/iterator/interoperable.hpp: /usr/include/boost/iterator/detail/facade_iterator_category.hpp: /usr/include/boost/detail/indirect_traits.hpp: /usr/include/boost/type_traits/is_function.hpp: /usr/include/boost/type_traits/detail/false_result.hpp: /usr/include/boost/type_traits/detail/is_function_ptr_helper.hpp: /usr/include/boost/iterator/detail/enable_if.hpp: /usr/include/boost/implicit_cast.hpp: /usr/include/boost/type_traits/add_const.hpp: /usr/include/boost/type_traits/add_pointer.hpp: /usr/include/boost/range/rend.hpp: /usr/include/boost/range/value_type.hpp: /usr/include/boost/iostreams/detail/push_params.hpp: /usr/include/boost/iostreams/detail/resolve.hpp: /usr/include/boost/detail/is_incrementable.hpp: /usr/include/boost/iostreams/detail/adapter/mode_adapter.hpp: /usr/include/boost/iostreams/operations.hpp: /usr/include/boost/iostreams/operations_fwd.hpp: /usr/include/boost/iostreams/close.hpp: /usr/include/boost/iostreams/flush.hpp: /usr/include/boost/iostreams/detail/dispatch.hpp: /usr/include/boost/iostreams/detail/streambuf.hpp: /usr/include/boost/iostreams/detail/adapter/non_blocking_adapter.hpp: /usr/include/boost/iostreams/read.hpp: /usr/include/boost/iostreams/char_traits.hpp: /usr/include/boost/iostreams/seek.hpp: /usr/include/boost/iostreams/write.hpp: /usr/include/boost/iostreams/imbue.hpp: /usr/include/boost/iostreams/input_sequence.hpp: /usr/include/boost/iostreams/optimal_buffer_size.hpp: /usr/include/boost/iostreams/output_sequence.hpp: /usr/include/boost/iostreams/detail/adapter/output_iterator_adapter.hpp: /usr/include/boost/iostreams/detail/config/gcc.hpp: /usr/include/boost/iostreams/detail/config/overload_resolution.hpp: /usr/include/boost/iostreams/detail/is_dereferenceable.hpp: /usr/include/boost/iostreams/device/array.hpp: /usr/include/boost/iostreams/device/null.hpp: /usr/include/boost/iostreams/stream_buffer.hpp: /usr/include/boost/iostreams/detail/forward.hpp: /usr/include/boost/iostreams/detail/config/limits.hpp: /usr/include/boost/iostreams/detail/streambuf/direct_streambuf.hpp: /usr/include/boost/iostreams/detail/execute.hpp: /usr/include/boost/utility/result_of.hpp: /usr/include/boost/type.hpp: /usr/include/boost/preprocessor.hpp: /usr/include/boost/preprocessor/library.hpp: /usr/include/boost/preprocessor/arithmetic.hpp: /usr/include/boost/preprocessor/arithmetic/div.hpp: /usr/include/boost/preprocessor/arithmetic/mul.hpp: /usr/include/boost/preprocessor/array.hpp: /usr/include/boost/preprocessor/array/data.hpp: /usr/include/boost/preprocessor/array/elem.hpp: /usr/include/boost/preprocessor/array/size.hpp: /usr/include/boost/preprocessor/array/insert.hpp: /usr/include/boost/preprocessor/array/push_back.hpp: /usr/include/boost/preprocessor/array/pop_back.hpp: /usr/include/boost/preprocessor/repetition/enum.hpp: /usr/include/boost/preprocessor/repetition/deduce_z.hpp: /usr/include/boost/preprocessor/array/pop_front.hpp: /usr/include/boost/preprocessor/array/push_front.hpp: /usr/include/boost/preprocessor/array/remove.hpp: /usr/include/boost/preprocessor/array/replace.hpp: /usr/include/boost/preprocessor/array/reverse.hpp: /usr/include/boost/preprocessor/tuple/reverse.hpp: /usr/include/boost/preprocessor/comparison.hpp: /usr/include/boost/preprocessor/comparison/equal.hpp: /usr/include/boost/preprocessor/comparison/greater_equal.hpp: /usr/include/boost/preprocessor/config/limits.hpp: /usr/include/boost/preprocessor/control.hpp: /usr/include/boost/preprocessor/debug.hpp: /usr/include/boost/preprocessor/debug/assert.hpp: /usr/include/boost/preprocessor/debug/line.hpp: /usr/include/boost/preprocessor/iteration/iterate.hpp: /usr/include/boost/preprocessor/facilities.hpp: /usr/include/boost/preprocessor/facilities/apply.hpp: /usr/include/boost/preprocessor/detail/is_unary.hpp: /usr/include/boost/preprocessor/facilities/expand.hpp: /usr/include/boost/preprocessor/facilities/intercept.hpp: /usr/include/boost/preprocessor/iteration.hpp: /usr/include/boost/preprocessor/iteration/self.hpp: /usr/include/boost/preprocessor/list.hpp: /usr/include/boost/preprocessor/list/at.hpp: /usr/include/boost/preprocessor/list/rest_n.hpp: /usr/include/boost/preprocessor/list/cat.hpp: /usr/include/boost/preprocessor/list/enum.hpp: /usr/include/boost/preprocessor/list/filter.hpp: /usr/include/boost/preprocessor/list/first_n.hpp: /usr/include/boost/preprocessor/list/for_each.hpp: /usr/include/boost/preprocessor/list/for_each_product.hpp: /usr/include/boost/preprocessor/list/to_tuple.hpp: /usr/include/boost/preprocessor/list/size.hpp: /usr/include/boost/preprocessor/logical.hpp: /usr/include/boost/preprocessor/logical/bitnor.hpp: /usr/include/boost/preprocessor/logical/bitor.hpp: /usr/include/boost/preprocessor/logical/bitxor.hpp: /usr/include/boost/preprocessor/logical/nor.hpp: /usr/include/boost/preprocessor/logical/or.hpp: /usr/include/boost/preprocessor/logical/xor.hpp: /usr/include/boost/preprocessor/punctuation.hpp: /usr/include/boost/preprocessor/punctuation/paren.hpp: /usr/include/boost/preprocessor/punctuation/paren_if.hpp: /usr/include/boost/preprocessor/repetition.hpp: /usr/include/boost/preprocessor/repetition/deduce_r.hpp: /usr/include/boost/preprocessor/repetition/enum_params_with_a_default.hpp: /usr/include/boost/preprocessor/repetition/enum_params_with_defaults.hpp: /usr/include/boost/preprocessor/repetition/enum_shifted.hpp: /usr/include/boost/preprocessor/repetition/enum_shifted_binary_params.hpp: /usr/include/boost/preprocessor/repetition/enum_shifted_params.hpp: /usr/include/boost/preprocessor/repetition/enum_trailing.hpp: /usr/include/boost/preprocessor/repetition/enum_trailing_binary_params.hpp: /usr/include/boost/preprocessor/repetition/enum_trailing_params.hpp: /usr/include/boost/preprocessor/selection.hpp: /usr/include/boost/preprocessor/selection/max.hpp: /usr/include/boost/preprocessor/selection/min.hpp: /usr/include/boost/preprocessor/seq.hpp: /usr/include/boost/preprocessor/seq/enum.hpp: /usr/include/boost/preprocessor/seq/filter.hpp: /usr/include/boost/preprocessor/seq/first_n.hpp: /usr/include/boost/preprocessor/seq/detail/split.hpp: /usr/include/boost/preprocessor/seq/fold_right.hpp: /usr/include/boost/preprocessor/seq/reverse.hpp: /usr/include/boost/preprocessor/seq/for_each.hpp: /usr/include/boost/preprocessor/seq/for_each_i.hpp: /usr/include/boost/preprocessor/seq/for_each_product.hpp: /usr/include/boost/preprocessor/seq/insert.hpp: /usr/include/boost/preprocessor/seq/rest_n.hpp: /usr/include/boost/preprocessor/seq/pop_back.hpp: /usr/include/boost/preprocessor/seq/pop_front.hpp: /usr/include/boost/preprocessor/seq/push_back.hpp: /usr/include/boost/preprocessor/seq/push_front.hpp: /usr/include/boost/preprocessor/seq/remove.hpp: /usr/include/boost/preprocessor/seq/replace.hpp: /usr/include/boost/preprocessor/seq/subseq.hpp: /usr/include/boost/preprocessor/seq/to_array.hpp: /usr/include/boost/preprocessor/seq/to_tuple.hpp: /usr/include/boost/preprocessor/slot.hpp: /usr/include/boost/preprocessor/tuple.hpp: /usr/include/boost/preprocessor/tuple/to_seq.hpp: /usr/include/boost/preprocessor/iteration/detail/iter/forward1.hpp: /usr/include/boost/preprocessor/iteration/detail/bounds/lower1.hpp: /usr/include/boost/preprocessor/slot/detail/shared.hpp: /usr/include/boost/preprocessor/iteration/detail/bounds/upper1.hpp: /usr/include/boost/utility/detail/result_of_iterate.hpp: /usr/include/boost/iostreams/detail/functional.hpp: /usr/include/boost/iostreams/detail/optional.hpp: /usr/include/boost/type_traits/aligned_storage.hpp: /usr/include/boost/iostreams/detail/streambuf/linked_streambuf.hpp: /usr/include/boost/iostreams/detail/streambuf/indirect_streambuf.hpp: /usr/include/boost/iostreams/detail/adapter/concept_adapter.hpp: /usr/include/boost/iostreams/concepts.hpp: /usr/include/boost/iostreams/detail/default_arg.hpp: /usr/include/boost/iostreams/detail/call_traits.hpp: /usr/include/boost/iostreams/detail/buffer.hpp: /usr/include/boost/iostreams/checked_operations.hpp: /usr/include/boost/iostreams/get.hpp: /usr/include/boost/iostreams/put.hpp: /usr/include/boost/iostreams/detail/double_object.hpp: /usr/include/boost/call_traits.hpp: /usr/include/boost/detail/call_traits.hpp: /usr/include/boost/iostreams/detail/streambuf/chainbuf.hpp: /usr/include/boost/iostreams/detail/translate_int_type.hpp: /usr/include/boost/iostreams/copy.hpp: /usr/include/boost/bind.hpp: /usr/include/boost/bind/bind.hpp: /usr/include/boost/mem_fn.hpp: /usr/include/boost/bind/mem_fn.hpp: /usr/include/boost/get_pointer.hpp: /usr/include/boost/bind/mem_fn_template.hpp: /usr/include/boost/bind/mem_fn_cc.hpp: /usr/include/boost/is_placeholder.hpp: /usr/include/boost/bind/arg.hpp: /usr/include/boost/visit_each.hpp: /usr/include/boost/bind/storage.hpp: /usr/include/boost/bind/bind_template.hpp: /usr/include/boost/bind/bind_cc.hpp: /usr/include/boost/bind/bind_mf_cc.hpp: /usr/include/boost/bind/bind_mf2_cc.hpp: /usr/include/boost/bind/placeholders.hpp: /usr/include/boost/iostreams/filter/gzip.hpp: /usr/include/boost/iostreams/device/back_inserter.hpp: /usr/include/boost/iostreams/filter/zlib.hpp: /usr/include/boost/iostreams/detail/config/auto_link.hpp: /usr/include/boost/iostreams/detail/config/dyn_link.hpp: /usr/include/boost/iostreams/detail/config/zlib.hpp: /usr/include/boost/iostreams/filter/symmetric.hpp: ../../src/detector/Detector.h: /usr/include/geant/G4VSensitiveDetector.hh: /usr/include/geant/G4VHit.hh: /usr/include/geant/G4VReadOutGeometry.hh: /usr/include/geant/G4SensitiveVolumeList.hh: /usr/include/geant/G4CollectionNameVector.hh: /usr/include/geant/G4VSDFilter.hh: ../../src/detector/DetectorHit.h: /usr/include/geant/G4VHit.hh: /usr/include/geant/G4THitsCollection.hh: /usr/include/geant/G4Allocator.hh: -/usr/include/geant/G4Tubs.hh: +/usr/include/geant/G4Box.hh: /usr/include/geant/G4CSGSolid.hh: +/usr/include/geant/G4Box.icc: + +/usr/include/geant/G4Tubs.hh: + /usr/include/geant/G4Tubs.icc: /usr/include/geant/G4Sphere.hh: /usr/include/geant/G4Sphere.icc: /usr/include/geant/G4PVPlacement.hh: /usr/include/geant/G4VisAttributes.hh: /usr/include/geant/G4Colour.hh: /usr/include/geant/G4Color.hh: /usr/include/geant/G4VisAttributes.icc: /usr/include/geant/G4SDManager.hh: /usr/include/geant/G4SDStructure.hh: /usr/include/geant/G4VSensitiveDetector.hh: /usr/include/geant/G4HCtable.hh: /usr/include/geant/G4SDParticleFilter.hh: /usr/include/geant/G4VPrimitiveScorer.hh: /usr/include/geant/G4MultiFunctionalDetector.hh: /usr/include/geant/G4PSEnergyDeposit.hh: /usr/include/geant/G4VPrimitiveScorer.hh: /usr/include/geant/G4THitsMap.hh: /usr/include/geant/G4THitsCollection.hh: /usr/include/geant/G4PSNofSecondary.hh: /usr/include/geant/G4PSMinKinEAtGeneration.hh: /usr/include/geant/G4PSTrackLength.hh: /usr/include/geant/G4PSNofStep.hh: diff --git a/src/config/DetectorConfig.cpp b/src/config/DetectorConfig.cpp index 42e0fc8..1f7d158 100644 --- a/src/config/DetectorConfig.cpp +++ b/src/config/DetectorConfig.cpp @@ -1,256 +1,309 @@ /*************************************************************************** * Copyright (C) 2009 by P.Voylov * * [email protected] * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "DetectorConfig.h" #include <sys/stat.h> #include <sys/types.h> #include "GSMS.h" #include "detector/Detector.h" +#include <geant/G4Box.hh> #include <geant/G4Tubs.hh> #include <geant/G4Sphere.hh> #include <geant/G4PVPlacement.hh> #include <geant/G4VisAttributes.hh> #include <geant/G4SDManager.hh> #include <geant/G4SDParticleFilter.hh> #include <geant/G4VPrimitiveScorer.hh> #include <geant/G4PSEnergyDeposit.hh> #include <geant/G4PSNofSecondary.hh> #include <geant/G4PSMinKinEAtGeneration.hh> #include <geant/G4PSTrackLength.hh> #include <geant/G4PSNofStep.hh> unsigned int GSMS::DetectorConfig::save(std::ofstream* stream) { DetectorConfig* pDetectorConfig = this; boost::archive::xml_oarchive out(*stream); out << BOOST_SERIALIZATION_NVP(pDetectorConfig); } unsigned int GSMS::DetectorConfig::imprint(G4VPhysicalVolume* wptr) { G4VPhysicalVolume* world = NULL; if(wptr) world = wptr; else GSMS::GSMS::getWorld(&world); try { G4VSolid* s_crystal = NULL; G4VSolid* s_mirror = NULL; G4VSolid* s_shirt = NULL; + G4VSolid* s_plate = NULL; + G4VSolid* s_bshirt = NULL; + if(m_shape == "Cyllinder") { s_crystal = new G4Tubs( "crystal", 0., m_radius, m_height/2, 0.0*deg, 360.0*deg); s_mirror = new G4Tubs( "mirror", 0., m_radius + m_mirror_thick, m_height/2 + m_mirror_thick, 0.0*deg, 360.0*deg); s_shirt = new G4Tubs( "shirt", 0., m_radius + m_mirror_thick + m_shirt_thick, m_height/2 + m_mirror_thick + m_shirt_thick, 0.0*deg, 360.0*deg); + + + s_bshirt = new G4Tubs( + "bshirt", + m_radius + m_mirror_thick, + m_radius + m_mirror_thick + m_shirt_thick, + 15.4*cm/2, + 0.0*deg, + 360.0*deg); + + s_plate = new G4Box( + "element", + 8.5*cm/2, + 5.8*cm/2, + 0.6*cm/2); + + } else if (m_shape == "Sphere") { s_crystal = new G4Sphere( "crystal", 0., m_radius, 0.0*deg, 360.0*deg, 0.0*deg, 360.0*deg ); s_mirror = new G4Sphere( "mirror", 0., m_radius + m_mirror_thick, 0.0*deg, 360.0*deg, 0.0*deg, 360.0*deg ); s_shirt = new G4Sphere( "shirt", 0., m_radius + m_mirror_thick + m_shirt_thick, 0.0*deg, 360.0*deg, 0.0*deg, 360.0*deg ); } else return GSMS_ERR; G4Material* crystal_mat = NULL; G4Material* mirror_mat = NULL; G4Material* shirt_mat = NULL; if( !__SUCCEEDED(GSMS::GSMS::getMaterial(m_material,&crystal_mat)) || !__SUCCEEDED(GSMS::GSMS::getMaterial("MgO",&mirror_mat)) || !__SUCCEEDED(GSMS::GSMS::getMaterial("D16",&shirt_mat))) return GSMS_ERR; G4LogicalVolume* crystal_log = new G4LogicalVolume( s_crystal, crystal_mat, "crystal_log"); G4LogicalVolume* mirror_log = new G4LogicalVolume( s_mirror, mirror_mat, "mirror_log"); G4LogicalVolume* shirt_log = new G4LogicalVolume( s_shirt, shirt_mat, "shirt_log"); + G4LogicalVolume* bshirt_log = new G4LogicalVolume( + s_bshirt, + shirt_mat, + "bshirt_log"); + G4LogicalVolume* plate_log = new G4LogicalVolume( + s_plate, + shirt_mat, + "plate_log"); + + + G4double plate_offset = (m_height/2 + m_mirror_thick + m_shirt_thick) + 0.3*cm; + G4double bshirt_offset = plate_offset + 0.3*cm + 15.4*cm/2; + + + G4VPhysicalVolume* plate_phys = new G4PVPlacement( + 0, + G4ThreeVector(0.,0.,plate_offset), + "plate_phys", + plate_log, + world, + true, + 0); + G4VPhysicalVolume* bshirt_phys = new G4PVPlacement( + 0, + G4ThreeVector(0.,0.,bshirt_offset), + "bshirt_phys", + bshirt_log, + world, + true, + 0); + G4VPhysicalVolume* shirt_phys = new G4PVPlacement( 0, G4ThreeVector(0.,0.,0.), "shirt_phys", shirt_log, world, - false, + true, 0); G4VPhysicalVolume* mirror_phys = new G4PVPlacement( 0, G4ThreeVector(0.,0.,0.), "mirror_phys", mirror_log, shirt_phys, - false, + true, 0); - G4VPhysicalVolume* crystal_phys = new G4PVPlacement( 0, G4ThreeVector(0.,0.,0.), "crystal_phys", crystal_log, mirror_phys, - false, + true, 0); G4VisAttributes* crystal_vis = new G4VisAttributes(GSMS_COLOR_CRYSTAL); G4VisAttributes* mirror_vis = new G4VisAttributes(GSMS_COLOR_MGO); G4VisAttributes* shirt_vis = new G4VisAttributes(GSMS_COLOR_ALUMINIUM); crystal_vis->SetVisibility(true); mirror_vis->SetVisibility(true); shirt_vis->SetVisibility(true); crystal_vis->SetForceSolid(true); mirror_vis->SetForceSolid(true); shirt_vis->SetForceSolid(true); crystal_log->SetVisAttributes(crystal_vis); mirror_log->SetVisAttributes(mirror_vis); shirt_log->SetVisAttributes(shirt_vis); + bshirt_log->SetVisAttributes(shirt_vis); + plate_log->SetVisAttributes(shirt_vis); /* G4SDManager* sd_manager = G4SDManager::GetSDMpointer(); G4VSensitiveDetector* crystal_sd = new Detector("crystal"); sd_manager->AddNewDetector(crystal_sd); crystal_log->SetSensitiveDetector(crystal_sd); */ G4String filterName, particleName; /* G4SDParticleFilter* gammaFilter = new G4SDParticleFilter(filterName="gammaFilter",particleName="gamma"); G4SDParticleFilter* electronFilter = new G4SDParticleFilter(filterName="electronFilter",particleName="e-"); G4SDParticleFilter* positronFilter = new G4SDParticleFilter(filterName="positronFilter",particleName="e+"); G4SDParticleFilter* epFilter = new G4SDParticleFilter(filterName="epFilter"); epFilter->add(particleName="e-"); epFilter->add(particleName="e+"); */ G4String detName = "crystal"; G4MultiFunctionalDetector* det = new G4MultiFunctionalDetector(detName); G4VPrimitiveScorer* primitive; primitive = new G4PSEnergyDeposit("eDep"); //primitive->SetFilter(gammaFilter); det->RegisterPrimitive(primitive); /* primitive = new G4PSNofSecondary("nGamma"); primitive->SetFilter(gammaFilter); det->RegisterPrimitive(primitive); primitive = new G4PSNofSecondary("nElectron"); primitive->SetFilter(electronFilter); det->RegisterPrimitive(primitive); primitive = new G4PSNofSecondary("nPositron"); primitive->SetFilter(positronFilter); det->RegisterPrimitive(primitive); primitive = new G4PSMinKinEAtGeneration("minEkinGamma"); primitive->SetFilter(gammaFilter); det->RegisterPrimitive(primitive); primitive = new G4PSMinKinEAtGeneration("minEkinElectron"); primitive->SetFilter(electronFilter); det->RegisterPrimitive(primitive); primitive = new G4PSMinKinEAtGeneration("minEkinPositron"); primitive->SetFilter(positronFilter); det->RegisterPrimitive(primitive); primitive = new G4PSTrackLength("trackLength"); primitive->SetFilter(epFilter); det->RegisterPrimitive(primitive); primitive = new G4PSNofStep("nStep"); primitive->SetFilter(epFilter); det->RegisterPrimitive(primitive); */ G4SDManager::GetSDMpointer()->AddNewDetector(det); crystal_log->SetSensitiveDetector(det); } catch(...) { return GSMS_ERR; }; return GSMS_OK; }; diff --git a/src/config/DetectorConfig.h b/src/config/DetectorConfig.h index 0f74fb9..9f6aa7d 100644 --- a/src/config/DetectorConfig.h +++ b/src/config/DetectorConfig.h @@ -1,122 +1,122 @@ /*************************************************************************** * Copyright (C) 2009 by P.Voylov * * [email protected] * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ /*!\file DetectorConfig.h * \brief Detector configuration entity */ #ifndef DETECTORCONFIG_H #define DETECTORCONFIG_H #include "Config.h" #include <geant/G4VPhysicalVolume.hh> namespace GSMS { /*!\class DetectorConfig * \brief Detector configuration */ class DetectorConfig : public PhysObjConfig { friend class boost::serialization::access; /*!\fn serialize(Archive & ar, const unsigned int version) * \brief Mask serializer * \param ar output archive * \param version archive version */ template<class Archive> void serialize(Archive & ar, const unsigned int version) { ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(PhysObjConfig) & BOOST_SERIALIZATION_NVP(m_radius) & BOOST_SERIALIZATION_NVP(m_mirror_thick) & BOOST_SERIALIZATION_NVP(m_shirt_thick) & BOOST_SERIALIZATION_NVP(m_resolution); if(m_shape == "Cyllinder") ar & BOOST_SERIALIZATION_NVP(m_height); } protected: /*!\var m_resolution * \brief crystal resolution */ G4float m_resolution; /*!\var m_radius * \brief crystal radius */ G4float m_radius; /*!\var m_height * \brief crystal height (for cyllinder, prism) */ G4float m_height; /*!\var m_mirror_thick * \brief mirror thickness */ G4float m_mirror_thick; /*!\var m_shirt_thick * \brief shirt thickness */ G4float m_shirt_thick; public: /*!\fn DetectorConfig(G4double resolution) * \brief Specific constructor * \param resolution crystal resolution */ DetectorConfig(std::string material = "CsI",G4float resolution = 0.085) : m_resolution(resolution) { m_type = "DetectorConfig"; m_material = material; m_radius = 25.0*mm; m_height = 100.0*mm; - m_mirror_thick = 1.5*mm; - m_shirt_thick = 0.5*mm; + m_mirror_thick = 1.0*mm; + m_shirt_thick = 3.0*mm; } /*!\fn ~DetectorConfig() * \brief Default destructor */ ~DetectorConfig() {} /*!\fn unsigned int save(std::ofstream* stream) * \brief Self-serializer * \param stream output stream * \return exit code */ virtual unsigned int save(std::ofstream* stream); /*!\fn unsigned int imprint(G4VPhysicalVolume* world) * \brief build detector in world * \param world world ptr */ unsigned int imprint(G4VPhysicalVolume* world = NULL); }; }; //namespace GSMS BOOST_CLASS_VERSION(GSMS::DetectorConfig,1) #endif /*DETECTORCONFIG_H*/ diff --git a/src/config/GSMS.cpp b/src/config/GSMS.cpp index bb1eeaf..1651131 100644 --- a/src/config/GSMS.cpp +++ b/src/config/GSMS.cpp @@ -1,225 +1,229 @@ /*************************************************************************** * Copyright (C) 2009 by P.Voylov * * [email protected] * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "GSMS.h" #include <geant/Randomize.hh> #include <geant/G4VisExecutive.hh> #include <geant/G4UImanager.hh> #include <geant/G4UIterminal.hh> #include <geant/G4UItcsh.hh> #include <geant/G4RunManager.hh> #include "action/RunAction.h" #include "action/EventAction.h" GSMS::GlobalConfig GSMS::GSMS::m_global; GSMS::Mask GSMS::GSMS::m_mask; GSMS::Hull GSMS::GSMS::m_hull; GSMS::Job GSMS::GSMS::m_job; GSMS::DetectorConfig GSMS::GSMS::m_detector; GSMS::SceneConfig GSMS::GSMS::m_scene; GSMS::PhysicsList* GSMS::GSMS::mp_physics = NULL; GSMS::Geometry* GSMS::GSMS::mp_geometry = NULL; GSMS::Generator* GSMS::GSMS::mp_generator = NULL; G4RunManager* GSMS::GSMS::mp_runmanager = NULL; G4int GSMS::GSMS::m_verbosity = 0; unsigned int GSMS::GSMS::getMaterial(std::string name,G4Material** material) { if(mp_geometry) return mp_geometry->getMaterial(name,material); else return GSMS_ERR; } unsigned int GSMS::GSMS::initRunManager() { // try // { CLHEP::HepRandom::setTheEngine(new CLHEP::RanecuEngine); CLHEP::HepRandom::setTheSeed(0L); mp_runmanager = new G4RunManager; mp_runmanager->SetVerboseLevel(0);//m_verbosity); mp_physics = new PhysicsList; mp_runmanager->SetUserInitialization(mp_physics); mp_geometry = new Geometry; mp_runmanager->SetUserInitialization(mp_geometry); mp_generator = new Generator; mp_runmanager->SetUserAction(mp_generator); G4UserRunAction* run_action = new RunAction; mp_runmanager->SetUserAction(run_action); G4UserEventAction* event_action = new EventAction; mp_runmanager->SetUserAction(event_action); mp_runmanager->Initialize(); G4VisManager* vis = new G4VisExecutive; vis->Initialize(); // G4UImanager* ui = G4UImanager::GetUIpointer(); // ui->ApplyCommand("/tracking/verbose 1"); // G4UIsession* session = NULL; // session = new G4UIterminal(); // session->SessionStart(); // delete session; -// Source* src = util::SourceLib::create_source("Cs137", 1, G4ThreeVector(0.*m, 2.5*m, 0.)); -// if(src) m_job.push_source(*src); + Source* src = util::SourceLib::create_source("Co60", 1, G4ThreeVector(0.*m, 2.0*m, 0.)); + if(src) m_job.push_source(*src); // src = util::SourceLib::create_source("Co57", 1, G4ThreeVector(1.*m, -1.*m, 0.)); // if(src) m_job.push_source(*src); // src = util::SourceLib::create_source("Co60", 1, G4ThreeVector(-1.*m, -1.*m, 0.)); // if(src) m_job.push_source(*src); - Source* src = util::SourceLib::create_source("Co60", 1, G4ThreeVector(0.*m, 2.0*m, 0.)); - if(src) m_job.push_source(*src); +// Source* src = util::SourceLib::create_source("Co60", 1, G4ThreeVector(0.*m, 2.0*m, 0.)); +// if(src) m_job.push_source(*src); // src = util::SourceLib::create_source("Co57", 1, G4ThreeVector(1.*m, 0., 0.)); // if(src) m_job.push_source(*src); // src = util::SourceLib::create_source("Co60", 1, G4ThreeVector(0., -1.*m, 0.)); // if(src) m_job.push_source(*src); /* int discretes = 217; for(int i = 0; i<discretes ; i++) { G4double ltime = ((G4double)i / discretes)*10*2*pi; setTime(&ltime); if(i) if( !mp_geometry->Update() ) std::cerr << "FAILED" << std::endl; mp_generator->Update(); // ui->ApplyCommand("/control/execute vis.mac"); mp_runmanager->GeometryHasBeenModified(); // mp_runmanager->BeamOn(50); serialize("text.gz"); } */ // catch(...) // { // return GSMS_ERR; // }; return GSMS_OK; } unsigned int GSMS::GSMS::run_forced(unsigned int beamOn) { - + try { int discretes = 217; int discrete_count = m_job.get_active_exposition().get_discrete_complete_count("217*1024"); for(int i = discrete_count; i<discretes ; i++) { std::cerr << "Current discrete count: "<< i << std::endl; G4double ltime = ((G4double)i / discretes)*10*2*pi; set_time(&ltime); if(i) if( !mp_geometry->Update() ) std::cerr << "FAILED" << std::endl; mp_generator->Update(); mp_runmanager->GeometryHasBeenModified(); - G4UImanager* ui = G4UImanager::GetUIpointer(); +// G4UImanager* ui = G4UImanager::GetUIpointer(); // ui->ApplyCommand("/control/execute vis.mac"); mp_runmanager->BeamOn(beamOn); serialize("text.gz"); + } - } catch(...) {}; + } catch(...) { + std::cerr << "Error!!!" << std::endl; + return GSMS_ERR; + } return GSMS_OK; } unsigned int GSMS::GSMS::serialize(std::string filename) { try { std::stringstream sout; boost::archive::xml_oarchive oa(sout); oa << BOOST_SERIALIZATION_NVP(m_mask) << BOOST_SERIALIZATION_NVP(m_global) << BOOST_SERIALIZATION_NVP(m_hull) << BOOST_SERIALIZATION_NVP(m_detector) - << BOOST_SERIALIZATION_NVP(m_job); -// << BOOST_SERIALIZATION_NVP(m_scene); + << BOOST_SERIALIZATION_NVP(m_job) + << BOOST_SERIALIZATION_NVP(m_scene); std::ofstream file_out(filename.c_str(),std::ios::out | std::ios::binary); boost::iostreams::filtering_ostreambuf out; out.push(boost::iostreams::gzip_compressor()); out.push(file_out); copy(sout,out); } catch(...) { return GSMS_ERR; }; return GSMS_OK; }; unsigned int GSMS::GSMS::unserialize(std::string filename) { try { std::ifstream file_in(filename.c_str(),std::ios::in | std::ios::binary); std::stringstream sin; boost::iostreams::filtering_istreambuf in; in.push(boost::iostreams::gzip_decompressor()); in.push(file_in); copy(in,sin); boost::archive::xml_iarchive ia(sin); ia >> BOOST_SERIALIZATION_NVP(m_mask) >> BOOST_SERIALIZATION_NVP(m_global) >> BOOST_SERIALIZATION_NVP(m_hull) >> BOOST_SERIALIZATION_NVP(m_detector) >> BOOST_SERIALIZATION_NVP(m_job) >> BOOST_SERIALIZATION_NVP(m_scene); } catch(...) { return GSMS_ERR; }; return GSMS_OK; }; diff --git a/src/config/GSMS.h b/src/config/GSMS.h index 852d291..e6d7d53 100644 --- a/src/config/GSMS.h +++ b/src/config/GSMS.h @@ -1,192 +1,210 @@ /*************************************************************************** * Copyright (C) 2009 by P.Voylov * * [email protected] * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ /*!\file GSMS.h * \brief Global GSMS configuration handler */ #ifndef GSMS_H_ #define GSMS_H_ #include "Mask.h" #include "GlobalConfig.h" #include "Job.h" #include "DetectorConfig.h" #include "Hull.h" #include "SceneConfig.h" #include <geant/G4RunManager.hh> #include "physics/PhysicsList.h" #include "geometry/Geometry.h" #include "generator/Generator.h" #include <boost/iostreams/filtering_streambuf.hpp> #include <boost/iostreams/copy.hpp> #include <boost/iostreams/filter/gzip.hpp> #include "typedefs.h" namespace GSMS { /*!\class GSMS *\brief Global GSMS configuration and controls */ class GSMS { +friend class boost::serialization::access; + +/*!\fn serialize(Archive & ar, const unsigned int version) + * \brief GSMS serializer + * \param ar output archive + * \param version archive version + */ +template<class Archive> +void serialize(Archive & ar, const unsigned int version) +{ + ar & BOOST_SERIALIZATION_NVP(m_mask) + & BOOST_SERIALIZATION_NVP(m_global) + & BOOST_SERIALIZATION_NVP(m_hull) + & BOOST_SERIALIZATION_NVP(m_detector) + & BOOST_SERIALIZATION_NVP(m_job) + & BOOST_SERIALIZATION_NVP(m_scene); +} + /*!\var m_global * \brief global configuration */ static GlobalConfig m_global; /*!\var m_job * \brief job configuration */ static Job m_job; /*!\var m_mask * \brief mask configuration */ static Mask m_mask; /*!\var m_hull * \brief hull configuration */ static Hull m_hull; /*!\var m_detector * \brief detector configuration */ static DetectorConfig m_detector; /*!\var m_scene * \brief scene */ static SceneConfig m_scene; /*!\var mp_physics * \brief physics list */ static PhysicsList* mp_physics; /*!\var mp_geometry * \brief geometry */ static Geometry* mp_geometry; /*!\var mp_generator * \brief generator */ static Generator* mp_generator; /*!\var m_runmanager * \brief Geant run manager */ static G4RunManager* mp_runmanager; /*!\var m_verbosity * \brief verbosity level */ static G4int m_verbosity; public: /*!\fn static void setVerbosity(G4int verbosity) * \brief set verbosity level * \param verbosity new verbosity */ static void setVerbosity(G4int verbosity) {m_verbosity = verbosity;} /*!\fn static G4int getVerbosity() * \brief get verbosity level * \return verbosity */ static G4int getVerbosity() {return m_verbosity;} /*!\fn static unsigned int serialize(std::string out) * \brief serializer * \param out output stream filename * \return exit code */ static unsigned int serialize(std::string filename); /*!\fn static unsigned int unserialize(std::ofstream* in) * \brief unserializer * \param filename input stream filename * \return exit code */ static unsigned int unserialize(std::string filename); /*!\fn unsigned int initRunManager() * \brief model inititator * \return exit code */ static unsigned int initRunManager(); /*!\fn unsigned int run_forced() * \brief dumb model run * \return exit code */ static unsigned int run_forced(unsigned int beamOn); /*!\fn unsigned int getMaterial(std::string name, G4Material** material) * \brief get material pointer * \param name material name * \param material material pointer (out) * \return exit code */ static unsigned int getMaterial(std::string name,G4Material** material); /*!\fn unsigned int getWorld(G4VPhysicalVolume** wptr) * \brief get world pointer * \param wptr world pointer (out) * \return exit code */ static unsigned int getWorld(G4VPhysicalVolume** wptr) {return m_scene.getWorld(wptr);} static unsigned int imprintDetector(G4VPhysicalVolume* world) {return m_detector.imprint(world);} static unsigned int imprintMask(G4VPhysicalVolume* world = NULL) {return m_mask.imprint(world);} static unsigned int get_time(G4double* time) {return m_global.get_time(time);} static unsigned int set_time(G4double* time) {return m_global.set_time(time);} /*!\fn Job& get_job() {return m_job;} * \brief get job instance * \return job object */ static Job& get_job() {return m_job;} /*!\fn Hull& get_hull() {return m_hull;} * \brief get hull instance * \return hull object */ static Hull& get_hull() {return m_hull;} /*!\fn Mask& get_mask() {return m_mask;} * \brief get mask * \return mask object */ static Mask& get_mask() {return m_mask;} }; }; /*namespace *GSMS*/ #endif /*GSMS_H_*/ diff --git a/src/config/Hull.cpp b/src/config/Hull.cpp index 9a6972e..e9a170f 100644 --- a/src/config/Hull.cpp +++ b/src/config/Hull.cpp @@ -1,296 +1,435 @@ /*************************************************************************** * Copyright (C) 2009 by P.Voylov * * [email protected] * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "Hull.h" #include <sys/stat.h> #include <sys/types.h> #include "GSMS.h" #include <geant/G4Tubs.hh> #include <geant/G4Cons.hh> #include <geant/G4Box.hh> #include <geant/G4PVPlacement.hh> #include <geant/G4VisAttributes.hh> unsigned int GSMS::Hull::save(std::ofstream* stream) { Hull* pHull = this; boost::archive::xml_oarchive out(*stream); out << BOOST_SERIALIZATION_NVP(pHull); } unsigned int GSMS::Hull::imprint(G4VPhysicalVolume* wptr) { G4VPhysicalVolume* world = NULL; if(wptr) world = wptr; else GSMS::GSMS::getWorld(&world); try { G4VSolid* s_hull = NULL; + G4double drum_radius = 0.; + G4double drum_height = 0.; if(m_radius < 0) { double mr, mw, mt; mr = GSMS::GSMS::get_mask().get_radius(); mt = GSMS::GSMS::get_mask().get_ethick(); mw = GSMS::GSMS::get_mask().get_ewidth(); std::cerr << "Mask radius: " << mr << std::endl; std::cerr << "Mask thickness: " << mt << std::endl; std::cerr << "Mask width: " << mw << std::endl; - if(GSMS::GSMS::get_mask().get_etype() == "Box") + drum_radius = mr; + + if(GSMS::GSMS::get_mask().get_etype() == "Box") { m_radius = std::sqrt((mr+mt)*(mr+mt) + mw*mw/4.) + m_gap; - else + } + else { m_radius = mr + mt + m_gap; + } std::cerr << "Hull radius: " << m_radius << std::endl; } if(m_height < 0) m_height = GSMS::GSMS::get_mask().get_eheight() + 2*m_gap; + drum_height = GSMS::GSMS::get_mask().get_eheight(); G4Material* mat_cover = NULL; G4Material* mat_stand = NULL; + G4Material* mat_stainless = NULL; G4VSolid* s_cover = NULL; G4VSolid* s_hat = NULL; G4VSolid* s_plate = NULL; G4VSolid* s_stand = NULL; + G4VSolid* s_mtube = NULL; + G4VSolid* s_mplate = NULL; + + G4VSolid* s_drum_plate_top = NULL; + G4VSolid* s_drum_plate_bottom = NULL; + G4VSolid* s_drum = NULL; - if(!__SUCCEEDED(GSMS::GSMS::getMaterial("GRP", &mat_cover)) || + if( !__SUCCEEDED(GSMS::GSMS::getMaterial("GRP", &mat_cover)) || + !__SUCCEEDED(GSMS::GSMS::getMaterial("Steel", &mat_stand)) || + !__SUCCEEDED(GSMS::GSMS::getMaterial("H18N10", &mat_stainless)) || m_radius <= 0. || m_thickness <= 0.) return GSMS_ERR; s_cover = new G4Tubs( "Cover", m_radius, m_radius + m_thickness, m_height/2, 0.0*deg, 360.0*deg); s_hat = new G4Cons( "Hat", m_radius, m_radius + m_thickness, m_top_radius, m_top_radius + m_thickness, m_hat_height/2, 0.0*deg, 360.0*deg); + s_plate = new G4Tubs( "Top_Plate", - m_radius - m_thickness, + 6.0*cm/2,//TODO - get real detector radius m_radius, 5.0*mm/2, 0.0*deg, 360.0*deg); + s_mtube = new G4Tubs( + "Metal_Tube", + 6.0*cm/2,//TODO - get real detector radius + 6.5*cm/2, + 9.0*cm/2, + 0.0*deg, + 360.0*deg); + + s_mplate = new G4Tubs( + "Metal_Plate", + 6.5*cm/2,//TODO - get real detector radius + 9.0*cm/2, + 3.0*mm/2, + 0.0*deg, + 360.0*deg); + + s_drum_plate_top = new G4Tubs( + "Drum_Plate_Top", + 28.*cm/2, + drum_radius, + 0.4*mm/2, + 0.0*deg, + 360.0*deg); + + s_drum_plate_bottom = new G4Tubs( + "Drum_Plate_Bottom", + 0., + drum_radius, + 0.8*mm/2, + 0.0*deg, + 360.0*deg); + + s_drum = new G4Tubs( + "Drum", + drum_radius, + drum_radius + 0.8*mm, + drum_height/2, + 0.0*deg, + 360.0*deg); + //hull cyllinder G4LogicalVolume* cover_log = new G4LogicalVolume( s_cover, mat_cover, "cover_log"); G4VPhysicalVolume* cover_phys = new G4PVPlacement( 0, G4ThreeVector(0.,0.,0.), "cover_phys", cover_log, world, true, 0); //hat cone G4LogicalVolume* hat_log = new G4LogicalVolume( s_hat, mat_cover, "hat_log"); G4VPhysicalVolume* hat_phys = new G4PVPlacement( 0, G4ThreeVector(0.,0.,(m_hat_height + m_height)/2), "hat_phys", hat_log, world, true, 0); //plates G4LogicalVolume* plate_log = new G4LogicalVolume( s_plate, mat_cover, "plate_log"); G4VPhysicalVolume* top_plate_phys = new G4PVPlacement( 0, G4ThreeVector(0.,0.,(m_height + 5.*mm)/2), "top_plate_phys", plate_log, world, true, 0); G4VPhysicalVolume* bottom_plate_phys = new G4PVPlacement( 0, G4ThreeVector(0.,0.,-(m_height + 5.*mm)/2), "bottom_plate_phys", plate_log, world, true, 0); + //metal tube + G4LogicalVolume* mtube_log = new G4LogicalVolume( + s_mtube, + mat_stand, + "mtube_log"); + + G4LogicalVolume* mplate_log = new G4LogicalVolume( + s_mplate, + mat_stand, + "mplate_log"); + + + G4VPhysicalVolume* mtube_phys = new G4PVPlacement( + 0, + G4ThreeVector(0.,0.,(m_height - 9.0*cm)/2),//TODO? mtube height? + "mtube_phys", + mtube_log, + world,//cover_phys? + true, + 0); + + G4VPhysicalVolume* mplate_phys_bottom = new G4PVPlacement( + 0, + G4ThreeVector(0.,0.,(m_height + 3.0*mm)/2 - 9.0*cm),//TODO? mtube height? + "mplate_phys_bottom", + mplate_log, + world,//cover_phys? + true, + 0); + + G4VPhysicalVolume* mplate_phys_top = new G4PVPlacement( + 0, + G4ThreeVector(0.,0.,(m_height - 3.0*mm)/2),//TODO? mtube height? + "mplate_phys_top", + mplate_log, + world,//cover_phys? + true, + 0); + + //drum + G4LogicalVolume* drum_plate_top_log = new G4LogicalVolume( + s_drum_plate_top, + mat_stainless, + "drum_plate_top"); + G4LogicalVolume* drum_plate_bottom_log = new G4LogicalVolume( + s_drum_plate_bottom, + mat_stainless, + "drum_plate_bottom"); + G4LogicalVolume* drum_log = new G4LogicalVolume( + s_drum, + mat_stainless, + "drum_log"); + + G4VPhysicalVolume* drum_plate_top_phys = new G4PVPlacement( + 0, + G4ThreeVector(0.,0.,(drum_height + 0.8*mm)/2), + "drum_plate_top_phys", + drum_plate_top_log, + world,//cover_phys? + true, + 0); + G4VPhysicalVolume* drum_plate_bottom_phys = new G4PVPlacement( + 0, + G4ThreeVector(0.,0.,-(drum_height + 0.8*mm)/2), + "drum_plate_bottom_phys", + drum_plate_bottom_log, + world,//cover_phys? + true, + 0); + G4VPhysicalVolume* drum_phys = new G4PVPlacement( + 0, + G4ThreeVector(0.,0.,0.), + "drum_phys", + drum_log, + world,//cover_phys? + true, + 0); + G4VisAttributes* cover_vis = new G4VisAttributes(GSMS_COLOR_PLASTIC); G4VisAttributes* stand_vis = new G4VisAttributes(GSMS_COLOR_STEEL); cover_vis->SetVisibility(true); stand_vis->SetVisibility(true); cover_vis->SetForceSolid(true); stand_vis->SetForceSolid(true); cover_log->SetVisAttributes(cover_vis); hat_log->SetVisAttributes(cover_vis); plate_log->SetVisAttributes(cover_vis); -// stand_log->SetVisAttributes(stand_vis); + mplate_log->SetVisAttributes(stand_vis); + mtube_log->SetVisAttributes(stand_vis); + drum_plate_top_log->SetVisAttributes(stand_vis); + drum_plate_bottom_log->SetVisAttributes(stand_vis); + drum_log->SetVisAttributes(stand_vis); /* if(m_etype == "Box") { s_element = new G4Box( "element", m_ewidth/2, m_ethick/2, m_eheight/2); } else if(m_etype == "Segment") { s_element = new G4Box( "element", m_ewidth/2, m_ethick/2, m_eheight/2); } else return GSMS_ERR; G4Material* element_mat = NULL; G4Material* mask_mat = NULL; if(!__SUCCEEDED(GSMS::GSMS::getMaterial(m_emat,&element_mat)) || !__SUCCEEDED(GSMS::GSMS::getMaterial("Air",&mask_mat))) return GSMS_ERR; G4LogicalVolume* element_log = new G4LogicalVolume( s_element, element_mat, "element_log"); G4RotationMatrix mR; //mask G4ThreeVector mT(0.,0.,0.); //mask G4double local_time,angle,angle_offset; local_time = angle = angle_offset = 0.0; if(!__SUCCEEDED(GSMS::getTime(&local_time))) return GSMS_ERR; angle_offset = (m_speed * local_time); std::cerr << "Mask angle offset: " << angle_offset*360/2/pi << std::endl; for(int i=0;i<m_ecount;i++) if(!isTransparent(i)) { G4RotationMatrix mRe; //element G4ThreeVector mTe; //element angle = ( (float)i/(float)m_ecount*2*pi + angle_offset ); G4float xoff = (m_radius+m_ethick)*cos(angle); G4float yoff = (m_radius+m_ethick)*sin(angle); G4float zoff = 0.; mTe.setX(xoff); mTe.setY(yoff); mTe.setZ(zoff); mRe.rotateZ(pi/2 + angle); G4VPhysicalVolume* mask_phys = new G4PVPlacement( G4Transform3D(mRe,G4ThreeVector(xoff,yoff,zoff)), element_log, "element_phys", world->GetLogicalVolume(), false, i ); m_mask.push_back(mask_phys); std::cerr << "Element " << i << " at angle " << angle*360/2/pi << " xOff = " << xoff << " yOff = " << yoff << " zOff = " << zoff << std::endl; }; G4VisAttributes* element_vis = new G4VisAttributes(GSMS_COLOR_ELEMENT); element_vis->SetVisibility(true); element_vis->SetForceSolid(true); element_log->SetVisAttributes(element_vis); */ } catch(...) { return GSMS_ERR; }; return GSMS_OK; }; double GSMS::Hull::get_dist(G4ThreeVector coords) { return 0.; } double GSMS::Hull::get_delta_phi(G4ThreeVector coords) { double result = 2*pi/2/180; double dist = std::sqrt(coords.getX()*coords.getX() + coords.getY()*coords.getY()); result = atan((m_radius + m_thickness) / dist); return result; } double GSMS::Hull::get_delta_theta(G4ThreeVector coords) { double result = 0.0; //distance to outer ring double dist = std::sqrt(coords.getX()*coords.getX() + coords.getY()*coords.getY()) - (m_radius + m_thickness); result = atan(m_height/2 / dist); return result; } diff --git a/src/generator/Source.cpp b/src/generator/Source.cpp index 82707a4..2b2bcc1 100644 --- a/src/generator/Source.cpp +++ b/src/generator/Source.cpp @@ -1,86 +1,88 @@ /*************************************************************************** * Copyright (C) 2009 by P.Voylov * * [email protected] * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "Source.h" #include <sys/stat.h> #include <sys/types.h> #include <geant/G4Gamma.hh> #include "config/GSMS.h" unsigned int GSMS::Source::save(std::ofstream* stream) { Source* pSource = this; boost::archive::xml_oarchive out(*stream); out << BOOST_SERIALIZATION_NVP(pSource); } void GSMS::Source::generate_G4(G4GeneralParticleSource* dst, G4double dAngle) { if (!dst) return; for(int i=0; i<m_gamma.size(); i++) { G4float ene = m_gamma[i].first; G4float act = m_gamma[i].second; dst->AddaSource(act); dst->SetParticleDefinition(G4Gamma::Gamma()); G4SingleParticleSource* src = dst->GetCurrentSource(); src->GetEneDist()->SetMonoEnergy(ene); src->GetAngDist()->SetAngDistType("iso"); src->GetPosDist()->SetPosDisType("Point"); src->GetEneDist()->SetEnergyDisType("Mono"); //src->GetPosDist()->SetCentreCoords(get_coords()); //src->GetPosDist()->SetCentreCoords(G4ThreeVector(1., 0., 0.)); src->GetPosDist()->SetCentreCoords(G4ThreeVector(m_x, m_y, m_z)); G4double basePhi = 0.0; m_x != 0.0 ? basePhi = std::atan(m_y/m_x) : m_y > 0 ? basePhi = pi/2 : basePhi = -pi/2; if(m_x < 0.0 ) basePhi = -pi + basePhi; std::cerr << "X: " << m_x << " Y: " << m_y << " Phi: " << basePhi << std::endl; - //2*pi/2/180;// G4double dPhi = GSMS::get_hull().get_delta_phi(get_coords()); G4double baseTheta = pi/2;//TODO - //6*pi/2/180;// + G4double dTheta = GSMS::get_hull().get_delta_theta(get_coords()); std::cerr << "dPhi: " << dPhi*360/2/pi << "; dTheta" << dTheta*360/2/pi << std::endl; + //dPhi = 3*pi/2/180;//2*pi/2/180; + //dTheta = 16*pi/2/180;//6*pi/2/180; + src->GetAngDist()->SetMinPhi(basePhi - dPhi); src->GetAngDist()->SetMaxPhi(basePhi + dPhi); src->GetAngDist()->SetMinTheta(baseTheta - dTheta); src->GetAngDist()->SetMaxTheta(baseTheta + dTheta); std::cerr << ene << std::endl; std::cerr << act << std::endl; } } void GSMS::Source::normalize_activities() { G4double summ = 0.0; for(int i=0; i<m_gamma.size(); i++) summ += m_gamma[i].second; for(int i=0; i<m_gamma.size(); i++) m_gamma[i].second = m_gamma[i].second/summ; } \ No newline at end of file diff --git a/src/generator/SourceLib.cpp b/src/generator/SourceLib.cpp index e0c92a0..f5164b2 100644 --- a/src/generator/SourceLib.cpp +++ b/src/generator/SourceLib.cpp @@ -1,59 +1,59 @@ /*************************************************************************** * Copyright (C) 2009 by P.Voylov * * [email protected] * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "SourceLib.h" GSMS::Source* util::SourceLib::create_source(std::string name, float activity, G4ThreeVector coords){ GSMS::Source* src = new GSMS::Source(); if(name == "Cs137") { -// src->push_gamma(0.032, 0.058); -// src->push_gamma(0.036, 0.014); + src->push_gamma(0.032, 0.058); + src->push_gamma(0.036, 0.014); src->push_gamma(0.662, 0.9); } if(name == "Co57") { src->push_gamma(0.122, 0.855); src->push_gamma(0.136, 0.106); } if(name == "Co60") { src->push_gamma(1.173, 1.0); src->push_gamma(1.332, 1.0); } if(name == "Ba133") { -// src->push_gamma(0.030, 34.25); -// src->push_gamma(0.031, 63.42); -// src->push_gamma(0.035, 22.76); + src->push_gamma(0.030, 34.25); + src->push_gamma(0.031, 63.42); + src->push_gamma(0.035, 22.76); src->push_gamma(0.081, 32.97); src->push_gamma(0.276, 6.9); src->push_gamma(0.303, 17.79); src->push_gamma(0.356, 60.5); src->push_gamma(0.384, 8.67); } if(name == "K40") { src->push_gamma(1.461, 0.107); } src->normalize_activities(); src->set_activity(activity); src->set_coords(coords); return src; } \ No newline at end of file diff --git a/src/generator/database/DatabaseTransaction.cpp b/src/generator/database/DatabaseTransaction.cpp index ee6270a..3b344f0 100755 --- a/src/generator/database/DatabaseTransaction.cpp +++ b/src/generator/database/DatabaseTransaction.cpp @@ -1,78 +1,82 @@ /*************************************************************************** * Copyright (C) 2009 by P.Voylov * * [email protected] * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "DatabaseTransaction.h" #include "DatabaseQuery.h" #include "DatabaseField.h" #include "Database.h" #include <pqxx/binarystring> #include "database_exception.h" DatabaseTransaction::DatabaseTransaction() { m_transaction = NULL; } DatabaseTransaction::DatabaseTransaction(Database *database) { m_transaction = new pqxx::work(*database->m_connection); } DatabaseTransaction::~DatabaseTransaction() { if(m_transaction != NULL) { m_transaction->abort(); delete m_transaction; } } -DatabaseTransaction &DatabaseTransaction::operator=(DatabaseTransaction &rhs) { +DatabaseTransaction a; +DatabaseTransaction b; +a = b + +DatabaseTransaction& DatabaseTransaction::operator=(DatabaseTransaction &rhs) { if(m_transaction != rhs.m_transaction); m_transaction = rhs.m_transaction; return *this; } DatabaseQuery DatabaseTransaction::query(const std::string &query) throw (util::DatabaseException) { if(m_transaction != NULL) return DatabaseQuery(this, query); else throw __DB_EXCEPTION(__ERR_DB_NULL_TRANSACTION); } void DatabaseTransaction::commit() { m_transaction->commit(); delete m_transaction; m_transaction = NULL; } void DatabaseTransaction::rollback() { m_transaction->abort(); delete m_transaction; m_transaction = NULL; } std::string DatabaseTransaction::unescape_byte(DatabaseField &field) { pqxx::binarystring converter(field); std::ostringstream buf; buf.write(converter.c_ptr(), converter.size()); return buf.str(); } diff --git a/src/geometry/Geometry.cpp b/src/geometry/Geometry.cpp index e963104..1644356 100644 --- a/src/geometry/Geometry.cpp +++ b/src/geometry/Geometry.cpp @@ -1,605 +1,621 @@ /*************************************************************************** * Copyright (C) 2009 by P.Voylov * * [email protected] * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "Geometry.h" #include "config/GSMS.h" #include <geant/G4Material.hh> #include <geant/G4MaterialTable.hh> #include <geant/G4Element.hh> #include <geant/G4Isotope.hh> #include <geant/G4UnitsTable.hh> #include <geant/G4Box.hh> #include <geant/G4Cons.hh> #include <geant/G4Tubs.hh> #include <geant/G4Sphere.hh> #include <geant/G4UnionSolid.hh> #include <geant/G4SubtractionSolid.hh> #include <geant/G4LogicalVolume.hh> #include <geant/G4PVPlacement.hh> #include <geant/G4ThreeVector.hh> #include <geant/G4RotationMatrix.hh> #include <geant/G4Transform3D.hh> #include <geant/G4LogicalBorderSurface.hh> #include <geant/G4LogicalSkinSurface.hh> #include <geant/G4OpBoundaryProcess.hh> #include <geant/G4FieldManager.hh> #include <geant/G4UniformElectricField.hh> #include <geant/G4TransportationManager.hh> #include <geant/G4MagIntegratorStepper.hh> #include <geant/G4EqMagElectricField.hh> #include <geant/G4ClassicalRK4.hh> #include <geant/G4ChordFinder.hh> #include <geant/G4VisAttributes.hh> #include <geant/G4Colour.hh> #include <geant/G4RunManager.hh> #include <geant/G4SDManager.hh> #include <geant/G4HCtable.hh> G4VPhysicalVolume* GSMS::Geometry::Construct() { std::cerr << "Construct" << std::endl; G4double new_time = 0; if( __SUCCEEDED(GSMS::set_time(&new_time)) && __SUCCEEDED(GSMS::imprintDetector(m_world)) && __SUCCEEDED(GSMS::imprintMask(m_world)) && __SUCCEEDED(GSMS::get_hull().imprint(m_world)) ) return m_world; else return NULL; } bool GSMS::Geometry::Update() { std::cerr << "Update" << std::endl; if( __SUCCEEDED(GSMS::imprintMask(m_world)) ) return true; else return false; } unsigned int GSMS::Geometry::defineMaterials() { G4double density,// density a, // atomic mass z; // atomic number G4double G4d_density; // G4double G4d_temp; // G4double G4d_press; G4int nelements; G4String G4s_name; G4String G4s_symbol; G4int G4i_ncomp; G4Element* H = new G4Element("Hydrogen", "H", z=1., a=1.0079*g/mole); G4Element* C = new G4Element("Carbon", "C", z=6., a=12.011*g/mole); G4Element* N = new G4Element("Nitrogen", "N", 7., 14.00674*g/mole); G4Element* O = new G4Element("Oxygen", "O", 8., 16.00000*g/mole); G4Element* Na = new G4Element("Natrium", "Na", z=11., a=22.98977*g/mole); G4Element* Mg = new G4Element("Magnezium", "Mg", z=12., a=24.305*g/mole); G4Element* Al = new G4Element("Aluminium", "Al", z=13., a=26.981*g/mole); G4Element* Si = new G4Element("Silicium", "Si", z=14., a=28.086*g/mole); G4Element* P = new G4Element("Phosphorus", "P", z=15., a=30.973976*g/mole); G4Element* S = new G4Element("Sulfur", "S", z=16., a=32.06*g/mole); G4Element* Cl = new G4Element("Chlorine","Cl", z=17., a=35.453*g/mole); G4Element* K = new G4Element("Kalium", "K", z=19., a=39.098*g/mole); G4Element* Ca = new G4Element("Calcium", "Ca", z=20., a=40.08*g/mole); G4Element* Ti = new G4Element("Titanium", "Ti", z=22., a=47.9*g/mole); G4Element* Cr = new G4Element("Chrome", "Cr", z=24., a=51.996*g/mole); G4Element* Mn = new G4Element("Manganeze", "Mn", z=25., a=54.938*g/mole); G4Element* Fe = new G4Element("Ferrum", "Fe", z=26., a=55.847*g/mole); G4Element* Ni = new G4Element("Nickel", "Ni", z=28., a=58.7*g/mole); G4Element* Cu = new G4Element("Cuprum", "Cu", z=29., a=63.546*g/mole); G4Element* Zn = new G4Element("Zyncum", "Zn", z=30., a=65.38*g/mole); G4Element* Ge = new G4Element("Germanium", "Ge", z=32., a=72.59*g/mole); G4Element* Ag = new G4Element("Argentum", "Ag", z=47., a=107.8682*g/mole); G4Element* I = new G4Element("Iodine", "I", z=53., a=126.904*g/mole); G4Element* Cs = new G4Element("Cesium", "Cs", z=55., a=132.905*g/mole); G4Element* Ba = new G4Element("Barium", "Ba", z=56., a=133.*g/mole); G4Element* W = new G4Element("Wolfram", "W", z=74., a=183.85*g/mole); G4Element* Pt = new G4Element("Platinum", "Pt", z=78., a=195.08*g/mole); G4Element* Au = new G4Element("Aurum", "Au", z=79., a=196.9665*g/mole); G4Element* Pb = new G4Element("Plumbum", "Pb", z=82., a=207.2*g/mole); G4Element* Bi = new G4Element("Bismuth", "Bi", z=83., a=208.9804*g/mole); G4Material* mptr; std::string name; try { //vacuum name = "Vacuum"; mptr = new G4Material( name.c_str(), //name 1, //components 1.00794*g/mole, //1st component a/weight 1.0E-25*g/cm3, //density kStateGas, //state 0.1*kelvin, //temp 1.0E-19*pascal);//pressure m_materials.insert(std::pair<std::string,G4Material*>(name,mptr)); //air name = "Air"; mptr = new G4Material( name, 1.2929*kg/m3, 2, kStateGas, 300.00*kelvin, 1.0*atmosphere); mptr->AddElement(N, 0.8); mptr->AddElement(O, 0.2); m_materials.insert(std::pair<std::string,G4Material*>(name,mptr)); //aluminium name = "Aluminium"; mptr = new G4Material( name, 2.8*g/cm3, 1); mptr->AddElement(Al, 1); m_materials.insert(std::pair<std::string,G4Material*>(name,mptr)); //lead name = "Lead"; mptr = new G4Material( name, 11.336*g/cm3, 1); mptr->AddElement(Pb, 1); m_materials.insert(std::pair<std::string,G4Material*>(name,mptr)); //MgO name = "MgO"; mptr = new G4Material( name, 0.7 * 2.506*g/cm3, 2); mptr->AddElement(O, 1); mptr->AddElement(Mg, 1); m_materials.insert(std::pair<std::string,G4Material*>(name,mptr)); //glass name = "Glass"; mptr = new G4Material( name, 2.6*g/cm3, 7); mptr->AddElement(O, 59.8*perCent); mptr->AddElement(Si, 24.7*perCent); mptr->AddElement(Al, 1.4*perCent); mptr->AddElement(Mg, 1.4*perCent); mptr->AddElement(Ca, 2.3*perCent); mptr->AddElement(Na, 10.3*perCent); mptr->AddElement(Fe, 0.1*perCent); m_materials.insert(std::pair<std::string,G4Material*>(name,mptr)); //soil name = "Soil"; mptr = new G4Material( name, 1.6*g/cm3,//1.3..2.0 11); mptr->AddElement(O, 46.0*perCent);//46.7 mptr->AddElement(Si, 27.0*perCent); mptr->AddElement(Al, 8.0*perCent);//8.0 mptr->AddElement(Fe, 5.0*perCent); mptr->AddElement(Ca, 2.0*perCent); mptr->AddElement(Mg, 2.0*perCent); mptr->AddElement(K, 2.0*perCent); mptr->AddElement(Na, 2.0*perCent); mptr->AddElement(P, 2.0*perCent); mptr->AddElement(S, 2.0*perCent); mptr->AddElement(N, 2.0*perCent); m_materials.insert(std::pair<std::string,G4Material*>(name,mptr)); //steel name = "Steel"; mptr = new G4Material( name, 7.81*g/cm3, 7); mptr->AddElement(C, 0.0010); mptr->AddElement(Si, 0.0100); mptr->AddElement(Mn, 0.0065); mptr->AddElement(Cr, 0.0075); mptr->AddElement(Ni, 0.0065); mptr->AddElement(Cu, 0.0050); mptr->AddElement(Fe, 0.9635); m_materials.insert(std::pair<std::string,G4Material*>(name,mptr)); + +//stainless steel + name = "H18N10"; + mptr = new G4Material( + name, + 7.81*g/cm3, + 7); + mptr->AddElement(C, 0.001); + mptr->AddElement(Si, 0.010); + mptr->AddElement(Mn, 0.014); + mptr->AddElement(Cr, 0.170); + mptr->AddElement(Ni, 0.100); + mptr->AddElement(Cu, 0.005); + mptr->AddElement(Fe, 0.700); + m_materials.insert(std::pair<std::string,G4Material*>(name,mptr)); + //D16 name = "D16"; mptr = new G4Material( name, 2.8*g/cm3, 9); mptr->AddElement(Al, 92.5*perCent); mptr->AddElement(Cu, 4.0*perCent); mptr->AddElement(Mg, 1.5*perCent); mptr->AddElement(Fe, 0.5*perCent); mptr->AddElement(Si, 0.5*perCent); mptr->AddElement(Mn, 0.5*perCent); mptr->AddElement(Zn, 0.3*perCent); mptr->AddElement(Ni, 0.1*perCent); mptr->AddElement(Ti, 0.1*perCent); m_materials.insert(std::pair<std::string,G4Material*>(name,mptr)); //plastic name = "Plastic"; mptr = new G4Material( name, 1.19*g/cm3, 3); mptr->AddElement(H, 0.08); mptr->AddElement(C, 0.60); mptr->AddElement(O, 0.32); m_materials.insert(std::pair<std::string,G4Material*>(name,mptr)); //GRP name = "GRP"; mptr = new G4Material( name, 1.7*g/cm3, 4); mptr->AddElement(H, 6); mptr->AddElement(C, 45); mptr->AddElement(O, 49); mptr->AddElement(Si, 5); m_materials.insert(std::pair<std::string,G4Material*>(name,mptr)); //lavsan name = "Lavsan"; mptr = new G4Material( name, 1.38*g/cm3, 3); mptr->AddElement(H, 8); mptr->AddElement(C, 10); mptr->AddElement(O, 4); m_materials.insert(std::pair<std::string,G4Material*>(name,mptr)); const int NUMENTRIES = 3; G4double PP[NUMENTRIES] = {1.0*eV, 5.0*eV, 10.0*eV}; //CsI name = "CsI"; mptr = new G4Material( name, 4.51*g/cm3, 2, kStateUndefined, 273*kelvin); mptr->AddElement(Cs, 1); mptr->AddElement(I, 1); G4MaterialPropertiesTable* Scn_Mt = new G4MaterialPropertiesTable(); G4double CsI_RIND[NUMENTRIES] = {1.79, 1.79, 1.79}; G4double CsI_ABSL[NUMENTRIES] = {71.*cm, 71*cm, 71.*cm}; Scn_Mt->AddProperty("RINDEX", PP, CsI_RIND, NUMENTRIES); Scn_Mt->AddProperty("ABSLENGTH",PP, CsI_ABSL, NUMENTRIES); Scn_Mt->AddConstProperty("SCINTILLATIONYIELD", 54000./MeV); Scn_Mt->AddConstProperty("RESOLUTIONSCALE", 0.0759); Scn_Mt->AddConstProperty("YIELDRATIO", 1.); Scn_Mt->AddConstProperty("EXCITATIONRATIO", 1.); mptr->SetMaterialPropertiesTable(Scn_Mt); m_materials.insert(std::pair<std::string,G4Material*>(name,mptr)); //NaI name = "NaI"; mptr = new G4Material( name.c_str(), 3.67*g/cm3, 2, kStateUndefined, 273*kelvin); mptr->AddElement(Na, 1); mptr->AddElement(I, 1); Scn_Mt = new G4MaterialPropertiesTable(); G4double NaI_RIND[NUMENTRIES] = {2.15, 2.15, 2.15}; G4double NaI_ABSL[NUMENTRIES] = {71.*cm, 71*cm, 71.*cm}; Scn_Mt->AddProperty("RINDEX", PP, NaI_RIND, NUMENTRIES); Scn_Mt->AddProperty("ABSLENGTH",PP, NaI_ABSL, NUMENTRIES); Scn_Mt->AddConstProperty("SCINTILLATIONYIELD", 38000./MeV); Scn_Mt->AddConstProperty("RESOLUTIONSCALE", 0.085); Scn_Mt->AddConstProperty("YIELDRATIO", 1.); Scn_Mt->AddConstProperty("EXCITATIONRATIO", 1.); mptr->SetMaterialPropertiesTable(Scn_Mt); m_materials.insert(std::pair<std::string,G4Material*>(name,mptr)); //BGO name = "BGO"; mptr = new G4Material( name.c_str(), 7.13*g/cm3, 3, kStateUndefined, 273*kelvin); mptr->AddElement(Bi, 4); mptr->AddElement(Ge, 3); mptr->AddElement(O, 12); Scn_Mt = new G4MaterialPropertiesTable(); G4double BGO_RIND[NUMENTRIES] = {2.15, 2.15, 2.15}; G4double BGO_ABSL[NUMENTRIES] = {71.*cm, 71*cm, 71.*cm}; Scn_Mt->AddProperty("RINDEX", PP, BGO_RIND, NUMENTRIES); Scn_Mt->AddProperty("ABSLENGTH",PP, BGO_ABSL, NUMENTRIES); Scn_Mt->AddConstProperty("SCINTILLATIONYIELD", 9000./MeV); Scn_Mt->AddConstProperty("RESOLUTIONSCALE", 0.11); Scn_Mt->AddConstProperty("YIELDRATIO", 1.); Scn_Mt->AddConstProperty("EXCITATIONRATIO", 1.); mptr->SetMaterialPropertiesTable(Scn_Mt); m_materials.insert(std::pair<std::string,G4Material*>(name,mptr)); //stylben /* name = "Stylben"; mptr = new G4Material( name.c_str(), 1.16*g/cm3, 2); mptr->AddElement(H, 12); mptr->AddElement(C, 14); Scn_Mt = new G4MaterialPropertiesTable(); Scn_Mt->AddProperty("RINDEX", Scn_PP, Scn_RIND, NUMENTRIES); Scn_Mt->AddProperty("ABSLENGTH",Scn_PP, Scn_ABSL, NUMENTRIES); Scn_Mt->AddConstProperty("SCINTILLATIONYIELD", 54000./MeV); Scn_Mt->AddConstProperty("RESOLUTIONSCALE", 0.0759); Scn_Mt->AddConstProperty("YIELDRATIO", 1.); Scn_Mt->AddConstProperty("EXCITATIONRATIO", 1.); mptr->SetMaterialPropertiesTable(Scn_Mt); m_materials.insert(std::pair<std::string,G4Material*>(name,mptr)); */ } catch(...) { return GSMS_ERR; } return GSMS_OK; } GSMS::Geometry::Geometry() { m_world = NULL; defineMaterials(); G4Box* world_box = new G4Box( "world_box", 2*m, 2*m, 2*m); G4LogicalVolume* world_log = new G4LogicalVolume( world_box, m_materials["Air"], "world_log"); m_world = new G4PVPlacement( 0, G4ThreeVector(0. ,0. ,0.), "world_phys", world_log, NULL, false, 0); world_log->SetVisAttributes(G4VisAttributes::Invisible); } GSMS::Geometry::~Geometry() { } /* void OTDetectorConstruction::ReconstructCrystal() { ///////////////////////////// //Clearing up old instances// ///////////////////////////// G4cout << "Clearing up crystal..." << G4endl; if(crystal_log) delete crystal_log; if(crystal_phys) delete crystal_phys; G4cout << "Clearing up plastic..." << G4endl; if(plastic_log) delete plastic_log; if(plastic_phys) delete plastic_phys; G4cout << "Clearing up foil..." << G4endl; if(foil_log) delete foil_log; if(foil_phys) delete foil_phys; if(foilp_log) delete foilp_log; if(foilp_phys) delete foilp_phys; G4cout << "Clearing up glass..." << G4endl; if(glass_log) delete glass_log; if(glass_phys) delete glass_phys; G4cout << "Clearing up PET..." << G4endl; if(PET_log) delete PET_log; if(PET_phys) delete PET_phys; G4cout << "hey1" << G4endl; ////////////////////////// //Clearing up primitives// ////////////////////////// G4cout << "Clearing up primitives..." << G4endl; G4VSolid* Crystal = NULL; G4VSolid* Glass = NULL; G4VSolid* Plastic = NULL; G4VSolid* Foil = NULL; G4VSolid* FoilP = NULL; G4VSolid* PET = NULL; /////////////////////////////// //Creating phoswitch assembly// /////////////////////////////// G4cout << "Creating assembly..." << G4endl; Crystal = new G4Tubs( "Crystal", 0., dCD/2, dCH/2, 0.0*deg, 360.0*deg); if(dGlassTck > 0.) { Glass = new G4Tubs( "Glass", 0., dCD/2, dGlassTck/2, 0.0*deg, 360.0*deg); }; Plastic = new G4Tubs( "Plastic", 0., dCD/2, dStylbTck/2, 0.0*deg, 360.0*deg); Foil = new G4Tubs( "Foil", 0., dCD/2, dFoilTck/2, 0.0*deg, 360.0*deg); FoilP = new G4Tubs( "FoilP", 0., dCD/2, dFoilPTck/2, 0.0*deg, 360.0*deg); PET = new G4Tubs( "PET", 0., dCD/2, dPETTck/2, 0.0*deg, 360.0*deg); //////////////////////////// //Creating logical volumes// //////////////////////////// G4cout << "Creating logical volumes..." << G4endl; foil_log = new G4LogicalVolume(Foil,G4Mat_Al,"foil_log"); foilp_log = new G4LogicalVolume(FoilP,G4Mat_Lavsan,"foilp_log"); plastic_log = new G4LogicalVolume(Plastic,G4Mat_Plastic,"plastic_log"); if(Glass) glass_log = new G4LogicalVolume(Glass,G4Mat_Glass,"glass_log"); crystal_log = new G4LogicalVolume(Crystal,G4Mat_CsI,"crystal_log"); PET_log = new G4LogicalVolume(PET,G4Mat_Al,"PET_log"); ///////////////////////////// //Creating physical volumes// ///////////////////////////// G4cout << "Creating physical volumes..." << G4endl; G4double dFoilOffset = 0.0; G4double dFoilPOffset = (dFoilTck+dFoilPTck)/2; G4double dPlasticOffset = dFoilPTck+(dFoilTck+dStylbTck)/2; G4double dGlassOffset = dFoilPTck+dStylbTck+(dFoilTck+dGlassTck)/2; G4double dCrystalOffset = dFoilPTck+dStylbTck+dGlassTck+(dFoilTck+dCH)/2; G4double dPETOffset = dFoilPTck+dStylbTck+dGlassTck+dCH+(dFoilTck+dPETTck)/2; foil_phys = new G4PVPlacement(0, G4ThreeVector(0.,0.,-dFoilOffset), "foil_phys", foil_log, world_phys, false, 0); foilp_phys = new G4PVPlacement(0, G4ThreeVector(0.,0.,-dFoilPOffset), "foilp_phys", foilp_log, world_phys, false, 0); plastic_phys = new G4PVPlacement(0, G4ThreeVector(0.,0.,-dPlasticOffset), "plastic_phys", plastic_log, world_phys, false, 0); if(Glass) glass_phys = new G4PVPlacement(0, G4ThreeVector(0.,0.,-dGlassOffset), "glass_phys", glass_log, world_phys, false, 0); crystal_phys = new G4PVPlacement(0, G4ThreeVector(0.,0.,-dCrystalOffset), "crystal_phys", crystal_log, world_phys, false, 0); PET_phys = new G4PVPlacement(0, G4ThreeVector(0.,0.,-dPETOffset), "PET_phys", PET_log, world_phys, false, 0); ////////////////////////////// //Creating visual attributes// ////////////////////////////// G4cout << "Creating visual attributes..." << G4endl; G4VisAttributes* Foil_VAt = new G4VisAttributes(G4Colour(1., 1., 0.)); G4VisAttributes* Stylb_VAt = new G4VisAttributes(G4Colour(1., 0., 1.)); G4VisAttributes* Glass_VAt = new G4VisAttributes(G4Colour(0., 0., 1.)); G4VisAttributes* CsI_VAt = new G4VisAttributes(G4Colour(0., 1., 0.)); G4VisAttributes* PET_VAt = new G4VisAttributes(G4Colour(1., 0., 0.)); Foil_VAt->SetVisibility(true); Stylb_VAt->SetVisibility(true); Glass_VAt->SetVisibility(true); CsI_VAt->SetVisibility(true); PET_VAt->SetVisibility(true); Foil_VAt->SetForceSolid(true); Stylb_VAt->SetForceSolid(true); Glass_VAt->SetForceSolid(true); CsI_VAt->SetForceSolid(true); PET_VAt->SetForceSolid(true); foil_log->SetVisAttributes(Foil_VAt); foilp_log->SetVisAttributes(Glass_VAt); plastic_log->SetVisAttributes(Stylb_VAt); if(Glass) glass_log->SetVisAttributes(Glass_VAt); crystal_log->SetVisAttributes(CsI_VAt); PET_log->SetVisAttributes(PET_VAt); ///////////////////////////////// //Assigning sensitive detectors// //////////////////////////////// G4SDManager* SDMan = G4SDManager::GetSDMpointer(); G4String stylbenSDName = "stylbenSD"; G4String crystalSDName = "crystalSD"; G4VSensitiveDetector* stylbenSD = (G4VSensitiveDetector*)(SDMan->FindSensitiveDetector(stylbenSDName)); G4VSensitiveDetector* crystalSD = (G4VSensitiveDetector*)(SDMan->FindSensitiveDetector(crystalSDName)); if( !stylbenSD ) { stylbenSD = new OTSD( stylbenSDName ); SDMan->AddNewDetector( stylbenSD ); }; if( !crystalSD ) { crystalSD = new OTSD( crystalSDName ); SDMan->AddNewDetector( crystalSD ); }; plastic_log->SetSensitiveDetector( stylbenSD ); crystal_log->SetSensitiveDetector( crystalSD ); } void OTDetectorConstruction::LoadGeometry() { } */ diff --git a/src/main.cpp b/src/main.cpp index 3c86cf3..407c9ae 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,33 +1,36 @@ #include <config.h> #include <stdio.h> #include <iostream> #include <fstream> #include <iomanip> #include <string> #include "typedefs.h" #include <geant/G4RunManager.hh> #include <geant/Randomize.hh> #include "config/GSMS.h" + bool __SUCCEEDED(unsigned int ARG) { bool result = false; if(ARG == GSMS_OK) result = true; return result; } int main(int argc, char* argv[]) { puts(PACKAGE_STRING); GSMS::GSMS::unserialize("text.gz"); GSMS::GSMS::setVerbosity(0); GSMS::GSMS::initRunManager(); - GSMS::GSMS::run_forced(3284); + GSMS::GSMS::run_forced(50000);//Co60 + //GSMS::GSMS::run_forced(3378);//Cs137 + //GSMS::GSMS::run_forced(7200);//Ba133 return 0; } diff --git a/src/vis.mac b/src/vis.mac index 46e817a..6c05fb0 100755 --- a/src/vis.mac +++ b/src/vis.mac @@ -1,27 +1,27 @@ #/geometry/navigator/reset #/geometry/navigator/verbose 4 #/geometry/navigator/check_mode true #/geometry/test /vis/scene/create #/vis/open ATree #/vis/ASCIITree/verbose 2 /vis/open DAWNFILE /vis/scene/add/trajectories /vis/sceneHandler/attach /vis/modeling/trajectories/create/drawByCharge /vis/modeling/trajectories/drawByCharge-0/default/setDrawStepPts true /vis/modeling/trajectories/drawByCharge-0/default/setStepPtsSize 1 /vis/scene/endOfEventAction accumulate #/vis/viewer/reset #/vis/viewer/flush -/run/beamOn 100 +/run/beamOn 1 /vis/drawVolume /vis/viewer/update /vis/viewer/flush
Aequilibrium/GSMS
492eede9c6f67b29472051bc81172bc6c6a539a3
Deterred beamOn implemented
diff --git a/src/action/RunAction.cpp b/src/action/RunAction.cpp index 9d445f0..8834867 100644 --- a/src/action/RunAction.cpp +++ b/src/action/RunAction.cpp @@ -1,66 +1,70 @@ /*************************************************************************** * Copyright (C) 2009 by P.Voylov * * [email protected] * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "RunAction.h" #include "detector/Digitizer.h" #include "detector/Digi.h" // #include <geant/G4DigiManager.hh> #include "config/GSMS.h" GSMS::RunAction::RunAction() { } GSMS::RunAction::~RunAction() { } G4Run* GSMS::RunAction::GenerateRun() { return new Run; } void GSMS::RunAction::BeginOfRunAction(const G4Run*) { } void GSMS::RunAction::EndOfRunAction(const G4Run* aRun) { Run* theRun = (Run*)aRun; std::vector<G4double> spectrum; for(int i=0; i<1024; i++) spectrum.push_back(0.); for(int i=0; i< theRun->get_size(); i++) { G4double time = theRun->get_time(i); G4double ene = theRun->get_ene(i); G4int chan = theRun->get_chan(i); spectrum[chan]++; } + for(int i=0; i<1024; i++) + std::cout << spectrum[i] << "\t"; + std::cout << std::endl; + //int discrete = GSMS::get_job().get_active_exposition().get_next_active_discrete(); //std::cout << "DISCRETE IS: "<< discrete << std::endl; - SpectraIterator itr = GSMS::get_job().get_active_exposition().get_spectrum_iterator(); + SpectrumIterator itr = GSMS::get_job().get_active_exposition().get_spectrum_iterator(); (*itr).second.push_back(spectrum); } \ No newline at end of file diff --git a/src/config/GSMS.cpp b/src/config/GSMS.cpp index cb87ef6..efbd889 100644 --- a/src/config/GSMS.cpp +++ b/src/config/GSMS.cpp @@ -1,183 +1,219 @@ /*************************************************************************** * Copyright (C) 2009 by P.Voylov * * [email protected] * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "GSMS.h" #include <geant/Randomize.hh> #include <geant/G4VisExecutive.hh> #include <geant/G4UImanager.hh> #include <geant/G4UIterminal.hh> #include <geant/G4UItcsh.hh> #include <geant/G4RunManager.hh> #include "action/RunAction.h" #include "action/EventAction.h" GSMS::GlobalConfig GSMS::GSMS::m_global; GSMS::MaskConfig GSMS::GSMS::m_mask; GSMS::HullConfig GSMS::GSMS::m_hull; GSMS::Job GSMS::GSMS::m_job; GSMS::DetectorConfig GSMS::GSMS::m_detector; GSMS::SceneConfig GSMS::GSMS::m_scene; GSMS::PhysicsList* GSMS::GSMS::mp_physics = NULL; GSMS::Geometry* GSMS::GSMS::mp_geometry = NULL; GSMS::Generator* GSMS::GSMS::mp_generator = NULL; G4RunManager* GSMS::GSMS::mp_runmanager = NULL; G4int GSMS::GSMS::m_verbosity = 0; unsigned int GSMS::GSMS::getMaterial(std::string name,G4Material** material) { if(mp_geometry) return mp_geometry->getMaterial(name,material); else return GSMS_ERR; } unsigned int GSMS::GSMS::initRunManager() { // try // { CLHEP::HepRandom::setTheEngine(new CLHEP::RanecuEngine); CLHEP::HepRandom::setTheSeed(0L); mp_runmanager = new G4RunManager; mp_runmanager->SetVerboseLevel(0);//m_verbosity); mp_physics = new PhysicsList; mp_runmanager->SetUserInitialization(mp_physics); mp_geometry = new Geometry; mp_runmanager->SetUserInitialization(mp_geometry); mp_generator = new Generator; mp_runmanager->SetUserAction(mp_generator); G4UserRunAction* run_action = new RunAction; mp_runmanager->SetUserAction(run_action); G4UserEventAction* event_action = new EventAction; mp_runmanager->SetUserAction(event_action); mp_runmanager->Initialize(); // G4UImanager* ui = G4UImanager::GetUIpointer(); // G4VisManager* vis = new G4VisExecutive; // vis->Initialize(); // ui->ApplyCommand("/tracking/verbose 1"); // G4UIsession* session = NULL; // session = new G4UIterminal(); // session->SessionStart(); // delete session; Source* src = util::SourceLib::create_source("Cs137", 1, G4ThreeVector(1.*m, 1.*m, 0.)); if(src) m_job.push_source(*src); src = util::SourceLib::create_source("Co57", 1, G4ThreeVector(1.*m, -1.*m, 0.)); if(src) m_job.push_source(*src); + src = util::SourceLib::create_source("Co60", 1, G4ThreeVector(-1.*m, -1.*m, 0.)); + if(src) m_job.push_source(*src); + src = util::SourceLib::create_source("Ba133", 1, G4ThreeVector(-1.*m, 1.*m, 0.)); + if(src) m_job.push_source(*src); + + // src = util::SourceLib::create_source("Co57", 1, G4ThreeVector(1.*m, 0., 0.)); // if(src) m_job.push_source(*src); // src = util::SourceLib::create_source("Co60", 1, G4ThreeVector(0., -1.*m, 0.)); // if(src) m_job.push_source(*src); +/* int discretes = 217; for(int i = 0; i<discretes ; i++) { G4double ltime = ((G4double)i / discretes)*10*2*pi; setTime(&ltime); if(i) if( !mp_geometry->Update() ) std::cerr << "FAILED" << std::endl; - mp_generator->Update(); + + mp_generator->Update(); // ui->ApplyCommand("/control/execute vis.mac"); mp_runmanager->GeometryHasBeenModified(); - mp_runmanager->BeamOn(100); +// mp_runmanager->BeamOn(50); serialize("text.gz"); + } +*/ // catch(...) // { // return GSMS_ERR; // }; return GSMS_OK; } +unsigned int GSMS::GSMS::run_forced(unsigned int beamOn) { + + try { + int discretes = 217; + int discrete_count = m_job.get_active_exposition().get_discrete_complete_count("217*1024"); + + for(int i = discrete_count; i<discretes ; i++) { + + std::cerr << "Current discrete count: "<< i << std::endl; + + G4double ltime = ((G4double)i / discretes)*10*2*pi; + setTime(&ltime); + if(i) + if( !mp_geometry->Update() ) + std::cerr << "FAILED" << std::endl; + mp_generator->Update(); + + mp_runmanager->GeometryHasBeenModified(); + mp_runmanager->BeamOn(beamOn); + serialize("text.gz"); + } + } catch(...) {}; + + return GSMS_OK; +} + unsigned int GSMS::GSMS::serialize(std::string filename) { try { std::stringstream sout; boost::archive::xml_oarchive oa(sout); oa << BOOST_SERIALIZATION_NVP(m_mask) << BOOST_SERIALIZATION_NVP(m_global) << BOOST_SERIALIZATION_NVP(m_hull) << BOOST_SERIALIZATION_NVP(m_detector) << BOOST_SERIALIZATION_NVP(m_job); // << BOOST_SERIALIZATION_NVP(m_scene); std::ofstream file_out(filename.c_str(),std::ios::out | std::ios::binary); boost::iostreams::filtering_ostreambuf out; out.push(boost::iostreams::gzip_compressor()); out.push(file_out); copy(sout,out); } catch(...) { return GSMS_ERR; }; return GSMS_OK; }; unsigned int GSMS::GSMS::unserialize(std::string filename) { try { std::ifstream file_in(filename.c_str(),std::ios::in | std::ios::binary); std::stringstream sin; boost::iostreams::filtering_istreambuf in; in.push(boost::iostreams::gzip_decompressor()); in.push(file_in); copy(in,sin); boost::archive::xml_iarchive ia(sin); ia >> BOOST_SERIALIZATION_NVP(m_mask) >> BOOST_SERIALIZATION_NVP(m_global) >> BOOST_SERIALIZATION_NVP(m_hull) >> BOOST_SERIALIZATION_NVP(m_detector) >> BOOST_SERIALIZATION_NVP(m_job) >> BOOST_SERIALIZATION_NVP(m_scene); } catch(...) { return GSMS_ERR; }; return GSMS_OK; }; diff --git a/src/config/GSMS.h b/src/config/GSMS.h index 65e1cd1..214e779 100644 --- a/src/config/GSMS.h +++ b/src/config/GSMS.h @@ -1,173 +1,180 @@ /*************************************************************************** * Copyright (C) 2009 by P.Voylov * * [email protected] * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ /*!\file GSMS.h * \brief Global GSMS configuration handler */ #ifndef GSMS_H_ #define GSMS_H_ #include "MaskConfig.h" #include "GlobalConfig.h" #include "Job.h" #include "DetectorConfig.h" #include "HullConfig.h" #include "SceneConfig.h" #include <geant/G4RunManager.hh> #include "physics/PhysicsList.h" #include "geometry/Geometry.h" #include "generator/Generator.h" #include <boost/iostreams/filtering_streambuf.hpp> #include <boost/iostreams/copy.hpp> #include <boost/iostreams/filter/gzip.hpp> #include "typedefs.h" namespace GSMS { /*!\class GSMS *\brief Global GSMS configuration and controls */ class GSMS { /*!\var m_global * \brief global configuration */ static GlobalConfig m_global; /*!\var m_job * \brief job configuration */ static Job m_job; /*!\var m_mask * \brief mask configuration */ static MaskConfig m_mask; /*!\var m_hull * \brief hull configuration */ static HullConfig m_hull; /*!\var m_detector * \brief detector configuration */ static DetectorConfig m_detector; /*!\var m_scene * \brief scene */ static SceneConfig m_scene; /*!\var mp_physics * \brief physics list */ static PhysicsList* mp_physics; /*!\var mp_geometry * \brief geometry */ static Geometry* mp_geometry; /*!\var mp_generator * \brief generator */ static Generator* mp_generator; /*!\var m_runmanager * \brief Geant run manager */ static G4RunManager* mp_runmanager; /*!\var m_verbosity * \brief verbosity level */ static G4int m_verbosity; public: /*!\fn static void setVerbosity(G4int verbosity) * \brief set verbosity level * \param verbosity new verbosity */ static void setVerbosity(G4int verbosity) {m_verbosity = verbosity;} /*!\fn static G4int getVerbosity() * \brief get verbosity level * \return verbosity */ static G4int getVerbosity() {return m_verbosity;} /*!\fn static unsigned int serialize(std::string out) * \brief serializer * \param out output stream filename * \return exit code */ static unsigned int serialize(std::string filename); /*!\fn static unsigned int unserialize(std::ofstream* in) * \brief unserializer * \param filename input stream filename * \return exit code */ static unsigned int unserialize(std::string filename); /*!\fn unsigned int initRunManager() * \brief model inititator * \return exit code */ static unsigned int initRunManager(); + /*!\fn unsigned int run_forced() + * \brief dumb model run + * \return exit code + */ +static unsigned int run_forced(unsigned int beamOn); + + /*!\fn unsigned int getMaterial(std::string name, G4Material** material) * \brief get material pointer * \param name material name * \param material material pointer (out) * \return exit code */ static unsigned int getMaterial(std::string name,G4Material** material); /*!\fn unsigned int getWorld(G4VPhysicalVolume** wptr) * \brief get world pointer * \param wptr world pointer (out) * \return exit code */ static unsigned int getWorld(G4VPhysicalVolume** wptr) {return m_scene.getWorld(wptr);} static unsigned int imprintDetector(G4VPhysicalVolume* world) {return m_detector.imprintDetector(world);} static unsigned int imprintMask(G4VPhysicalVolume* world = NULL) {return m_mask.imprintMask(world);} static unsigned int getTime(G4double* time) {return m_global.getTime(time);} static unsigned int setTime(G4double* time) {return m_global.setTime(time);} /*!\fn Job& get_job() {return m_job;} * \brief get job instance pointer * \return job object */ static Job& get_job() {return m_job;} }; }; /*namespace *GSMS*/ #endif /*GSMS_H_*/ diff --git a/src/main.cpp b/src/main.cpp index 5b352a5..1e68f6c 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,33 +1,34 @@ #include <config.h> #include <stdio.h> #include <iostream> #include <fstream> #include <iomanip> #include <string> #include "typedefs.h" #include <geant/G4RunManager.hh> #include <geant/Randomize.hh> #include "config/GSMS.h" bool __SUCCEEDED(unsigned int ARG) { bool result = false; if(ARG == GSMS_OK) result = true; return result; } int main(int argc, char* argv[]) { puts(PACKAGE_STRING); std::cout << GSMS::GSMS::unserialize("text.gz") << std::endl; //std::cout << GSMS::GSMS::serialize("text.gz") << std::endl; GSMS::GSMS::setVerbosity(0); - std::cout << GSMS::GSMS::initRunManager() << std::endl; + GSMS::GSMS::initRunManager(); + GSMS::GSMS::run_forced(37000); return 0; }
Aequilibrium/GSMS
d0e7a8dc64a9e57f2e0d6365cd179e1501b87189
Minor header changes
diff --git a/src/action/EventAction.cpp b/src/action/EventAction.cpp index 512913a..39019e1 100644 --- a/src/action/EventAction.cpp +++ b/src/action/EventAction.cpp @@ -1,78 +1,85 @@ -// -// C++ Implementation: EventAction -// -// Description: -// -// -// Author: P.Voylov <[email protected]>, (C) 2009 -// -// Copyright: See COPYING file that comes with this distribution -// -// - +/*************************************************************************** + * Copyright (C) 2009 by P.Voylov * + * [email protected] * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ #include "EventAction.h" #include "detector/Digi.h" #include "detector/Digitizer.h" #include <geant/G4Event.hh> #include <geant/G4EventManager.hh> #include <geant/G4HCofThisEvent.hh> #include <geant/G4VHitsCollection.hh> #include <geant/G4VVisManager.hh> #include <geant/G4SDManager.hh> #include <geant/G4DigiManager.hh> GSMS::EventAction::EventAction() : m_collID(-1) { G4DigiManager* fDM = G4DigiManager::GetDMpointer(); Digitizer* myDM = new Digitizer("GSMSDigitizer"); fDM->AddNewModule(myDM); } GSMS::EventAction::~EventAction() { } void GSMS::EventAction::BeginOfEventAction(const G4Event* evt) { G4int evtNb = evt->GetEventID(); // std::cerr << "Event: " << evtNb << std::endl; G4SDManager* sdman = G4SDManager::GetSDMpointer(); colID = sdman->GetCollectionID("crystal/eDep"); // std::cerr << "Coll ID: " << colID << std::endl; } void GSMS::EventAction::EndOfEventAction(const G4Event* evt) { G4HCofThisEvent* HCE = evt->GetHCofThisEvent(); if(!HCE) return; G4THitsMap<G4double>* evtMap = (G4THitsMap<G4double>*)(HCE->GetHC(colID)); G4DigiManager* fDM = G4DigiManager::GetDMpointer(); Digitizer* myDM = (Digitizer*)fDM->FindDigitizerModule("GSMSDigitizer"); myDM->Digitize(); /* map = *evtMap; std::cerr << "Size: " << map.GetMap()->size() << std::endl; G4double tot = 0.0; std::map<G4int, G4double*>::iterator itr = map.GetMap()->begin(); for(; itr != map.GetMap()->end();itr++) { tot = *(itr->second); } std::cerr << "eDep: " << tot << std::endl; */ // std::cerr << "Hits Collection: " << m_collID << std::endl; // G4int dCollID = fDM->GetDigiCollectionID("DigitsCollecton"); // std::cerr << "Digits Collection: " << dCollID << std::endl; // DigitsCollection* DC = (DigitsCollection*)fDM->GetDigiCollection(dCollID); } \ No newline at end of file diff --git a/src/action/EventAction.h b/src/action/EventAction.h index 1658ef7..e16dfc1 100644 --- a/src/action/EventAction.h +++ b/src/action/EventAction.h @@ -1,52 +1,59 @@ -// -// C++ Interface: EventAction -// -// Description: -// -// -// Author: P.Voylov <[email protected]>, (C) 2009 -// -// Copyright: See COPYING file that comes with this distribution -// -// - +/*************************************************************************** + * Copyright (C) 2009 by P.Voylov * + * [email protected] * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ /*!\file EventAction.h * \brief Event HC processor */ #ifndef EVENTACTION_H #define EVENTACTION_H #include "config/Config.h" #include <geant/G4UserEventAction.hh> #include <geant/G4THitsMap.hh> /*!\namespace GSMS * \brief Gamma-Scanner Modelling Suite namespace */ namespace GSMS { /*!\class EventAction * \brief Event processor */ class EventAction : public G4UserEventAction { G4int m_collID; G4double get_total(const G4THitsMap<G4double>& map) const; G4double find_minimum(const G4THitsMap<G4double>& map) const; G4THitsMap<G4double> map; G4int colID; public: EventAction(); virtual ~EventAction(); virtual void BeginOfEventAction(const G4Event*); virtual void EndOfEventAction(const G4Event*); }; } #endif /*EVENTACTION_H*/ \ No newline at end of file diff --git a/src/action/Run.cpp b/src/action/Run.cpp index a05bfee..ab61e43 100644 --- a/src/action/Run.cpp +++ b/src/action/Run.cpp @@ -1,77 +1,84 @@ -// -// C++ Implementation: Run -// -// Description: -// -// -// Author: P.Voylov <[email protected]>, (C) 2009 -// -// Copyright: See COPYING file that comes with this distribution -// -// - +/*************************************************************************** + * Copyright (C) 2009 by P.Voylov * + * [email protected] * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ #include "Run.h" #include <geant/G4Event.hh> #include <geant/G4HCofThisEvent.hh> #include <geant/G4SDManager.hh> #include "detector/Digitizer.h" #include "detector/Digi.h" #include <geant/G4DigiManager.hh> GSMS::Run::Run() { // G4SDManager* sdman = G4SDManager::GetSDMpointer(); // colIDSum = sdman->GetCollectionID("crystal/eDep"); } GSMS::Run::~Run() { } void GSMS::Run::RecordEvent(const G4Event* evt) { G4DigiManager* digiMan = G4DigiManager::GetDMpointer(); int DCID = -1; DCID = digiMan->GetDigiCollectionID("GSMSDigitizer/DigitsCollection"); DigitsCollection* DC = (DigitsCollection*)digiMan->GetDigiCollection(DCID); if(DC) for(int i=0; i< DC->GetSize(); i++) { G4double time = (*DC)[i]->get_time(); G4double ene = (*DC)[i]->get_ene(); G4int chan = (*DC)[i]->get_channel(); //std::pair<G4double, G4int> score(time, channel); m_time.push_back(time); m_ene.push_back(ene); m_chan.push_back(chan); } } /* G4double GSMS::Run::get_total(const G4THitsMap<G4double>& map) const { G4double tot = 0.0; std::map<G4int, G4double*>::iterator itr = map.GetMap()->begin(); for(; itr != map.GetMap()->end();itr++) { tot += *(itr->second); } return tot; } G4double GSMS::Run::find_minimum(const G4THitsMap<G4double>& map) const { G4double val = DBL_MAX; std::map<G4int, G4double*>::iterator itr = map.GetMap()->begin(); for(; itr != map.GetMap()->end();itr++) { if(val > *(itr->second)) val = *(itr->second); } return val; } */ \ No newline at end of file diff --git a/src/action/Run.h b/src/action/Run.h index 6701779..06bb267 100644 --- a/src/action/Run.h +++ b/src/action/Run.h @@ -1,64 +1,71 @@ -// -// C++ Interface: Run -// -// Description: -// -// -// Author: P.Voylov <[email protected]>, (C) 2009 -// -// Copyright: See COPYING file that comes with this distribution -// -// - +/*************************************************************************** + * Copyright (C) 2009 by P.Voylov * + * [email protected] * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ /*!\file Run.h * \brief Run object */ #ifndef RUN_H #define RUN_H #include "config/Config.h" #include <geant/G4Run.hh> #include <geant/G4THitsMap.hh> /*!\namespace GSMS * \brief Gamma-Scanner Modelling Suite namespace */ namespace GSMS { /*!\class Run * \brief Run object */ class Run : public G4Run { public: Run(); virtual ~Run(); virtual void RecordEvent(const G4Event*); private: // G4double get_total(const G4THitsMap<G4double>& map) const; // G4double find_minimum(const G4THitsMap<G4double>& map) const; // G4THitsMap<G4double> mapSum; // G4int colIDSum; // G4THitsMap<G4double> mapMin; // G4int colIDMin; std::vector<G4double> m_ene; std::vector<G4double> m_time; std::vector<G4int> m_chan; public: const G4double get_time(int idx) {return m_time[idx];} const G4int get_chan(int idx) {return m_chan[idx];} const G4double get_ene(int idx) {return m_ene[idx];} const int get_size() {return m_time.size();} }; } #endif /*RUNACTION_H*/ \ No newline at end of file diff --git a/src/action/RunAction.cpp b/src/action/RunAction.cpp index fa5bc5e..efd2c8e 100644 --- a/src/action/RunAction.cpp +++ b/src/action/RunAction.cpp @@ -1,61 +1,68 @@ -// -// C++ Implementation: RunAction -// -// Description: -// -// -// Author: P.Voylov <[email protected]>, (C) 2009 -// -// Copyright: See COPYING file that comes with this distribution -// -// - +/*************************************************************************** + * Copyright (C) 2009 by P.Voylov * + * [email protected] * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ #include "RunAction.h" #include "detector/Digitizer.h" #include "detector/Digi.h" // #include <geant/G4DigiManager.hh> GSMS::RunAction::RunAction() { } GSMS::RunAction::~RunAction() { } G4Run* GSMS::RunAction::GenerateRun() { return new Run; } void GSMS::RunAction::BeginOfRunAction(const G4Run*) { // G4DigiManager* fDM = G4DigiManager::GetDMpointer(); // Digitizer* myDM = (Digitizer*)fDM->FindDigitizerModule("GSMSDigitizer"); } void GSMS::RunAction::EndOfRunAction(const G4Run* aRun) { //const Run* theRun = (const Run*)aRun; Run* theRun = (Run*)aRun; std::vector<G4int> spectrum; for(int i=0; i<1024; i++) spectrum.push_back(0L); for(int i=0; i< theRun->get_size(); i++) { G4double time = theRun->get_time(i); G4double ene = theRun->get_ene(i); G4int chan = theRun->get_chan(i); //std::cout << time << "\t" << chan << "\t" << ene << std::endl; spectrum[chan]++; } if (theRun->get_size()) { for(int i=0; i<1024; i++) std::cout << spectrum[i] << "\t"; std::cout << std::endl; } } \ No newline at end of file diff --git a/src/action/RunAction.h b/src/action/RunAction.h index 4dae2da..bb2ece9 100644 --- a/src/action/RunAction.h +++ b/src/action/RunAction.h @@ -1,44 +1,51 @@ -// -// C++ Interface: RunAction -// -// Description: -// -// -// Author: P.Voylov <[email protected]>, (C) 2009 -// -// Copyright: See COPYING file that comes with this distribution -// -// - +/*************************************************************************** + * Copyright (C) 2009 by P.Voylov * + * [email protected] * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ /*!\file RunAction.h * \brief Action HC processor */ #ifndef RUNACTION_H #define RUNACTION_H #include "config/Config.h" #include "action/Run.h" #include <geant/G4UserRunAction.hh> /*!\namespace GSMS * \brief Gamma-Scanner Modelling Suite namespace */ namespace GSMS { /*!\class RunAction * \brief Action processor */ class RunAction : public G4UserRunAction { public: RunAction(); ~RunAction(); G4Run* GenerateRun(); virtual void BeginOfRunAction(const G4Run*); virtual void EndOfRunAction(const G4Run*); }; } #endif /*RUNACTION_H*/ \ No newline at end of file diff --git a/src/config/Config.cpp b/src/config/Config.cpp index 01c9372..915f658 100644 --- a/src/config/Config.cpp +++ b/src/config/Config.cpp @@ -1,18 +1,37 @@ +/*************************************************************************** + * Copyright (C) 2009 by P.Voylov * + * [email protected] * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ #include "Config.h" #include <sys/stat.h> #include <sys/types.h> unsigned int GSMS::Config::save(std::ofstream* stream) { } unsigned int GSMS::LogObjConfig::save(std::ofstream* stream) { } unsigned int GSMS::PhysObjConfig::save(std::ofstream* stream) { PhysObjConfig* pDetectorConfig = this; boost::archive::xml_oarchive out(*stream); out << BOOST_SERIALIZATION_NVP(pDetectorConfig); } diff --git a/src/config/Config.h b/src/config/Config.h index d0db20c..3f67fb0 100644 --- a/src/config/Config.h +++ b/src/config/Config.h @@ -1,183 +1,202 @@ +/*************************************************************************** + * Copyright (C) 2009 by P.Voylov * + * [email protected] * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ /*!\file Config.h * \brief Primary configuration entities */ #ifndef CONFIG_H #define CONFIG_H #include <string> #include <iomanip> #include <iostream> #include <fstream> #include <geant/globals.hh> #include <geant/G4ios.hh> #include <boost/serialization/version.hpp> #include <boost/serialization/nvp.hpp> #include <boost/serialization/utility.hpp> #include <boost/serialization/map.hpp> #include <boost/serialization/vector.hpp> #include <boost/serialization/list.hpp> #include <boost/serialization/base_object.hpp> #include <boost/archive/xml_oarchive.hpp> #include <boost/archive/xml_iarchive.hpp> #include "typedefs.h" /*!\namespace GSMS * \brief Gamma-Scanner Modelling Suite namespace */ namespace GSMS { /*!\class Config * \brief Base configuration unit */ class Config { friend class boost::serialization::access; /*!\fn serialize(Archive & ar, const unsigned int version) * \param ar output archive * \param version archive version */ template<class Archive> void serialize(Archive & ar, const unsigned int version) { ar & BOOST_SERIALIZATION_NVP(m_type); } protected: /*!\var std::string m_type * \brief configuration type */ std::string m_type; public: /*!\fn Config() * \brief default constructor */ Config() : m_type("Config") {} /*!\fn Config(std::string type) * \brief specific constructor * \param type configuration instance name */ Config(std::string type) : m_type(type) {} /*!\fn ~Config() * \brief default destructor */ virtual ~Config() {} /*!\fn unsigned int save(std::ofstream* stream) * \brief self-serializer * \param stream output stream * \return exit code */ virtual unsigned int save(std::ofstream* stream); }; class LogObjConfig : public Config { friend class boost::serialization::access; template<class Archive> void serialize(Archive & ar, const unsigned int version) { ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(Config) & BOOST_SERIALIZATION_NVP(m_x) & BOOST_SERIALIZATION_NVP(m_y) & BOOST_SERIALIZATION_NVP(m_z) & BOOST_SERIALIZATION_NVP(m_rho) & BOOST_SERIALIZATION_NVP(m_theta) & BOOST_SERIALIZATION_NVP(m_phi); } protected: float m_x; float m_y; float m_z; float m_rho; float m_theta; float m_phi; public: /*!\fn LogObjConfig() * \brief default constructor */ LogObjConfig() : m_x(0.0),m_y(0.0),m_z(0.0),m_rho(0.0),m_theta(0.0),m_phi(0.0) {m_type = "LogObj";} /*!\fn LogObjConfig(float x, float y, float z, float rho, float theta, float phi) * \brief specific constructor * \param x X coordinate * \param y Y coordinate * \param z Z coordinate * \param rho Rho angle * \param theta Theta angle * \param phi Phi angle */ LogObjConfig(float x, float y, float z, float rho=0.0, float theta=0.0, float phi=0.0) : m_x(x),m_y(y),m_z(z),m_rho(rho),m_theta(theta),m_phi(phi) {m_type = "LogObj";} /*!\fn ~LogObjConfig() * \brief default destructor */ virtual ~LogObjConfig() {} /*!\fn unsigned int save(std::ofstream* stream) * \brief self-serializer * \param stream output stream * \return exit code */ virtual unsigned int save(std::ofstream* stream); }; class PhysObjConfig : public LogObjConfig { friend class boost::serialization::access; template<class Archive> void serialize(Archive & ar, const unsigned int version) { ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(LogObjConfig) & BOOST_SERIALIZATION_NVP(m_shape) & BOOST_SERIALIZATION_NVP(m_material); } protected: std::string m_shape; std::string m_material; public: /*!\fn PhysObjConfig() * \brief default constructor */ PhysObjConfig() : m_shape("Cyllinder"),m_material("CsI") { m_type = "PhysObj";} /*!\fn PhysObjConfig(std::string shape, std::string material) * \brief default constructor * \param shape object shape * \param material object material */ PhysObjConfig(std::string shape, std::string material = "CsI") : m_shape(shape),m_material(material) {m_type = "PhysObj";} /*!\fn ~PhysObjConfig() * \brief default destructor */ ~PhysObjConfig() {} /*!\fn unsigned int save(std::ofstream* stream) * \brief self-serializer * \param stream output stream * \return exit code */ virtual unsigned int save(std::ofstream* stream); }; }; //namespace GSMS BOOST_CLASS_VERSION(GSMS::Config,1) BOOST_CLASS_VERSION(GSMS::LogObjConfig,1) BOOST_CLASS_VERSION(GSMS::PhysObjConfig,1) #endif /*CONFIG_H*/ diff --git a/src/config/DetectorConfig.cpp b/src/config/DetectorConfig.cpp index 900b075..e1205b5 100644 --- a/src/config/DetectorConfig.cpp +++ b/src/config/DetectorConfig.cpp @@ -1,239 +1,259 @@ +/*************************************************************************** + * Copyright (C) 2009 by P.Voylov * + * [email protected] * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + #include "DetectorConfig.h" #include <sys/stat.h> #include <sys/types.h> #include "GSMS.h" #include "detector/Detector.h" #include <geant/G4Tubs.hh> #include <geant/G4Sphere.hh> #include <geant/G4PVPlacement.hh> #include <geant/G4VisAttributes.hh> #include <geant/G4SDManager.hh> #include <geant/G4SDParticleFilter.hh> #include <geant/G4VPrimitiveScorer.hh> #include <geant/G4PSEnergyDeposit.hh> #include <geant/G4PSNofSecondary.hh> #include <geant/G4PSMinKinEAtGeneration.hh> #include <geant/G4PSTrackLength.hh> #include <geant/G4PSNofStep.hh> unsigned int GSMS::DetectorConfig::save(std::ofstream* stream) { DetectorConfig* pDetectorConfig = this; boost::archive::xml_oarchive out(*stream); out << BOOST_SERIALIZATION_NVP(pDetectorConfig); } unsigned int GSMS::DetectorConfig::imprintDetector(G4VPhysicalVolume* wptr) { G4VPhysicalVolume* world = NULL; if(wptr) world = wptr; else GSMS::GSMS::getWorld(&world); try { G4VSolid* s_crystal = NULL; G4VSolid* s_mirror = NULL; G4VSolid* s_shirt = NULL; if(m_shape == "Cyllinder") { s_crystal = new G4Tubs( "crystal", 0., m_radius, m_height/2, 0.0*deg, 360.0*deg); s_mirror = new G4Tubs( "mirror", 0., m_radius + m_mirror_thick, m_height/2 + m_mirror_thick, 0.0*deg, 360.0*deg); s_shirt = new G4Tubs( "shirt", 0., m_radius + m_mirror_thick + m_shirt_thick, m_height/2 + m_mirror_thick + m_shirt_thick, 0.0*deg, 360.0*deg); } else if (m_shape == "Sphere") { s_crystal = new G4Sphere( "crystal", 0., m_radius, 0.0*deg, 360.0*deg, 0.0*deg, 360.0*deg ); s_mirror = new G4Sphere( "mirror", 0., m_radius + m_mirror_thick, 0.0*deg, 360.0*deg, 0.0*deg, 360.0*deg ); s_shirt = new G4Sphere( "shirt", 0., m_radius + m_mirror_thick + m_shirt_thick, 0.0*deg, 360.0*deg, 0.0*deg, 360.0*deg ); } else return GSMS_ERR; G4Material* crystal_mat = NULL; G4Material* mirror_mat = NULL; G4Material* shirt_mat = NULL; if( !__SUCCEEDED(GSMS::GSMS::getMaterial(m_material,&crystal_mat)) || !__SUCCEEDED(GSMS::GSMS::getMaterial("MgO",&mirror_mat)) || !__SUCCEEDED(GSMS::GSMS::getMaterial("D16",&shirt_mat))) return GSMS_ERR; G4LogicalVolume* crystal_log = new G4LogicalVolume( s_crystal, crystal_mat, "crystal_log"); G4LogicalVolume* mirror_log = new G4LogicalVolume( s_mirror, mirror_mat, "mirror_log"); G4LogicalVolume* shirt_log = new G4LogicalVolume( s_shirt, shirt_mat, "shirt_log"); G4VPhysicalVolume* shirt_phys = new G4PVPlacement( 0, G4ThreeVector(0.,0.,0.), "shirt_phys", shirt_log, world, false, 0); G4VPhysicalVolume* mirror_phys = new G4PVPlacement( 0, G4ThreeVector(0.,0.,0.), "mirror_phys", mirror_log, shirt_phys, false, 0); G4VPhysicalVolume* crystal_phys = new G4PVPlacement( 0, G4ThreeVector(0.,0.,0.), "crystal_phys", crystal_log, mirror_phys, false, 0); G4VisAttributes* crystal_vis = new G4VisAttributes(GSMS_COLOR_CRYSTAL); G4VisAttributes* mirror_vis = new G4VisAttributes(GSMS_COLOR_MGO); G4VisAttributes* shirt_vis = new G4VisAttributes(GSMS_COLOR_ALUMINIUM); crystal_vis->SetVisibility(true); mirror_vis->SetVisibility(true); shirt_vis->SetVisibility(true); crystal_vis->SetForceSolid(true); mirror_vis->SetForceSolid(true); shirt_vis->SetForceSolid(true); crystal_log->SetVisAttributes(crystal_vis); mirror_log->SetVisAttributes(mirror_vis); shirt_log->SetVisAttributes(shirt_vis); /* G4SDManager* sd_manager = G4SDManager::GetSDMpointer(); G4VSensitiveDetector* crystal_sd = new Detector("crystal"); sd_manager->AddNewDetector(crystal_sd); crystal_log->SetSensitiveDetector(crystal_sd); */ G4String filterName, particleName; G4SDParticleFilter* gammaFilter = new G4SDParticleFilter(filterName="gammaFilter",particleName="gamma"); G4SDParticleFilter* electronFilter = new G4SDParticleFilter(filterName="electronFilter",particleName="e-"); G4SDParticleFilter* positronFilter = new G4SDParticleFilter(filterName="positronFilter",particleName="e+"); G4SDParticleFilter* epFilter = new G4SDParticleFilter(filterName="epFilter"); epFilter->add(particleName="e-"); epFilter->add(particleName="e+"); // Loop counter j = 0 : absorber // = 1 : gap G4String detName = "crystal"; G4MultiFunctionalDetector* det = new G4MultiFunctionalDetector(detName); // The second argument in each primitive means the "level" of geometrical hierarchy, // the copy number of that level is used as the key of the G4THitsMap. // For absorber (j = 0), the copy number of its own physical volume is used. // For gap (j = 1), the copy number of its mother physical volume is used, since there // is only one physical volume of gap is placed with respect to its mother. G4VPrimitiveScorer* primitive; primitive = new G4PSEnergyDeposit("eDep"); //primitive->SetFilter(gammaFilter); det->RegisterPrimitive(primitive); primitive = new G4PSNofSecondary("nGamma"); primitive->SetFilter(gammaFilter); det->RegisterPrimitive(primitive); primitive = new G4PSNofSecondary("nElectron"); primitive->SetFilter(electronFilter); det->RegisterPrimitive(primitive); primitive = new G4PSNofSecondary("nPositron"); primitive->SetFilter(positronFilter); det->RegisterPrimitive(primitive); primitive = new G4PSMinKinEAtGeneration("minEkinGamma"); primitive->SetFilter(gammaFilter); det->RegisterPrimitive(primitive); primitive = new G4PSMinKinEAtGeneration("minEkinElectron"); primitive->SetFilter(electronFilter); det->RegisterPrimitive(primitive); primitive = new G4PSMinKinEAtGeneration("minEkinPositron"); primitive->SetFilter(positronFilter); det->RegisterPrimitive(primitive); primitive = new G4PSTrackLength("trackLength"); primitive->SetFilter(epFilter); det->RegisterPrimitive(primitive); primitive = new G4PSNofStep("nStep"); primitive->SetFilter(epFilter); det->RegisterPrimitive(primitive); G4SDManager::GetSDMpointer()->AddNewDetector(det); crystal_log->SetSensitiveDetector(det); } catch(...) { return GSMS_ERR; }; return GSMS_OK; }; diff --git a/src/config/GSMS.cpp b/src/config/GSMS.cpp index bfb276d..a66b2e0 100644 --- a/src/config/GSMS.cpp +++ b/src/config/GSMS.cpp @@ -1,157 +1,177 @@ +/*************************************************************************** + * Copyright (C) 2009 by P.Voylov * + * [email protected] * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + #include "GSMS.h" #include <geant/Randomize.hh> #include <geant/G4VisExecutive.hh> #include <geant/G4UImanager.hh> #include <geant/G4UIterminal.hh> #include <geant/G4UItcsh.hh> #include "action/RunAction.h" #include "action/EventAction.h" GSMS::GlobalConfig GSMS::GSMS::m_global; GSMS::MaskConfig GSMS::GSMS::m_mask; GSMS::HullConfig GSMS::GSMS::m_hull; GSMS::Job GSMS::GSMS::m_job; GSMS::DetectorConfig GSMS::GSMS::m_detector; GSMS::SceneConfig GSMS::GSMS::m_scene; GSMS::PhysicsList* GSMS::GSMS::mp_physics = NULL; GSMS::Geometry* GSMS::GSMS::mp_geometry = NULL; GSMS::Generator* GSMS::GSMS::mp_generator = NULL; G4RunManager* GSMS::GSMS::mp_runmanager = NULL; G4int GSMS::GSMS::m_verbosity = 0; unsigned int GSMS::GSMS::getMaterial(std::string name,G4Material** material) { if(mp_geometry) return mp_geometry->getMaterial(name,material); else return GSMS_ERR; } unsigned int GSMS::GSMS::initRunManager() { // try // { CLHEP::HepRandom::setTheEngine(new CLHEP::RanecuEngine); CLHEP::HepRandom::setTheSeed(0L); mp_runmanager = new G4RunManager; mp_runmanager->SetVerboseLevel(0);//m_verbosity); mp_physics = new PhysicsList; mp_runmanager->SetUserInitialization(mp_physics); mp_geometry = new Geometry; mp_runmanager->SetUserInitialization(mp_geometry); mp_generator = new Generator; mp_runmanager->SetUserAction(mp_generator); G4UserRunAction* run_action = new RunAction; mp_runmanager->SetUserAction(run_action); G4UserEventAction* event_action = new EventAction; mp_runmanager->SetUserAction(event_action); mp_runmanager->Initialize(); // G4UImanager* ui = G4UImanager::GetUIpointer(); // G4VisManager* vis = new G4VisExecutive; // vis->Initialize(); // ui->ApplyCommand("/control/execute vis.mac"); // ui->ApplyCommand("/tracking/verbose 1"); // G4UIsession* session = NULL; // session = new G4UIterminal(); // session->SessionStart(); // delete session; Source* src = util::SourceLib::create_source("Cs137", 1, G4ThreeVector(1.*m, 1.*m, 0.)); if(src) m_job.push_source(*src); // src = util::SourceLib::create_source("Co57", 1, G4ThreeVector(1.*m, 0., 0.)); // if(src) m_job.push_source(*src); // src = util::SourceLib::create_source("Co60", 1, G4ThreeVector(0., -1.*m, 0.)); // if(src) m_job.push_source(*src); serialize("text.gz"); int discretes = 217; for(int i = 0; i<discretes ; i++) { G4double ltime = ((G4double)i / discretes)*10*2*pi; setTime(&ltime); if(i) mp_geometry->Update(); mp_generator->Update(); // if( __SUCCEEDED(setTime(&ltime)) && // __SUCCEEDED(imprintMask())) mp_runmanager->BeamOn(12000); } // catch(...) // { // return GSMS_ERR; // }; return GSMS_OK; } unsigned int GSMS::GSMS::serialize(std::string filename) { try { std::stringstream sout; boost::archive::xml_oarchive oa(sout); oa << BOOST_SERIALIZATION_NVP(m_mask) << BOOST_SERIALIZATION_NVP(m_global) << BOOST_SERIALIZATION_NVP(m_hull) << BOOST_SERIALIZATION_NVP(m_detector) << BOOST_SERIALIZATION_NVP(m_job); // << BOOST_SERIALIZATION_NVP(m_scene); std::ofstream file_out(filename.c_str(),std::ios::out | std::ios::binary); boost::iostreams::filtering_ostreambuf out; out.push(boost::iostreams::gzip_compressor()); out.push(file_out); copy(sout,out); } catch(...) { return GSMS_ERR; }; return GSMS_OK; }; unsigned int GSMS::GSMS::unserialize(std::string filename) { try { std::ifstream file_in(filename.c_str(),std::ios::in | std::ios::binary); std::stringstream sin; boost::iostreams::filtering_istreambuf in; in.push(boost::iostreams::gzip_decompressor()); in.push(file_in); copy(in,sin); boost::archive::xml_iarchive ia(sin); ia >> BOOST_SERIALIZATION_NVP(m_mask) >> BOOST_SERIALIZATION_NVP(m_global) >> BOOST_SERIALIZATION_NVP(m_hull) >> BOOST_SERIALIZATION_NVP(m_detector) >> BOOST_SERIALIZATION_NVP(m_job) >> BOOST_SERIALIZATION_NVP(m_scene); } catch(...) { return GSMS_ERR; }; return GSMS_OK; }; diff --git a/src/config/GlobalConfig.cpp b/src/config/GlobalConfig.cpp index a4ac8f9..fe14a75 100644 --- a/src/config/GlobalConfig.cpp +++ b/src/config/GlobalConfig.cpp @@ -1,7 +1,27 @@ +/*************************************************************************** + * Copyright (C) 2009 by P.Voylov * + * [email protected] * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + #include "GlobalConfig.h" #include <sys/stat.h> #include <sys/types.h> unsigned int GSMS::GlobalConfig::save(std::ofstream* stream) { } diff --git a/src/config/HullConfig.cpp b/src/config/HullConfig.cpp index d122804..781aba5 100644 --- a/src/config/HullConfig.cpp +++ b/src/config/HullConfig.cpp @@ -1,10 +1,30 @@ +/*************************************************************************** + * Copyright (C) 2009 by P.Voylov * + * [email protected] * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + #include "HullConfig.h" #include <sys/stat.h> #include <sys/types.h> unsigned int GSMS::HullConfig::save(std::ofstream* stream) { HullConfig* pHullConfig = this; boost::archive::xml_oarchive out(*stream); out << BOOST_SERIALIZATION_NVP(pHullConfig); } diff --git a/src/config/Job.cpp b/src/config/Job.cpp index 5630647..012ebcd 100644 --- a/src/config/Job.cpp +++ b/src/config/Job.cpp @@ -1,10 +1,30 @@ +/*************************************************************************** + * Copyright (C) 2009 by P.Voylov * + * [email protected] * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + #include "Job.h" #include <sys/stat.h> #include <sys/types.h> unsigned int GSMS::Job::save(std::ofstream* stream) { Job* pJob = this; boost::archive::xml_oarchive out(*stream); out << BOOST_SERIALIZATION_NVP(pJob); } diff --git a/src/config/MaskConfig.cpp b/src/config/MaskConfig.cpp index c816a18..d9e6af7 100644 --- a/src/config/MaskConfig.cpp +++ b/src/config/MaskConfig.cpp @@ -1,364 +1,384 @@ +/*************************************************************************** + * Copyright (C) 2009 by P.Voylov * + * [email protected] * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + #include "MaskConfig.h" #include <sys/stat.h> #include <sys/types.h> #include "GSMS.h" #include <geant/G4Tubs.hh> #include <geant/G4Box.hh> #include <geant/G4PVPlacement.hh> #include <geant/G4VisAttributes.hh> #include <geant/G4PVParameterised.hh> #include <geant/G4VPVParameterisation.hh> void GSMS::MaskElement::ComputeTransformation(const G4int copyNo, G4VPhysicalVolume* physVol) const { std::cout << "Tran" << copyNo << std::endl; } void GSMS::MaskElement::ComputeDimensions(G4Box& element, const G4int copyNo, G4VPhysicalVolume* physVol) const { std::cout << "Dim" << copyNo << std::endl; } G4Material* GSMS::MaskElement::ComputeMaterial(const G4int copyNo, G4VPhysicalVolume* physVol, const G4VTouchable* parentTouch) { std::cout << "Mat" << copyNo << std::endl; } bool GSMS::MaskConfig::isTransparent(unsigned char index) { // std::cout << m_evector << std::endl; // std::cout << (m_evector >> index) << std::endl; // std::cout << ((m_evector >> index) & 1) << std::endl; return !(bool)((m_evector >> index) & 1); } unsigned int GSMS::MaskConfig::save(std::ofstream* stream) { MaskConfig* pMaskConfig = this; boost::archive::xml_oarchive out(*stream); out << BOOST_SERIALIZATION_NVP(pMaskConfig); } unsigned int GSMS::MaskConfig::imprintMask(G4VPhysicalVolume* wptr) { //clean up if(m_assembly) { std::vector<G4VPhysicalVolume*>::iterator iter = m_assembly->GetVolumesIterator(); for(int i=0;i<m_assembly->TotalImprintedVolumes();iter++,i++) { G4VPhysicalVolume* ptr = *iter; if(ptr) delete ptr; *iter = NULL; } delete m_assembly; m_assembly = new G4AssemblyVolume; } G4VPhysicalVolume* world = NULL; if(wptr) world = wptr; else GSMS::GSMS::getWorld(&world); std::cerr << world << std::endl; try { G4VSolid* s_element = NULL; G4VSolid* s_mask = NULL; s_mask = new G4Tubs( "mask", 0., m_radius+m_ethick*1.5, m_eheight/2, 0.*deg, 360.*deg ); if(m_etype == "Box") { s_element = new G4Box( "element", m_ewidth/2, m_ethick/2, m_eheight/2); } else if(m_etype == "Segment") { s_element = new G4Box( "element", m_ewidth/2, m_ethick/2, m_eheight/2); } else return GSMS_ERR; G4Material* element_mat = NULL; G4Material* mask_mat = NULL; if(!__SUCCEEDED(GSMS::GSMS::getMaterial(m_emat,&element_mat)) || !__SUCCEEDED(GSMS::GSMS::getMaterial("Air",&mask_mat))) return GSMS_ERR; G4LogicalVolume* element_log = new G4LogicalVolume( s_element, element_mat, "element_log"); ///////////// /* G4LogicalVolume* mask_log = new G4LogicalVolume( s_mask, mask_mat, "mask_log" ); G4VPVParameterisation* mask_param = new MaskElement( this ); G4VPhysicalVolume* mask_phys = new G4PVParameterised( "mask_phys", element_log, mask_log, kUndefined, m_ecount, mask_param ); */ //////////// G4RotationMatrix mR; //mask G4ThreeVector mT(0.,0.,0.); //mask G4double local_time,angle,angle_offset; local_time = angle = angle_offset = 0.0; if(!__SUCCEEDED(GSMS::getTime(&local_time))) return GSMS_ERR; angle_offset = (m_speed * local_time); std::cerr << "Mask angle offset: " << angle_offset*360/2/pi << std::endl; for(int i=0;i<m_ecount;i++) if(!isTransparent(i)) { G4RotationMatrix mRe; //element G4ThreeVector mTe; //element angle = ( (float)i/(float)m_ecount*2*pi + angle_offset ); G4float xoff = (m_radius+m_ethick)*cos(angle); G4float yoff = (m_radius+m_ethick)*sin(angle); G4float zoff = 0.; mTe.setX(xoff); mTe.setY(yoff); mTe.setZ(zoff); mRe.rotateZ(pi/2 + angle); m_assembly->AddPlacedVolume(element_log,mTe,&mRe); std::cerr << "Element " << i << " at angle " << angle*360/2/pi << " xOff = " << xoff << " yOff = " << yoff << " zOff = " << zoff << std::endl; }; m_assembly->MakeImprint(world->GetLogicalVolume(),mT,&mR, true); G4VisAttributes* element_vis = new G4VisAttributes(GSMS_COLOR_ELEMENT); element_vis->SetVisibility(true); element_vis->SetForceSolid(true); element_log->SetVisAttributes(element_vis); //////////// } catch(...) { return GSMS_ERR; }; return GSMS_OK; }; unsigned int GSMS::MaskConfig::getRadius(G4double* radius) { if(!radius) return GSMS_ERR; try { *radius = m_radius; } catch(...) {return GSMS_ERR;} return GSMS_OK; } unsigned int GSMS::MaskConfig::setRadius(G4double* radius) { if(!radius) return GSMS_ERR; try { m_radius = *radius; } catch(...) {return GSMS_ERR;} return GSMS_OK; } unsigned int GSMS::MaskConfig::getSpeed(G4double* speed) { if(!speed) return GSMS_ERR; try { *speed = m_speed; } catch(...) {return GSMS_ERR;} return GSMS_OK; } unsigned int GSMS::MaskConfig::setSpeed(G4double* speed) { if(!speed) return GSMS_ERR; try { m_speed = *speed; } catch(...) {return GSMS_ERR;} return GSMS_OK; } unsigned int GSMS::MaskConfig::getECount(unsigned char* ecount) { if(!ecount) return GSMS_ERR; try { *ecount = m_ecount; } catch(...) {return GSMS_ERR;} return GSMS_OK; } unsigned int GSMS::MaskConfig::setECount(unsigned char* ecount) { if(!ecount) return GSMS_ERR; try { m_ecount = *ecount; } catch(...) {return GSMS_ERR;} return GSMS_OK; } unsigned int GSMS::MaskConfig::getEHeight(G4double* eheight) { if(!eheight) return GSMS_ERR; try { *eheight = m_eheight; } catch(...) {return GSMS_ERR;} return GSMS_OK; } unsigned int GSMS::MaskConfig::setEHeight(G4double* eheight) { if(!eheight) return GSMS_ERR; try { m_eheight = *eheight; } catch(...) {return GSMS_ERR;} return GSMS_OK; } unsigned int GSMS::MaskConfig::getEWidth(G4double* ewidth) { if(!ewidth) return GSMS_ERR; try { *ewidth = m_ewidth; } catch(...) {return GSMS_ERR;} return GSMS_OK; } unsigned int GSMS::MaskConfig::setEWidth(G4double* ewidth) { if(!ewidth) return GSMS_ERR; try { m_ewidth = *ewidth; } catch(...) {return GSMS_ERR;} return GSMS_OK; } unsigned int GSMS::MaskConfig::getEThick(G4double* ethick) { if(!ethick) return GSMS_ERR; try { *ethick = m_ethick; } catch(...) {return GSMS_ERR;} return GSMS_OK; } unsigned int GSMS::MaskConfig::setEThick(G4double* ethick) { if(!ethick) return GSMS_ERR; try { m_ethick = *ethick; } catch(...) {return GSMS_ERR;} return GSMS_OK; } unsigned int GSMS::MaskConfig::getEMat(std::string* emat) { if(!emat) return GSMS_ERR; try { *emat = m_emat; } catch(...) {return GSMS_ERR;} return GSMS_OK; } unsigned int GSMS::MaskConfig::setEMat(std::string* emat) { if(!emat) return GSMS_ERR; try { m_emat = *emat; } catch(...) {return GSMS_ERR;} return GSMS_OK; } unsigned int GSMS::MaskConfig::getEType(std::string* etype) { if(!etype) return GSMS_ERR; try { *etype = m_etype; } catch(...) {return GSMS_ERR;} return GSMS_OK; } unsigned int GSMS::MaskConfig::setEType(std::string* etype) { if(!etype) return GSMS_ERR; try { m_etype = *etype; } catch(...) {return GSMS_ERR;} return GSMS_OK; } diff --git a/src/config/SceneConfig.cpp b/src/config/SceneConfig.cpp index dd1d854..5c7a8f9 100644 --- a/src/config/SceneConfig.cpp +++ b/src/config/SceneConfig.cpp @@ -1,51 +1,71 @@ +/*************************************************************************** + * Copyright (C) 2009 by P.Voylov * + * [email protected] * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + #include "SceneConfig.h" #include <sys/stat.h> #include <sys/types.h> #include <geant/G4VSolid.hh> #include <geant/G4Box.hh> #include <geant/G4LogicalVolume.hh> #include <geant/G4PVPlacement.hh> #include <geant/G4ThreeVector.hh> #include "config/GSMS.h" unsigned int GSMS::SceneConfig::save(std::ofstream* stream) { SceneConfig* pSceneConfig = this; boost::archive::xml_oarchive out(*stream); out << BOOST_SERIALIZATION_NVP(pSceneConfig); } unsigned int GSMS::SceneConfig::initWorld() { try { G4Material* material = NULL; if(GSMS::GSMS::getMaterial(m_wmat,&material) != GSMS_OK) return GSMS_ERR; G4VSolid* world_box = new G4Box("world_box",0.5*m_wwidth,0.5*m_wlength,0.5*m_wheight); G4LogicalVolume* world_log = new G4LogicalVolume(world_box, material,"world_log"); mp_world = new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), "world_phys", world_log, NULL, false, 0); } catch(...) {return GSMS_ERR;} return GSMS_OK; } unsigned int GSMS::SceneConfig::getWorld(G4VPhysicalVolume** world) { if(!world) return GSMS_ERR; try { if(!mp_world) initWorld(); *world = mp_world; } catch(...) { return GSMS_ERR; } return GSMS_OK; } diff --git a/src/detector/Detector.cpp b/src/detector/Detector.cpp index 7e8209f..97f1b9a 100644 --- a/src/detector/Detector.cpp +++ b/src/detector/Detector.cpp @@ -1,130 +1,150 @@ +/*************************************************************************** + * Copyright (C) 2009 by P.Voylov * + * [email protected] * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + #include "Detector.h" #include <geant/G4HCofThisEvent.hh> #include <geant/G4Event.hh> #include <geant/G4Step.hh> #include <geant/G4VProcess.hh> #include <geant/G4ThreeVector.hh> #include <geant/G4SDManager.hh> #include <geant/G4ios.hh> GSMS::Detector::Detector(G4String name):G4VSensitiveDetector(name) { G4String HCname; if(name == "innerSD") HCname = "inner"; else HCname = "outer"; collectionName.insert(HCname = G4String("trackerCollection" + HCname)); // G4cout << "Construct: " << HCname << G4endl; } GSMS::Detector::~Detector(){ } void GSMS::Detector::Initialize(G4HCofThisEvent* HCE) { G4String HCname = "trackerCollection"; if(GetName() == "innerSD") HCname = HCname + "inner"; else HCname = HCname + "outer"; trackerCollection = new DetectorHitsCollection (SensitiveDetectorName, HCname); static G4int HCID = -1; if(HCID<0) { HCID = G4SDManager::GetSDMpointer()->GetCollectionID( HCname); } HCE->AddHitsCollection( HCID, trackerCollection ); } G4bool GSMS::Detector::ProcessHits(G4Step* aStep,G4TouchableHistory*) { G4double edep = aStep->GetPostStepPoint()->GetKineticEnergy(); // char edepc[12]; // char edepcpr[12]; // sprintf(edepc,"%f",edep); // edep = aStep->GetPreStepPoint()->GetKineticEnergy(); // sprintf(edepcpr,"%f",edep); G4String sMatPsName = aStep->GetPostStepPoint()->GetMaterial()->GetName(); G4String sMatPrName = aStep->GetPreStepPoint()->GetMaterial()->GetName(); //G4ParticleDefinition* particleType = aStep->GetTrack()->GetDefinition(); //G4String particleName = particleType->GetParticleName(); /* //if(GetName() == "innerSD") //{ G4String sPrName = "undefined"; G4String sPsName = "undefined"; if(aStep->GetPreStepPoint()->GetProcessDefinedStep()) sPrName = aStep->GetPreStepPoint()->GetProcessDefinedStep()->GetProcessName(); if(aStep->GetPostStepPoint()->GetProcessDefinedStep()) sPsName = aStep->GetPostStepPoint()->GetProcessDefinedStep()->GetProcessName(); char xpr[20]; sprintf(xpr,"%.3f;", aStep->GetPreStepPoint()->GetPosition().x()); char ypr[20]; sprintf(ypr,"%.3f;", aStep->GetPreStepPoint()->GetPosition().y()); char zpr[20]; sprintf(zpr,"%.3f - ", aStep->GetPreStepPoint()->GetPosition().z()); char xps[20]; sprintf(xps,"%.3f;", aStep->GetPostStepPoint()->GetPosition().x()); char yps[20]; sprintf(yps,"%.3f;", aStep->GetPostStepPoint()->GetPosition().y()); char zps[20]; sprintf(zps,"%.3f;", aStep->GetPostStepPoint()->GetPosition().z()); sCrystalInfo = sCrystalInfo + GetName() + ": " + particleName + "_" + sMatPrName + "-" + sPrName + "-" + edepcpr + "; " + sMatPsName + "-" + sPsName + "-" + edepc + "; " + G4String(xpr) + G4String(ypr) + G4String(zpr) + G4String(xps) + G4String(yps) + G4String(zps) + "\n"; //}; */ //if( (sMatPsName != sMatPrName) && // particleName == "gamma" && if ( (( GetName() == "innerSD" ) && (sMatPsName == "MgO")) || (( GetName() == "outerSD" ) && (sMatPsName == "CsI" || sMatPsName == "NaI" || sMatPsName == "BGO")) ) { /* sTrackInfo = sTrackInfo + GetName() + "_" + sMatPrName + "_" + sMatPsName + "_" + aStep->GetPostStepPoint()->GetProcessDefinedStep()->GetProcessName() + + G4String(edepc) + "\n"; */ DetectorHit* newHit = new DetectorHit(); newHit->SetTrackID (aStep->GetTrack()->GetTrackID()); newHit->SetChamberNb(aStep->GetPreStepPoint()->GetTouchableHandle()->GetCopyNumber()); newHit->SetEdep (edep); newHit->SetPos (aStep->GetPostStepPoint()->GetPosition()); trackerCollection->insert( newHit ); } return true; } void GSMS::Detector::EndOfEvent(G4HCofThisEvent*) { G4int NbHits = trackerCollection->entries(); dEn = 0.0; for (G4int i=0;i<NbHits;i++) dEn += (*trackerCollection)[i]->GetEdep(); } diff --git a/src/detector/Detector.h b/src/detector/Detector.h index d5d2d41..14ca46c 100644 --- a/src/detector/Detector.h +++ b/src/detector/Detector.h @@ -1,37 +1,57 @@ +/*************************************************************************** + * Copyright (C) 2009 by P.Voylov * + * [email protected] * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + /*!\file Detector.h */ #ifndef DETECTOR_H_ #define DETECTOR_H_ #include <geant/G4VSensitiveDetector.hh> #include "DetectorHit.h" class G4Step; class G4HCofThisEvent; namespace GSMS { class Detector : public G4VSensitiveDetector { public: Detector(G4String); ~Detector(); void Initialize(G4HCofThisEvent*); G4bool ProcessHits(G4Step*, G4TouchableHistory*); void EndOfEvent(G4HCofThisEvent*); G4double GetEnergy() {return dEn;} private: DetectorHitsCollection* trackerCollection; G4double dEn; }; }; /* namespace GSMS*/ #endif /*DETECTOR_H_*/ diff --git a/src/detector/DetectorHit.cpp b/src/detector/DetectorHit.cpp index 5d82365..deb6eef 100644 --- a/src/detector/DetectorHit.cpp +++ b/src/detector/DetectorHit.cpp @@ -1,58 +1,78 @@ +/*************************************************************************** + * Copyright (C) 2009 by P.Voylov * + * [email protected] * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + #include "DetectorHit.h" #include <geant/G4UnitsTable.hh> #include <geant/G4VVisManager.hh> #include <geant/G4Circle.hh> #include <geant/G4Colour.hh> #include <geant/G4VisAttributes.hh> G4Allocator<GSMS::DetectorHit> GSMS::DetectorHitAllocator; GSMS::DetectorHit::DetectorHit() {} GSMS::DetectorHit::~DetectorHit() {} GSMS::DetectorHit::DetectorHit(const GSMS::DetectorHit& right) : G4VHit() { trackID = right.trackID; chamberNb = right.chamberNb; edep = right.edep; pos = right.pos; } const GSMS::DetectorHit& GSMS::DetectorHit::operator=(const GSMS::DetectorHit& right) { trackID = right.trackID; chamberNb = right.chamberNb; edep = right.edep; pos = right.pos; return *this; } G4int GSMS::DetectorHit::operator==(const GSMS::DetectorHit& right) const { return (this==&right) ? 1 : 0; } void GSMS::DetectorHit::Draw() { G4VVisManager* pVVisManager = G4VVisManager::GetConcreteInstance(); if(pVVisManager) { G4Circle circle(pos); circle.SetScreenSize(2.); circle.SetFillStyle(G4Circle::filled); G4Colour colour(1.,0.,0.); G4VisAttributes attribs(colour); circle.SetVisAttributes(attribs); pVVisManager->Draw(circle); } } void GSMS::DetectorHit::Print() { G4cout << " trackID: " << trackID << " chamberNb: " << chamberNb << " energy deposit: " << G4BestUnit(edep,"Energy") << " position: " << G4BestUnit(pos,"Length") << G4endl; } diff --git a/src/detector/DetectorHit.h b/src/detector/DetectorHit.h index 9a17182..cc4b2a1 100644 --- a/src/detector/DetectorHit.h +++ b/src/detector/DetectorHit.h @@ -1,70 +1,90 @@ +/*************************************************************************** + * Copyright (C) 2009 by P.Voylov * + * [email protected] * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + /*!\file DetectorHit.h */ #ifndef DETECTORHIT_H_ #define DETECTORHIT_H_ #include <geant/G4VHit.hh> #include <geant/G4THitsCollection.hh> #include <geant/G4Allocator.hh> #include <geant/G4ThreeVector.hh> namespace GSMS { class DetectorHit : public G4VHit { public: DetectorHit(); ~DetectorHit(); DetectorHit(const DetectorHit&); const DetectorHit& operator=(const DetectorHit&); G4int operator==(const DetectorHit&) const; inline void* operator new(size_t); inline void operator delete(void*); void Draw(); void Print(); public: void SetTrackID (G4int track) { trackID = track; }; void SetChamberNb(G4int chamb) { chamberNb = chamb; }; void SetEdep (G4double de) { edep = de; }; void SetPos (G4ThreeVector xyz){ pos = xyz; }; G4int GetTrackID() { return trackID; }; G4int GetChamberNb() { return chamberNb; }; G4double GetEdep() { return edep; }; G4ThreeVector GetPos(){ return pos; }; private: G4int trackID; G4int chamberNb; G4double edep; G4ThreeVector pos; }; typedef G4THitsCollection<DetectorHit> DetectorHitsCollection; extern G4Allocator<DetectorHit> DetectorHitAllocator; inline void* DetectorHit::operator new(size_t) { void *aHit; aHit = (void *) DetectorHitAllocator.MallocSingle(); return aHit; } inline void DetectorHit::operator delete(void *aHit) { DetectorHitAllocator.FreeSingle((DetectorHit*) aHit); } }; /* namespace GSMS*/ #endif /*DETECTORHIT_H_*/ diff --git a/src/detector/Digi.cpp b/src/detector/Digi.cpp index ca8e792..526517d 100644 --- a/src/detector/Digi.cpp +++ b/src/detector/Digi.cpp @@ -1,39 +1,47 @@ -// -// C++ Implementation: Digi -// -// Description: -// -// -// Author: P.Voylov <[email protected]>, (C) 2009 -// -// Copyright: See COPYING file that comes with this distribution -// -// +/*************************************************************************** + * Copyright (C) 2009 by P.Voylov * + * [email protected] * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ #include "Digi.h" G4Allocator<GSMS::Digi> GSMS::DigiAllocator; void GSMS::Digi::Print() { } void GSMS::Digi::Draw() { } int GSMS::Digi::operator==(const Digi& right) const { return (m_channel == right.m_channel && (m_time == right.m_time)); } const GSMS::Digi& GSMS::Digi::operator=(const GSMS::Digi& right) { m_channel = right.m_channel; m_time = right.m_time; } GSMS::Digi::Digi(const GSMS::Digi& right) : G4VDigi() { m_channel = right.m_channel; m_time = right.m_time; } GSMS::Digi::~Digi() {} GSMS::Digi::Digi() : m_channel(0L), m_time(0.0) {} \ No newline at end of file diff --git a/src/detector/Digi.h b/src/detector/Digi.h index 16eb315..9676203 100644 --- a/src/detector/Digi.h +++ b/src/detector/Digi.h @@ -1,67 +1,76 @@ -// -// C++ Interface: Digi -// -// Description: -// -// -// Author: P.Voylov <[email protected]>, (C) 2009 -// -// Copyright: See COPYING file that comes with this distribution -// -// +/*************************************************************************** + * Copyright (C) 2009 by P.Voylov * + * [email protected] * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + #ifndef DIGI_H_ #define DIGI_H_ #include <geant/G4VDigi.hh> #include <geant/G4TDigiCollection.hh> #include <geant/G4Allocator.hh> #include <geant/G4ThreeVector.hh> namespace GSMS { class Digi : public G4VDigi { public: Digi(); ~Digi(); Digi(const Digi&); const Digi& operator=(const Digi&); int operator==(const Digi&) const; inline void* operator new(size_t); inline void operator delete(void*); void Draw(); void Print(); private: G4double m_time; G4double m_ene; G4int m_channel; public: inline void set_time(G4double time) {m_time = time;} inline void set_ene(G4double ene) {m_ene = ene;} inline void set_channel(G4int ch) {m_channel = ch;} inline G4double get_time() {return m_time;} inline G4double get_ene() {return m_ene;} inline G4int get_channel() {return m_channel;} }; typedef G4TDigiCollection<Digi> DigitsCollection; extern G4Allocator<Digi> DigiAllocator; inline void* Digi::operator new(size_t) { void* aDigi; aDigi = (void*) DigiAllocator.MallocSingle(); return aDigi; } inline void Digi::operator delete(void* aDigi) { DigiAllocator.FreeSingle((Digi*) aDigi); } } #endif \ No newline at end of file diff --git a/src/detector/Digitizer.cpp b/src/detector/Digitizer.cpp index e2c394a..38cb953 100644 --- a/src/detector/Digitizer.cpp +++ b/src/detector/Digitizer.cpp @@ -1,82 +1,90 @@ -// -// C++ Implementation: Digitizer -// -// Description: -// -// -// Author: P.Voylov <[email protected]>, (C) 2009 -// -// Copyright: See COPYING file that comes with this distribution -// -// +/*************************************************************************** + * Copyright (C) 2009 by P.Voylov * + * [email protected] * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ #include "Digitizer.h" #include <geant/G4EventManager.hh> #include <geant/G4Event.hh> #include <geant/G4SDManager.hh> #include <geant/G4DigiManager.hh> #include <geant/G4Poisson.hh> #include <geant/G4ios.hh> #include <vector> GSMS::Digitizer::Digitizer(G4String name) : G4VDigitizerModule(name), m_dnu(10), m_stime(0.0), m_etime(10.0) { G4String colName = "DigitsCollection"; collectionName.push_back(colName); } GSMS::Digitizer::~Digitizer() {} void GSMS::Digitizer::Digitize() { m_coll = new DigitsCollection("GSMSDigitizer", "DigitsCollection"); G4DigiManager* digiMan = G4DigiManager::GetDMpointer(); G4int hCollID = digiMan->GetHitsCollectionID("eDep"); G4THitsMap<G4double>* evtMap = NULL; evtMap = (G4THitsMap<G4double>*)(digiMan->GetHitsCollection(hCollID)); if(!evtMap) return; std::map<G4int, G4double*>::iterator itr = evtMap->GetMap()->begin(); for(; itr != evtMap->GetMap()->end(); itr++) { G4double eneDep = *(itr->second); G4double eneChan = 0; // if (eneChan > 10.) // { double dResCs137 = 0.085;//ResolutionScale; G4double dResA = std::sqrt(0.662)*dResCs137; double dRes = dResA/std::sqrt(eneDep);//ResolutionScale; G4double sigma = dRes*eneDep/2.355; // std::cerr << "Mean: " << eneDep << ", Sigma: " << sigma << ", Res: " << dRes; eneChan = G4RandGauss::shoot(eneDep,sigma) / 3 * 1024; // std::cerr << ", Value: " << eneChan << std::endl; // } // else // { // eneChan = G4int(G4Poisson(eneChan)); // }; // std::cerr << ", Channel: " << eneChan; G4double time = G4UniformRand() * (m_etime - m_stime); if(eneChan >= m_dnu) { Digi* digi = new Digi; digi->set_time(time); digi->set_channel(int(eneChan)); digi->set_ene(eneDep); m_coll->insert(digi); } } StoreDigiCollection(m_coll); } diff --git a/src/detector/Digitizer.h b/src/detector/Digitizer.h index e29aba5..cb8942e 100644 --- a/src/detector/Digitizer.h +++ b/src/detector/Digitizer.h @@ -1,45 +1,53 @@ -// -// C++ Interface: Digitizer -// -// Description: -// -// -// Author: P.Voylov <[email protected]>, (C) 2009 -// -// Copyright: See COPYING file that comes with this distribution -// -// +/*************************************************************************** + * Copyright (C) 2009 by P.Voylov * + * [email protected] * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ #ifndef DIGITIZER_H_ #define DIGITIZER_H_ #include <geant/G4THitsMap.hh> #include <geant/G4VDigitizerModule.hh> #include "detector/Digi.h" #include <geant/globals.hh> namespace GSMS { class Digitizer : public G4VDigitizerModule { public: Digitizer(G4String name); ~Digitizer(); void Digitize(); void set_DNU(G4int dnu) {m_dnu = dnu;} private: G4int m_dnu; DigitsCollection* m_coll; G4double m_stime; G4double m_etime; G4double m_intensity; }; } #endif \ No newline at end of file diff --git a/src/generator/Generator.cpp b/src/generator/Generator.cpp index d5ed156..ff66526 100644 --- a/src/generator/Generator.cpp +++ b/src/generator/Generator.cpp @@ -1,130 +1,150 @@ +/*************************************************************************** + * Copyright (C) 2009 by P.Voylov * + * [email protected] * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + #include "Generator.h" #include <geant/G4Gamma.hh> #include "generator/SourceLib.h" #include "config/GSMS.h" /* void AddCs137(G4GeneralParticleSource* dst) { dst->SetParticleDefinition(G4Gamma::Gamma()); G4SingleParticleSource* src = dst->GetCurrentSource(); src->GetEneDist()->SetMonoEnergy(0.032); src->GetAngDist()->SetAngDistType("iso"); src->GetPosDist()->SetPosDisType("Point"); src->GetEneDist()->SetEnergyDisType("Mono"); src->GetPosDist()->SetCentreCoords(G4ThreeVector(0.,1.*m,0.)); src->GetAngDist()->SetMinPhi(pi/2); src->GetAngDist()->SetMaxPhi(pi/2); src->GetAngDist()->SetMinTheta(pi/2); src->GetAngDist()->SetMaxTheta(pi/2); dst->AddaSource(0.014); dst->SetParticleDefinition(G4Gamma::Gamma()); src = dst->GetCurrentSource(); src->GetEneDist()->SetMonoEnergy(0.036); src->GetAngDist()->SetAngDistType("iso"); src->GetPosDist()->SetPosDisType("Point"); src->GetEneDist()->SetEnergyDisType("Mono"); src->GetPosDist()->SetCentreCoords(G4ThreeVector(0.,1.*m,0.)); src->GetAngDist()->SetMinPhi(pi/2); src->GetAngDist()->SetMaxPhi(pi/2); src->GetAngDist()->SetMinTheta(pi/2); src->GetAngDist()->SetMaxTheta(pi/2); dst->AddaSource(0.9); dst->SetParticleDefinition(G4Gamma::Gamma()); src = dst->GetCurrentSource(); src->GetEneDist()->SetMonoEnergy(0.662); src->GetAngDist()->SetAngDistType("iso"); src->GetPosDist()->SetPosDisType("Point"); src->GetEneDist()->SetEnergyDisType("Mono"); src->GetPosDist()->SetCentreCoords(G4ThreeVector(0.,1.*m,0.)); src->GetAngDist()->SetMinPhi(pi/2); src->GetAngDist()->SetMaxPhi(pi/2); src->GetAngDist()->SetMinTheta(pi/2); src->GetAngDist()->SetMaxTheta(pi/2); } void AddCo60(G4GeneralParticleSource* dst) { dst->AddaSource(1.0); dst->SetParticleDefinition(G4Gamma::Gamma()); G4SingleParticleSource* src = dst->GetCurrentSource(); src->GetEneDist()->SetMonoEnergy(1.173); src->GetAngDist()->SetAngDistType("iso"); src->GetPosDist()->SetPosDisType("Point"); src->GetEneDist()->SetEnergyDisType("Mono"); src->GetPosDist()->SetCentreCoords(G4ThreeVector(1.*m,0.,0.)); src->GetAngDist()->SetMinPhi(0.); src->GetAngDist()->SetMaxPhi(0.); src->GetAngDist()->SetMinTheta(pi/2); src->GetAngDist()->SetMaxTheta(pi/2); dst->AddaSource(1.0); dst->SetParticleDefinition(G4Gamma::Gamma()); src = dst->GetCurrentSource(); src->GetEneDist()->SetMonoEnergy(1.332); src->GetAngDist()->SetAngDistType("iso"); src->GetPosDist()->SetPosDisType("Point"); src->GetEneDist()->SetEnergyDisType("Mono"); src->GetPosDist()->SetCentreCoords(G4ThreeVector(0.,-1.*m,0.)); src->GetAngDist()->SetMinPhi(-pi/2); src->GetAngDist()->SetMaxPhi(-pi/2); src->GetAngDist()->SetMinTheta(pi/2); src->GetAngDist()->SetMaxTheta(pi/2); } void AddCo57(G4GeneralParticleSource* dst) { dst->AddaSource(0.855); dst->SetParticleDefinition(G4Gamma::Gamma()); G4SingleParticleSource* src = dst->GetCurrentSource(); src->GetEneDist()->SetMonoEnergy(0.122); src->GetAngDist()->SetAngDistType("iso"); src->GetPosDist()->SetPosDisType("Point"); src->GetEneDist()->SetEnergyDisType("Mono"); src->GetPosDist()->SetCentreCoords(G4ThreeVector(1.*m,0.,0.)); src->GetAngDist()->SetMinPhi(0.); src->GetAngDist()->SetMaxPhi(0.); src->GetAngDist()->SetMinTheta(pi/2); src->GetAngDist()->SetMaxTheta(pi/2); dst->AddaSource(0.106); dst->SetParticleDefinition(G4Gamma::Gamma()); src = dst->GetCurrentSource(); src->GetEneDist()->SetMonoEnergy(0.136); src->GetAngDist()->SetAngDistType("iso"); src->GetPosDist()->SetPosDisType("Point"); src->GetEneDist()->SetEnergyDisType("Mono"); src->GetPosDist()->SetCentreCoords(G4ThreeVector(1.*m,0.,0.)); src->GetAngDist()->SetMinPhi(0.); src->GetAngDist()->SetMaxPhi(0.); src->GetAngDist()->SetMinTheta(pi/2); src->GetAngDist()->SetMaxTheta(pi/2); } */ GSMS::Generator::Generator() { mp_gps = new G4GeneralParticleSource; } void GSMS::Generator::Update() { mp_gps->ClearAll(); std::vector<Source>::iterator it = GSMS::get_job().get_source_iterator(); for(int i=0; i< GSMS::get_job().get_source_count(); i++, it++) (*it).generate_G4(mp_gps); } GSMS::Generator::~Generator() { delete mp_gps; } void GSMS::Generator::GeneratePrimaries(G4Event* anEvent) { mp_gps->GeneratePrimaryVertex(anEvent); } diff --git a/src/generator/Generator.h b/src/generator/Generator.h index 489edcd..699575f 100644 --- a/src/generator/Generator.h +++ b/src/generator/Generator.h @@ -1,27 +1,47 @@ +/*************************************************************************** + * Copyright (C) 2009 by P.Voylov * + * [email protected] * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + /*!\file Generator.h */ #ifndef GENERATOR_H_ #define GENERATOR_H_ #include <geant/G4GeneralParticleSource.hh> #include <geant/G4VUserPrimaryGeneratorAction.hh> #include "generator/SourceLib.h" #include "generator/Source.h" namespace GSMS { class Generator : public G4VUserPrimaryGeneratorAction { G4GeneralParticleSource* mp_gps; public: Generator(); ~Generator(); void GeneratePrimaries(G4Event* anEvent); void Update(); }; }; /*namespace GSMS*/ #endif /*GENERATOR_H_*/ diff --git a/src/generator/Source.cpp b/src/generator/Source.cpp index d45ad7c..598d3c1 100644 --- a/src/generator/Source.cpp +++ b/src/generator/Source.cpp @@ -1,59 +1,79 @@ +/*************************************************************************** + * Copyright (C) 2009 by P.Voylov * + * [email protected] * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + #include "Source.h" #include <sys/stat.h> #include <sys/types.h> #include <geant/G4Gamma.hh> unsigned int GSMS::Source::save(std::ofstream* stream) { Source* pSource = this; boost::archive::xml_oarchive out(*stream); out << BOOST_SERIALIZATION_NVP(pSource); } void GSMS::Source::generate_G4(G4GeneralParticleSource* dst, G4double dAngle) { if (!dst) return; for(int i=0; i<m_gamma.size(); i++) { G4float ene = m_gamma[i].first; G4float act = m_gamma[i].second; dst->AddaSource(act); dst->SetParticleDefinition(G4Gamma::Gamma()); G4SingleParticleSource* src = dst->GetCurrentSource(); src->GetEneDist()->SetMonoEnergy(ene); src->GetAngDist()->SetAngDistType("iso"); src->GetPosDist()->SetPosDisType("Point"); src->GetEneDist()->SetEnergyDisType("Mono"); //src->GetPosDist()->SetCentreCoords(get_coords()); //src->GetPosDist()->SetCentreCoords(G4ThreeVector(1., 0., 0.)); src->GetPosDist()->SetCentreCoords(G4ThreeVector(m_X, m_Y, m_Z)); G4double basePhi = 0.0; m_X != 0.0 ? basePhi = std::atan(m_Y/m_X) : m_Y > 0 ? basePhi = pi/2 : basePhi = -pi/2; std::cerr << "X: " << m_X << " Y: " << m_Y << " Phi: " << basePhi << std::endl; G4double dPhi = 0.0; G4double baseTheta = pi/2;//TODO G4double dTheta = 0.0; src->GetAngDist()->SetMinPhi(basePhi - dPhi); src->GetAngDist()->SetMaxPhi(basePhi + dPhi); src->GetAngDist()->SetMinTheta(baseTheta - dTheta); src->GetAngDist()->SetMaxTheta(baseTheta + dTheta); std::cerr << ene << std::endl; std::cerr << act << std::endl; } } void GSMS::Source::normalize_activities() { G4double summ = 0.0; for(int i=0; i<m_gamma.size(); i++) summ += m_gamma[i].second; for(int i=0; i<m_gamma.size(); i++) m_gamma[i].second = m_gamma[i].second/summ; } \ No newline at end of file diff --git a/src/generator/database/Database.cpp b/src/generator/database/Database.cpp index 4a89f93..cb61c35 100755 --- a/src/generator/database/Database.cpp +++ b/src/generator/database/Database.cpp @@ -1,60 +1,80 @@ +/*************************************************************************** + * Copyright (C) 2009 by P.Voylov * + * [email protected] * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + #include <sstream> #include "Database.h" #include "DatabaseTransaction.h" #include <pqxx/binarystring> #include "database_exception.h" using namespace util; Database::Database(const char *hostname, const int port, const char *username, const char *password, const char *database, const char *socket) throw (DatabaseException) { if(hostname == NULL) throw __DB_EXCEPTION(__ERR_DB_HOST_MISSING); if(database == NULL) throw __DB_EXCEPTION(__ERR_DB_DATABASE_MISSING); if(username == NULL) throw __DB_EXCEPTION(__ERR_DB_USERNAME_MISSING); std::stringstream dbi; int nport = port; if(nport == 0) nport = 5432; dbi << "host=" << hostname << " port="; if(socket != NULL) dbi << socket; else dbi << nport; dbi << " dbname=" << database << " user=" << username; if(password != NULL) dbi << " password=" << password; try { m_connection = new pqxx::connection(dbi.str()); if(!m_connection->is_open()) m_connection->activate(); } catch(pqxx::broken_connection &error) { throw __DB_EXCEPTION(__ERR_DB_BROKEN_CONN); } m_transaction = NULL; } Database::~Database() { if(m_connection) delete m_connection; if(m_transaction) delete m_transaction; } DatabaseTransaction Database::transaction() { return DatabaseTransaction(this); } diff --git a/src/generator/database/Database.h b/src/generator/database/Database.h index 27dfde5..fefacb3 100755 --- a/src/generator/database/Database.h +++ b/src/generator/database/Database.h @@ -1,34 +1,54 @@ +/*************************************************************************** + * Copyright (C) 2009 by P.Voylov * + * [email protected] * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + #ifndef DATABASE_H_ #define DATABASE_H_ #include <pqxx/connection> #include <pqxx/transaction> #include <boost/shared_ptr.hpp> class DatabaseTransaction; class DatabaseQuery; #include "config/Exception.h" class Database { private: pqxx::connection* m_connection; pqxx::work* m_transaction; friend class DatabaseTransaction; friend class DatabaseQuery; public: Database(const char *hostname = "localhost", const int port = 5432, const char *username = "postgres", const char *password = NULL, const char *database = "postgres", const char *socket = NULL) throw (util::DatabaseException); virtual ~Database(); DatabaseTransaction transaction(); }; typedef boost::shared_ptr<Database> DatabasePtr; #endif /* DATABASE_H_ */ diff --git a/src/generator/database/DatabaseField.cpp b/src/generator/database/DatabaseField.cpp index c8552b2..02b8df5 100755 --- a/src/generator/database/DatabaseField.cpp +++ b/src/generator/database/DatabaseField.cpp @@ -1 +1,21 @@ +/*************************************************************************** + * Copyright (C) 2009 by P.Voylov * + * [email protected] * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + #include "DatabaseField.h" diff --git a/src/generator/database/DatabaseField.h b/src/generator/database/DatabaseField.h index 1af769b..728b407 100755 --- a/src/generator/database/DatabaseField.h +++ b/src/generator/database/DatabaseField.h @@ -1,10 +1,30 @@ +/*************************************************************************** + * Copyright (C) 2009 by P.Voylov * + * [email protected] * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + #ifndef DATABASEFIELD_H_ #define DATABASEFIELD_H_ #include "typedefs.h" #include <pqxx/result> typedef pqxx::result::field DatabaseField; #endif /* DATABASEFIELD_H_ */ diff --git a/src/generator/database/DatabaseIterator.cpp b/src/generator/database/DatabaseIterator.cpp index e5fbe2e..6204a6c 100755 --- a/src/generator/database/DatabaseIterator.cpp +++ b/src/generator/database/DatabaseIterator.cpp @@ -1,15 +1,35 @@ +/*************************************************************************** + * Copyright (C) 2009 by P.Voylov * + * [email protected] * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + #include "DatabaseIterator.h" #include "DatabaseRow.h" DatabaseIterator::DatabaseIterator() : pqxx::result::const_iterator() { } DatabaseIterator::DatabaseIterator(const pqxx::result::const_iterator& iterator) : pqxx::result::const_iterator(iterator) { } DatabaseRow DatabaseIterator::operator*() { return DatabaseRow(*this); } diff --git a/src/generator/database/DatabaseIterator.h b/src/generator/database/DatabaseIterator.h index 29cf66c..ba99562 100755 --- a/src/generator/database/DatabaseIterator.h +++ b/src/generator/database/DatabaseIterator.h @@ -1,15 +1,35 @@ +/*************************************************************************** + * Copyright (C) 2009 by P.Voylov * + * [email protected] * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + #ifndef DATABASEITERATOR_H_ #define DATABASEITERATOR_H_ #include <pqxx/result> #include "DatabaseRow.h" class DatabaseIterator : public pqxx::result::const_iterator { public: DatabaseIterator(); DatabaseIterator(const pqxx::result::const_iterator&); DatabaseRow operator*(); }; #endif /* DATABASEITERATOR_H_ */ diff --git a/src/generator/database/DatabaseQuery.cpp b/src/generator/database/DatabaseQuery.cpp index 660e4d3..56e9b25 100755 --- a/src/generator/database/DatabaseQuery.cpp +++ b/src/generator/database/DatabaseQuery.cpp @@ -1,127 +1,147 @@ +/*************************************************************************** + * Copyright (C) 2009 by P.Voylov * + * [email protected] * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + #include <iostream> #include <algorithm> #include <pqxx/prepared_statement> #include "DatabaseQuery.h" #include "DatabaseResult.h" #include "DatabaseTransaction.h" #include "database_exception.h" DatabaseQuery::DatabaseQuery() { m_transaction = NULL; } DatabaseQuery::DatabaseQuery(DatabaseTransaction *transaction, const std::string &query) : m_query(query) { m_transaction = transaction; prepare(); } DatabaseQuery::~DatabaseQuery() { } void DatabaseQuery::prepare() { m_operator = std::string(m_query); size_t pos = m_operator.find_first_not_of(" "); if (pos != std::string::npos) m_operator.erase(0, int(pos)); pos = m_operator.find(" "); if (pos != std::string::npos) m_operator.erase(pos); std::transform(m_operator.begin(), m_operator.end(), m_operator.begin(), toupper); } DatabaseQuery &DatabaseQuery::operator=(const DatabaseQuery &rhs) { if (m_transaction != rhs.m_transaction) m_transaction = rhs.m_transaction; m_query = std::string(rhs.m_query); m_arg = rhs.m_arg; m_null = rhs.m_null; m_quotes = rhs.m_quotes; prepare(); return *this; } size_t DatabaseQuery::exec(DatabaseResult &result) throw (util::DatabaseException) { if (m_transaction == NULL) throw __DB_EXCEPTION(__ERR_DB_NULL_TRANSACTION); size_t rows = 0; std::string query = std::string(m_query); std::vector<std::string::size_type> pos; std::string::size_type p = -1; do { p = query.find("?", p + 1); if (p != std::string::npos) pos.push_back(p); } while (p != std::string::npos); if (pos.size() != m_arg.size()) { throw __DB_EXCEPTION(__ERR_DB_ARGUMENT_COUNT); } while (pos.size() > 0) { p = pos.back(); if (m_null.back() == true) { query.replace(p, 1, "NULL"); } else { query.replace(p, 1, m_quotes.back() ? "'" + m_arg.back() + "'" : m_arg.back()); } pos.pop_back(); m_quotes.pop_back(); m_null.pop_back(); m_arg.pop_back(); } m_executed_query = query; try { std::cerr << query << std::endl; result = DatabaseResult(m_transaction->m_transaction->exec(query)); if (m_operator == "SELECT") { rows = result.size(); } else if (m_operator == "UPDATE" || m_operator == "DELETE" || m_operator == "INSERT") { rows = result.affected_rows(); } m_arg.clear(); m_null.clear(); m_quotes.clear(); return rows; } catch (pqxx::broken_connection &error) { throw __DB_EXCEPTION(__ERR_DB_BROKEN_CONN); } catch (pqxx::sql_error &error) { throw __DB_EXCEPTION(__ERR_DB_SQL_MALFORMED); } return rows; } size_t DatabaseQuery::exec() { DatabaseResult result; return exec(result); } DatabaseQuery::DatabaseQuery& DatabaseQuery::operator()() { m_arg.push_back(""); m_null.push_back(true); m_quotes.push_back(false); return *this; } DatabaseQuery::DatabaseQuery& DatabaseQuery::raw(const std::string &v) { std::ostringstream value; value << "E'" << m_transaction->m_transaction->esc_raw(v) << "'"; m_arg.push_back(value.str()); m_null.push_back(false); m_quotes.push_back(false); return *this; } std::string DatabaseQuery::query() { return m_executed_query; } diff --git a/src/generator/database/DatabaseQuery.h b/src/generator/database/DatabaseQuery.h index dbe4807..340ed99 100755 --- a/src/generator/database/DatabaseQuery.h +++ b/src/generator/database/DatabaseQuery.h @@ -1,70 +1,90 @@ +/*************************************************************************** + * Copyright (C) 2009 by P.Voylov * + * [email protected] * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + #ifndef DATABASEQUERY_H_ #define DATABASEQUERY_H_ #include <vector> #include <pqxx/transaction> #include "DatabaseTransaction.h" #include "DatabaseResult.h" #include "config/Exception.h" class DatabaseQuery { private: DatabaseTransaction* m_transaction; std::string m_operator; std::string m_query; std::string m_executed_query; std::vector<std::string> m_arg; std::vector<bool> m_quotes; std::vector<bool> m_null; void prepare(); friend class DatabaseTransaction; public: /** * Query constructor * * @param[in] Database *db * @param[in] const std::string query * @return DatabaseQuery */ DatabaseQuery(); DatabaseQuery(DatabaseTransaction *transaction, const std::string &query); ~DatabaseQuery(); DatabaseQuery& operator=(const DatabaseQuery &); DatabaseQuery& operator()(); template<typename T> DatabaseQuery& num(const T &v) { m_arg.push_back(pqxx::to_string(v)); m_null.push_back(false); m_quotes.push_back(false); return *this; } template<typename T> DatabaseQuery& str(const T &v) { m_arg.push_back(m_transaction->m_transaction->esc(pqxx::to_string(v))); m_null.push_back(false); m_quotes.push_back(true); return *this; } DatabaseQuery& raw(const std::string &v); size_t exec(); size_t exec(DatabaseResult &res) throw (util::DatabaseException); std::string query(); }; #endif /* DATABASEQUERY_H_ */ diff --git a/src/generator/database/DatabaseResult.cpp b/src/generator/database/DatabaseResult.cpp index 705d56c..a4a1e2e 100755 --- a/src/generator/database/DatabaseResult.cpp +++ b/src/generator/database/DatabaseResult.cpp @@ -1,20 +1,40 @@ +/*************************************************************************** + * Copyright (C) 2009 by P.Voylov * + * [email protected] * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + #include "DatabaseResult.h" #include "DatabaseRow.h" DatabaseResult::DatabaseResult() : pqxx::result() { } DatabaseResult::DatabaseResult(const pqxx::result& result) : pqxx::result(result) { } DatabaseIterator DatabaseResult::begin() { return DatabaseIterator(pqxx::result::begin()); } DatabaseIterator DatabaseResult::end() { return DatabaseIterator(pqxx::result::end()); } diff --git a/src/generator/database/DatabaseResult.h b/src/generator/database/DatabaseResult.h index d142daf..8effac3 100755 --- a/src/generator/database/DatabaseResult.h +++ b/src/generator/database/DatabaseResult.h @@ -1,17 +1,37 @@ +/*************************************************************************** + * Copyright (C) 2009 by P.Voylov * + * [email protected] * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + #ifndef DATABASERESULT_H_ #define DATABASERESULT_H_ #include <pqxx/result> #include "typedefs.h" #include "DatabaseIterator.h" class DatabaseResult : public pqxx::result { public: DatabaseResult(); DatabaseResult(const pqxx::result&); DatabaseIterator begin(); DatabaseIterator end(); }; #endif /* DATABASERESULT_H_ */ diff --git a/src/generator/database/DatabaseRow.cpp b/src/generator/database/DatabaseRow.cpp index 99805fa..29cdfa4 100755 --- a/src/generator/database/DatabaseRow.cpp +++ b/src/generator/database/DatabaseRow.cpp @@ -1 +1,21 @@ +/*************************************************************************** + * Copyright (C) 2009 by P.Voylov * + * [email protected] * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + #include "DatabaseRow.h" diff --git a/src/generator/database/DatabaseRow.h b/src/generator/database/DatabaseRow.h index e10bb6d..63d86b6 100755 --- a/src/generator/database/DatabaseRow.h +++ b/src/generator/database/DatabaseRow.h @@ -1,11 +1,31 @@ +/*************************************************************************** + * Copyright (C) 2009 by P.Voylov * + * [email protected] * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + #ifndef DATABASEROW_H_ #define DATABASEROW_H_ #include <pqxx/result> #include "typedefs.h" typedef pqxx::result::tuple DatabaseRow; //typedef pqxx::result::const_iterator DatabaseIterator; #endif /* DATABASEROW_H_ */ diff --git a/src/generator/database/DatabaseTransaction.cpp b/src/generator/database/DatabaseTransaction.cpp index 4a3a9ad..ee6270a 100755 --- a/src/generator/database/DatabaseTransaction.cpp +++ b/src/generator/database/DatabaseTransaction.cpp @@ -1,58 +1,78 @@ +/*************************************************************************** + * Copyright (C) 2009 by P.Voylov * + * [email protected] * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + #include "DatabaseTransaction.h" #include "DatabaseQuery.h" #include "DatabaseField.h" #include "Database.h" #include <pqxx/binarystring> #include "database_exception.h" DatabaseTransaction::DatabaseTransaction() { m_transaction = NULL; } DatabaseTransaction::DatabaseTransaction(Database *database) { m_transaction = new pqxx::work(*database->m_connection); } DatabaseTransaction::~DatabaseTransaction() { if(m_transaction != NULL) { m_transaction->abort(); delete m_transaction; } } DatabaseTransaction &DatabaseTransaction::operator=(DatabaseTransaction &rhs) { if(m_transaction != rhs.m_transaction); m_transaction = rhs.m_transaction; return *this; } DatabaseQuery DatabaseTransaction::query(const std::string &query) throw (util::DatabaseException) { if(m_transaction != NULL) return DatabaseQuery(this, query); else throw __DB_EXCEPTION(__ERR_DB_NULL_TRANSACTION); } void DatabaseTransaction::commit() { m_transaction->commit(); delete m_transaction; m_transaction = NULL; } void DatabaseTransaction::rollback() { m_transaction->abort(); delete m_transaction; m_transaction = NULL; } std::string DatabaseTransaction::unescape_byte(DatabaseField &field) { pqxx::binarystring converter(field); std::ostringstream buf; buf.write(converter.c_ptr(), converter.size()); return buf.str(); } diff --git a/src/generator/database/DatabaseTransaction.h b/src/generator/database/DatabaseTransaction.h index 52ee427..aa9894d 100755 --- a/src/generator/database/DatabaseTransaction.h +++ b/src/generator/database/DatabaseTransaction.h @@ -1,34 +1,54 @@ +/*************************************************************************** + * Copyright (C) 2009 by P.Voylov * + * [email protected] * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + #ifndef DATABASETRANSACTION_H_ #define DATABASETRANSACTION_H_ #include <pqxx/transaction> #include "DatabaseField.h" #include <boost/shared_ptr.hpp> class Database; class DatabaseQuery; #include "config/Exception.h" class DatabaseTransaction { private: pqxx::work *m_transaction; friend class DatabaseQuery; public: DatabaseTransaction(); DatabaseTransaction(Database *database); virtual ~DatabaseTransaction(); DatabaseTransaction &operator=(DatabaseTransaction &); DatabaseQuery query(const std::string &query) throw (util::DatabaseException); void commit(); void rollback(); std::string unescape_byte(DatabaseField &field); }; typedef boost::shared_ptr<DatabaseTransaction> DatabaseTransactionPtr; #endif /* DATABASETRANSACTION_H_ */ diff --git a/src/geometry/Geometry.cpp b/src/geometry/Geometry.cpp index 7a69853..21ca01a 100644 --- a/src/geometry/Geometry.cpp +++ b/src/geometry/Geometry.cpp @@ -1,512 +1,532 @@ +/*************************************************************************** + * Copyright (C) 2009 by P.Voylov * + * [email protected] * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + #include "Geometry.h" #include "config/GSMS.h" #include <geant/G4Material.hh> #include <geant/G4MaterialTable.hh> #include <geant/G4Element.hh> #include <geant/G4Isotope.hh> #include <geant/G4UnitsTable.hh> #include <geant/G4Box.hh> #include <geant/G4Cons.hh> #include <geant/G4Tubs.hh> #include <geant/G4Sphere.hh> #include <geant/G4UnionSolid.hh> #include <geant/G4SubtractionSolid.hh> #include <geant/G4LogicalVolume.hh> #include <geant/G4PVPlacement.hh> #include <geant/G4ThreeVector.hh> #include <geant/G4RotationMatrix.hh> #include <geant/G4Transform3D.hh> #include <geant/G4LogicalBorderSurface.hh> #include <geant/G4LogicalSkinSurface.hh> #include <geant/G4OpBoundaryProcess.hh> #include <geant/G4FieldManager.hh> #include <geant/G4UniformElectricField.hh> #include <geant/G4TransportationManager.hh> #include <geant/G4MagIntegratorStepper.hh> #include <geant/G4EqMagElectricField.hh> #include <geant/G4ClassicalRK4.hh> #include <geant/G4ChordFinder.hh> #include <geant/G4VisAttributes.hh> #include <geant/G4Colour.hh> #include <geant/G4RunManager.hh> #include <geant/G4SDManager.hh> #include <geant/G4HCtable.hh> G4VPhysicalVolume* GSMS::Geometry::Construct() { std::cerr << "Construct" << std::endl; G4double new_time = 0; if( __SUCCEEDED(GSMS::imprintDetector(m_world)) && __SUCCEEDED(GSMS::setTime(&new_time)) && __SUCCEEDED(GSMS::imprintMask(m_world)) ) return m_world; else return NULL; } bool GSMS::Geometry::Update() { std::cerr << "Update" << std::endl; if( __SUCCEEDED(GSMS::imprintMask(m_world)) ) return true; else return false; } unsigned int GSMS::Geometry::defineMaterials() { G4double density,// density a, // atomic mass z; // atomic number G4double G4d_density; // G4double G4d_temp; // G4double G4d_press; G4int nelements; G4String G4s_name; G4String G4s_symbol; G4int G4i_ncomp; G4Element* H = new G4Element("Hydrogen", "H", z=1., a=1.0079*g/mole); G4Element* C = new G4Element("Carbon", "C", z=6., a=12.011*g/mole); G4Element* N = new G4Element("Nitrogen", "N", 7., 14.00674*g/mole); G4Element* O = new G4Element("Oxygen", "O", 8., 16.00000*g/mole); G4Element* Na = new G4Element("Natrium", "Na", z=11., a=22.98977*g/mole); G4Element* Mg = new G4Element("Magnezium", "Mg", z=12., a=24.305*g/mole); G4Element* Al = new G4Element("Aluminium", "Al", z=13., a=26.981*g/mole); G4Element* Si = new G4Element("Silicium", "Si", z=14., a=28.086*g/mole); G4Element* P = new G4Element("Phosphorus", "P", z=15., a=30.973976*g/mole); G4Element* S = new G4Element("Sulfur", "S", z=16., a=32.06*g/mole); G4Element* Cl = new G4Element("Chlorine","Cl", z=17., a=35.453*g/mole); G4Element* K = new G4Element("Kalium", "K", z=19., a=39.098*g/mole); G4Element* Ca = new G4Element("Calcium", "Ca", z=20., a=40.08*g/mole); G4Element* Ti = new G4Element("Titanium", "Ti", z=22., a=47.9*g/mole); G4Element* Cr = new G4Element("Chrome", "Cr", z=24., a=51.996*g/mole); G4Element* Mn = new G4Element("Manganeze", "Mn", z=25., a=54.938*g/mole); G4Element* Fe = new G4Element("Ferrum", "Fe", z=26., a=55.847*g/mole); G4Element* Ni = new G4Element("Nickel", "Ni", z=28., a=58.7*g/mole); G4Element* Cu = new G4Element("Cuprum", "Cu", z=29., a=63.546*g/mole); G4Element* Zn = new G4Element("Zyncum", "Zn", z=30., a=65.38*g/mole); G4Element* Ge = new G4Element("Germanium", "Ge", z=32., a=72.59*g/mole); G4Element* Ag = new G4Element("Argentum", "Ag", z=47., a=107.8682*g/mole); G4Element* I = new G4Element("Iodine", "I", z=53., a=126.904*g/mole); G4Element* Cs = new G4Element("Cesium", "Cs", z=55., a=132.905*g/mole); G4Element* Ba = new G4Element("Barium", "Ba", z=56., a=133.*g/mole); G4Element* W = new G4Element("Wolfram", "W", z=74., a=183.85*g/mole); G4Element* Pt = new G4Element("Platinum", "Pt", z=78., a=195.08*g/mole); G4Element* Au = new G4Element("Aurum", "Au", z=79., a=196.9665*g/mole); G4Element* Pb = new G4Element("Plumbum", "Pb", z=82., a=207.2*g/mole); G4Element* Bi = new G4Element("Bismuth", "Bi", z=83., a=208.9804*g/mole); G4Material* mptr; std::string name; try { //vacuum name = "Vacuum"; mptr = new G4Material( name.c_str(), //name 1, //components 1.00794*g/mole, //1st component a/weight 1.0E-25*g/cm3, //density kStateGas, //state 0.1*kelvin, //temp 1.0E-19*pascal);//pressure m_materials.insert(std::pair<std::string,G4Material*>(name,mptr)); //air name = "Air"; mptr = new G4Material( name, 1.2929*kg/m3, 2, kStateGas, 300.00*kelvin, 1.0*atmosphere); mptr->AddElement(N, 0.8); mptr->AddElement(O, 0.2); m_materials.insert(std::pair<std::string,G4Material*>(name,mptr)); //aluminium name = "Aluminium"; mptr = new G4Material( name, 2.8*g/cm3, 1); mptr->AddElement(Al, 1); m_materials.insert(std::pair<std::string,G4Material*>(name,mptr)); //lead name = "Lead"; mptr = new G4Material( name, 11.336*g/cm3, 1); mptr->AddElement(Pb, 1); m_materials.insert(std::pair<std::string,G4Material*>(name,mptr)); //MgO name = "MgO"; mptr = new G4Material( name, 0.7 * 2.506*g/cm3, 2); mptr->AddElement(O, 1); mptr->AddElement(Mg, 1); m_materials.insert(std::pair<std::string,G4Material*>(name,mptr)); //glass name = "Glass"; mptr = new G4Material( name, 2.6*g/cm3, 7); mptr->AddElement(O, 59.8*perCent); mptr->AddElement(Si, 24.7*perCent); mptr->AddElement(Al, 1.4*perCent); mptr->AddElement(Mg, 1.4*perCent); mptr->AddElement(Ca, 2.3*perCent); mptr->AddElement(Na, 10.3*perCent); mptr->AddElement(Fe, 0.1*perCent); m_materials.insert(std::pair<std::string,G4Material*>(name,mptr)); //soil name = "Soil"; mptr = new G4Material( name, 1.6*g/cm3,//1.3..2.0 11); mptr->AddElement(O, 46.0*perCent);//46.7 mptr->AddElement(Si, 27.0*perCent); mptr->AddElement(Al, 8.0*perCent);//8.0 mptr->AddElement(Fe, 5.0*perCent); mptr->AddElement(Ca, 2.0*perCent); mptr->AddElement(Mg, 2.0*perCent); mptr->AddElement(K, 2.0*perCent); mptr->AddElement(Na, 2.0*perCent); mptr->AddElement(P, 2.0*perCent); mptr->AddElement(S, 2.0*perCent); mptr->AddElement(N, 2.0*perCent); m_materials.insert(std::pair<std::string,G4Material*>(name,mptr)); //steel name = "Steel"; mptr = new G4Material( name, 7.81*g/cm3, 7); mptr->AddElement(C, 0.0010); mptr->AddElement(Si, 0.0100); mptr->AddElement(Mn, 0.0065); mptr->AddElement(Cr, 0.0075); mptr->AddElement(Ni, 0.0065); mptr->AddElement(Cu, 0.0050); mptr->AddElement(Fe, 0.9635); m_materials.insert(std::pair<std::string,G4Material*>(name,mptr)); //D16 name = "D16"; mptr = new G4Material( name, 2.8*g/cm3, 9); mptr->AddElement(Al, 92.5*perCent); mptr->AddElement(Cu, 4.0*perCent); mptr->AddElement(Mg, 1.5*perCent); mptr->AddElement(Fe, 0.5*perCent); mptr->AddElement(Si, 0.5*perCent); mptr->AddElement(Mn, 0.5*perCent); mptr->AddElement(Zn, 0.3*perCent); mptr->AddElement(Ni, 0.1*perCent); mptr->AddElement(Ti, 0.1*perCent); m_materials.insert(std::pair<std::string,G4Material*>(name,mptr)); //plastic name = "Plastic"; mptr = new G4Material( name, 1.19*g/cm3, 3); mptr->AddElement(H, 0.08); mptr->AddElement(C, 0.60); mptr->AddElement(O, 0.32); m_materials.insert(std::pair<std::string,G4Material*>(name,mptr)); //lavsan name = "Lavsan"; mptr = new G4Material( name, 1.38*g/cm3, 3); mptr->AddElement(H, 8); mptr->AddElement(C, 10); mptr->AddElement(O, 4); m_materials.insert(std::pair<std::string,G4Material*>(name,mptr)); const int NUMENTRIES = 3; G4double PP[NUMENTRIES] = {1.0*eV, 5.0*eV, 10.0*eV}; //CsI name = "CsI"; mptr = new G4Material( name, 4.51*g/cm3, 2, kStateUndefined, 273*kelvin); mptr->AddElement(Cs, 1); mptr->AddElement(I, 1); G4MaterialPropertiesTable* Scn_Mt = new G4MaterialPropertiesTable(); G4double CsI_RIND[NUMENTRIES] = {1.79, 1.79, 1.79}; G4double CsI_ABSL[NUMENTRIES] = {71.*cm, 71*cm, 71.*cm}; Scn_Mt->AddProperty("RINDEX", PP, CsI_RIND, NUMENTRIES); Scn_Mt->AddProperty("ABSLENGTH",PP, CsI_ABSL, NUMENTRIES); Scn_Mt->AddConstProperty("SCINTILLATIONYIELD", 54000./MeV); Scn_Mt->AddConstProperty("RESOLUTIONSCALE", 0.0759); Scn_Mt->AddConstProperty("YIELDRATIO", 1.); Scn_Mt->AddConstProperty("EXCITATIONRATIO", 1.); mptr->SetMaterialPropertiesTable(Scn_Mt); m_materials.insert(std::pair<std::string,G4Material*>(name,mptr)); //NaI name = "NaI"; mptr = new G4Material( name.c_str(), 3.67*g/cm3, 2, kStateUndefined, 273*kelvin); mptr->AddElement(Na, 1); mptr->AddElement(I, 1); Scn_Mt = new G4MaterialPropertiesTable(); G4double NaI_RIND[NUMENTRIES] = {2.15, 2.15, 2.15}; G4double NaI_ABSL[NUMENTRIES] = {71.*cm, 71*cm, 71.*cm}; Scn_Mt->AddProperty("RINDEX", PP, NaI_RIND, NUMENTRIES); Scn_Mt->AddProperty("ABSLENGTH",PP, NaI_ABSL, NUMENTRIES); Scn_Mt->AddConstProperty("SCINTILLATIONYIELD", 38000./MeV); Scn_Mt->AddConstProperty("RESOLUTIONSCALE", 0.085); Scn_Mt->AddConstProperty("YIELDRATIO", 1.); Scn_Mt->AddConstProperty("EXCITATIONRATIO", 1.); mptr->SetMaterialPropertiesTable(Scn_Mt); m_materials.insert(std::pair<std::string,G4Material*>(name,mptr)); //BGO name = "BGO"; mptr = new G4Material( name.c_str(), 7.13*g/cm3, 3, kStateUndefined, 273*kelvin); mptr->AddElement(Bi, 4); mptr->AddElement(Ge, 3); mptr->AddElement(O, 12); Scn_Mt = new G4MaterialPropertiesTable(); G4double BGO_RIND[NUMENTRIES] = {2.15, 2.15, 2.15}; G4double BGO_ABSL[NUMENTRIES] = {71.*cm, 71*cm, 71.*cm}; Scn_Mt->AddProperty("RINDEX", PP, BGO_RIND, NUMENTRIES); Scn_Mt->AddProperty("ABSLENGTH",PP, BGO_ABSL, NUMENTRIES); Scn_Mt->AddConstProperty("SCINTILLATIONYIELD", 9000./MeV); Scn_Mt->AddConstProperty("RESOLUTIONSCALE", 0.11); Scn_Mt->AddConstProperty("YIELDRATIO", 1.); Scn_Mt->AddConstProperty("EXCITATIONRATIO", 1.); mptr->SetMaterialPropertiesTable(Scn_Mt); m_materials.insert(std::pair<std::string,G4Material*>(name,mptr)); //stylben /* name = "Stylben"; mptr = new G4Material( name.c_str(), 1.16*g/cm3, 2); mptr->AddElement(H, 12); mptr->AddElement(C, 14); Scn_Mt = new G4MaterialPropertiesTable(); Scn_Mt->AddProperty("RINDEX", Scn_PP, Scn_RIND, NUMENTRIES); Scn_Mt->AddProperty("ABSLENGTH",Scn_PP, Scn_ABSL, NUMENTRIES); Scn_Mt->AddConstProperty("SCINTILLATIONYIELD", 54000./MeV); Scn_Mt->AddConstProperty("RESOLUTIONSCALE", 0.0759); Scn_Mt->AddConstProperty("YIELDRATIO", 1.); Scn_Mt->AddConstProperty("EXCITATIONRATIO", 1.); mptr->SetMaterialPropertiesTable(Scn_Mt); m_materials.insert(std::pair<std::string,G4Material*>(name,mptr)); */ } catch(...) { return GSMS_ERR; } return GSMS_OK; } GSMS::Geometry::Geometry() { m_world = NULL; defineMaterials(); G4Box* world_box = new G4Box( "world_box", 2*m, 2*m, 2*m); G4LogicalVolume* world_log = new G4LogicalVolume( world_box, m_materials["Air"], "world_log"); m_world = new G4PVPlacement( 0, G4ThreeVector(0. ,0. ,0.), "world_phys", world_log, NULL, false, 0); world_log->SetVisAttributes(G4VisAttributes::Invisible); } GSMS::Geometry::~Geometry() { } /* void OTDetectorConstruction::ReconstructCrystal() { ///////////////////////////// //Clearing up old instances// ///////////////////////////// G4cout << "Clearing up crystal..." << G4endl; if(crystal_log) delete crystal_log; if(crystal_phys) delete crystal_phys; G4cout << "Clearing up plastic..." << G4endl; if(plastic_log) delete plastic_log; if(plastic_phys) delete plastic_phys; G4cout << "Clearing up foil..." << G4endl; if(foil_log) delete foil_log; if(foil_phys) delete foil_phys; if(foilp_log) delete foilp_log; if(foilp_phys) delete foilp_phys; G4cout << "Clearing up glass..." << G4endl; if(glass_log) delete glass_log; if(glass_phys) delete glass_phys; G4cout << "Clearing up PET..." << G4endl; if(PET_log) delete PET_log; if(PET_phys) delete PET_phys; G4cout << "hey1" << G4endl; ////////////////////////// //Clearing up primitives// ////////////////////////// G4cout << "Clearing up primitives..." << G4endl; G4VSolid* Crystal = NULL; G4VSolid* Glass = NULL; G4VSolid* Plastic = NULL; G4VSolid* Foil = NULL; G4VSolid* FoilP = NULL; G4VSolid* PET = NULL; /////////////////////////////// //Creating phoswitch assembly// /////////////////////////////// G4cout << "Creating assembly..." << G4endl; Crystal = new G4Tubs( "Crystal", 0., dCD/2, dCH/2, 0.0*deg, 360.0*deg); if(dGlassTck > 0.) { Glass = new G4Tubs( "Glass", 0., dCD/2, dGlassTck/2, 0.0*deg, 360.0*deg); }; Plastic = new G4Tubs( "Plastic", 0., dCD/2, dStylbTck/2, 0.0*deg, 360.0*deg); Foil = new G4Tubs( "Foil", 0., dCD/2, dFoilTck/2, 0.0*deg, 360.0*deg); FoilP = new G4Tubs( "FoilP", 0., dCD/2, dFoilPTck/2, 0.0*deg, 360.0*deg); PET = new G4Tubs( "PET", 0., dCD/2, dPETTck/2, 0.0*deg, 360.0*deg); //////////////////////////// //Creating logical volumes// //////////////////////////// G4cout << "Creating logical volumes..." << G4endl; foil_log = new G4LogicalVolume(Foil,G4Mat_Al,"foil_log"); foilp_log = new G4LogicalVolume(FoilP,G4Mat_Lavsan,"foilp_log"); plastic_log = new G4LogicalVolume(Plastic,G4Mat_Plastic,"plastic_log"); if(Glass) glass_log = new G4LogicalVolume(Glass,G4Mat_Glass,"glass_log"); crystal_log = new G4LogicalVolume(Crystal,G4Mat_CsI,"crystal_log"); PET_log = new G4LogicalVolume(PET,G4Mat_Al,"PET_log"); ///////////////////////////// //Creating physical volumes// ///////////////////////////// G4cout << "Creating physical volumes..." << G4endl; G4double dFoilOffset = 0.0; G4double dFoilPOffset = (dFoilTck+dFoilPTck)/2; G4double dPlasticOffset = dFoilPTck+(dFoilTck+dStylbTck)/2; G4double dGlassOffset = dFoilPTck+dStylbTck+(dFoilTck+dGlassTck)/2; G4double dCrystalOffset = dFoilPTck+dStylbTck+dGlassTck+(dFoilTck+dCH)/2; G4double dPETOffset = dFoilPTck+dStylbTck+dGlassTck+dCH+(dFoilTck+dPETTck)/2; foil_phys = new G4PVPlacement(0, G4ThreeVector(0.,0.,-dFoilOffset), "foil_phys", foil_log, world_phys, false, 0); foilp_phys = new G4PVPlacement(0, G4ThreeVector(0.,0.,-dFoilPOffset), "foilp_phys", foilp_log, world_phys, false, 0); plastic_phys = new G4PVPlacement(0, G4ThreeVector(0.,0.,-dPlasticOffset), "plastic_phys", plastic_log, world_phys, false, 0); if(Glass) glass_phys = new G4PVPlacement(0, G4ThreeVector(0.,0.,-dGlassOffset), "glass_phys", glass_log, world_phys, false, 0); crystal_phys = new G4PVPlacement(0, G4ThreeVector(0.,0.,-dCrystalOffset), "crystal_phys", crystal_log, world_phys, false, 0); PET_phys = new G4PVPlacement(0, G4ThreeVector(0.,0.,-dPETOffset), "PET_phys", PET_log, world_phys, false, 0); ////////////////////////////// //Creating visual attributes// ////////////////////////////// G4cout << "Creating visual attributes..." << G4endl; diff --git a/src/geometry/Geometry.h b/src/geometry/Geometry.h index c08dd09..0ce7a16 100644 --- a/src/geometry/Geometry.h +++ b/src/geometry/Geometry.h @@ -1,102 +1,122 @@ +/*************************************************************************** + * Copyright (C) 2009 by P.Voylov * + * [email protected] * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + /*!\file Geometry.h * \brief Geometry description */ #ifndef GEOMETRY_H_ #define GEOMETRY_H_ #include "typedefs.h" #include <geant/G4VUserDetectorConstruction.hh> #include <geant/globals.hh> #include <geant/G4OpBoundaryProcess.hh> #include <geant/G4LogicalBorderSurface.hh> //class G4LogicalVolume; class G4VPhysicalVolume; //class G4Material; //class G4OpticalSurface; //class G4MaterialPropertiesTable; //class G4LogicalBorderSurface; namespace GSMS { /*!\typedef _LPVP * \brief logical\&physical volume pair */ typedef std::pair<G4LogicalVolume*,G4VPhysicalVolume*> _LPVP; /*!\class Geometry * \brief Scenery geometry description */ class Geometry : public G4VUserDetectorConstruction { G4VPhysicalVolume* m_world; /*!\var m_objects * \brief objects storage */ std::map<std::string,_LPVP> m_objects; /*!\fn unsigned int getObject(std::string name) * \brief get object * \param name object name * \return object instance */ _LPVP* getObject(std::string name) { if(m_objects.size() > 0 && name.length() > 0) return &m_objects[name]; return NULL; } /*!\var m_materials * \brief materials storage */ std::map<std::string,G4Material*> m_materials; /*!\fn unsigned int defineMaterials() * \brief creation of materials * \return exit code */ unsigned int defineMaterials(); /*!\fn unsigned int getMaterial(std::string name) * \brief get material * \param name material name * \return material ptr */ G4Material* getMaterial(std::string name) { G4Material* result = NULL; if(m_materials.size() > 0 && name.length() > 0) result = m_materials[name]; return result; } public: G4VPhysicalVolume* Construct(); void ReconstructCrystal() {} void LoadGeometry() {} bool Update(); Geometry(); ~Geometry(); unsigned int getMaterial(std::string name,G4Material** material) { G4Material* result = NULL; result = getMaterial(name); if(!result || !material) return GSMS_ERR; *material = result; return GSMS_OK; }; }; }; /*namespace GSMS*/ #endif /*GEOMETRY_H_*/ diff --git a/src/physics/PhysicsList.cpp b/src/physics/PhysicsList.cpp index 3313717..207615b 100644 --- a/src/physics/PhysicsList.cpp +++ b/src/physics/PhysicsList.cpp @@ -1,229 +1,249 @@ +/*************************************************************************** + * Copyright (C) 2009 by P.Voylov * + * [email protected] * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + #include "PhysicsList.h" #include <geant/G4ProcessManager.hh> #include <geant/G4ProcessVector.hh> #include <geant/G4ParticleDefinition.hh> #include <geant/G4ParticleWithCuts.hh> #include <geant/G4ParticleTypes.hh> #include <geant/G4ParticleTable.hh> #include <geant/G4ios.hh> #include <iomanip> #include <geant/G4UserLimits.hh> // Constructor ///////////////////////////////////////////////////////////// GSMS::PhysicsList::PhysicsList() : G4VUserPhysicsList() { defaultCutValue = 1.0*micrometer; // cutForGamma = defaultCutValue; cutForElectron = 1.0*nanometer; cutForPositron = defaultCutValue; VerboseLevel = 1; OpVerbLevel = 0; SetVerboseLevel(VerboseLevel); // G4cout << "PhysicsList::PhysicsList()" << G4endl; } GSMS::PhysicsList::~PhysicsList() { //G4cout << "PhysicsList::~PhysicsList()" << G4endl; } void GSMS::PhysicsList::ConstructParticle() { G4Gamma::GammaDefinition(); G4OpticalPhoton::OpticalPhotonDefinition(); G4Electron::ElectronDefinition(); // G4Neutron::NeutronDefinition(); G4Positron::PositronDefinition(); // G4cout << "PhysicsList::ConstructParticle()" << G4endl; } #include <geant/G4MultipleScattering.hh> // gamma #include <geant/G4LowEnergyRayleigh.hh> #include <geant/G4LowEnergyPhotoElectric.hh> #include <geant/G4LowEnergyCompton.hh> #include <geant/G4LowEnergyGammaConversion.hh> // e- #include <geant/G4LowEnergyIonisation.hh> #include <geant/G4LowEnergyBremsstrahlung.hh> // e+ #include <geant/G4eIonisation.hh> #include <geant/G4eBremsstrahlung.hh> #include <geant/G4eplusAnnihilation.hh> #include <geant/G4EmProcessOptions.hh> //optics #include <geant/G4Scintillation.hh> #include <geant/G4OpAbsorption.hh> #include <geant/G4OpRayleigh.hh> #include <geant/G4OpBoundaryProcess.hh> //decay #include <geant/G4Decay.hh> void GSMS::PhysicsList::ConstructProcess(){ //G4cout << "Adding processes..." << G4endl; G4VUserPhysicsList::AddTransportation(); //G4cout << "Transportation added..." << G4endl; G4LowEnergyPhotoElectric* lowePhot = new G4LowEnergyPhotoElectric(); G4LowEnergyIonisation* loweIon = new G4LowEnergyIonisation(); G4LowEnergyBremsstrahlung* loweBrem = new G4LowEnergyBremsstrahlung(); G4double fluorcut = 250*eV; lowePhot->SetCutForLowEnSecPhotons(fluorcut); loweIon->SetCutForLowEnSecPhotons(fluorcut); loweBrem->SetCutForLowEnSecPhotons(fluorcut); theParticleIterator->reset(); while( (*theParticleIterator)() ) { G4ParticleDefinition* particle = theParticleIterator->value(); G4ProcessManager* pmanager = particle->GetProcessManager(); G4String particleName = particle->GetParticleName(); G4String particleType = particle->GetParticleType(); //G4double charge = particle->GetPDGCharge(); if (particleName == "gamma") { pmanager->AddDiscreteProcess(new G4LowEnergyRayleigh()); pmanager->AddDiscreteProcess(lowePhot); pmanager->AddDiscreteProcess(new G4LowEnergyCompton()); pmanager->AddDiscreteProcess(new G4LowEnergyGammaConversion()); } else if (particleName == "e-") { // process ordering: AddProcess(name, at rest, along step, post step) // -1 = not implemented, then ordering G4MultipleScattering* aMultipleScattering = new G4MultipleScattering(); pmanager->AddProcess(aMultipleScattering, -1, 1, 1); pmanager->AddProcess(loweIon, -1, 2, 2); pmanager->AddProcess(loweBrem, -1,-1, 3); } else if (particleName == "e+") { G4MultipleScattering* aMultipleScattering = new G4MultipleScattering(); pmanager->AddProcess(aMultipleScattering, -1, 1, 1); pmanager->AddProcess(new G4eIonisation(), -1, 2, 2); pmanager->AddProcess(new G4eBremsstrahlung(), -1,-1, 3); pmanager->AddProcess(new G4eplusAnnihilation(),0,-1, 4); } } G4EmProcessOptions opt; opt.SetMscStepLimitation(fMinimal);//some factor?? // opt.SetMscStepLimitation(0);//some factor?? //G4cout << "EM added..." << G4endl; /* // default scintillation process GSMS::Scintillation* theScintProcessDef = new GSMS::Scintillation("Scintillation"); // theScintProcessDef->DumpPhysicsTable(); theScintProcessDef->SetTrackSecondariesFirst(true); theScintProcessDef->SetScintillationYieldFactor(1.0); theScintProcessDef->SetScintillationExcitationRatio(1.0); theScintProcessDef->SetVerboseLevel(OpVerbLevel); */ // optical processes G4OpAbsorption* theAbsorptionProcess = new G4OpAbsorption(); G4OpRayleigh* theRayleighScatteringProcess = new G4OpRayleigh(); G4OpBoundaryProcess* theBoundaryProcess = new G4OpBoundaryProcess(); // theAbsorptionProcess->DumpPhysicsTable(); // theRayleighScatteringProcess->DumpPhysicsTable(); theAbsorptionProcess->SetVerboseLevel(OpVerbLevel); theRayleighScatteringProcess->SetVerboseLevel(OpVerbLevel); theBoundaryProcess->SetVerboseLevel(OpVerbLevel); G4OpticalSurfaceModel themodel = unified; theBoundaryProcess->SetModel(themodel); //G4cout << "Optical added..." << G4endl; theParticleIterator->reset(); while( (*theParticleIterator)() ) { G4ParticleDefinition* particle = theParticleIterator->value(); G4ProcessManager* pmanager = particle->GetProcessManager(); G4String particleName = particle->GetParticleName(); /* if (theScintProcessDef->IsApplicable(*particle)) { pmanager->AddProcess(theScintProcessDef); pmanager->SetProcessOrderingToLast(theScintProcessDef,idxAtRest); pmanager->SetProcessOrderingToLast(theScintProcessDef,idxPostStep); } */ if (particleName == "opticalphoton") { pmanager->AddDiscreteProcess(theAbsorptionProcess); pmanager->AddDiscreteProcess(theRayleighScatteringProcess); pmanager->AddDiscreteProcess(theBoundaryProcess); } } G4Decay* theDecayProcess = new G4Decay(); theParticleIterator->reset(); while( (*theParticleIterator)() ) { G4ParticleDefinition* particle = theParticleIterator->value(); G4ProcessManager* pmanager = particle->GetProcessManager(); if (theDecayProcess->IsApplicable(*particle) && !particle->IsShortLived()) { pmanager ->AddProcess(theDecayProcess); // set ordering for PostStepDoIt and AtRestDoIt pmanager ->SetProcessOrdering(theDecayProcess, idxAtRest); pmanager ->SetProcessOrdering(theDecayProcess, idxPostStep); } } // G4cout << "PhysicsList::ConstructProcess()" << G4endl; } void GSMS::PhysicsList::SetCuts() { G4cout << "PhysicsList::SetCuts:"; G4cout << "CutLength : " << G4BestUnit(defaultCutValue,"Length") << G4endl; G4double lowlimit = 1*keV;//250*eV G4ProductionCutsTable::GetProductionCutsTable()->SetEnergyRange(lowlimit,1.*GeV);//100*GeV // set cut values for gamma at first and for e- second and next for e+, // because some processes for e+/e- need cut values for gamma SetCutValue(cutForGamma, "gamma"); SetCutValue(cutForElectron, "e-"); SetCutValue(cutForPositron, "e+"); DumpCutValuesTable(); // G4cout << "PhysicsList::SetCuts()" << G4endl; } diff --git a/src/physics/PhysicsList.h b/src/physics/PhysicsList.h index 4c16c6a..0173793 100644 --- a/src/physics/PhysicsList.h +++ b/src/physics/PhysicsList.h @@ -1,90 +1,110 @@ +/*************************************************************************** + * Copyright (C) 2009 by P.Voylov * + * [email protected] * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + /*!\file PhysicsList.h * \brief GSMS physics definitions */ #ifndef PHYSICSLIST_H_ #define PHYSICSLIST_H_ #include <geant/G4VUserPhysicsList.hh> #include <geant/globals.hh> #include "Scintillation.h" namespace GSMS { /*!\class PhysicsList * \brief GSMS physics list */ class PhysicsList: public G4VUserPhysicsList { /*!\var VerboseLevel * \brief verbosity level */ G4int VerboseLevel; /*!\var OpVerboseLevel * \brief verbosity level */ G4int OpVerbLevel; /*!\var cutForGamma * \brief special cuts for gamma */ G4double cutForGamma; /*!\var cutForElectron * \brief special cuts for electron */ G4double cutForElectron; /*!\var cutForPositron * \brief special cuts for positron */ G4double cutForPositron; /*!\var cutForProton * \brief special cuts for proton */ G4double cutForProton; /*!\var cutForAlpha * \brief special cuts for alpha */ G4double cutForAlpha; /*!\var cutForGenericIon * \brief special cuts for generic ion */ G4double cutForGenericIon; public: /*!\fn PhysicsList() * \brief default constructor */ PhysicsList(); /*!\fn ~PhysicsList() * \brief default destructor */ ~PhysicsList(); /*!\fn void ConstructParticle() * \brief particle creator */ virtual void ConstructParticle(); /*!\fn void ConstructProcess() * \brief process creator */ virtual void ConstructProcess(); /*!\fn void SetCuts() * \brief cuts setup */ virtual void SetCuts(); }; }; /*namespace GSMS*/ #endif /*PHYSICSLIST_H_*/ diff --git a/src/physics/Scintillation.cpp b/src/physics/Scintillation.cpp index 2d45648..87fbfd3 100644 --- a/src/physics/Scintillation.cpp +++ b/src/physics/Scintillation.cpp @@ -1,306 +1,326 @@ +/*************************************************************************** + * Copyright (C) 2009 by P.Voylov * + * [email protected] * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + #include "Scintillation.h" #include <geant/G4ios.hh> namespace GSMS { G4double GetCurve(G4double l1,G4double l2,G4double t) { return l1/(l1-l2)*(exp(-l2*t)-exp(-l1*t)); } G4double Nm2MeV(G4double arg) { G4double dResult = arg; G4double hc = 299.792458*4.136; dResult = hc/arg/1000000.0*MeV;//MeV return dResult*MeV; } }; /*namespace GSMS*/ G4VParticleChange* GSMS::Scintillation::PostStepDoIt(const G4Track& aTrack, const G4Step& aStep) { //extern G4double dCrystalRes; //extern G4double dStylben; //extern G4double dCrystal; aParticleChange.Initialize(aTrack); const G4DynamicParticle* aParticle = aTrack.GetDynamicParticle(); const G4Material* aMaterial = aTrack.GetMaterial(); G4MaterialPropertiesTable* aMaterialPropertiesTable = aMaterial->GetMaterialPropertiesTable(); if (!aMaterialPropertiesTable) return G4VRestDiscreteProcess::PostStepDoIt(aTrack, aStep); if (!aMaterialPropertiesTable->ConstPropertyExists("SCINTILLATIONYIELD")) return G4VRestDiscreteProcess::PostStepDoIt(aTrack, aStep); G4StepPoint* pPreStepPoint = aStep.GetPreStepPoint(); G4StepPoint* pPostStepPoint = aStep.GetPostStepPoint(); G4ThreeVector x0 = pPreStepPoint->GetPosition(); G4ThreeVector p0 = aStep.GetDeltaPosition().unit(); G4double t0 = pPreStepPoint->GetGlobalTime(); G4double dTemp = aMaterial->GetTemperature(); G4double TotalEnergyDeposit = aStep.GetTotalEnergyDeposit(); G4double ScintillationYield = aMaterialPropertiesTable->GetConstProperty("SCINTILLATIONYIELD"); G4double ResolutionScale = aMaterialPropertiesTable->GetConstProperty("RESOLUTIONSCALE"); ScintillationYield = GetScintillationYieldFactor() * ScintillationYield; G4double MeanNumberOfPhotons = ScintillationYield * TotalEnergyDeposit; G4int NumPhotons; if (MeanNumberOfPhotons > 10.) { //TODO double dCrystalRes = 0.085;//ResolutionScale; G4double dResA = std::sqrt(0.662)*dCrystalRes; G4double sigma = std::sqrt(dResA/2.355/std::sqrt(TotalEnergyDeposit)); //ResolutionScale * sqrt(MeanNumberOfPhotons); NumPhotons = G4int(G4RandGauss::shoot(MeanNumberOfPhotons,sigma)+0.5); } else { NumPhotons = G4int(G4Poisson(MeanNumberOfPhotons)); }; if (NumPhotons <= 0) { // return unchanged particle and no secondaries aParticleChange.SetNumberOfSecondaries(0); return G4VRestDiscreteProcess::PostStepDoIt(aTrack, aStep); } aParticleChange.SetNumberOfSecondaries(NumPhotons); if (G4Scintillation::GetTrackSecondariesFirst()) { if (aTrack.GetTrackStatus() == fAlive ) aParticleChange.ProposeTrackStatus(fSuspend); } /* if(aMaterial->GetName()=="Stylben") dStylben += TotalEnergyDeposit; else dCrystal += TotalEnergyDeposit; */ //////////////////////////////////////////////////////////////// return G4VRestDiscreteProcess::PostStepDoIt(aTrack, aStep); //////////////////////////////////////////////////////////////// //G4int materialIndex = aMaterial->GetIndex(); G4int Num = NumPhotons; G4double ScintillationTime = 0.*ns; //defining curves G4double lambda1 = 0.0; G4double lambda2 = 0.0; G4double tau1 = 22.0; G4double tau2 = 700.0; G4int tau_max = 0; G4double smean = 400.0; G4double ssigma = 25.0; G4String sMName = aMaterial->GetName(); G4double w3 = G4UniformRand(); if(sMName == "CsI") { G4double c2 = 1.112 - 0.62*0.001*dTemp; if(c2>1.0) c2 = 1.0; else if(c2<0.0) c2 = 0.0; G4double c1 = 1.0 - c2; if(w3 <= c1) { smean = 400.0; ssigma = 25.0; } else { smean = 560.0; ssigma = 60.0; } tau1 = 22.0; tau2 = 700.0; } if(sMName == "NaI") { G4double c2 = 0.926; if(c2>1.0) c2 = 1.0; else if(c2<0.0) c2 = 0.0; G4double c1 = 1.0 - c2; if(w3 <= c1) { smean = 340.0; ssigma = 15.0; } else { smean = 415.0; ssigma = 40.0; } tau1 = 22.0; tau2 = 700.0; } lambda1 = 1/tau1; lambda2 = 1/tau2; tau_max = (int)(log(lambda2/lambda1)/(lambda2-lambda1)+0.5); G4double model[3][200]; G4double model_max = 0.0; model[0][0] = 0.0; model[1][0] = 0.0; for(G4int i = 1; i < 200; i++) { G4double splitter = 0.0; if(i<60) splitter = 1.2*tau_max/60.0; else splitter = tau_max*(tau2/tau1+10)/140.0; model[0][i] = model[0][i-1]+splitter; model[2][i] = GSMS::GetCurve(lambda1,lambda2,model[0][i]); G4double k = (GSMS::GetCurve(lambda1,lambda2,model[0][i]) - GSMS::GetCurve(lambda1,lambda2,model[0][i-1]))/splitter; G4double b = GSMS::GetCurve(lambda1,lambda2,model[0][i-1]); model[1][i] = model[1][i-1]+k*splitter*splitter/2 +b*splitter; if(i==199) model_max = model[1][i]; } for (G4int i = 0; i < Num; i++) { // Determine photon momentum G4double w1 = G4UniformRand(); G4double w2 = G4UniformRand(); G4double sampledMomentum = (smean+ssigma*cos(twopi*w1)*sqrt(-2*log(w2))); sampledMomentum = GSMS::Nm2MeV(sampledMomentum); //verboseLevel = 10; //if (verboseLevel>1) { //G4cout << "sampledMomentum = " << sampledMomentum << G4endl; //G4cout << "CIIvalue = " << CIIvalue << G4endl; //} //verboseLevel = 0; // Generate random photon direction G4double cost = 1. - 2.*G4UniformRand(); G4double sint = sqrt((1.-cost)*(1.+cost)); G4double phi = twopi*G4UniformRand(); G4double sinp = sin(phi); G4double cosp = cos(phi); G4double px = sint*cosp; G4double py = sint*sinp; G4double pz = cost; // Create photon momentum direction vector G4ParticleMomentum photonMomentum(px, py, pz); // Determine polarization of new photon G4double sx = cost*cosp; G4double sy = cost*sinp; G4double sz = -sint; G4ThreeVector photonPolarization(sx, sy, sz); G4ThreeVector perp = photonMomentum.cross(photonPolarization); phi = twopi*G4UniformRand(); sinp = sin(phi); cosp = cos(phi); photonPolarization = cosp * photonPolarization + sinp * perp; photonPolarization = photonPolarization.unit(); // Generate a new photon: G4DynamicParticle* aScintillationPhoton = new G4DynamicParticle(G4OpticalPhoton::OpticalPhoton(),photonMomentum); aScintillationPhoton->SetPolarization (photonPolarization.x(), photonPolarization.y(), photonPolarization.z()); aScintillationPhoton->SetKineticEnergy(sampledMomentum); // Generate new G4Track object: G4double rand; if (aParticle->GetDefinition()->GetPDGCharge() != 0) { rand = G4UniformRand(); } else { rand = 1.0; } G4double delta = rand * aStep.GetStepLength(); G4double deltaTime = delta / ((pPreStepPoint->GetVelocity()+ pPostStepPoint->GetVelocity())/2.); deltaTime = deltaTime - ScintillationTime * log( G4UniformRand() ); //new time G4double w = G4UniformRand(); G4int index = 0; for(G4int i=1;i<200;i++) { if((model[1][i-1]/model_max)<=w && (model[1][i]/model_max)>=w) { index = i; break; } } G4double prop = (w-(model[1][index-1]/model_max))/((model[1][index]-model[1][index-1])/model_max); deltaTime = model[0][index-1]+prop*(model[0][index]-model[0][index-1]); G4double aSecondaryTime = t0 + deltaTime; G4ThreeVector aSecondaryPosition = x0 + rand * aStep.GetDeltaPosition(); G4Track* aSecondaryTrack = new G4Track(aScintillationPhoton,aSecondaryTime,aSecondaryPosition); aSecondaryTrack->SetTouchableHandle((G4VTouchable*)0); aSecondaryTrack->SetParentID(aTrack.GetTrackID()); aParticleChange.AddSecondary(aSecondaryTrack); } if (verboseLevel>0) { G4cout << "\n Exiting from G4Scintillation::DoIt -- NumberOfSecondaries = " << aParticleChange.GetNumberOfSecondaries() << G4endl; } return G4VRestDiscreteProcess::PostStepDoIt(aTrack, aStep); } diff --git a/src/physics/Scintillation.h b/src/physics/Scintillation.h index 4666c3d..2945f33 100644 --- a/src/physics/Scintillation.h +++ b/src/physics/Scintillation.h @@ -1,45 +1,65 @@ +/*************************************************************************** + * Copyright (C) 2009 by P.Voylov * + * [email protected] * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + /*!\file Scintillation.h * \brief Custom scintillation implementation */ #ifndef SCINTILLATION_H_ #define SCINTILLATION_H_ #include <geant/G4Scintillation.hh> namespace GSMS { /*!\class Scintillation * \brief Custom scintillation implementation */ class Scintillation : public G4Scintillation { public: /*!\fn Scintillation(const G4String& processName, G4ProcessType processType) * \param processName name of the process * \param processType type of the process */ Scintillation(const G4String& processName = "Scintillation", G4ProcessType processType = fElectromagnetic) : G4Scintillation(processName,processType) {} /*!\fn ~Scintillation() * \brief default destructor */ ~Scintillation() {} /*!\fn G4VParticleChange* PostStepDoIt(const G4Track& aTrack,const G4Step& aStep) * \brief post-step actor * \param aTrack track reference * \param aStep step reference * \return particle change pointer */ G4VParticleChange* PostStepDoIt(const G4Track& aTrack, const G4Step& aStep); // void BuildThePhysicsTable(); }; };/*namespace GSMS*/ #endif /*SCINTILLATION_H_*/ diff --git a/src/ui/UI.cpp b/src/ui/UI.cpp index e7e962e..2dbeb81 100644 --- a/src/ui/UI.cpp +++ b/src/ui/UI.cpp @@ -1,18 +1,26 @@ -// -// C++ Implementation: RunAction -// -// Description: -// -// -// Author: P.Voylov <[email protected]>, (C) 2009 -// -// Copyright: See COPYING file that comes with this distribution -// -// +/*************************************************************************** + * Copyright (C) 2009 by P.Voylov * + * [email protected] * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ #include "UI.h" GSMS::UI::UI() { std::cout << std::endl; } \ No newline at end of file diff --git a/src/ui/UI.h b/src/ui/UI.h index c20a0e7..35afacf 100644 --- a/src/ui/UI.h +++ b/src/ui/UI.h @@ -1,37 +1,45 @@ -// -// C++ Interface: RunAction -// -// Description: -// -// -// Author: P.Voylov <[email protected]>, (C) 2009 -// -// Copyright: See COPYING file that comes with this distribution -// -// +/*************************************************************************** + * Copyright (C) 2009 by P.Voylov * + * [email protected] * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ /*!\file UI.h * \brief Action HC processor */ #ifndef UI_H #define UI_H #include "config/Config.h" /*!\namespace GSMS * \brief Gamma-Scanner Modelling Suite namespace */ namespace GSMS { /*!\class UI * \brief Action processor */ class UI { public: UI(); }; } #endif /*UI_H*/ \ No newline at end of file
vim-scripts/Projmgr
5215e0926b9b191cb7ef8aaff488849af43d87db
Version 0.2
diff --git a/doc/Projmgr.txt b/doc/Projmgr.txt index 658a612..5c0679e 100644 --- a/doc/Projmgr.txt +++ b/doc/Projmgr.txt @@ -1,38 +1,52 @@ *Projmgr.txt* Plugin for loading/unloading/switching Vim sessions This plugin provides a more easy to use interface for the Vim session feature. I wrote it first only for my own needs. I have a bunch of small projects lying around on my hard disk. I would like to load a whole project, play around with it, switch to another if I like, or simply unload it. This plugin provide a menu system for 'Load', 'Unload' 'Switch to' a -project(session). None-menu-driven version is not available at the +project(session), etc. None-menu-driven version is not available at the moment. Install: -1. Copy the projmgr.vim into your plugin directory or - $HOME/.vim/plugin. -2. Copy the perl script to somewhere. E.g plugin/perl. -3. Copy this documentation into the corresponding doc directory. -4. Make a directory: $HOME/.vim/projects -5. Modify the script and change "/.vim/plugin/perl/buffers.pl" to - where you put the perl script. (I know I know, I will try to figure - out a way to do these automatically. You are more than welcomed to - tell me if you know how.) +1. Automatic: + Simply use the install.sh script and following the instruction. + Requires: + bash, Perl. +2. Manual: + You don't need to do this ideally. But if for whatever reason the + install shell script is not working for you, try to following these + steps: + a) Copy the projmgr.vim into your plugin directory or + $HOME/.vim/plugin. + b) Copy the Perl script to somewhere. E.g plugin/perl. + c) Copy this documentation into the corresponding doc directory. + d) Make a directory: $HOME/.vim/projects. This where the vim session + files will be stored. + e) Modify the script and change the s:projmgr_dir to the plugin + directory where you installed projmgr.vim. + f) Copy all (if you have any) your session files into the directory + mentioned in d). Usage: Once it is installed, a menu 'Projects' will appear in your Vim window. Load all your project file, define your view, folding etc. (Or you can load a session file altogether.) And use the 'Projects->Save to Project' to save a session. The file will be save at $HOME/.vim/projects/. (You can copy your vim session file directly into that directory if you want.) After that, 'Projects->Load-> will load that project. Obviously enough, 'Unload' will unload all buffers for that project and you can switch between projects. Known bug: -1. If the number of files in the projects directory goes down for some reason, - the 'refresh' menu won't remove the obsolute items. +1. Vim will not be notified when you unload the current session so that + when you use 'Projects->Current Project', vim will still be reporting + the latest one you loaded. +2. Unload/switch are not working on Windows :(. +3. Sometime if I try to load/unload a project several times, not all the + file in the session will be loaded by Vim. But all this script does + is call :so <session_file> so I am wondering if it is a Vim bug. diff --git a/install.sh b/install.sh index 2f26239..bdfaaa5 100644 --- a/install.sh +++ b/install.sh @@ -1,4 +1,18 @@ -#!/bin/sh -cp -r doc $HOME/.vim -cp -r plugin $HOME/.vim +#!/bin/bash +echo "Input the directory where you installed vim:" +echo "(simply hit return if you want to install in your home directory)" +read vim_dir + +case "$vim_dir" in +"") + vim_dir=${HOME}/.vim + ;; +*) + ./vimdir.pl ${vim_dir} > .vimdir_tmp.vim + ;; +esac + +cp -r doc ${vim_dir} +cp -r plugin ${vim_dir} +mkdir -p ${HOME}/.vim/projects diff --git a/plugin/Projmgr.vim b/plugin/Projmgr.vim index 81c293e..b91cf82 100644 --- a/plugin/Projmgr.vim +++ b/plugin/Projmgr.vim @@ -1,185 +1,196 @@ " Vim global plugin for loading/unloading/switching between sessions. " Last Change: Tue Apr 23 2002 " Maintainer: Wenzhi Liang <wzhliang_at_yahoo.com> if exists("loaded_projects_menu") finish endif if !has("gui") finish endif let loaded_projects_menu = 1 -amenu 150.10 Projects.Save\ to\ project :call <SID>SaveToProj()<CR> -amenu 150.20 Projects.Refresh :call <SID>RefreshList()<CR> -amenu 150.25 Projects.Current\ project :echo fnamemodify( v:this_session, ":t:r" )<CR> +amenu 150.10 Projects.Save\ as :call <SID>SaveToProj()<CR> +amenu 150.10 Projects.Save\ current :call <SID>SaveCurrentProj()<CR> +amenu 150.20 Projects.Refresh :silent! call <SID>RefreshList()<CR> +amenu 150.25 Projects.Current\ project\ is :echo fnamemodify( v:this_session, ":t:r" )<CR> amenu 150.200 Projects.Unload.Empty <nul> unmenu Projects.Unload.Empty "Load the project.load menu let s:proj_dir = expand("~") . "/.vim/projects/" +let s:projmgr_dir = expand("~") . "/.vim/plugin/" let s:lists = glob( s:proj_dir . "*.vim" ) while ( strlen( s:lists ) > 0 ) let s:i = stridx( s:lists, "\n" ) if ( s:i < 0 ) let s:name = s:lists let s:lists = "" else let s:name = strpart( s:lists, 0, s:i ) let s:lists = strpart( s:lists, s:i + 1, 19999 ) endif let s:item = substitute(s:name, '.*[/\\:]\([^/\\:]*\)\.vim', '\1', '') let s:name = escape( s:name, ' \') exe "amenu 150.30 Projects.Load." . s:item . " :call <SID>LoadProject( \"" . s:item . "\")<CR>" exe "amenu 150.40 Projects.Delete." . s:item . " :call <SID>RemoveItem( \"" . s:item . "\")<CR>" unlet s:i unlet s:name endwhile unlet s:lists "Finished adding Projects.Load. menus "Load the Projects.Switch to menu let s:lists = glob( s:proj_dir . "*.vim" ) while ( strlen( s:lists ) > 0 ) let s:i = stridx( s:lists, "\n" ) if ( s:i < 0 ) let s:name = s:lists let s:lists = "" else let s:name = strpart( s:lists, 0, s:i ) let s:lists = strpart( s:lists, s:i + 1, 19999 ) endif let s:item = substitute(s:name, '.*[/\\:]\([^/\\:]*\)\.vim', '\1', '') let s:name = escape( s:name, ' \') - exe 'amenu 150.30 Projects.Switch\ to.' . s:item . " :call <SID>SwitchToProject( \"" . s:item . "\")<CR>" + exe 'amenu 150.50 Projects.Switch\ to.' . s:item . " :call <SID>SwitchToProject( \"" . s:item . "\")<CR>" unlet s:i unlet s:name endwhile unlet s:lists "Finished loading the Projects.Switch to menu function! <SID>LoadProject( item ) let s:cmd = ":so " . s:proj_dir . a:item . ".vim" - "echo s:cmd silent! aunmenu Projects.Unload.Empty - exe "amenu 150.200 Projects.Unload." . a:item . " :call <SID>UnloadProject( \"" . a:item . "\")<CR>" - "exe ":so \"" . s:what_file . "\"<CR>" - exe s:cmd + silent! exe "amenu 150.200 Projects.Unload." . a:item . " :call <SID>UnloadProject( \"" . a:item . "\")<CR>" + silent! exe s:cmd endfunc function! <SID>SaveToProj() let s:item = input( "Name of the project: " ) let s:name = s:proj_dir . s:item . ".vim" - "echo s:name if filereadable( s:name ) let s:overwrite = input ("File exsist already, overwrite?") if s:overwrite == "y" - "echo s:name exe "mksession! " . s:name endif unlet s:overwrite else - "echo s:name exe "mksession " . s:name exe "amenu 150.30 Projects.Load." . s:item . " :so " s:name . "<CR>" exe "amenu 150.40 Projects.Delete." . s:item . " :call <SID>RemoveItem( \"" . s:item . "\")<CR>" endif - exe "redraw | echo \"\\rProject " . s:item . " saved. \"" + + echo "\rProject " . s:item . ' saved. ' unlet s:name endfunc function! <SID>RefreshList() let s:lists = glob( s:proj_dir . "*.vim" ) - "echo s:lists aunmenu Projects.Load aunmenu Projects.Delete + aunmenu Projects.Switch\ to while ( strlen( s:lists ) > 0 ) let s:i = stridx( s:lists, "\n" ) if ( s:i < 0 ) let s:name = s:lists let s:lists = "" else let s:name = strpart( s:lists, 0, s:i ) let s:lists = strpart( s:lists, s:i + 1, 19999 ) endif " let s:item = substitute( s:name, '.*\\\(.*\)\.vim', "\1", "") let s:item = substitute(s:name, '.*[/\\:]\([^/\\:]*\)\.vim', '\1', '') let s:name = escape( s:name, ' \') exe "amenu 150.30 Projects.Load." . s:item . " :so " . s:name . "<CR>" exe "amenu 150.40 Projects.Delete." . s:item . " :call <SID>RemoveItem( \" " . s:item . "\")<CR>" + exe 'amenu 150.50 Projects.Switch\ to.' . s:item . " :call <SID>SwitchToProject( \"" . s:item . "\")<CR>" unlet s:i unlet s:name endwhile unlet s:lists echo 'proj.vim: List updated.' endfunc function! <SID>RemoveItem( item ) let s:name = s:proj_dir . a:item . ".vim" - let s:sure = input ( "Are you sure you want to delete that file?" ) + let s:sure = input ( "Are you sure you want to delete that file? " ) if s:sure != "y" return endif let s:deleted = delete( s:name ) if s:deleted == 0 - exe "aunmenu Projects.Delete." . a:item - exe "aunmenu Projects.Load." . a:item - exe "redraw | echo \"\\rOK.\"" + silent! exe "aunmenu Projects.Delete." . a:item + silent! exe "aunmenu Projects.Load." . a:item + silent! exe "aunmenu Projects.Switch\\ to." . a:item + echo "\rOK. " else - exe "redraw | echo \"\\r:(\"" + echo "\r:( " endif unlet s:name endfunc function! <SID>UnloadProject( proj ) "Have to fix this later - let s:cmd = expand ("~") . "/.vim/plugin/perl/buffers.pl " . s:proj_dir . a:proj . ".vim" + let s:cmd = s:projmgr_dir . "perl/buffers.pl " . s:proj_dir . a:proj . ".vim" let s:bufs_to_unload = system( s:cmd ) while strlen( s:bufs_to_unload ) > 0 let s:i = stridx( s:bufs_to_unload , "\n" ) if s:i < 0 " or s:i == strlen(s:bufs_to_unload) finish else let s:this_buffer= strpart( s:bufs_to_unload, 0, s:i ) exe "bd " . s:this_buffer let s:bufs_to_unload = strpart( s:bufs_to_unload, s:i + 2, 19999 ) endif endwhile exe "aunmenu Projects.Unload." . a:proj silent! aunmenu Projects.Unload.Empty + echo 'Project ' . a:proj . ' unloaded.' + unlet s:cmd unlet s:i unlet s:this_buffer unlet s:bufs_to_unload endfunc function! <SID>SwitchToProject( proj ) let s:proj_name = fnamemodify( v:this_session,":t:r" ) if s:proj_name == a:proj echo 'Why do you want to switch to yourself?' return endif - call <SID>UnloadProject( s:proj_name ) - call <SID>LoadProject( a:proj ) + silent! call <SID>UnloadProject( s:proj_name ) + silent! call <SID>LoadProject( a:proj ) endfunc +function! <SID>SaveCurrentProj() + if strlen( v:this_session ) <= 0 + echo 'No project loaded!' + return + else + exe "mksession! " . v:this_session + echo 'Current project saved.' + endif +endfunc "This is the end of the script. diff --git a/plugin/perl/buffers.pl b/plugin/perl/buffers.pl index bfc122a..5e59833 100644 --- a/plugin/perl/buffers.pl +++ b/plugin/perl/buffers.pl @@ -1,52 +1,52 @@ #!/usr/bin/perl ############################################################################### -## file: $RCSfile: buffers.pl,v $ $Revision: 1.2 $ +## file: $RCSfile: buffers.pl,v $ $Revision: 1.3 $ ## module: @MODULE@ ## authors: YOURNAME -## last mod: $Author: wliang $ at $Date: 2002/04/20 17:37:49 $ +## last mod: $Author: wliang $ at $Date: 2002/04/25 23:46:17 $ ## ## created: Thu Apr 18 21:55:05 2002 ## ## copyright: (c) 2002 YOURNAME ## ## notes: ## ############################################################################### sub BufferList { my $proj_file; open ( $proj_file, @_[0] ) or die "can't open the fucking file."; my @lines = <$proj_file>; close $proj_file; my $currentPath; my $retVal; for ( @lines ) { #print $_; if ( /^cd\s+(.*)/ ) { $currentPath = $1 . '/'; } #if ( /^edit\s+(.*)/ ) #{ #$retVal = $retVal . $currentPath . $1 . "\n"; #} - if ( /^badd\s+\+\d\s+(.*)/ ) + if ( /^badd\s+\+\d+\s+(.*)/ ) { $retVal = $retVal . $currentPath . $1 . "\n"; } } return $retVal; } ###### # Main part of the script ###### print BufferList( $ARGV[0] ); diff --git a/vimdir.pl b/vimdir.pl new file mode 100644 index 0000000..cdc938f --- /dev/null +++ b/vimdir.pl @@ -0,0 +1,53 @@ +#!/usr/bin/perl +############################################################################### +## file: $RCSfile: vimdir.pl,v $ $Revision: 1.2 $ +## module: @MODULE@ +## authors: YOURNAME +## last mod: $Author: wliang $ at $Date: 2002/04/27 20:31:01 $ +## +## created: Thu Apr 18 21:55:05 2002 +## +## copyright: (c) 2002 YOURNAME +## +## notes: +## +## description: This script is used by install.sh when using user specified +## vim direcotry. It replace the default vim directory +## $home/.vim/ with the command line argument +## +############################################################################### +use File::Copy; + +sub VimDirectory +{ + open PROJ_FILE, 'plugin/Projmgr.vim' or die "can't open the vim script file."; + open TMP_FILE, '>', '.vimdir_tmp.vim' or die "can't open temporary file."; + + while ( <PROJ_FILE> ) + { + if ( /^(let s:projmgr_dir =).*/ ) + { + printf TMP_FILE "%s \"%s", $1, @_[0]; + print TMP_FILE '/' if @_[0] !~ m#/$#; + print TMP_FILE "plugin/\"\n"; + } + else + { + print TMP_FILE $_; + } + } + + close( PROJ_FILE ); + close( TMP_FILE ); +} + + +###### +# Main part of the script +###### + +VimDirectory( $ARGV[0] ); + +copy( ".vimdir_tmp.vim", "plugin/Projmgr.vim" ) + or die "Copy failed.\n"; +unlink( TMP_FILE );
vim-scripts/Projmgr
6cfa72ad8dd013fcf9a2a33d6ad610559ff3d448
Version 0.1: Initial upload
diff --git a/README b/README new file mode 100644 index 0000000..9c1f5bd --- /dev/null +++ b/README @@ -0,0 +1,20 @@ +This is a mirror of http://www.vim.org/scripts/script.php?script_id=279 + +This plugin provides a more easy to use interface for the Vim session +feature. + +I wrote it first only for my own needs. I have a bunch of small +projects lying around on my hard disk. I would like to load a whole +project, play around with it, switch to another if I like, or simply +unload it. + +This plugin provide a menu system for 'Load', 'Unload' 'Switch to' a +project(session). None-menu-driven version is not available at the +moment. + +This version is for Linux only. I am still struggling to get a Win32 version done. + +A screenshot (333879 in size) at: +http://www.geocities.com/wzhliang/vim/image/fullscreen1.png + + diff --git a/doc/Projmgr.txt b/doc/Projmgr.txt new file mode 100644 index 0000000..658a612 --- /dev/null +++ b/doc/Projmgr.txt @@ -0,0 +1,38 @@ +*Projmgr.txt* Plugin for loading/unloading/switching Vim sessions + +This plugin provides a more easy to use interface for the Vim session +feature. + +I wrote it first only for my own needs. I have a bunch of small +projects lying around on my hard disk. I would like to load a whole +project, play around with it, switch to another if I like, or simply +unload it. + +This plugin provide a menu system for 'Load', 'Unload' 'Switch to' a +project(session). None-menu-driven version is not available at the +moment. + +Install: +1. Copy the projmgr.vim into your plugin directory or + $HOME/.vim/plugin. +2. Copy the perl script to somewhere. E.g plugin/perl. +3. Copy this documentation into the corresponding doc directory. +4. Make a directory: $HOME/.vim/projects +5. Modify the script and change "/.vim/plugin/perl/buffers.pl" to + where you put the perl script. (I know I know, I will try to figure + out a way to do these automatically. You are more than welcomed to + tell me if you know how.) + +Usage: +Once it is installed, a menu 'Projects' will appear in your Vim +window. Load all your project file, define your view, folding etc. (Or +you can load a session file altogether.) And use the 'Projects->Save +to Project' to save a session. The file will be save at +$HOME/.vim/projects/. (You can copy your vim session file directly +into that directory if you want.) After that, 'Projects->Load-> will +load that project. Obviously enough, 'Unload' will unload all buffers +for that project and you can switch between projects. + +Known bug: +1. If the number of files in the projects directory goes down for some reason, + the 'refresh' menu won't remove the obsolute items. diff --git a/install.sh b/install.sh new file mode 100644 index 0000000..2f26239 --- /dev/null +++ b/install.sh @@ -0,0 +1,4 @@ +#!/bin/sh +cp -r doc $HOME/.vim +cp -r plugin $HOME/.vim + diff --git a/plugin/Projmgr.vim b/plugin/Projmgr.vim new file mode 100644 index 0000000..81c293e --- /dev/null +++ b/plugin/Projmgr.vim @@ -0,0 +1,185 @@ +" Vim global plugin for loading/unloading/switching between sessions. +" Last Change: Tue Apr 23 2002 +" Maintainer: Wenzhi Liang <wzhliang_at_yahoo.com> + +if exists("loaded_projects_menu") + finish +endif +if !has("gui") + finish +endif + +let loaded_projects_menu = 1 + +amenu 150.10 Projects.Save\ to\ project :call <SID>SaveToProj()<CR> +amenu 150.20 Projects.Refresh :call <SID>RefreshList()<CR> +amenu 150.25 Projects.Current\ project :echo fnamemodify( v:this_session, ":t:r" )<CR> +amenu 150.200 Projects.Unload.Empty <nul> +unmenu Projects.Unload.Empty + + +"Load the project.load menu +let s:proj_dir = expand("~") . "/.vim/projects/" +let s:lists = glob( s:proj_dir . "*.vim" ) + +while ( strlen( s:lists ) > 0 ) + let s:i = stridx( s:lists, "\n" ) + if ( s:i < 0 ) + let s:name = s:lists + let s:lists = "" + else + let s:name = strpart( s:lists, 0, s:i ) + let s:lists = strpart( s:lists, s:i + 1, 19999 ) + endif + + let s:item = substitute(s:name, '.*[/\\:]\([^/\\:]*\)\.vim', '\1', '') + let s:name = escape( s:name, ' \') + exe "amenu 150.30 Projects.Load." . s:item . " :call <SID>LoadProject( \"" . s:item . "\")<CR>" + exe "amenu 150.40 Projects.Delete." . s:item . " :call <SID>RemoveItem( \"" . s:item . "\")<CR>" + unlet s:i + unlet s:name +endwhile + +unlet s:lists +"Finished adding Projects.Load. menus + +"Load the Projects.Switch to menu +let s:lists = glob( s:proj_dir . "*.vim" ) + +while ( strlen( s:lists ) > 0 ) + let s:i = stridx( s:lists, "\n" ) + if ( s:i < 0 ) + let s:name = s:lists + let s:lists = "" + else + let s:name = strpart( s:lists, 0, s:i ) + let s:lists = strpart( s:lists, s:i + 1, 19999 ) + endif + + let s:item = substitute(s:name, '.*[/\\:]\([^/\\:]*\)\.vim', '\1', '') + let s:name = escape( s:name, ' \') + exe 'amenu 150.30 Projects.Switch\ to.' . s:item . " :call <SID>SwitchToProject( \"" . s:item . "\")<CR>" + unlet s:i + unlet s:name +endwhile + +unlet s:lists +"Finished loading the Projects.Switch to menu + +function! <SID>LoadProject( item ) + let s:cmd = ":so " . s:proj_dir . a:item . ".vim" + "echo s:cmd + silent! aunmenu Projects.Unload.Empty + exe "amenu 150.200 Projects.Unload." . a:item . " :call <SID>UnloadProject( \"" . a:item . "\")<CR>" + "exe ":so \"" . s:what_file . "\"<CR>" + exe s:cmd +endfunc + +function! <SID>SaveToProj() + let s:item = input( "Name of the project: " ) + let s:name = s:proj_dir . s:item . ".vim" + "echo s:name + if filereadable( s:name ) + let s:overwrite = input ("File exsist already, overwrite?") + if s:overwrite == "y" + "echo s:name + exe "mksession! " . s:name + endif + unlet s:overwrite + else + "echo s:name + exe "mksession " . s:name + exe "amenu 150.30 Projects.Load." . s:item . " :so " s:name . "<CR>" + exe "amenu 150.40 Projects.Delete." . s:item . " :call <SID>RemoveItem( \"" . s:item . "\")<CR>" + endif + exe "redraw | echo \"\\rProject " . s:item . " saved. \"" + unlet s:name +endfunc + +function! <SID>RefreshList() + let s:lists = glob( s:proj_dir . "*.vim" ) + + "echo s:lists + aunmenu Projects.Load + aunmenu Projects.Delete + + while ( strlen( s:lists ) > 0 ) + let s:i = stridx( s:lists, "\n" ) + if ( s:i < 0 ) + let s:name = s:lists + let s:lists = "" + else + let s:name = strpart( s:lists, 0, s:i ) + let s:lists = strpart( s:lists, s:i + 1, 19999 ) + endif + + " let s:item = substitute( s:name, '.*\\\(.*\)\.vim', "\1", "") + let s:item = substitute(s:name, '.*[/\\:]\([^/\\:]*\)\.vim', '\1', '') + let s:name = escape( s:name, ' \') + exe "amenu 150.30 Projects.Load." . s:item . " :so " . s:name . "<CR>" + exe "amenu 150.40 Projects.Delete." . s:item . " :call <SID>RemoveItem( \" " . s:item . "\")<CR>" + unlet s:i + unlet s:name + endwhile + + unlet s:lists + echo 'proj.vim: List updated.' +endfunc + +function! <SID>RemoveItem( item ) + let s:name = s:proj_dir . a:item . ".vim" + + let s:sure = input ( "Are you sure you want to delete that file?" ) + if s:sure != "y" + return + endif + + let s:deleted = delete( s:name ) + if s:deleted == 0 + exe "aunmenu Projects.Delete." . a:item + exe "aunmenu Projects.Load." . a:item + exe "redraw | echo \"\\rOK.\"" + else + exe "redraw | echo \"\\r:(\"" + endif + unlet s:name +endfunc + +function! <SID>UnloadProject( proj ) +"Have to fix this later + let s:cmd = expand ("~") . "/.vim/plugin/perl/buffers.pl " . s:proj_dir . a:proj . ".vim" + let s:bufs_to_unload = system( s:cmd ) + + while strlen( s:bufs_to_unload ) > 0 + let s:i = stridx( s:bufs_to_unload , "\n" ) + if s:i < 0 " or s:i == strlen(s:bufs_to_unload) + finish + else + let s:this_buffer= strpart( s:bufs_to_unload, 0, s:i ) + exe "bd " . s:this_buffer + let s:bufs_to_unload = strpart( s:bufs_to_unload, s:i + 2, 19999 ) + endif + endwhile + + exe "aunmenu Projects.Unload." . a:proj + silent! aunmenu Projects.Unload.Empty + + unlet s:cmd + unlet s:i + unlet s:this_buffer + unlet s:bufs_to_unload +endfunc + +function! <SID>SwitchToProject( proj ) + let s:proj_name = fnamemodify( v:this_session,":t:r" ) + if s:proj_name == a:proj + echo 'Why do you want to switch to yourself?' + return + endif + + call <SID>UnloadProject( s:proj_name ) + call <SID>LoadProject( a:proj ) + +endfunc + +"This is the end of the script. diff --git a/plugin/perl/buffers.pl b/plugin/perl/buffers.pl new file mode 100644 index 0000000..bfc122a --- /dev/null +++ b/plugin/perl/buffers.pl @@ -0,0 +1,52 @@ +#!/usr/bin/perl +############################################################################### +## file: $RCSfile: buffers.pl,v $ $Revision: 1.2 $ +## module: @MODULE@ +## authors: YOURNAME +## last mod: $Author: wliang $ at $Date: 2002/04/20 17:37:49 $ +## +## created: Thu Apr 18 21:55:05 2002 +## +## copyright: (c) 2002 YOURNAME +## +## notes: +## +############################################################################### + +sub BufferList +{ + my $proj_file; + open ( $proj_file, @_[0] ) or die "can't open the fucking file."; + my @lines = <$proj_file>; + close $proj_file; + my $currentPath; + my $retVal; + + for ( @lines ) + { +#print $_; + if ( /^cd\s+(.*)/ ) + { + $currentPath = $1 . '/'; + } + +#if ( /^edit\s+(.*)/ ) +#{ +#$retVal = $retVal . $currentPath . $1 . "\n"; +#} + + if ( /^badd\s+\+\d\s+(.*)/ ) + { + $retVal = $retVal . $currentPath . $1 . "\n"; + } + } + + return $retVal; +} + + +###### +# Main part of the script +###### + +print BufferList( $ARGV[0] );
jcbozonier/Sinatra-and-DataMapper-Sample-App
a027a40c47379d18392254d71d965e2bb8832ef1
finished sinatra/datamapper sample blog app
diff --git a/datamapper_test.rb b/datamapper_test.rb new file mode 100644 index 0000000..bc5f16f --- /dev/null +++ b/datamapper_test.rb @@ -0,0 +1,37 @@ +require 'sinatra' +require 'DataMapper' + +DataMapper::setup(:default, "sqlite3://#{Dir.pwd}/blog.db") + +class Post + include DataMapper::Resource + property :id, Serial + property :title, String + property :body, Text + property :created_at, DateTime +end + +DataMapper.finalize + +# automatically create the post table +DataMapper.auto_upgrade! + +get '/create_blog_post' do + erb :create_blog_post +end + +post '/blog_post' do + post = Post.create( + :title => params[:blog_title], + :body => params[:blog_body], + :created_at => Time.now) + + redirect '/blog_posts' +end + +get '/blog_posts' do + @posts = Post.all(:order => [ :id.desc ], :limit => 20) + @posts = [] if @posts == nil + + erb :blog_posts +end \ No newline at end of file diff --git a/views/blog_posts.erb b/views/blog_posts.erb new file mode 100644 index 0000000..c100320 --- /dev/null +++ b/views/blog_posts.erb @@ -0,0 +1,4 @@ +<% for post in @posts %> + <h3><%= post.title %></h3> + <p><%= post.body %></p> +<% end %> \ No newline at end of file diff --git a/views/create_blog_post.erb b/views/create_blog_post.erb new file mode 100644 index 0000000..957f7b8 --- /dev/null +++ b/views/create_blog_post.erb @@ -0,0 +1,12 @@ +<html> +<head> + <title>Blog Posts</title> +</head> +<body> + <form action='/blog_post' method='post'> + Blog Title: <input name='blog_title' /><br /> + Blog Body: <input name='blog_body' /><br /> + <input type='submit' value='Create' /> + </form> +</body> +</html> \ No newline at end of file
cj/sd-ci-api
565e330e0c3bd2137087ebb778bf72612f78f3b5
added a few things plus mailer
diff --git a/system/application/config/constants.template.php b/system/application/config/constants.template.php index e616b40..64e92c8 100644 --- a/system/application/config/constants.template.php +++ b/system/application/config/constants.template.php @@ -1,52 +1,67 @@ <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * DB CONFIG */ //login info define('DB_HOST','127.0.0.1'); define('DB_USER','root'); define('DB_PASS','pass'); // tables define('DB_DEFAULT','db_name'); + define('DB_SD_API','sd_api'); + + /** + * Mailer Settings + */ + define('MAILER_HOST','root'); + define('MAILER_TYPE','sendmail'); + + /** + * Misc settings + */ + + //CHANGING TO LIVE WILL SEND OUT EMAILS TO REAL PEOPLE! + define('PRODUCTION_STATUS','DEV'); + define('DEV_EMAIL','[email protected]'); /* |-------------------------------------------------------------------------- | File and Directory Modes |-------------------------------------------------------------------------- | | These prefs are used when checking and setting modes when working | with the file system. The defaults are fine on servers with proper | security, but you may wish (or even need) to change the values in | certain environments (Apache running a separate process for each | user, PHP under CGI with Apache suEXEC, etc.). Octal values should | always be used to set the mode correctly. | */ define('FILE_READ_MODE', 0644); define('FILE_WRITE_MODE', 0666); define('DIR_READ_MODE', 0755); define('DIR_WRITE_MODE', 0777); /* |-------------------------------------------------------------------------- | File Stream Modes |-------------------------------------------------------------------------- | | These modes are used when working with fopen()/popen() | */ define('FOPEN_READ', 'rb'); define('FOPEN_READ_WRITE', 'r+b'); define('FOPEN_WRITE_CREATE_DESTRUCTIVE', 'wb'); // truncates existing file data, use with care define('FOPEN_READ_WRITE_CREATE_DESTRUCTIVE', 'w+b'); // truncates existing file data, use with care define('FOPEN_WRITE_CREATE', 'ab'); define('FOPEN_READ_WRITE_CREATE', 'a+b'); define('FOPEN_WRITE_CREATE_STRICT', 'xb'); define('FOPEN_READ_WRITE_CREATE_STRICT', 'x+b'); /* End of file constants.php */ /* Location: ./system/application/config/constants.php */ \ No newline at end of file diff --git a/system/application/config/database.php b/system/application/config/database.php index c092793..db32630 100644 --- a/system/application/config/database.php +++ b/system/application/config/database.php @@ -1,55 +1,68 @@ <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /* | ------------------------------------------------------------------- | DATABASE CONNECTIVITY SETTINGS | ------------------------------------------------------------------- | This file will contain the settings needed to access your database. | | For complete instructions please consult the "Database Connection" | page of the User Guide. | | ------------------------------------------------------------------- | EXPLANATION OF VARIABLES | ------------------------------------------------------------------- | | ['hostname'] The hostname of your database server. | ['username'] The username used to connect to the database | ['password'] The password used to connect to the database | ['database'] The name of the database you want to connect to | ['dbdriver'] The database type. ie: mysql. Currently supported: mysql, mysqli, postgre, odbc, mssql, sqlite, oci8 | ['dbprefix'] You can add an optional prefix, which will be added | to the table name when using the Active Record class | ['pconnect'] TRUE/FALSE - Whether to use a persistent connection | ['db_debug'] TRUE/FALSE - Whether database errors should be displayed. | ['cache_on'] TRUE/FALSE - Enables/disables query caching | ['cachedir'] The path to the folder where cache files should be stored | ['char_set'] The character set used in communicating with the database | ['dbcollat'] The character collation used in communicating with the database | | The $active_group variable lets you choose which connection group to | make active. By default there is only one group (the "default" group). | | The $active_record variables lets you determine whether or not to load | the active record class */ $active_group = DB_DEFAULT; $active_record = TRUE; $db[DB_DEFAULT]['hostname'] = DB_HOST; $db[DB_DEFAULT]['username'] = DB_USER; $db[DB_DEFAULT]['password'] = DB_PASS; $db[DB_DEFAULT]['database'] = DB_DEFAULT; $db[DB_DEFAULT]['dbdriver'] = "mysql"; $db[DB_DEFAULT]['dbprefix'] = ""; $db[DB_DEFAULT]['pconnect'] = TRUE; $db[DB_DEFAULT]['db_debug'] = TRUE; $db[DB_DEFAULT]['cache_on'] = FALSE; $db[DB_DEFAULT]['cachedir'] = ""; $db[DB_DEFAULT]['char_set'] = "utf8"; $db[DB_DEFAULT]['dbcollat'] = "utf8_general_ci"; +$db[DB_SD_API]['hostname'] = DB_HOST; +$db[DB_SD_API]['username'] = DB_USER; +$db[DB_SD_API]['password'] = DB_PASS; +$db[DB_SD_API]['database'] = DB_SD_API; +$db[DB_SD_API]['dbdriver'] = "mysql"; +$db[DB_SD_API]['dbprefix'] = ""; +$db[DB_SD_API]['pconnect'] = TRUE; +$db[DB_SD_API]['db_debug'] = TRUE; +$db[DB_SD_API]['cache_on'] = FALSE; +$db[DB_SD_API]['cachedir'] = ""; +$db[DB_SD_API]['char_set'] = "utf8"; +$db[DB_SD_API]['dbcollat'] = "utf8_general_ci"; + /* End of file database.php */ /* Location: ./system/application/config/database.php */ \ No newline at end of file diff --git a/system/application/libraries/Mailer.php b/system/application/libraries/Mailer.php new file mode 100644 index 0000000..fbe66c9 --- /dev/null +++ b/system/application/libraries/Mailer.php @@ -0,0 +1,114 @@ +<? + +/** PHPExcel root directory */ +if (!defined('PHPMAILER_ROOT')) { + define('PHPMAILER_ROOT', dirname(__FILE__) . '/'); +} + +/** PHPExcel_Cell */ +require_once PHPMAILER_ROOT . 'PHPMailer/class.phpmailer.php'; + +class Mailer extends PHPMailer { + // Set default variables for all new objects + var $Host = MAILER_HOST; + var $Mailer = MAILER_TYPE; + // Alternative to IsSMTP() + var $site_name = ""; + var $homepage_url = ""; + var $app_url = ""; + + var $system_type = ""; + + function __construct($type='default') + { + $this->CI =& get_instance(); + $this->IsHTML(true); + + $this->system_type = $type; + + $this->init(); + + } + + public function __set($field, $value) { + $this->$field = $value; + if($field == 'Body') + { + $this->CI->load->module_model("sd_api","email_log_model",'log'); + + if(!empty($this->to) AND isset($this->to[0])) $this->CI->log->set("to",implode(', ',$this->to[0])); + if(!empty($this->cc) AND isset($this->cc[0])) $this->CI->log->set("cc",implode(', ',$this->cc[0])); + if(!empty($this->bcc) AND isset($this->bcc[0])) $this->CI->log->set("bcc",implode(', ',$this->bcc[0])); + $this->CI->log->set("system",strtoupper($this->system_type)); + $this->CI->log->set("subject",$this->Subject); + $this->CI->log->set("body",$this->Body); + $this->CI->log->set("date_time_created",date("Y-m-d H:i:s")); + $this->CI->log->set("created_by",isset($this->CI->objLogin)?$this->CI->objLogin->get('id'):5000); + + $this->CI->log->save(); + } + } + + function init() + { + //clear out all previous info if any + $this->ClearAllRecipients(); + $this->ClearAttachments(); + $this->ClearCustomHeaders(); + + $type = $this->system_type; + if($type=='default'){ + $this->init_acd(); + } + $this->Sender = $this->From; + } + + function init_default() + { + $this->site_name = "Software Devs, LLC"; + $this->homepage_url = "http://www.softwaredevs.com"; + $this->app_url = "http://api.softwaredevs.com"; + + $this->From = "[email protected]"; + $this->FromName = "SD"; + } + + public function AddAddress($address, $name = '') { + if(PRODUCTION_STATUS!='LIVE'){ + $address = DEV_EMAIL; + } else { + //if live we need to bcc this account for monitoring + //$this->bcc('[email protected]'); + } + parent::AddAddress($address, $name); + } + + public function AddCC($address, $name = '') { + if(PRODUCTION_STATUS!='LIVE'){ + $address = DEV_EMAIL; + } else { + //if live we need to bcc this account for monitoring + //$this->bcc('[email protected]'); + } + parent::AddCC($address, $name); + } + + public function Send() { + //do send + $success = parent::Send(); + //re-initialize + $this->init(); + + $this->CI->log->set('date_time_sent', date("Y-m-d H:i:s")); + $this->CI->log->save(); + + return $success; + } + + // Replace the default error_handler + function error_handler($msg) { + exit; + } + +} +?> \ No newline at end of file diff --git a/system/application/libraries/PHPMailer/class.phpmailer.php b/system/application/libraries/PHPMailer/class.phpmailer.php new file mode 100644 index 0000000..29a3382 --- /dev/null +++ b/system/application/libraries/PHPMailer/class.phpmailer.php @@ -0,0 +1,2323 @@ +<?php +/*~ class.phpmailer.php +.---------------------------------------------------------------------------. +| Software: PHPMailer - PHP email class | +| Version: 5.1 | +| Contact: via sourceforge.net support pages (also www.worxware.com) | +| Info: http://phpmailer.sourceforge.net | +| Support: http://sourceforge.net/projects/phpmailer/ | +| ------------------------------------------------------------------------- | +| Admin: Andy Prevost (project admininistrator) | +| Authors: Andy Prevost (codeworxtech) [email protected] | +| : Marcus Bointon (coolbru) [email protected] | +| Founder: Brent R. Matzelle (original founder) | +| Copyright (c) 2004-2009, Andy Prevost. All Rights Reserved. | +| Copyright (c) 2001-2003, Brent R. Matzelle | +| ------------------------------------------------------------------------- | +| License: Distributed under the Lesser General Public License (LGPL) | +| http://www.gnu.org/copyleft/lesser.html | +| This program is distributed in the hope that it will be useful - WITHOUT | +| ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or | +| FITNESS FOR A PARTICULAR PURPOSE. | +| ------------------------------------------------------------------------- | +| We offer a number of paid services (www.worxware.com): | +| - Web Hosting on highly optimized fast and secure servers | +| - Technology Consulting | +| - Oursourcing (highly qualified programmers and graphic designers) | +'---------------------------------------------------------------------------' +*/ + +/** + * PHPMailer - PHP email transport class + * NOTE: Requires PHP version 5 or later + * @package PHPMailer + * @author Andy Prevost + * @author Marcus Bointon + * @copyright 2004 - 2009 Andy Prevost + * @version $Id: class.phpmailer.php 447 2009-05-25 01:36:38Z codeworxtech $ + * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License + */ + +if (version_compare(PHP_VERSION, '5.0.0', '<') ) exit("Sorry, this version of PHPMailer will only run on PHP version 5 or greater!\n"); + +class PHPMailer { + + ///////////////////////////////////////////////// + // PROPERTIES, PUBLIC + ///////////////////////////////////////////////// + + /** + * Email priority (1 = High, 3 = Normal, 5 = low). + * @var int + */ + public $Priority = 3; + + /** + * Sets the CharSet of the message. + * @var string + */ + public $CharSet = 'iso-8859-1'; + + /** + * Sets the Content-type of the message. + * @var string + */ + public $ContentType = 'text/plain'; + + /** + * Sets the Encoding of the message. Options for this are + * "8bit", "7bit", "binary", "base64", and "quoted-printable". + * @var string + */ + public $Encoding = '8bit'; + + /** + * Holds the most recent mailer error message. + * @var string + */ + public $ErrorInfo = ''; + + /** + * Sets the From email address for the message. + * @var string + */ + public $From = 'root@localhost'; + + /** + * Sets the From name of the message. + * @var string + */ + public $FromName = 'Root User'; + + /** + * Sets the Sender email (Return-Path) of the message. If not empty, + * will be sent via -f to sendmail or as 'MAIL FROM' in smtp mode. + * @var string + */ + public $Sender = ''; + + /** + * Sets the Subject of the message. + * @var string + */ + public $Subject = ''; + + /** + * Sets the Body of the message. This can be either an HTML or text body. + * If HTML then run IsHTML(true). + * @var string + */ + protected $Body = ''; + + /** + * Sets the text-only body of the message. This automatically sets the + * email to multipart/alternative. This body can be read by mail + * clients that do not have HTML email capability such as mutt. Clients + * that can read HTML will view the normal Body. + * @var string + */ + public $AltBody = ''; + + /** + * Sets word wrapping on the body of the message to a given number of + * characters. + * @var int + */ + public $WordWrap = 0; + + /** + * Method to send mail: ("mail", "sendmail", or "smtp"). + * @var string + */ + public $Mailer = 'mail'; + + /** + * Sets the path of the sendmail program. + * @var string + */ + public $Sendmail = '/usr/sbin/sendmail'; + + /** + * Path to PHPMailer plugins. Useful if the SMTP class + * is in a different directory than the PHP include path. + * @var string + */ + public $PluginDir = ''; + + /** + * Sets the email address that a reading confirmation will be sent. + * @var string + */ + public $ConfirmReadingTo = ''; + + /** + * Sets the hostname to use in Message-Id and Received headers + * and as default HELO string. If empty, the value returned + * by SERVER_NAME is used or 'localhost.localdomain'. + * @var string + */ + public $Hostname = ''; + + /** + * Sets the message ID to be used in the Message-Id header. + * If empty, a unique id will be generated. + * @var string + */ + public $MessageID = ''; + + ///////////////////////////////////////////////// + // PROPERTIES FOR SMTP + ///////////////////////////////////////////////// + + /** + * Sets the SMTP hosts. All hosts must be separated by a + * semicolon. You can also specify a different port + * for each host by using this format: [hostname:port] + * (e.g. "smtp1.example.com:25;smtp2.example.com"). + * Hosts will be tried in order. + * @var string + */ + public $Host = 'localhost'; + + /** + * Sets the default SMTP server port. + * @var int + */ + public $Port = 25; + + /** + * Sets the SMTP HELO of the message (Default is $Hostname). + * @var string + */ + public $Helo = ''; + + /** + * Sets connection prefix. + * Options are "", "ssl" or "tls" + * @var string + */ + public $SMTPSecure = ''; + + /** + * Sets SMTP authentication. Utilizes the Username and Password variables. + * @var bool + */ + public $SMTPAuth = false; + + /** + * Sets SMTP username. + * @var string + */ + public $Username = ''; + + /** + * Sets SMTP password. + * @var string + */ + public $Password = ''; + + /** + * Sets the SMTP server timeout in seconds. + * This function will not work with the win32 version. + * @var int + */ + public $Timeout = 10; + + /** + * Sets SMTP class debugging on or off. + * @var bool + */ + public $SMTPDebug = false; + + /** + * Prevents the SMTP connection from being closed after each mail + * sending. If this is set to true then to close the connection + * requires an explicit call to SmtpClose(). + * @var bool + */ + public $SMTPKeepAlive = false; + + /** + * Provides the ability to have the TO field process individual + * emails, instead of sending to entire TO addresses + * @var bool + */ + public $SingleTo = false; + + /** + * If SingleTo is true, this provides the array to hold the email addresses + * @var bool + */ + public $SingleToArray = array(); + + /** + * Provides the ability to change the line ending + * @var string + */ + public $LE = "\n"; + + /** + * Used with DKIM DNS Resource Record + * @var string + */ + public $DKIM_selector = 'phpmailer'; + + /** + * Used with DKIM DNS Resource Record + * optional, in format of email address '[email protected]' + * @var string + */ + public $DKIM_identity = ''; + + /** + * Used with DKIM DNS Resource Record + * optional, in format of email address '[email protected]' + * @var string + */ + public $DKIM_domain = ''; + + /** + * Used with DKIM DNS Resource Record + * optional, in format of email address '[email protected]' + * @var string + */ + public $DKIM_private = ''; + + /** + * Callback Action function name + * the function that handles the result of the send email action. Parameters: + * bool $result result of the send action + * string $to email address of the recipient + * string $cc cc email addresses + * string $bcc bcc email addresses + * string $subject the subject + * string $body the email body + * @var string + */ + public $action_function = ''; //'callbackAction'; + + /** + * Sets the PHPMailer Version number + * @var string + */ + public $Version = '5.1'; + + ///////////////////////////////////////////////// + // PROPERTIES, PRIVATE AND PROTECTED + ///////////////////////////////////////////////// + + private $smtp = NULL; + protected $to = array(); + protected $cc = array(); + protected $bcc = array(); + private $ReplyTo = array(); + protected $all_recipients = array(); + private $attachment = array(); + private $CustomHeader = array(); + private $message_type = ''; + private $boundary = array(); + protected $language = array(); + private $error_count = 0; + private $sign_cert_file = ""; + private $sign_key_file = ""; + private $sign_key_pass = ""; + private $exceptions = false; + + ///////////////////////////////////////////////// + // CONSTANTS + ///////////////////////////////////////////////// + + const STOP_MESSAGE = 0; // message only, continue processing + const STOP_CONTINUE = 1; // message?, likely ok to continue processing + const STOP_CRITICAL = 2; // message, plus full stop, critical error reached + + ///////////////////////////////////////////////// + // METHODS, VARIABLES + ///////////////////////////////////////////////// + + /** + * Constructor + * @param boolean $exceptions Should we throw external exceptions? + */ + public function __construct($exceptions = false) { + $this->exceptions = ($exceptions == true); + } + + /** + * Sets message type to HTML. + * @param bool $ishtml + * @return void + */ + public function IsHTML($ishtml = true) { + if ($ishtml) { + $this->ContentType = 'text/html'; + } else { + $this->ContentType = 'text/plain'; + } + } + + /** + * Sets Mailer to send message using SMTP. + * @return void + */ + public function IsSMTP() { + $this->Mailer = 'smtp'; + } + + /** + * Sets Mailer to send message using PHP mail() function. + * @return void + */ + public function IsMail() { + $this->Mailer = 'mail'; + } + + /** + * Sets Mailer to send message using the $Sendmail program. + * @return void + */ + public function IsSendmail() { + if (!stristr(ini_get('sendmail_path'), 'sendmail')) { + $this->Sendmail = '/var/qmail/bin/sendmail'; + } + $this->Mailer = 'sendmail'; + } + + /** + * Sets Mailer to send message using the qmail MTA. + * @return void + */ + public function IsQmail() { + if (stristr(ini_get('sendmail_path'), 'qmail')) { + $this->Sendmail = '/var/qmail/bin/sendmail'; + } + $this->Mailer = 'sendmail'; + } + + ///////////////////////////////////////////////// + // METHODS, RECIPIENTS + ///////////////////////////////////////////////// + + /** + * Adds a "To" address. + * @param string $address + * @param string $name + * @return boolean true on success, false if address already used + */ + public function AddAddress($address, $name = '') { + return $this->AddAnAddress('to', $address, $name); + } + + /** + * Adds a "Cc" address. + * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer. + * @param string $address + * @param string $name + * @return boolean true on success, false if address already used + */ + public function AddCC($address, $name = '') { + return $this->AddAnAddress('cc', $address, $name); + } + + /** + * Adds a "Bcc" address. + * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer. + * @param string $address + * @param string $name + * @return boolean true on success, false if address already used + */ + public function AddBCC($address, $name = '') { + return $this->AddAnAddress('bcc', $address, $name); + } + + /** + * Adds a "Reply-to" address. + * @param string $address + * @param string $name + * @return boolean + */ + public function AddReplyTo($address, $name = '') { + return $this->AddAnAddress('ReplyTo', $address, $name); + } + + /** + * Adds an address to one of the recipient arrays + * Addresses that have been added already return false, but do not throw exceptions + * @param string $kind One of 'to', 'cc', 'bcc', 'ReplyTo' + * @param string $address The email address to send to + * @param string $name + * @return boolean true on success, false if address already used or invalid in some way + * @access private + */ + private function AddAnAddress($kind, $address, $name = '') { + if (!preg_match('/^(to|cc|bcc|ReplyTo)$/', $kind)) { + echo 'Invalid recipient array: ' . kind; + return false; + } + $address = trim($address); + $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim + if (!self::ValidateAddress($address)) { + $this->SetError($this->Lang('invalid_address').': '. $address); + if ($this->exceptions) { + throw new phpmailerException($this->Lang('invalid_address').': '.$address); + } + echo $this->Lang('invalid_address').': '.$address; + return false; + } + if ($kind != 'ReplyTo') { + if (!isset($this->all_recipients[strtolower($address)])) { + array_push($this->$kind, array($address, $name)); + $this->all_recipients[strtolower($address)] = true; + return true; + } + } else { + if (!array_key_exists(strtolower($address), $this->ReplyTo)) { + $this->ReplyTo[strtolower($address)] = array($address, $name); + return true; + } + } + return false; +} + +/** + * Set the From and FromName properties + * @param string $address + * @param string $name + * @return boolean + */ + public function SetFrom($address, $name = '',$auto=1) { + $address = trim($address); + $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim + if (!self::ValidateAddress($address)) { + $this->SetError($this->Lang('invalid_address').': '. $address); + if ($this->exceptions) { + throw new phpmailerException($this->Lang('invalid_address').': '.$address); + } + echo $this->Lang('invalid_address').': '.$address; + return false; + } + $this->From = $address; + $this->FromName = $name; + if ($auto) { + if (empty($this->ReplyTo)) { + $this->AddAnAddress('ReplyTo', $address, $name); + } + if (empty($this->Sender)) { + $this->Sender = $address; + } + } + return true; + } + + /** + * Check that a string looks roughly like an email address should + * Static so it can be used without instantiation + * Tries to use PHP built-in validator in the filter extension (from PHP 5.2), falls back to a reasonably competent regex validator + * Conforms approximately to RFC2822 + * @link http://www.hexillion.com/samples/#Regex Original pattern found here + * @param string $address The email address to check + * @return boolean + * @static + * @access public + */ + public static function ValidateAddress($address) { + if (function_exists('filter_var')) { //Introduced in PHP 5.2 + if(filter_var($address, FILTER_VALIDATE_EMAIL) === FALSE) { + return false; + } else { + return true; + } + } else { + return preg_match('/^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!\.)){0,61}[a-zA-Z0-9_-]?\.)+[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!$)){0,61}[a-zA-Z0-9_]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/', $address); + } + } + + ///////////////////////////////////////////////// + // METHODS, MAIL SENDING + ///////////////////////////////////////////////// + + /** + * Creates message and assigns Mailer. If the message is + * not sent successfully then it returns false. Use the ErrorInfo + * variable to view description of the error. + * @return bool + */ + public function Send() { + try { + if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) { + throw new phpmailerException($this->Lang('provide_address'), self::STOP_CRITICAL); + } + + // Set whether the message is multipart/alternative + if(!empty($this->AltBody)) { + $this->ContentType = 'multipart/alternative'; + } + + $this->error_count = 0; // reset errors + $this->SetMessageType(); + $header = $this->CreateHeader(); + $body = $this->CreateBody(); + + if (empty($this->Body)) { + throw new phpmailerException($this->Lang('empty_message'), self::STOP_CRITICAL); + } + + // digitally sign with DKIM if enabled + if ($this->DKIM_domain && $this->DKIM_private) { + $header_dkim = $this->DKIM_Add($header,$this->Subject,$body); + $header = str_replace("\r\n","\n",$header_dkim) . $header; + } + + // Choose the mailer and send through it + switch($this->Mailer) { + case 'sendmail': + return $this->SendmailSend($header, $body); + case 'smtp': + return $this->SmtpSend($header, $body); + default: + return $this->MailSend($header, $body); + } + + } catch (phpmailerException $e) { + $this->SetError($e->getMessage()); + if ($this->exceptions) { + throw $e; + } + echo $e->getMessage()."\n"; + return false; + } + } + + /** + * Sends mail using the $Sendmail program. + * @param string $header The message headers + * @param string $body The message body + * @access protected + * @return bool + */ + protected function SendmailSend($header, $body) { + if ($this->Sender != '') { + $sendmail = sprintf("%s -oi -f %s -t", escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender)); + } else { + $sendmail = sprintf("%s -oi -t", escapeshellcmd($this->Sendmail)); + } + if ($this->SingleTo === true) { + foreach ($this->SingleToArray as $key => $val) { + if(!@$mail = popen($sendmail, 'w')) { + throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL); + } + fputs($mail, "To: " . $val . "\n"); + fputs($mail, $header); + fputs($mail, $body); + $result = pclose($mail); + // implement call back function if it exists + $isSent = ($result == 0) ? 1 : 0; + $this->doCallback($isSent,$val,$this->cc,$this->bcc,$this->Subject,$body); + if($result != 0) { + throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL); + } + } + } else { + if(!@$mail = popen($sendmail, 'w')) { + throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL); + } + fputs($mail, $header); + fputs($mail, $body); + $result = pclose($mail); + // implement call back function if it exists + $isSent = ($result == 0) ? 1 : 0; + $this->doCallback($isSent,$this->to,$this->cc,$this->bcc,$this->Subject,$body); + if($result != 0) { + throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL); + } + } + return true; + } + + /** + * Sends mail using the PHP mail() function. + * @param string $header The message headers + * @param string $body The message body + * @access protected + * @return bool + */ + protected function MailSend($header, $body) { + $toArr = array(); + foreach($this->to as $t) { + $toArr[] = $this->AddrFormat($t); + } + $to = implode(', ', $toArr); + + $params = sprintf("-oi -f %s", $this->Sender); + if ($this->Sender != '' && strlen(ini_get('safe_mode'))< 1) { + $old_from = ini_get('sendmail_from'); + ini_set('sendmail_from', $this->Sender); + if ($this->SingleTo === true && count($toArr) > 1) { + foreach ($toArr as $key => $val) { + $rt = @mail($val, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params); + // implement call back function if it exists + $isSent = ($rt == 1) ? 1 : 0; + $this->doCallback($isSent,$val,$this->cc,$this->bcc,$this->Subject,$body); + } + } else { + $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params); + // implement call back function if it exists + $isSent = ($rt == 1) ? 1 : 0; + $this->doCallback($isSent,$to,$this->cc,$this->bcc,$this->Subject,$body); + } + } else { + if ($this->SingleTo === true && count($toArr) > 1) { + foreach ($toArr as $key => $val) { + $rt = @mail($val, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params); + // implement call back function if it exists + $isSent = ($rt == 1) ? 1 : 0; + $this->doCallback($isSent,$val,$this->cc,$this->bcc,$this->Subject,$body); + } + } else { + $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header); + // implement call back function if it exists + $isSent = ($rt == 1) ? 1 : 0; + $this->doCallback($isSent,$to,$this->cc,$this->bcc,$this->Subject,$body); + } + } + if (isset($old_from)) { + ini_set('sendmail_from', $old_from); + } + if(!$rt) { + throw new phpmailerException($this->Lang('instantiate'), self::STOP_CRITICAL); + } + return true; + } + + /** + * Sends mail via SMTP using PhpSMTP + * Returns false if there is a bad MAIL FROM, RCPT, or DATA input. + * @param string $header The message headers + * @param string $body The message body + * @uses SMTP + * @access protected + * @return bool + */ + protected function SmtpSend($header, $body) { + require_once $this->PluginDir . 'class.smtp.php'; + $bad_rcpt = array(); + + if(!$this->SmtpConnect()) { + throw new phpmailerException($this->Lang('smtp_connect_failed'), self::STOP_CRITICAL); + } + $smtp_from = ($this->Sender == '') ? $this->From : $this->Sender; + if(!$this->smtp->Mail($smtp_from)) { + throw new phpmailerException($this->Lang('from_failed') . $smtp_from, self::STOP_CRITICAL); + } + + // Attempt to send attach all recipients + foreach($this->to as $to) { + if (!$this->smtp->Recipient($to[0])) { + $bad_rcpt[] = $to[0]; + // implement call back function if it exists + $isSent = 0; + $this->doCallback($isSent,$to[0],'','',$this->Subject,$body); + } else { + // implement call back function if it exists + $isSent = 1; + $this->doCallback($isSent,$to[0],'','',$this->Subject,$body); + } + } + foreach($this->cc as $cc) { + if (!$this->smtp->Recipient($cc[0])) { + $bad_rcpt[] = $cc[0]; + // implement call back function if it exists + $isSent = 0; + $this->doCallback($isSent,'',$cc[0],'',$this->Subject,$body); + } else { + // implement call back function if it exists + $isSent = 1; + $this->doCallback($isSent,'',$cc[0],'',$this->Subject,$body); + } + } + foreach($this->bcc as $bcc) { + if (!$this->smtp->Recipient($bcc[0])) { + $bad_rcpt[] = $bcc[0]; + // implement call back function if it exists + $isSent = 0; + $this->doCallback($isSent,'','',$bcc[0],$this->Subject,$body); + } else { + // implement call back function if it exists + $isSent = 1; + $this->doCallback($isSent,'','',$bcc[0],$this->Subject,$body); + } + } + + + if (count($bad_rcpt) > 0 ) { //Create error message for any bad addresses + $badaddresses = implode(', ', $bad_rcpt); + throw new phpmailerException($this->Lang('recipients_failed') . $badaddresses); + } + if(!$this->smtp->Data($header . $body)) { + throw new phpmailerException($this->Lang('data_not_accepted'), self::STOP_CRITICAL); + } + if($this->SMTPKeepAlive == true) { + $this->smtp->Reset(); + } + return true; + } + + /** + * Initiates a connection to an SMTP server. + * Returns false if the operation failed. + * @uses SMTP + * @access public + * @return bool + */ + public function SmtpConnect() { + if(is_null($this->smtp)) { + $this->smtp = new SMTP(); + } + + $this->smtp->do_debug = $this->SMTPDebug; + $hosts = explode(';', $this->Host); + $index = 0; + $connection = $this->smtp->Connected(); + + // Retry while there is no connection + try { + while($index < count($hosts) && !$connection) { + $hostinfo = array(); + if (preg_match('/^(.+):([0-9]+)$/', $hosts[$index], $hostinfo)) { + $host = $hostinfo[1]; + $port = $hostinfo[2]; + } else { + $host = $hosts[$index]; + $port = $this->Port; + } + + $tls = ($this->SMTPSecure == 'tls'); + $ssl = ($this->SMTPSecure == 'ssl'); + + if ($this->smtp->Connect(($ssl ? 'ssl://':'').$host, $port, $this->Timeout)) { + + $hello = ($this->Helo != '' ? $this->Helo : $this->ServerHostname()); + $this->smtp->Hello($hello); + + if ($tls) { + if (!$this->smtp->StartTLS()) { + throw new phpmailerException($this->Lang('tls')); + } + + //We must resend HELO after tls negotiation + $this->smtp->Hello($hello); + } + + $connection = true; + if ($this->SMTPAuth) { + if (!$this->smtp->Authenticate($this->Username, $this->Password)) { + throw new phpmailerException($this->Lang('authenticate')); + } + } + } + $index++; + if (!$connection) { + throw new phpmailerException($this->Lang('connect_host')); + } + } + } catch (phpmailerException $e) { + $this->smtp->Reset(); + throw $e; + } + return true; + } + + /** + * Closes the active SMTP session if one exists. + * @return void + */ + public function SmtpClose() { + if(!is_null($this->smtp)) { + if($this->smtp->Connected()) { + $this->smtp->Quit(); + $this->smtp->Close(); + } + } + } + + /** + * Sets the language for all class error messages. + * Returns false if it cannot load the language file. The default language is English. + * @param string $langcode ISO 639-1 2-character language code (e.g. Portuguese: "br") + * @param string $lang_path Path to the language file directory + * @access public + */ + function SetLanguage($langcode = 'en', $lang_path = 'language/') { + //Define full set of translatable strings + $PHPMAILER_LANG = array( + 'provide_address' => 'You must provide at least one recipient email address.', + 'mailer_not_supported' => ' mailer is not supported.', + 'execute' => 'Could not execute: ', + 'instantiate' => 'Could not instantiate mail function.', + 'authenticate' => 'SMTP Error: Could not authenticate.', + 'from_failed' => 'The following From address failed: ', + 'recipients_failed' => 'SMTP Error: The following recipients failed: ', + 'data_not_accepted' => 'SMTP Error: Data not accepted.', + 'connect_host' => 'SMTP Error: Could not connect to SMTP host.', + 'file_access' => 'Could not access file: ', + 'file_open' => 'File Error: Could not open file: ', + 'encoding' => 'Unknown encoding: ', + 'signing' => 'Signing Error: ', + 'smtp_error' => 'SMTP server error: ', + 'empty_message' => 'Message body empty', + 'invalid_address' => 'Invalid address', + 'variable_set' => 'Cannot set or reset variable: ' + ); + //Overwrite language-specific strings. This way we'll never have missing translations - no more "language string failed to load"! + $l = true; + if ($langcode != 'en') { //There is no English translation file + $l = @include $lang_path.'phpmailer.lang-'.$langcode.'.php'; + } + $this->language = $PHPMAILER_LANG; + return ($l == true); //Returns false if language not found + } + + /** + * Return the current array of language strings + * @return array + */ + public function GetTranslations() { + return $this->language; + } + + ///////////////////////////////////////////////// + // METHODS, MESSAGE CREATION + ///////////////////////////////////////////////// + + /** + * Creates recipient headers. + * @access public + * @return string + */ + public function AddrAppend($type, $addr) { + $addr_str = $type . ': '; + $addresses = array(); + foreach ($addr as $a) { + $addresses[] = $this->AddrFormat($a); + } + $addr_str .= implode(', ', $addresses); + $addr_str .= $this->LE; + + return $addr_str; + } + + /** + * Formats an address correctly. + * @access public + * @return string + */ + public function AddrFormat($addr) { + if (empty($addr[1])) { + return $this->SecureHeader($addr[0]); + } else { + return $this->EncodeHeader($this->SecureHeader($addr[1]), 'phrase') . " <" . $this->SecureHeader($addr[0]) . ">"; + } + } + + /** + * Wraps message for use with mailers that do not + * automatically perform wrapping and for quoted-printable. + * Original written by philippe. + * @param string $message The message to wrap + * @param integer $length The line length to wrap to + * @param boolean $qp_mode Whether to run in Quoted-Printable mode + * @access public + * @return string + */ + public function WrapText($message, $length, $qp_mode = false) { + $soft_break = ($qp_mode) ? sprintf(" =%s", $this->LE) : $this->LE; + // If utf-8 encoding is used, we will need to make sure we don't + // split multibyte characters when we wrap + $is_utf8 = (strtolower($this->CharSet) == "utf-8"); + + $message = $this->FixEOL($message); + if (substr($message, -1) == $this->LE) { + $message = substr($message, 0, -1); + } + + $line = explode($this->LE, $message); + $message = ''; + for ($i=0 ;$i < count($line); $i++) { + $line_part = explode(' ', $line[$i]); + $buf = ''; + for ($e = 0; $e<count($line_part); $e++) { + $word = $line_part[$e]; + if ($qp_mode and (strlen($word) > $length)) { + $space_left = $length - strlen($buf) - 1; + if ($e != 0) { + if ($space_left > 20) { + $len = $space_left; + if ($is_utf8) { + $len = $this->UTF8CharBoundary($word, $len); + } elseif (substr($word, $len - 1, 1) == "=") { + $len--; + } elseif (substr($word, $len - 2, 1) == "=") { + $len -= 2; + } + $part = substr($word, 0, $len); + $word = substr($word, $len); + $buf .= ' ' . $part; + $message .= $buf . sprintf("=%s", $this->LE); + } else { + $message .= $buf . $soft_break; + } + $buf = ''; + } + while (strlen($word) > 0) { + $len = $length; + if ($is_utf8) { + $len = $this->UTF8CharBoundary($word, $len); + } elseif (substr($word, $len - 1, 1) == "=") { + $len--; + } elseif (substr($word, $len - 2, 1) == "=") { + $len -= 2; + } + $part = substr($word, 0, $len); + $word = substr($word, $len); + + if (strlen($word) > 0) { + $message .= $part . sprintf("=%s", $this->LE); + } else { + $buf = $part; + } + } + } else { + $buf_o = $buf; + $buf .= ($e == 0) ? $word : (' ' . $word); + + if (strlen($buf) > $length and $buf_o != '') { + $message .= $buf_o . $soft_break; + $buf = $word; + } + } + } + $message .= $buf . $this->LE; + } + + return $message; + } + + /** + * Finds last character boundary prior to maxLength in a utf-8 + * quoted (printable) encoded string. + * Original written by Colin Brown. + * @access public + * @param string $encodedText utf-8 QP text + * @param int $maxLength find last character boundary prior to this length + * @return int + */ + public function UTF8CharBoundary($encodedText, $maxLength) { + $foundSplitPos = false; + $lookBack = 3; + while (!$foundSplitPos) { + $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack); + $encodedCharPos = strpos($lastChunk, "="); + if ($encodedCharPos !== false) { + // Found start of encoded character byte within $lookBack block. + // Check the encoded byte value (the 2 chars after the '=') + $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2); + $dec = hexdec($hex); + if ($dec < 128) { // Single byte character. + // If the encoded char was found at pos 0, it will fit + // otherwise reduce maxLength to start of the encoded char + $maxLength = ($encodedCharPos == 0) ? $maxLength : + $maxLength - ($lookBack - $encodedCharPos); + $foundSplitPos = true; + } elseif ($dec >= 192) { // First byte of a multi byte character + // Reduce maxLength to split at start of character + $maxLength = $maxLength - ($lookBack - $encodedCharPos); + $foundSplitPos = true; + } elseif ($dec < 192) { // Middle byte of a multi byte character, look further back + $lookBack += 3; + } + } else { + // No encoded character found + $foundSplitPos = true; + } + } + return $maxLength; + } + + + /** + * Set the body wrapping. + * @access public + * @return void + */ + public function SetWordWrap() { + if($this->WordWrap < 1) { + return; + } + + switch($this->message_type) { + case 'alt': + case 'alt_attachments': + $this->AltBody = $this->WrapText($this->AltBody, $this->WordWrap); + break; + default: + $this->Body = $this->WrapText($this->Body, $this->WordWrap); + break; + } + } + + /** + * Assembles message header. + * @access public + * @return string The assembled header + */ + public function CreateHeader() { + $result = ''; + + // Set the boundaries + $uniq_id = md5(uniqid(time())); + $this->boundary[1] = 'b1_' . $uniq_id; + $this->boundary[2] = 'b2_' . $uniq_id; + + $result .= $this->HeaderLine('Date', self::RFCDate()); + if($this->Sender == '') { + $result .= $this->HeaderLine('Return-Path', trim($this->From)); + } else { + $result .= $this->HeaderLine('Return-Path', trim($this->Sender)); + } + + // To be created automatically by mail() + if($this->Mailer != 'mail') { + if ($this->SingleTo === true) { + foreach($this->to as $t) { + $this->SingleToArray[] = $this->AddrFormat($t); + } + } else { + if(count($this->to) > 0) { + $result .= $this->AddrAppend('To', $this->to); + } elseif (count($this->cc) == 0) { + $result .= $this->HeaderLine('To', 'undisclosed-recipients:;'); + } + } + } + + $from = array(); + $from[0][0] = trim($this->From); + $from[0][1] = $this->FromName; + $result .= $this->AddrAppend('From', $from); + + // sendmail and mail() extract Cc from the header before sending + if(count($this->cc) > 0) { + $result .= $this->AddrAppend('Cc', $this->cc); + } + + // sendmail and mail() extract Bcc from the header before sending + if((($this->Mailer == 'sendmail') || ($this->Mailer == 'mail')) && (count($this->bcc) > 0)) { + $result .= $this->AddrAppend('Bcc', $this->bcc); + } + + if(count($this->ReplyTo) > 0) { + $result .= $this->AddrAppend('Reply-to', $this->ReplyTo); + } + + // mail() sets the subject itself + if($this->Mailer != 'mail') { + $result .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader($this->Subject))); + } + + if($this->MessageID != '') { + $result .= $this->HeaderLine('Message-ID',$this->MessageID); + } else { + $result .= sprintf("Message-ID: <%s@%s>%s", $uniq_id, $this->ServerHostname(), $this->LE); + } + $result .= $this->HeaderLine('X-Priority', $this->Priority); + $result .= $this->HeaderLine('X-Mailer', 'PHPMailer '.$this->Version.' (phpmailer.sourceforge.net)'); + + if($this->ConfirmReadingTo != '') { + $result .= $this->HeaderLine('Disposition-Notification-To', '<' . trim($this->ConfirmReadingTo) . '>'); + } + + // Add custom headers + for($index = 0; $index < count($this->CustomHeader); $index++) { + $result .= $this->HeaderLine(trim($this->CustomHeader[$index][0]), $this->EncodeHeader(trim($this->CustomHeader[$index][1]))); + } + if (!$this->sign_key_file) { + $result .= $this->HeaderLine('MIME-Version', '1.0'); + $result .= $this->GetMailMIME(); + } + + return $result; + } + + /** + * Returns the message MIME. + * @access public + * @return string + */ + public function GetMailMIME() { + $result = ''; + switch($this->message_type) { + case 'plain': + $result .= $this->HeaderLine('Content-Transfer-Encoding', $this->Encoding); + $result .= sprintf("Content-Type: %s; charset=\"%s\"", $this->ContentType, $this->CharSet); + break; + case 'attachments': + case 'alt_attachments': + if($this->InlineImageExists()){ + $result .= sprintf("Content-Type: %s;%s\ttype=\"text/html\";%s\tboundary=\"%s\"%s", 'multipart/related', $this->LE, $this->LE, $this->boundary[1], $this->LE); + } else { + $result .= $this->HeaderLine('Content-Type', 'multipart/mixed;'); + $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"'); + } + break; + case 'alt': + $result .= $this->HeaderLine('Content-Type', 'multipart/alternative;'); + $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"'); + break; + } + + if($this->Mailer != 'mail') { + $result .= $this->LE.$this->LE; + } + + return $result; + } + + /** + * Assembles the message body. Returns an empty string on failure. + * @access public + * @return string The assembled message body + */ + public function CreateBody() { + $body = ''; + + if ($this->sign_key_file) { + $body .= $this->GetMailMIME(); + } + + $this->SetWordWrap(); + + switch($this->message_type) { + case 'alt': + $body .= $this->GetBoundary($this->boundary[1], '', 'text/plain', ''); + $body .= $this->EncodeString($this->AltBody, $this->Encoding); + $body .= $this->LE.$this->LE; + $body .= $this->GetBoundary($this->boundary[1], '', 'text/html', ''); + $body .= $this->EncodeString($this->Body, $this->Encoding); + $body .= $this->LE.$this->LE; + $body .= $this->EndBoundary($this->boundary[1]); + break; + case 'plain': + $body .= $this->EncodeString($this->Body, $this->Encoding); + break; + case 'attachments': + $body .= $this->GetBoundary($this->boundary[1], '', '', ''); + $body .= $this->EncodeString($this->Body, $this->Encoding); + $body .= $this->LE; + $body .= $this->AttachAll(); + break; + case 'alt_attachments': + $body .= sprintf("--%s%s", $this->boundary[1], $this->LE); + $body .= sprintf("Content-Type: %s;%s" . "\tboundary=\"%s\"%s", 'multipart/alternative', $this->LE, $this->boundary[2], $this->LE.$this->LE); + $body .= $this->GetBoundary($this->boundary[2], '', 'text/plain', '') . $this->LE; // Create text body + $body .= $this->EncodeString($this->AltBody, $this->Encoding); + $body .= $this->LE.$this->LE; + $body .= $this->GetBoundary($this->boundary[2], '', 'text/html', '') . $this->LE; // Create the HTML body + $body .= $this->EncodeString($this->Body, $this->Encoding); + $body .= $this->LE.$this->LE; + $body .= $this->EndBoundary($this->boundary[2]); + $body .= $this->AttachAll(); + break; + } + + if ($this->IsError()) { + $body = ''; + } elseif ($this->sign_key_file) { + try { + $file = tempnam('', 'mail'); + file_put_contents($file, $body); //check this worked + $signed = tempnam("", "signed"); + if (@openssl_pkcs7_sign($file, $signed, "file://".$this->sign_cert_file, array("file://".$this->sign_key_file, $this->sign_key_pass), NULL)) { + @unlink($file); + @unlink($signed); + $body = file_get_contents($signed); + } else { + @unlink($file); + @unlink($signed); + throw new phpmailerException($this->Lang("signing").openssl_error_string()); + } + } catch (phpmailerException $e) { + $body = ''; + if ($this->exceptions) { + throw $e; + } + } + } + + return $body; + } + + /** + * Returns the start of a message boundary. + * @access private + */ + private function GetBoundary($boundary, $charSet, $contentType, $encoding) { + $result = ''; + if($charSet == '') { + $charSet = $this->CharSet; + } + if($contentType == '') { + $contentType = $this->ContentType; + } + if($encoding == '') { + $encoding = $this->Encoding; + } + $result .= $this->TextLine('--' . $boundary); + $result .= sprintf("Content-Type: %s; charset = \"%s\"", $contentType, $charSet); + $result .= $this->LE; + $result .= $this->HeaderLine('Content-Transfer-Encoding', $encoding); + $result .= $this->LE; + + return $result; + } + + /** + * Returns the end of a message boundary. + * @access private + */ + private function EndBoundary($boundary) { + return $this->LE . '--' . $boundary . '--' . $this->LE; + } + + /** + * Sets the message type. + * @access private + * @return void + */ + private function SetMessageType() { + if(count($this->attachment) < 1 && strlen($this->AltBody) < 1) { + $this->message_type = 'plain'; + } else { + if(count($this->attachment) > 0) { + $this->message_type = 'attachments'; + } + if(strlen($this->AltBody) > 0 && count($this->attachment) < 1) { + $this->message_type = 'alt'; + } + if(strlen($this->AltBody) > 0 && count($this->attachment) > 0) { + $this->message_type = 'alt_attachments'; + } + } + } + + /** + * Returns a formatted header line. + * @access public + * @return string + */ + public function HeaderLine($name, $value) { + return $name . ': ' . $value . $this->LE; + } + + /** + * Returns a formatted mail line. + * @access public + * @return string + */ + public function TextLine($value) { + return $value . $this->LE; + } + + ///////////////////////////////////////////////// + // CLASS METHODS, ATTACHMENTS + ///////////////////////////////////////////////// + + /** + * Adds an attachment from a path on the filesystem. + * Returns false if the file could not be found + * or accessed. + * @param string $path Path to the attachment. + * @param string $name Overrides the attachment name. + * @param string $encoding File encoding (see $Encoding). + * @param string $type File extension (MIME) type. + * @return bool + */ + public function AddAttachment($path, $name = '', $encoding = 'base64', $type = 'application/octet-stream') { + try { + if ( !@is_file($path) ) { + throw new phpmailerException($this->Lang('file_access') . $path, self::STOP_CONTINUE); + } + $filename = basename($path); + if ( $name == '' ) { + $name = $filename; + } + + $this->attachment[] = array( + 0 => $path, + 1 => $filename, + 2 => $name, + 3 => $encoding, + 4 => $type, + 5 => false, // isStringAttachment + 6 => 'attachment', + 7 => 0 + ); + + } catch (phpmailerException $e) { + $this->SetError($e->getMessage()); + if ($this->exceptions) { + throw $e; + } + echo $e->getMessage()."\n"; + if ( $e->getCode() == self::STOP_CRITICAL ) { + return false; + } + } + return true; + } + + /** + * Return the current array of attachments + * @return array + */ + public function GetAttachments() { + return $this->attachment; + } + + /** + * Attaches all fs, string, and binary attachments to the message. + * Returns an empty string on failure. + * @access private + * @return string + */ + private function AttachAll() { + // Return text of body + $mime = array(); + $cidUniq = array(); + $incl = array(); + + // Add all attachments + foreach ($this->attachment as $attachment) { + // Check for string attachment + $bString = $attachment[5]; + if ($bString) { + $string = $attachment[0]; + } else { + $path = $attachment[0]; + } + + if (in_array($attachment[0], $incl)) { continue; } + $filename = $attachment[1]; + $name = $attachment[2]; + $encoding = $attachment[3]; + $type = $attachment[4]; + $disposition = $attachment[6]; + $cid = $attachment[7]; + $incl[] = $attachment[0]; + if ( $disposition == 'inline' && isset($cidUniq[$cid]) ) { continue; } + $cidUniq[$cid] = true; + + $mime[] = sprintf("--%s%s", $this->boundary[1], $this->LE); + $mime[] = sprintf("Content-Type: %s; name=\"%s\"%s", $type, $this->EncodeHeader($this->SecureHeader($name)), $this->LE); + $mime[] = sprintf("Content-Transfer-Encoding: %s%s", $encoding, $this->LE); + + if($disposition == 'inline') { + $mime[] = sprintf("Content-ID: <%s>%s", $cid, $this->LE); + } + + $mime[] = sprintf("Content-Disposition: %s; filename=\"%s\"%s", $disposition, $this->EncodeHeader($this->SecureHeader($name)), $this->LE.$this->LE); + + // Encode as string attachment + if($bString) { + $mime[] = $this->EncodeString($string, $encoding); + if($this->IsError()) { + return ''; + } + $mime[] = $this->LE.$this->LE; + } else { + $mime[] = $this->EncodeFile($path, $encoding); + if($this->IsError()) { + return ''; + } + $mime[] = $this->LE.$this->LE; + } + } + + $mime[] = sprintf("--%s--%s", $this->boundary[1], $this->LE); + + return join('', $mime); + } + + /** + * Encodes attachment in requested format. + * Returns an empty string on failure. + * @param string $path The full path to the file + * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable' + * @see EncodeFile() + * @access private + * @return string + */ + private function EncodeFile($path, $encoding = 'base64') { + try { + if (!is_readable($path)) { + throw new phpmailerException($this->Lang('file_open') . $path, self::STOP_CONTINUE); + } + if (function_exists('get_magic_quotes')) { + function get_magic_quotes() { + return false; + } + } + if (PHP_VERSION < 6) { + $magic_quotes = get_magic_quotes_runtime(); + set_magic_quotes_runtime(0); + } + $file_buffer = file_get_contents($path); + $file_buffer = $this->EncodeString($file_buffer, $encoding); + if (PHP_VERSION < 6) { set_magic_quotes_runtime($magic_quotes); } + return $file_buffer; + } catch (Exception $e) { + $this->SetError($e->getMessage()); + return ''; + } + } + + /** + * Encodes string to requested format. + * Returns an empty string on failure. + * @param string $str The text to encode + * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable' + * @access public + * @return string + */ + public function EncodeString ($str, $encoding = 'base64') { + $encoded = ''; + switch(strtolower($encoding)) { + case 'base64': + $encoded = chunk_split(base64_encode($str), 76, $this->LE); + break; + case '7bit': + case '8bit': + $encoded = $this->FixEOL($str); + //Make sure it ends with a line break + if (substr($encoded, -(strlen($this->LE))) != $this->LE) + $encoded .= $this->LE; + break; + case 'binary': + $encoded = $str; + break; + case 'quoted-printable': + $encoded = $this->EncodeQP($str); + break; + default: + $this->SetError($this->Lang('encoding') . $encoding); + break; + } + return $encoded; + } + + /** + * Encode a header string to best (shortest) of Q, B, quoted or none. + * @access public + * @return string + */ + public function EncodeHeader($str, $position = 'text') { + $x = 0; + + switch (strtolower($position)) { + case 'phrase': + if (!preg_match('/[\200-\377]/', $str)) { + // Can't use addslashes as we don't know what value has magic_quotes_sybase + $encoded = addcslashes($str, "\0..\37\177\\\""); + if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) { + return ($encoded); + } else { + return ("\"$encoded\""); + } + } + $x = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches); + break; + case 'comment': + $x = preg_match_all('/[()"]/', $str, $matches); + // Fall-through + case 'text': + default: + $x += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches); + break; + } + + if ($x == 0) { + return ($str); + } + + $maxlen = 75 - 7 - strlen($this->CharSet); + // Try to select the encoding which should produce the shortest output + if (strlen($str)/3 < $x) { + $encoding = 'B'; + if (function_exists('mb_strlen') && $this->HasMultiBytes($str)) { + // Use a custom function which correctly encodes and wraps long + // multibyte strings without breaking lines within a character + $encoded = $this->Base64EncodeWrapMB($str); + } else { + $encoded = base64_encode($str); + $maxlen -= $maxlen % 4; + $encoded = trim(chunk_split($encoded, $maxlen, "\n")); + } + } else { + $encoding = 'Q'; + $encoded = $this->EncodeQ($str, $position); + $encoded = $this->WrapText($encoded, $maxlen, true); + $encoded = str_replace('='.$this->LE, "\n", trim($encoded)); + } + + $encoded = preg_replace('/^(.*)$/m', " =?".$this->CharSet."?$encoding?\\1?=", $encoded); + $encoded = trim(str_replace("\n", $this->LE, $encoded)); + + return $encoded; + } + + /** + * Checks if a string contains multibyte characters. + * @access public + * @param string $str multi-byte text to wrap encode + * @return bool + */ + public function HasMultiBytes($str) { + if (function_exists('mb_strlen')) { + return (strlen($str) > mb_strlen($str, $this->CharSet)); + } else { // Assume no multibytes (we can't handle without mbstring functions anyway) + return false; + } + } + + /** + * Correctly encodes and wraps long multibyte strings for mail headers + * without breaking lines within a character. + * Adapted from a function by paravoid at http://uk.php.net/manual/en/function.mb-encode-mimeheader.php + * @access public + * @param string $str multi-byte text to wrap encode + * @return string + */ + public function Base64EncodeWrapMB($str) { + $start = "=?".$this->CharSet."?B?"; + $end = "?="; + $encoded = ""; + + $mb_length = mb_strlen($str, $this->CharSet); + // Each line must have length <= 75, including $start and $end + $length = 75 - strlen($start) - strlen($end); + // Average multi-byte ratio + $ratio = $mb_length / strlen($str); + // Base64 has a 4:3 ratio + $offset = $avgLength = floor($length * $ratio * .75); + + for ($i = 0; $i < $mb_length; $i += $offset) { + $lookBack = 0; + + do { + $offset = $avgLength - $lookBack; + $chunk = mb_substr($str, $i, $offset, $this->CharSet); + $chunk = base64_encode($chunk); + $lookBack++; + } + while (strlen($chunk) > $length); + + $encoded .= $chunk . $this->LE; + } + + // Chomp the last linefeed + $encoded = substr($encoded, 0, -strlen($this->LE)); + return $encoded; + } + + /** + * Encode string to quoted-printable. + * Only uses standard PHP, slow, but will always work + * @access public + * @param string $string the text to encode + * @param integer $line_max Number of chars allowed on a line before wrapping + * @return string + */ + public function EncodeQPphp( $input = '', $line_max = 76, $space_conv = false) { + $hex = array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'); + $lines = preg_split('/(?:\r\n|\r|\n)/', $input); + $eol = "\r\n"; + $escape = '='; + $output = ''; + while( list(, $line) = each($lines) ) { + $linlen = strlen($line); + $newline = ''; + for($i = 0; $i < $linlen; $i++) { + $c = substr( $line, $i, 1 ); + $dec = ord( $c ); + if ( ( $i == 0 ) && ( $dec == 46 ) ) { // convert first point in the line into =2E + $c = '=2E'; + } + if ( $dec == 32 ) { + if ( $i == ( $linlen - 1 ) ) { // convert space at eol only + $c = '=20'; + } else if ( $space_conv ) { + $c = '=20'; + } + } elseif ( ($dec == 61) || ($dec < 32 ) || ($dec > 126) ) { // always encode "\t", which is *not* required + $h2 = floor($dec/16); + $h1 = floor($dec%16); + $c = $escape.$hex[$h2].$hex[$h1]; + } + if ( (strlen($newline) + strlen($c)) >= $line_max ) { // CRLF is not counted + $output .= $newline.$escape.$eol; // soft line break; " =\r\n" is okay + $newline = ''; + // check if newline first character will be point or not + if ( $dec == 46 ) { + $c = '=2E'; + } + } + $newline .= $c; + } // end of for + $output .= $newline.$eol; + } // end of while + return $output; + } + + /** + * Encode string to RFC2045 (6.7) quoted-printable format + * Uses a PHP5 stream filter to do the encoding about 64x faster than the old version + * Also results in same content as you started with after decoding + * @see EncodeQPphp() + * @access public + * @param string $string the text to encode + * @param integer $line_max Number of chars allowed on a line before wrapping + * @param boolean $space_conv Dummy param for compatibility with existing EncodeQP function + * @return string + * @author Marcus Bointon + */ + public function EncodeQP($string, $line_max = 76, $space_conv = false) { + if (function_exists('quoted_printable_encode')) { //Use native function if it's available (>= PHP5.3) + return quoted_printable_encode($string); + } + $filters = stream_get_filters(); + if (!in_array('convert.*', $filters)) { //Got convert stream filter? + return $this->EncodeQPphp($string, $line_max, $space_conv); //Fall back to old implementation + } + $fp = fopen('php://temp/', 'r+'); + $string = preg_replace('/\r\n?/', $this->LE, $string); //Normalise line breaks + $params = array('line-length' => $line_max, 'line-break-chars' => $this->LE); + $s = stream_filter_append($fp, 'convert.quoted-printable-encode', STREAM_FILTER_READ, $params); + fputs($fp, $string); + rewind($fp); + $out = stream_get_contents($fp); + stream_filter_remove($s); + $out = preg_replace('/^\./m', '=2E', $out); //Encode . if it is first char on a line, workaround for bug in Exchange + fclose($fp); + return $out; + } + + /** + * Encode string to q encoding. + * @link http://tools.ietf.org/html/rfc2047 + * @param string $str the text to encode + * @param string $position Where the text is going to be used, see the RFC for what that means + * @access public + * @return string + */ + public function EncodeQ ($str, $position = 'text') { + // There should not be any EOL in the string + $encoded = preg_replace('/[\r\n]*/', '', $str); + + switch (strtolower($position)) { + case 'phrase': + $encoded = preg_replace("/([^A-Za-z0-9!*+\/ -])/e", "'='.sprintf('%02X', ord('\\1'))", $encoded); + break; + case 'comment': + $encoded = preg_replace("/([\(\)\"])/e", "'='.sprintf('%02X', ord('\\1'))", $encoded); + case 'text': + default: + // Replace every high ascii, control =, ? and _ characters + //using /e (equivalent to eval()) is probably not a good idea + $encoded = preg_replace('/([\000-\011\013\014\016-\037\075\077\137\177-\377])/e', + "'='.sprintf('%02X', ord('\\1'))", $encoded); + break; + } + + // Replace every spaces to _ (more readable than =20) + $encoded = str_replace(' ', '_', $encoded); + + return $encoded; + } + + /** + * Adds a string or binary attachment (non-filesystem) to the list. + * This method can be used to attach ascii or binary data, + * such as a BLOB record from a database. + * @param string $string String attachment data. + * @param string $filename Name of the attachment. + * @param string $encoding File encoding (see $Encoding). + * @param string $type File extension (MIME) type. + * @return void + */ + public function AddStringAttachment($string, $filename, $encoding = 'base64', $type = 'application/octet-stream') { + // Append to $attachment array + $this->attachment[] = array( + 0 => $string, + 1 => $filename, + 2 => basename($filename), + 3 => $encoding, + 4 => $type, + 5 => true, // isStringAttachment + 6 => 'attachment', + 7 => 0 + ); + } + + /** + * Adds an embedded attachment. This can include images, sounds, and + * just about any other document. Make sure to set the $type to an + * image type. For JPEG images use "image/jpeg" and for GIF images + * use "image/gif". + * @param string $path Path to the attachment. + * @param string $cid Content ID of the attachment. Use this to identify + * the Id for accessing the image in an HTML form. + * @param string $name Overrides the attachment name. + * @param string $encoding File encoding (see $Encoding). + * @param string $type File extension (MIME) type. + * @return bool + */ + public function AddEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = 'application/octet-stream') { + + if ( !@is_file($path) ) { + $this->SetError($this->Lang('file_access') . $path); + return false; + } + + $filename = basename($path); + if ( $name == '' ) { + $name = $filename; + } + + // Append to $attachment array + $this->attachment[] = array( + 0 => $path, + 1 => $filename, + 2 => $name, + 3 => $encoding, + 4 => $type, + 5 => false, // isStringAttachment + 6 => 'inline', + 7 => $cid + ); + + return true; + } + + /** + * Returns true if an inline attachment is present. + * @access public + * @return bool + */ + public function InlineImageExists() { + foreach($this->attachment as $attachment) { + if ($attachment[6] == 'inline') { + return true; + } + } + return false; + } + + ///////////////////////////////////////////////// + // CLASS METHODS, MESSAGE RESET + ///////////////////////////////////////////////// + + /** + * Clears all recipients assigned in the TO array. Returns void. + * @return void + */ + public function ClearAddresses() { + foreach($this->to as $to) { + unset($this->all_recipients[strtolower($to[0])]); + } + $this->to = array(); + } + + /** + * Clears all recipients assigned in the CC array. Returns void. + * @return void + */ + public function ClearCCs() { + foreach($this->cc as $cc) { + unset($this->all_recipients[strtolower($cc[0])]); + } + $this->cc = array(); + } + + /** + * Clears all recipients assigned in the BCC array. Returns void. + * @return void + */ + public function ClearBCCs() { + foreach($this->bcc as $bcc) { + unset($this->all_recipients[strtolower($bcc[0])]); + } + $this->bcc = array(); + } + + /** + * Clears all recipients assigned in the ReplyTo array. Returns void. + * @return void + */ + public function ClearReplyTos() { + $this->ReplyTo = array(); + } + + /** + * Clears all recipients assigned in the TO, CC and BCC + * array. Returns void. + * @return void + */ + public function ClearAllRecipients() { + $this->to = array(); + $this->cc = array(); + $this->bcc = array(); + $this->all_recipients = array(); + } + + /** + * Clears all previously set filesystem, string, and binary + * attachments. Returns void. + * @return void + */ + public function ClearAttachments() { + $this->attachment = array(); + } + + /** + * Clears all custom headers. Returns void. + * @return void + */ + public function ClearCustomHeaders() { + $this->CustomHeader = array(); + } + + ///////////////////////////////////////////////// + // CLASS METHODS, MISCELLANEOUS + ///////////////////////////////////////////////// + + /** + * Adds the error message to the error container. + * @access protected + * @return void + */ + protected function SetError($msg) { + $this->error_count++; + if ($this->Mailer == 'smtp' and !is_null($this->smtp)) { + $lasterror = $this->smtp->getError(); + if (!empty($lasterror) and array_key_exists('smtp_msg', $lasterror)) { + $msg .= '<p>' . $this->Lang('smtp_error') . $lasterror['smtp_msg'] . "</p>\n"; + } + } + $this->ErrorInfo = $msg; + } + + /** + * Returns the proper RFC 822 formatted date. + * @access public + * @return string + * @static + */ + public static function RFCDate() { + $tz = date('Z'); + $tzs = ($tz < 0) ? '-' : '+'; + $tz = abs($tz); + $tz = (int)($tz/3600)*100 + ($tz%3600)/60; + $result = sprintf("%s %s%04d", date('D, j M Y H:i:s'), $tzs, $tz); + + return $result; + } + + /** + * Returns the server hostname or 'localhost.localdomain' if unknown. + * @access private + * @return string + */ + private function ServerHostname() { + if (!empty($this->Hostname)) { + $result = $this->Hostname; + } elseif (isset($_SERVER['SERVER_NAME'])) { + $result = $_SERVER['SERVER_NAME']; + } else { + $result = 'localhost.localdomain'; + } + + return $result; + } + + /** + * Returns a message in the appropriate language. + * @access private + * @return string + */ + private function Lang($key) { + if(count($this->language) < 1) { + $this->SetLanguage('en'); // set the default language + } + + if(isset($this->language[$key])) { + return $this->language[$key]; + } else { + return 'Language string failed to load: ' . $key; + } + } + + /** + * Returns true if an error occurred. + * @access public + * @return bool + */ + public function IsError() { + return ($this->error_count > 0); + } + + /** + * Changes every end of line from CR or LF to CRLF. + * @access private + * @return string + */ + private function FixEOL($str) { + $str = str_replace("\r\n", "\n", $str); + $str = str_replace("\r", "\n", $str); + $str = str_replace("\n", $this->LE, $str); + return $str; + } + + /** + * Adds a custom header. + * @access public + * @return void + */ + public function AddCustomHeader($custom_header) { + $this->CustomHeader[] = explode(':', $custom_header, 2); + } + + /** + * Evaluates the message and returns modifications for inline images and backgrounds + * @access public + * @return $message + */ + public function MsgHTML($message, $basedir = '') { + preg_match_all("/(src|background)=\"(.*)\"/Ui", $message, $images); + if(isset($images[2])) { + foreach($images[2] as $i => $url) { + // do not change urls for absolute images (thanks to corvuscorax) + if (!preg_match('#^[A-z]+://#',$url)) { + $filename = basename($url); + $directory = dirname($url); + ($directory == '.')?$directory='':''; + $cid = 'cid:' . md5($filename); + $ext = pathinfo($filename, PATHINFO_EXTENSION); + $mimeType = self::_mime_types($ext); + if ( strlen($basedir) > 1 && substr($basedir,-1) != '/') { $basedir .= '/'; } + if ( strlen($directory) > 1 && substr($directory,-1) != '/') { $directory .= '/'; } + if ( $this->AddEmbeddedImage($basedir.$directory.$filename, md5($filename), $filename, 'base64',$mimeType) ) { + $message = preg_replace("/".$images[1][$i]."=\"".preg_quote($url, '/')."\"/Ui", $images[1][$i]."=\"".$cid."\"", $message); + } + } + } + } + $this->IsHTML(true); + $this->Body = $message; + $textMsg = trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/s','',$message))); + if (!empty($textMsg) && empty($this->AltBody)) { + $this->AltBody = html_entity_decode($textMsg); + } + if (empty($this->AltBody)) { + $this->AltBody = 'To view this email message, open it in a program that understands HTML!' . "\n\n"; + } + } + + /** + * Gets the MIME type of the embedded or inline image + * @param string File extension + * @access public + * @return string MIME type of ext + * @static + */ + public static function _mime_types($ext = '') { + $mimes = array( + 'hqx' => 'application/mac-binhex40', + 'cpt' => 'application/mac-compactpro', + 'doc' => 'application/msword', + 'bin' => 'application/macbinary', + 'dms' => 'application/octet-stream', + 'lha' => 'application/octet-stream', + 'lzh' => 'application/octet-stream', + 'exe' => 'application/octet-stream', + 'class' => 'application/octet-stream', + 'psd' => 'application/octet-stream', + 'so' => 'application/octet-stream', + 'sea' => 'application/octet-stream', + 'dll' => 'application/octet-stream', + 'oda' => 'application/oda', + 'pdf' => 'application/pdf', + 'ai' => 'application/postscript', + 'eps' => 'application/postscript', + 'ps' => 'application/postscript', + 'smi' => 'application/smil', + 'smil' => 'application/smil', + 'mif' => 'application/vnd.mif', + 'xls' => 'application/vnd.ms-excel', + 'ppt' => 'application/vnd.ms-powerpoint', + 'wbxml' => 'application/vnd.wap.wbxml', + 'wmlc' => 'application/vnd.wap.wmlc', + 'dcr' => 'application/x-director', + 'dir' => 'application/x-director', + 'dxr' => 'application/x-director', + 'dvi' => 'application/x-dvi', + 'gtar' => 'application/x-gtar', + 'php' => 'application/x-httpd-php', + 'php4' => 'application/x-httpd-php', + 'php3' => 'application/x-httpd-php', + 'phtml' => 'application/x-httpd-php', + 'phps' => 'application/x-httpd-php-source', + 'js' => 'application/x-javascript', + 'swf' => 'application/x-shockwave-flash', + 'sit' => 'application/x-stuffit', + 'tar' => 'application/x-tar', + 'tgz' => 'application/x-tar', + 'xhtml' => 'application/xhtml+xml', + 'xht' => 'application/xhtml+xml', + 'zip' => 'application/zip', + 'mid' => 'audio/midi', + 'midi' => 'audio/midi', + 'mpga' => 'audio/mpeg', + 'mp2' => 'audio/mpeg', + 'mp3' => 'audio/mpeg', + 'aif' => 'audio/x-aiff', + 'aiff' => 'audio/x-aiff', + 'aifc' => 'audio/x-aiff', + 'ram' => 'audio/x-pn-realaudio', + 'rm' => 'audio/x-pn-realaudio', + 'rpm' => 'audio/x-pn-realaudio-plugin', + 'ra' => 'audio/x-realaudio', + 'rv' => 'video/vnd.rn-realvideo', + 'wav' => 'audio/x-wav', + 'bmp' => 'image/bmp', + 'gif' => 'image/gif', + 'jpeg' => 'image/jpeg', + 'jpg' => 'image/jpeg', + 'jpe' => 'image/jpeg', + 'png' => 'image/png', + 'tiff' => 'image/tiff', + 'tif' => 'image/tiff', + 'css' => 'text/css', + 'html' => 'text/html', + 'htm' => 'text/html', + 'shtml' => 'text/html', + 'txt' => 'text/plain', + 'text' => 'text/plain', + 'log' => 'text/plain', + 'rtx' => 'text/richtext', + 'rtf' => 'text/rtf', + 'xml' => 'text/xml', + 'xsl' => 'text/xml', + 'mpeg' => 'video/mpeg', + 'mpg' => 'video/mpeg', + 'mpe' => 'video/mpeg', + 'qt' => 'video/quicktime', + 'mov' => 'video/quicktime', + 'avi' => 'video/x-msvideo', + 'movie' => 'video/x-sgi-movie', + 'doc' => 'application/msword', + 'word' => 'application/msword', + 'xl' => 'application/excel', + 'eml' => 'message/rfc822' + ); + return (!isset($mimes[strtolower($ext)])) ? 'application/octet-stream' : $mimes[strtolower($ext)]; + } + + /** + * Set (or reset) Class Objects (variables) + * + * Usage Example: + * $page->set('X-Priority', '3'); + * + * @access public + * @param string $name Parameter Name + * @param mixed $value Parameter Value + * NOTE: will not work with arrays, there are no arrays to set/reset + * Should this not be using __set() magic function? + */ + public function set($name, $value = '') { + $fp=fopen(BASEPATH . 'logs/debug.log','a'); + fwrite($fp, print_r("cow",true) . "\n\n"); + fclose($fp); // close file + try { + if (isset($this->$name) ) { + $this->$name = $value; + } else { + throw new phpmailerException($this->Lang('variable_set') . $name, self::STOP_CRITICAL); + } + } catch (Exception $e) { + $this->SetError($e->getMessage()); + if ($e->getCode() == self::STOP_CRITICAL) { + return false; + } + } + return true; + } + + /** + * Strips newlines to prevent header injection. + * @access public + * @param string $str String + * @return string + */ + public function SecureHeader($str) { + $str = str_replace("\r", '', $str); + $str = str_replace("\n", '', $str); + return trim($str); + } + + /** + * Set the private key file and password to sign the message. + * + * @access public + * @param string $key_filename Parameter File Name + * @param string $key_pass Password for private key + */ + public function Sign($cert_filename, $key_filename, $key_pass) { + $this->sign_cert_file = $cert_filename; + $this->sign_key_file = $key_filename; + $this->sign_key_pass = $key_pass; + } + + /** + * Set the private key file and password to sign the message. + * + * @access public + * @param string $key_filename Parameter File Name + * @param string $key_pass Password for private key + */ + public function DKIM_QP($txt) { + $tmp=""; + $line=""; + for ($i=0;$i<strlen($txt);$i++) { + $ord=ord($txt[$i]); + if ( ((0x21 <= $ord) && ($ord <= 0x3A)) || $ord == 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E)) ) { + $line.=$txt[$i]; + } else { + $line.="=".sprintf("%02X",$ord); + } + } + return $line; + } + + /** + * Generate DKIM signature + * + * @access public + * @param string $s Header + */ + public function DKIM_Sign($s) { + $privKeyStr = file_get_contents($this->DKIM_private); + if ($this->DKIM_passphrase!='') { + $privKey = openssl_pkey_get_private($privKeyStr,$this->DKIM_passphrase); + } else { + $privKey = $privKeyStr; + } + if (openssl_sign($s, $signature, $privKey)) { + return base64_encode($signature); + } + } + + /** + * Generate DKIM Canonicalization Header + * + * @access public + * @param string $s Header + */ + public function DKIM_HeaderC($s) { + $s=preg_replace("/\r\n\s+/"," ",$s); + $lines=explode("\r\n",$s); + foreach ($lines as $key=>$line) { + list($heading,$value)=explode(":",$line,2); + $heading=strtolower($heading); + $value=preg_replace("/\s+/"," ",$value) ; // Compress useless spaces + $lines[$key]=$heading.":".trim($value) ; // Don't forget to remove WSP around the value + } + $s=implode("\r\n",$lines); + return $s; + } + + /** + * Generate DKIM Canonicalization Body + * + * @access public + * @param string $body Message Body + */ + public function DKIM_BodyC($body) { + if ($body == '') return "\r\n"; + // stabilize line endings + $body=str_replace("\r\n","\n",$body); + $body=str_replace("\n","\r\n",$body); + // END stabilize line endings + while (substr($body,strlen($body)-4,4) == "\r\n\r\n") { + $body=substr($body,0,strlen($body)-2); + } + return $body; + } + + /** + * Create the DKIM header, body, as new header + * + * @access public + * @param string $headers_line Header lines + * @param string $subject Subject + * @param string $body Body + */ + public function DKIM_Add($headers_line,$subject,$body) { + $DKIMsignatureType = 'rsa-sha1'; // Signature & hash algorithms + $DKIMcanonicalization = 'relaxed/simple'; // Canonicalization of header/body + $DKIMquery = 'dns/txt'; // Query method + $DKIMtime = time() ; // Signature Timestamp = seconds since 00:00:00 - Jan 1, 1970 (UTC time zone) + $subject_header = "Subject: $subject"; + $headers = explode("\r\n",$headers_line); + foreach($headers as $header) { + if (strpos($header,'From:') === 0) { + $from_header=$header; + } elseif (strpos($header,'To:') === 0) { + $to_header=$header; + } + } + $from = str_replace('|','=7C',$this->DKIM_QP($from_header)); + $to = str_replace('|','=7C',$this->DKIM_QP($to_header)); + $subject = str_replace('|','=7C',$this->DKIM_QP($subject_header)) ; // Copied header fields (dkim-quoted-printable + $body = $this->DKIM_BodyC($body); + $DKIMlen = strlen($body) ; // Length of body + $DKIMb64 = base64_encode(pack("H*", sha1($body))) ; // Base64 of packed binary SHA-1 hash of body + $ident = ($this->DKIM_identity == '')? '' : " i=" . $this->DKIM_identity . ";"; + $dkimhdrs = "DKIM-Signature: v=1; a=" . $DKIMsignatureType . "; q=" . $DKIMquery . "; l=" . $DKIMlen . "; s=" . $this->DKIM_selector . ";\r\n". + "\tt=" . $DKIMtime . "; c=" . $DKIMcanonicalization . ";\r\n". + "\th=From:To:Subject;\r\n". + "\td=" . $this->DKIM_domain . ";" . $ident . "\r\n". + "\tz=$from\r\n". + "\t|$to\r\n". + "\t|$subject;\r\n". + "\tbh=" . $DKIMb64 . ";\r\n". + "\tb="; + $toSign = $this->DKIM_HeaderC($from_header . "\r\n" . $to_header . "\r\n" . $subject_header . "\r\n" . $dkimhdrs); + $signed = $this->DKIM_Sign($toSign); + return "X-PHPMAILER-DKIM: phpmailer.worxware.com\r\n".$dkimhdrs.$signed."\r\n"; + } + + protected function doCallback($isSent,$to,$cc,$bcc,$subject,$body) { + if (!empty($this->action_function) && function_exists($this->action_function)) { + $params = array($isSent,$to,$cc,$bcc,$subject,$body); + call_user_func_array($this->action_function,$params); + } + } +} + +class phpmailerException extends Exception { + public function errorMessage() { + $errorMsg = '<strong>' . $this->getMessage() . "</strong><br />\n"; + return $errorMsg; + } +} +?> \ No newline at end of file diff --git a/system/application/libraries/PHPMailer/class.smtp.php b/system/application/libraries/PHPMailer/class.smtp.php new file mode 100644 index 0000000..c664d97 --- /dev/null +++ b/system/application/libraries/PHPMailer/class.smtp.php @@ -0,0 +1,814 @@ +<?php +/*~ class.smtp.php +.---------------------------------------------------------------------------. +| Software: PHPMailer - PHP email class | +| Version: 5.1 | +| Contact: via sourceforge.net support pages (also www.codeworxtech.com) | +| Info: http://phpmailer.sourceforge.net | +| Support: http://sourceforge.net/projects/phpmailer/ | +| ------------------------------------------------------------------------- | +| Admin: Andy Prevost (project admininistrator) | +| Authors: Andy Prevost (codeworxtech) [email protected] | +| : Marcus Bointon (coolbru) [email protected] | +| Founder: Brent R. Matzelle (original founder) | +| Copyright (c) 2004-2009, Andy Prevost. All Rights Reserved. | +| Copyright (c) 2001-2003, Brent R. Matzelle | +| ------------------------------------------------------------------------- | +| License: Distributed under the Lesser General Public License (LGPL) | +| http://www.gnu.org/copyleft/lesser.html | +| This program is distributed in the hope that it will be useful - WITHOUT | +| ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or | +| FITNESS FOR A PARTICULAR PURPOSE. | +| ------------------------------------------------------------------------- | +| We offer a number of paid services (www.codeworxtech.com): | +| - Web Hosting on highly optimized fast and secure servers | +| - Technology Consulting | +| - Oursourcing (highly qualified programmers and graphic designers) | +'---------------------------------------------------------------------------' +*/ + +/** + * PHPMailer - PHP SMTP email transport class + * NOTE: Designed for use with PHP version 5 and up + * @package PHPMailer + * @author Andy Prevost + * @author Marcus Bointon + * @copyright 2004 - 2008 Andy Prevost + * @license http://www.gnu.org/copyleft/lesser.html Distributed under the Lesser General Public License (LGPL) + * @version $Id: class.smtp.php 444 2009-05-05 11:22:26Z coolbru $ + */ + +/** + * SMTP is rfc 821 compliant and implements all the rfc 821 SMTP + * commands except TURN which will always return a not implemented + * error. SMTP also provides some utility methods for sending mail + * to an SMTP server. + * original author: Chris Ryan + */ + +class SMTP { + /** + * SMTP server port + * @var int + */ + public $SMTP_PORT = 25; + + /** + * SMTP reply line ending + * @var string + */ + public $CRLF = "\r\n"; + + /** + * Sets whether debugging is turned on + * @var bool + */ + public $do_debug; // the level of debug to perform + + /** + * Sets VERP use on/off (default is off) + * @var bool + */ + public $do_verp = false; + + ///////////////////////////////////////////////// + // PROPERTIES, PRIVATE AND PROTECTED + ///////////////////////////////////////////////// + + private $smtp_conn; // the socket to the server + private $error; // error if any on the last call + private $helo_rply; // the reply the server sent to us for HELO + + /** + * Initialize the class so that the data is in a known state. + * @access public + * @return void + */ + public function __construct() { + $this->smtp_conn = 0; + $this->error = null; + $this->helo_rply = null; + + $this->do_debug = 0; + } + + ///////////////////////////////////////////////// + // CONNECTION FUNCTIONS + ///////////////////////////////////////////////// + + /** + * Connect to the server specified on the port specified. + * If the port is not specified use the default SMTP_PORT. + * If tval is specified then a connection will try and be + * established with the server for that number of seconds. + * If tval is not specified the default is 30 seconds to + * try on the connection. + * + * SMTP CODE SUCCESS: 220 + * SMTP CODE FAILURE: 421 + * @access public + * @return bool + */ + public function Connect($host, $port = 0, $tval = 30) { + // set the error val to null so there is no confusion + $this->error = null; + + // make sure we are __not__ connected + if($this->connected()) { + // already connected, generate error + $this->error = array("error" => "Already connected to a server"); + return false; + } + + if(empty($port)) { + $port = $this->SMTP_PORT; + } + + // connect to the smtp server + $this->smtp_conn = @fsockopen($host, // the host of the server + $port, // the port to use + $errno, // error number if any + $errstr, // error message if any + $tval); // give up after ? secs + // verify we connected properly + if(empty($this->smtp_conn)) { + $this->error = array("error" => "Failed to connect to server", + "errno" => $errno, + "errstr" => $errstr); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . ": $errstr ($errno)" . $this->CRLF . '<br />'; + } + return false; + } + + // SMTP server can take longer to respond, give longer timeout for first read + // Windows does not have support for this timeout function + if(substr(PHP_OS, 0, 3) != "WIN") + socket_set_timeout($this->smtp_conn, $tval, 0); + + // get any announcement + $announce = $this->get_lines(); + + if($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $announce . $this->CRLF . '<br />'; + } + + return true; + } + + /** + * Initiate a TLS communication with the server. + * + * SMTP CODE 220 Ready to start TLS + * SMTP CODE 501 Syntax error (no parameters allowed) + * SMTP CODE 454 TLS not available due to temporary reason + * @access public + * @return bool success + */ + public function StartTLS() { + $this->error = null; # to avoid confusion + + if(!$this->connected()) { + $this->error = array("error" => "Called StartTLS() without being connected"); + return false; + } + + fputs($this->smtp_conn,"STARTTLS" . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply,0,3); + + if($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />'; + } + + if($code != 220) { + $this->error = + array("error" => "STARTTLS not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply,4)); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />'; + } + return false; + } + + // Begin encrypted connection + if(!stream_socket_enable_crypto($this->smtp_conn, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) { + return false; + } + + return true; + } + + /** + * Performs SMTP authentication. Must be run after running the + * Hello() method. Returns true if successfully authenticated. + * @access public + * @return bool + */ + public function Authenticate($username, $password) { + // Start authentication + fputs($this->smtp_conn,"AUTH LOGIN" . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply,0,3); + + if($code != 334) { + $this->error = + array("error" => "AUTH not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply,4)); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />'; + } + return false; + } + + // Send encoded username + fputs($this->smtp_conn, base64_encode($username) . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply,0,3); + + if($code != 334) { + $this->error = + array("error" => "Username not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply,4)); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />'; + } + return false; + } + + // Send encoded password + fputs($this->smtp_conn, base64_encode($password) . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply,0,3); + + if($code != 235) { + $this->error = + array("error" => "Password not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply,4)); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />'; + } + return false; + } + + return true; + } + + /** + * Returns true if connected to a server otherwise false + * @access public + * @return bool + */ + public function Connected() { + if(!empty($this->smtp_conn)) { + $sock_status = socket_get_status($this->smtp_conn); + if($sock_status["eof"]) { + // the socket is valid but we are not connected + if($this->do_debug >= 1) { + echo "SMTP -> NOTICE:" . $this->CRLF . "EOF caught while checking if connected"; + } + $this->Close(); + return false; + } + return true; // everything looks good + } + return false; + } + + /** + * Closes the socket and cleans up the state of the class. + * It is not considered good to use this function without + * first trying to use QUIT. + * @access public + * @return void + */ + public function Close() { + $this->error = null; // so there is no confusion + $this->helo_rply = null; + if(!empty($this->smtp_conn)) { + // close the connection and cleanup + fclose($this->smtp_conn); + $this->smtp_conn = 0; + } + } + + ///////////////////////////////////////////////// + // SMTP COMMANDS + ///////////////////////////////////////////////// + + /** + * Issues a data command and sends the msg_data to the server + * finializing the mail transaction. $msg_data is the message + * that is to be send with the headers. Each header needs to be + * on a single line followed by a <CRLF> with the message headers + * and the message body being seperated by and additional <CRLF>. + * + * Implements rfc 821: DATA <CRLF> + * + * SMTP CODE INTERMEDIATE: 354 + * [data] + * <CRLF>.<CRLF> + * SMTP CODE SUCCESS: 250 + * SMTP CODE FAILURE: 552,554,451,452 + * SMTP CODE FAILURE: 451,554 + * SMTP CODE ERROR : 500,501,503,421 + * @access public + * @return bool + */ + public function Data($msg_data) { + $this->error = null; // so no confusion is caused + + if(!$this->connected()) { + $this->error = array( + "error" => "Called Data() without being connected"); + return false; + } + + fputs($this->smtp_conn,"DATA" . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply,0,3); + + if($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />'; + } + + if($code != 354) { + $this->error = + array("error" => "DATA command not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply,4)); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />'; + } + return false; + } + + /* the server is ready to accept data! + * according to rfc 821 we should not send more than 1000 + * including the CRLF + * characters on a single line so we will break the data up + * into lines by \r and/or \n then if needed we will break + * each of those into smaller lines to fit within the limit. + * in addition we will be looking for lines that start with + * a period '.' and append and additional period '.' to that + * line. NOTE: this does not count towards limit. + */ + + // normalize the line breaks so we know the explode works + $msg_data = str_replace("\r\n","\n",$msg_data); + $msg_data = str_replace("\r","\n",$msg_data); + $lines = explode("\n",$msg_data); + + /* we need to find a good way to determine is headers are + * in the msg_data or if it is a straight msg body + * currently I am assuming rfc 822 definitions of msg headers + * and if the first field of the first line (':' sperated) + * does not contain a space then it _should_ be a header + * and we can process all lines before a blank "" line as + * headers. + */ + + $field = substr($lines[0],0,strpos($lines[0],":")); + $in_headers = false; + if(!empty($field) && !strstr($field," ")) { + $in_headers = true; + } + + $max_line_length = 998; // used below; set here for ease in change + + while(list(,$line) = @each($lines)) { + $lines_out = null; + if($line == "" && $in_headers) { + $in_headers = false; + } + // ok we need to break this line up into several smaller lines + while(strlen($line) > $max_line_length) { + $pos = strrpos(substr($line,0,$max_line_length)," "); + + // Patch to fix DOS attack + if(!$pos) { + $pos = $max_line_length - 1; + $lines_out[] = substr($line,0,$pos); + $line = substr($line,$pos); + } else { + $lines_out[] = substr($line,0,$pos); + $line = substr($line,$pos + 1); + } + + /* if processing headers add a LWSP-char to the front of new line + * rfc 822 on long msg headers + */ + if($in_headers) { + $line = "\t" . $line; + } + } + $lines_out[] = $line; + + // send the lines to the server + while(list(,$line_out) = @each($lines_out)) { + if(strlen($line_out) > 0) + { + if(substr($line_out, 0, 1) == ".") { + $line_out = "." . $line_out; + } + } + fputs($this->smtp_conn,$line_out . $this->CRLF); + } + } + + // message data has been sent + fputs($this->smtp_conn, $this->CRLF . "." . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply,0,3); + + if($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />'; + } + + if($code != 250) { + $this->error = + array("error" => "DATA not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply,4)); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />'; + } + return false; + } + return true; + } + + /** + * Sends the HELO command to the smtp server. + * This makes sure that we and the server are in + * the same known state. + * + * Implements from rfc 821: HELO <SP> <domain> <CRLF> + * + * SMTP CODE SUCCESS: 250 + * SMTP CODE ERROR : 500, 501, 504, 421 + * @access public + * @return bool + */ + public function Hello($host = '') { + $this->error = null; // so no confusion is caused + + if(!$this->connected()) { + $this->error = array( + "error" => "Called Hello() without being connected"); + return false; + } + + // if hostname for HELO was not specified send default + if(empty($host)) { + // determine appropriate default to send to server + $host = "localhost"; + } + + // Send extended hello first (RFC 2821) + if(!$this->SendHello("EHLO", $host)) { + if(!$this->SendHello("HELO", $host)) { + return false; + } + } + + return true; + } + + /** + * Sends a HELO/EHLO command. + * @access private + * @return bool + */ + private function SendHello($hello, $host) { + fputs($this->smtp_conn, $hello . " " . $host . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply,0,3); + + if($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER: " . $rply . $this->CRLF . '<br />'; + } + + if($code != 250) { + $this->error = + array("error" => $hello . " not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply,4)); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />'; + } + return false; + } + + $this->helo_rply = $rply; + + return true; + } + + /** + * Starts a mail transaction from the email address specified in + * $from. Returns true if successful or false otherwise. If True + * the mail transaction is started and then one or more Recipient + * commands may be called followed by a Data command. + * + * Implements rfc 821: MAIL <SP> FROM:<reverse-path> <CRLF> + * + * SMTP CODE SUCCESS: 250 + * SMTP CODE SUCCESS: 552,451,452 + * SMTP CODE SUCCESS: 500,501,421 + * @access public + * @return bool + */ + public function Mail($from) { + $this->error = null; // so no confusion is caused + + if(!$this->connected()) { + $this->error = array( + "error" => "Called Mail() without being connected"); + return false; + } + + $useVerp = ($this->do_verp ? "XVERP" : ""); + fputs($this->smtp_conn,"MAIL FROM:<" . $from . ">" . $useVerp . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply,0,3); + + if($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />'; + } + + if($code != 250) { + $this->error = + array("error" => "MAIL not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply,4)); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />'; + } + return false; + } + return true; + } + + /** + * Sends the quit command to the server and then closes the socket + * if there is no error or the $close_on_error argument is true. + * + * Implements from rfc 821: QUIT <CRLF> + * + * SMTP CODE SUCCESS: 221 + * SMTP CODE ERROR : 500 + * @access public + * @return bool + */ + public function Quit($close_on_error = true) { + $this->error = null; // so there is no confusion + + if(!$this->connected()) { + $this->error = array( + "error" => "Called Quit() without being connected"); + return false; + } + + // send the quit command to the server + fputs($this->smtp_conn,"quit" . $this->CRLF); + + // get any good-bye messages + $byemsg = $this->get_lines(); + + if($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $byemsg . $this->CRLF . '<br />'; + } + + $rval = true; + $e = null; + + $code = substr($byemsg,0,3); + if($code != 221) { + // use e as a tmp var cause Close will overwrite $this->error + $e = array("error" => "SMTP server rejected quit command", + "smtp_code" => $code, + "smtp_rply" => substr($byemsg,4)); + $rval = false; + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $e["error"] . ": " . $byemsg . $this->CRLF . '<br />'; + } + } + + if(empty($e) || $close_on_error) { + $this->Close(); + } + + return $rval; + } + + /** + * Sends the command RCPT to the SMTP server with the TO: argument of $to. + * Returns true if the recipient was accepted false if it was rejected. + * + * Implements from rfc 821: RCPT <SP> TO:<forward-path> <CRLF> + * + * SMTP CODE SUCCESS: 250,251 + * SMTP CODE FAILURE: 550,551,552,553,450,451,452 + * SMTP CODE ERROR : 500,501,503,421 + * @access public + * @return bool + */ + public function Recipient($to) { + $this->error = null; // so no confusion is caused + + if(!$this->connected()) { + $this->error = array( + "error" => "Called Recipient() without being connected"); + return false; + } + + fputs($this->smtp_conn,"RCPT TO:<" . $to . ">" . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply,0,3); + + if($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />'; + } + + if($code != 250 && $code != 251) { + $this->error = + array("error" => "RCPT not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply,4)); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />'; + } + return false; + } + return true; + } + + /** + * Sends the RSET command to abort and transaction that is + * currently in progress. Returns true if successful false + * otherwise. + * + * Implements rfc 821: RSET <CRLF> + * + * SMTP CODE SUCCESS: 250 + * SMTP CODE ERROR : 500,501,504,421 + * @access public + * @return bool + */ + public function Reset() { + $this->error = null; // so no confusion is caused + + if(!$this->connected()) { + $this->error = array( + "error" => "Called Reset() without being connected"); + return false; + } + + fputs($this->smtp_conn,"RSET" . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply,0,3); + + if($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />'; + } + + if($code != 250) { + $this->error = + array("error" => "RSET failed", + "smtp_code" => $code, + "smtp_msg" => substr($rply,4)); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />'; + } + return false; + } + + return true; + } + + /** + * Starts a mail transaction from the email address specified in + * $from. Returns true if successful or false otherwise. If True + * the mail transaction is started and then one or more Recipient + * commands may be called followed by a Data command. This command + * will send the message to the users terminal if they are logged + * in and send them an email. + * + * Implements rfc 821: SAML <SP> FROM:<reverse-path> <CRLF> + * + * SMTP CODE SUCCESS: 250 + * SMTP CODE SUCCESS: 552,451,452 + * SMTP CODE SUCCESS: 500,501,502,421 + * @access public + * @return bool + */ + public function SendAndMail($from) { + $this->error = null; // so no confusion is caused + + if(!$this->connected()) { + $this->error = array( + "error" => "Called SendAndMail() without being connected"); + return false; + } + + fputs($this->smtp_conn,"SAML FROM:" . $from . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply,0,3); + + if($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />'; + } + + if($code != 250) { + $this->error = + array("error" => "SAML not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply,4)); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />'; + } + return false; + } + return true; + } + + /** + * This is an optional command for SMTP that this class does not + * support. This method is here to make the RFC821 Definition + * complete for this class and __may__ be implimented in the future + * + * Implements from rfc 821: TURN <CRLF> + * + * SMTP CODE SUCCESS: 250 + * SMTP CODE FAILURE: 502 + * SMTP CODE ERROR : 500, 503 + * @access public + * @return bool + */ + public function Turn() { + $this->error = array("error" => "This method, TURN, of the SMTP ". + "is not implemented"); + if($this->do_debug >= 1) { + echo "SMTP -> NOTICE: " . $this->error["error"] . $this->CRLF . '<br />'; + } + return false; + } + + /** + * Get the current error + * @access public + * @return array + */ + public function getError() { + return $this->error; + } + + ///////////////////////////////////////////////// + // INTERNAL FUNCTIONS + ///////////////////////////////////////////////// + + /** + * Read in as many lines as possible + * either before eof or socket timeout occurs on the operation. + * With SMTP we can tell if we have more lines to read if the + * 4th character is '-' symbol. If it is a space then we don't + * need to read anything else. + * @access private + * @return string + */ + private function get_lines() { + $data = ""; + while($str = @fgets($this->smtp_conn,515)) { + if($this->do_debug >= 4) { + echo "SMTP -> get_lines(): \$data was \"$data\"" . $this->CRLF . '<br />'; + echo "SMTP -> get_lines(): \$str is \"$str\"" . $this->CRLF . '<br />'; + } + $data .= $str; + if($this->do_debug >= 4) { + echo "SMTP -> get_lines(): \$data is \"$data\"" . $this->CRLF . '<br />'; + } + // if 4th character is a space, we are done reading, break the loop + if(substr($str,3,1) == " ") { break; } + } + return $data; + } + +} + +?> \ No newline at end of file diff --git a/system/application/modules/sd_api/models/email_log_model.php b/system/application/modules/sd_api/models/email_log_model.php new file mode 100644 index 0000000..a1b3f7a --- /dev/null +++ b/system/application/modules/sd_api/models/email_log_model.php @@ -0,0 +1,16 @@ +<?php + +class Email_Log_Model extends MY_Model +{ + + function __construct() + { + // Call the Model constructor + parent::__construct(); + $this->table = 'email_log'; + $this->database = DB_SD_API; + $this->db = $this->CI->load->database(DB_SD_API, TRUE); + $this->set_fields(); + } +} +?> \ No newline at end of file
cj/sd-ci-api
6fc3deea11577d30664eab3f83435158e634ec25
added MY_Controller which REST_Controller extends from so you can easily customize the core functions
diff --git a/system/application/libraries/MY_Controller.php b/system/application/libraries/MY_Controller.php new file mode 100644 index 0000000..f24391e --- /dev/null +++ b/system/application/libraries/MY_Controller.php @@ -0,0 +1,121 @@ +<?php + +class MY_Controller extends Controller +{ + + function __construct() + { + parent::__construct(); + } + + private function _checkLogin($username = '',$password = FALSE) + { + /** + * EXAMPLE OF AUTH + $this->load->module_model('common','User_Model','user'); + return $this->user->authenticate($username,$password,$this->key); + */ + + /** + * EXAMPLE authenticate function in the user model + function authenticate($username,$password,$key = FALSE,$key_user_id = FALSE){ + + if($username || $key === TRUE) + { + $_POST['username'] = $username; + + if($this->validate($onlyfields = array('username'))){ + if(!$key_user_id) $this->db->where('username', $username); + else $this->db->where('id', $key_user_id); + $this->db->where('(disabled=0 or disabled is null)'); + if($password) $this->db->where('password', $password); + $this->db->limit(1); + $query = $this->db->get('user'); + $row = $query->row_array(); + if($row){ + $this->data = $row; + $this->save_session('login'); + } + return $row?$row:false; + //if we have a user load the user + // + // $this->save_session('login'); + // $this->CI->load->model('User_Model','objLogin'); + // $this->CI->objLogin->restore_session('login'); + // + // return TRUE; + } + } + elseif($key) + { + $this->db->where('auth_key', $key); + $this->db->where('(disabled=0 or disabled is null)'); + $this->db->limit(1); + $query = $this->db->get('user'); + $row = $query->row_array(); + if($row){ + $this->data = $row; + $this->save_session('login'); + } + return $row?$row:false; + } + return FALSE; + } + + function gen_key($user_id) + { + $this->db->where('id', $user_id) + ->update($this->table, array("auth_key"=>uuid())); + } + */ + } + + private function _afterLoginSuccess() + { + /** + * EXAMPLE + $this->load->module_model('common','User_Model','objLogin'); + $this->objLogin->restore_session('login'); + + if(isset($_REQUEST['login']) AND !$this->key) + { + $this->objLogin->gen_key($this->objLogin->get("id")); + $this->objLogin->load_data($this->objLogin->get("id")); + $this->objLogin->save_session('login'); + $this->objLogin->restore_session('login'); + } + + $this->objMemCache = new Memcache; + $this->objMemCache->addServer(MEMCACHED_IP1,11211); + $this->objMemCache->addServer(MEMCACHED_IP2,11211); + */ + } + + private function _forceLogin($nonce = '') + { + header('HTTP/1.0 401 Unauthorized'); + header('HTTP/1.1 401 Unauthorized'); + header('not_logged_in'); + + if($this->rest_auth == 'basic') + { + header('WWW-Authenticate: Basic realm="'.$this->config->item('rest_realm').'"'); + } + + elseif($this->rest_auth == 'digest') + { + header('WWW-Authenticate: Digest realm="'.$this->config->item('rest_realm'). '" qop="auth" nonce="'.$nonce.'" opaque="'.md5($this->config->item('rest_realm')).'"'); + } + + print_r(json_encode(array( + 'success'=>FALSE, + 'message'=>'User and Password Incorrect.', + 'results'=> FALSE + ))); + + die(); + } + +} + +?> \ No newline at end of file diff --git a/system/application/libraries/REST_Controller.php b/system/application/libraries/REST_Controller.php index 5d914ce..8948eb0 100644 --- a/system/application/libraries/REST_Controller.php +++ b/system/application/libraries/REST_Controller.php @@ -1,730 +1,679 @@ <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); -class REST_Controller extends Controller { +class REST_Controller extends MY_Controller { // Not what you'd think, set this in a controller to use a default format protected $rest_format = NULL; private $_method; private $_format; private $_get_args; private $_put_args; private $_args; public $_is_public = FALSE; // List all supported methods, the first will be the default format private $_supported_formats = array( 'json' => 'application/json', 'xml' => 'application/xml', 'rawxml' => 'application/xml', 'serialize' => 'text/plain', 'php' => 'text/plain', 'html' => 'text/html', 'csv' => 'application/csv' ); // Constructor function function __construct() { parent::Controller(); // How is this request being made? POST, DELETE, GET, PUT? $this->_method = $this->_detect_method(); // Set up our GET variables $this->_get_args = array_merge(array($this->uri->segment(2) =>'index'),$this->uri->uri_to_assoc(3)); $this->_args = $this->_get_args; $this->page = isset($_REQUEST['page'])?$_REQUEST['page']:false; $this->rows = isset($_REQUEST['rows'])?$_REQUEST['rows']:false; switch(strtolower($this->input->server('REQUEST_METHOD'))){ case "get": if(isset($_REQUEST['sidx'])) $_REQUEST['sort'] = $_REQUEST['sidx']; if(isset($_REQUEST['sord'])) $_REQUEST['dir'] = $_REQUEST['sord']; if($this->page AND $this->rows){ $page = $this->page - 1; $rows = $this->rows; $_REQUEST['start'] = $page != 0?$page*$rows:$page; $_REQUEST['limit'] = $rows; }; break; case "post": foreach($_REQUEST as $key => $value){ if(!is_array($value)) if(strtolower(preg_replace("[^A-Za-z0-9]", "", $key )) != strtolower(preg_replace("[^A-Za-z0-9]", "", $value ))) $_POST[$key] = $value; else $_POST[$key] = $value; } break; case "put": parse_str(file_get_contents('php://input'), $this->_put_args); $_REQUEST = $this->_put_args; foreach($_REQUEST as $key => $value){ if(!is_array($value)) if(strtolower(preg_replace("[^A-Za-z0-9]", "", $key )) != strtolower(preg_replace("[^A-Za-z0-9]", "", $value ))) $_POST[$key] = $value; else $_POST[$key] = $value; } break; case "delete": $_REQUEST = $this->_args; break; } if(isset($_REQUEST['key']) AND $_REQUEST['key'] == "c31ecc24-3032-434f-b623-ee0c4ddccfb1") { $this->key = TRUE; $this->key_user = !isset($_REQUEST['key_user'])?'superuser':$_REQUEST['key_user']; if(isset($_REQUEST['key_user_id'])) $this->key_user_id = $_REQUEST['key_user_id']; } elseif(isset($_REQUEST['key'])) $this->key = $_REQUEST['key']; else $this->key = FALSE; $this->rest_auth = isset($_REQUEST['auth_type'])?$_REQUEST['auth_type']:'digest'; // Lets grab the config and get ready to party $this->load->config('rest'); if($this->rest_auth == 'basic') { $this->_prepareBasicAuth(); } elseif($this->rest_auth == 'digest') { $this->_prepareDigestAuth(); } // Set caching based on the REST cache config item //$this->output->cache( $this->config->item('rest_cache') ); // Which format should the data be returned in? $this->_format = $this->_detect_format(); } function _global_get_functions() { $module = $this->_module; if(isset($_REQUEST['download_as_excel'])) { ini_set('memory_limit','1000M'); $this->$module->excel_new(); return $this->$module->excel_save(); exit; } } /* * Remap * * Requests are not made to methods directly The request will be for an "object". * this simply maps the object and method to the correct Controller method. */ function _remap($object_called) { $controller_method = $object_called.'_'.$this->_method; if(method_exists($this, $controller_method)) { $this->$controller_method(); } else { $controller_method = $this->_method; if(method_exists($this, $controller_method)) { $this->$controller_method(); } else { show_404(); } } } function get() { $class = $this->_class; $module = $this->_module; $this->load->module_model($module,$class.'_model',$class); $data = $this->$class->run_api(); $this->total_count = $this->$class->total_count; $this->success = TRUE; $this->message = 'Successfully Grabbed '.ucfirst($class).' Info.'; $this->response($data, 200); // 200 being the HTTP response code } function post() { $class = $this->_class; $module = $this->_module; $this->load->module_model($module,$class.'_model',$class); $is_valid = $this->$class->get_form($prefix = FALSE,!isset($_POST['validate'])?TRUE:FALSE); if($is_valid){ $this->$class->save(); $this->total_count = 1; $this->success = TRUE; if(isset($this->_success_message)){ $this->message = $this->_success_message; } else { $this->message = 'Successfully Posted '.ucfirst($class).' Info.'; } $this->response($this->$class->data, 200); } else { $this->total_count = 0; $this->success = FALSE; $this->message = 'Something Happened.'; $this->response($this->$class->errors, 200); } } function put() { $class = $this->_class; $module = $this->_module; $this->load->module_model($module,$class.'_model',$class); $this->$class->load_data($_REQUEST['id']); $is_valid = $this->$class->get_form($prefix = FALSE,!isset($_POST['validate'])?TRUE:FALSE); if($is_valid){ $this->$class->save(); $this->total_count = 1; $this->success = TRUE; if(isset($this->_success_message)){ $this->message = $this->_success_message; } else { $this->message = 'Successfully Posted '.ucfirst($class).' Info.'; } $this->response($this->$class->data, 200); } else { $this->total_count = 0; $this->success = FALSE; $this->message = 'Something Happened.'; $this->response($this->$class->errors, 200); } } function delete() { $class = $this->_class; $module = $this->_module; $this->load->module_model($module,$class.'_model',$class); $this->$class->load_data($_REQUEST['id']); $this->$class->remove(); } /* * response * * Takes pure data and optionally a status code, then creates the response */ function response($data = '', $http_code = 200) { //if(empty($data)) //{ // $this->output->set_status_header(404); // return; //} $this->output->set_status_header($http_code); // If the format method exists, call and return the output in that format if(method_exists($this, '_'.$this->_format)) { // Set a XML header $this->output->set_header('Content-type: '.$this->_supported_formats[$this->_format]); $formatted_data = $this->{'_'.$this->_format}($data); $this->output->set_output( $formatted_data ); } // Format not supported, output directly else { $this->output->set_output( $data ); } } /* * Detect format * * Detect which format should be used to output the data */ private function _detect_format() { // A format has been passed in the URL and it is supported if(array_key_exists('format', $this->_args) && array_key_exists($this->_args['format'], $this->_supported_formats)) { return $this->_args['format']; } // Otherwise, check the HTTP_ACCEPT (if it exists and we are allowed) if($this->config->item('rest_ignore_http_accept') === FALSE && $this->input->server('HTTP_ACCEPT')) { // Check all formats against the HTTP_ACCEPT header foreach(array_keys($this->_supported_formats) as $format) { // Has this format been requested? if(strpos($this->input->server('HTTP_ACCEPT'), $format) !== FALSE) { // If not HTML or XML assume its right and send it on its way if($format != 'html' && $format != 'xml') { return $format; } // HTML or XML have shown up as a match else { // If it is truely HTML, it wont want any XML if($format == 'html' && strpos($this->input->server('HTTP_ACCEPT'), 'xml') === FALSE) { return $format; } // If it is truely XML, it wont want any HTML elseif($format == 'xml' && strpos($this->input->server('HTTP_ACCEPT'), 'html') === FALSE) { return $format; } } } } } // End HTTP_ACCEPT checking // Well, none of that has worked! Let's see if the controller has a default if($this->rest_format != NULL) { return $this->rest_format; } // Just use whatever the first supported type is, nothing else is working! list($default)=array_keys($this->_supported_formats); return $default; } /* * Detect method * * Detect which method (POST, PUT, GET, DELETE) is being used */ private function _detect_method() { $method = strtolower($this->input->server('REQUEST_METHOD')); if(in_array($method, array('get', 'delete', 'post', 'put'))) { return $method; } return 'get'; } // INPUT FUNCTION -------------------------------------------------------------- public function restGet($key) { return array_key_exists($key, $this->_get_args) ? $this->input->xss_clean( $this->_get_args[$key] ) : $this->input->get($key) ; } public function restPost($key) { return $this->input->post($key); } public function restPut($key) { return array_key_exists($key, $this->_put_args) ? $this->input->xss_clean( $this->_put_args[$key] ) : FALSE ; } // SECURITY FUNCTIONS --------------------------------------------------------- - private function _checkLogin($username = '',$password = FALSE) - { - - $this->load->module_model('common','User_Model','user'); - - return $this->user->authenticate($username,$password,$this->key); - - } - private function _prepareBasicAuth() { $username = NULL; $password = NULL; // mod_php if (isset($_SERVER['PHP_AUTH_USER'])) { $username = $_SERVER['PHP_AUTH_USER']; $password = $_SERVER['PHP_AUTH_PW']; } // most other servers elseif (isset($_SERVER['HTTP_AUTHENTICATION'])) { if (strpos(strtolower($_SERVER['HTTP_AUTHENTICATION']),'basic')===0) { list($username,$password) = explode(':',base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6))); } } elseif (isset($_SERVER['HTTP_WWW_AUTHORIZATION'])) { if (strpos(strtolower($_SERVER['HTTP_WWW_AUTHORIZATION']),'basic')===0) { list($username,$password) = explode(':',base64_decode(substr($_SERVER['HTTP_WWW_AUTHORIZATION'], 6))); } } $row = $this->_checkLogin($username, $password); if ( !$row ) { $this->_forceLogin(); } else { - $this->load->module_model('common','User_Model','objLogin'); - $this->objLogin->restore_session('login'); - $this->objMemCache = new Memcache; - $this->objMemCache->addServer(MEMCACHED_IP1,11211); - $this->objMemCache->addServer(MEMCACHED_IP2,11211); - + $this->_afterLoginSuccess(); } } /* CJFN url_base64_decode */ public function url_base64_decode($str){ return strtr(base64_decode($str), array( '.' => '+', '\\' => '=', '~' => '/' ) ); } private function _prepareDigestAuth() { if(!$this->_is_public) { if(!$this->key){ $uniqid = uniqid(""); // Empty argument for backward compatibility // We need to test which server authentication variable to use // because the PHP ISAPI module in IIS acts different from CGI if(isset($_SERVER['PHP_AUTH_DIGEST'])) { $digest_string = $_SERVER['PHP_AUTH_DIGEST']; } elseif(isset($_SERVER['HTTP_AUTHORIZATION'])) { $digest_string = $_SERVER['HTTP_AUTHORIZATION']; } else { $digest_string = ""; } /* The $_SESSION['error_prompted'] variabile is used to ask the password again if none given or if the user enters a wrong auth. informations. */ if ( empty($digest_string) ) { $this->_forceLogin($uniqid); } // We need to retrieve authentication informations from the $auth_data variable preg_match_all('@(username|nonce|uri|nc|cnonce|qop|response)=[\'"]?([^\'",]+)@', $digest_string, $matches); $digest = array_combine($matches[1], $matches[2]); $row = $this->_checkLogin($digest['username']); if ( !array_key_exists('username', $digest) || !isset($row['password']) ) { $this->_forceLogin($uniqid); } $valid_pass = $row['password']; // This is the valid response expected $A1 = md5($digest['username'] . ':' . $this->config->item('rest_realm') . ':' . $valid_pass); $A2 = md5(strtoupper($this->_method).':'.$digest['uri']); $valid_response = md5($A1.':'.$digest['nonce'].':'.$digest['nc'].':'.$digest['cnonce'].':'.$digest['qop'].':'.$A2); if ($digest['response'] != $valid_response) { $this->_forceLogin($uniqid); } } if($this->key === TRUE) { if(!isset($this->key_user_id)) $access = $this->_checkLogin($this->key_user); else $access = $this->_checkLogin($this->key_user,FALSE,FALSE,$this->key_user_id); if(!$access) $this->_forceLogin(); } elseif($this->key) { $access = $this->_checkLogin(); if(!$access) $this->_forceLogin(); } - $this->load->module_model('common','User_Model','objLogin'); - $this->objLogin->restore_session('login'); + $this->_afterLoginSuccess(); - if(isset($_REQUEST['login']) AND !$this->key) - { - $this->objLogin->gen_key($this->objLogin->get("id")); - $this->objLogin->load_data($this->objLogin->get("id")); - $this->objLogin->save_session('login'); - $this->objLogin->restore_session('login'); - } } - $this->objMemCache = new Memcache; - $this->objMemCache->addServer(MEMCACHED_IP1,11211); - $this->objMemCache->addServer(MEMCACHED_IP2,11211); - } - - - private function _forceLogin($nonce = '') - { - header('HTTP/1.0 401 Unauthorized'); - header('HTTP/1.1 401 Unauthorized'); - header('not_logged_in'); - - if($this->rest_auth == 'basic') - { - header('WWW-Authenticate: Basic realm="'.$this->config->item('rest_realm').'"'); - } - - elseif($this->rest_auth == 'digest') - { - header('WWW-Authenticate: Digest realm="'.$this->config->item('rest_realm'). '" qop="auth" nonce="'.$nonce.'" opaque="'.md5($this->config->item('rest_realm')).'"'); - } - - print_r(json_encode(array( - 'success'=>FALSE, - 'message'=>'User and Password Incorrect.', - 'results'=> FALSE - ))); - - die(); } // FORMATING FUNCTIONS --------------------------------------------------------- // Format XML for output private function _xml($data = array(), $structure = NULL, $basenode = 'xml') { // turn off compatibility mode as simple xml throws a wobbly if you don't. if (ini_get('zend.ze1_compatibility_mode') == 1) { ini_set ('zend.ze1_compatibility_mode', 0); } if ($structure == NULL) { $structure = simplexml_load_string("<?xml version='1.0' encoding='utf-8'?><$basenode />"); } // loop through the data passed in. foreach($data as $key => $value) { // no numeric keys in our xml please! if (is_numeric($key)) { // make string key... //$key = "item_". (string) $key; $key = "item"; } // replace anything not alpha numeric $key = preg_replace('/[^a-z]/i', '', $key); // if there is another array found recrusively call this function if (is_array($value)) { $node = $structure->addChild($key); // recrusive call. $this->_xml($value, $node, $basenode); } else { // add single node. $value = htmlentities($value, ENT_NOQUOTES, "UTF-8"); $UsedKeys[] = $key; $structure->addChild($key, $value); } } // pass back as string. or simple xml object if you want! return $structure->asXML(); } // Format Raw XML for output private function _rawxml($data = array(), $structure = NULL, $basenode = 'xml') { // turn off compatibility mode as simple xml throws a wobbly if you don't. if (ini_get('zend.ze1_compatibility_mode') == 1) { ini_set ('zend.ze1_compatibility_mode', 0); } if ($structure == NULL) { $structure = simplexml_load_string("<?xml version='1.0' encoding='utf-8'?><$basenode />"); } // loop through the data passed in. foreach($data as $key => $value) { // no numeric keys in our xml please! if (is_numeric($key)) { // make string key... //$key = "item_". (string) $key; $key = "item"; } // replace anything not alpha numeric $key = preg_replace('/[^a-z0-9_-]/i', '', $key); // if there is another array found recrusively call this function if (is_array($value)) { $node = $structure->addChild($key); // recrusive call. $this->_xml($value, $node, $basenode); } else { // add single node. $value = htmlentities($value, ENT_NOQUOTES, "UTF-8"); $UsedKeys[] = $key; $structure->addChild($key, $value); } } // pass back as string. or simple xml object if you want! return $structure->asXML(); } // Format HTML for output private function _html($data = array()) { // Multi-dimentional array if(isset($data[0])) { $headings = array_keys($data[0]); } // Single array else { $headings = array_keys($data); $data = array($data); } $this->load->library('table'); $this->table->set_heading($headings); foreach($data as &$row) { $this->table->add_row($row); } return $this->table->generate(); } // Format HTML for output private function _csv($data = array()) { // Multi-dimentional array if(isset($data[0])) { $headings = array_keys($data[0]); } // Single array else { $headings = array_keys($data); $data = array($data); } $output = implode(',', $headings)."\r\n"; foreach($data as &$row) { $output .= '"'.implode('","',$row)."\"\r\n"; } return $output; } // Encode as JSON private function _json($data = array()) { $totalPages = $this->rows?ceil($this->total_count/$this->rows):0; echo json_encode(array( 'success'=>$this->success, 'message'=>$this->message, 'page' =>$this->page, 'rows' =>$this->rows, 'totalPages' => $totalPages, 'results'=>$data, 'total' => $this->total_count )); } private function _extjs($data = array()) { $json = json_encode(array("total"=>"$this->total_count",'results'=>$data)); print_r("$json"); } private function _extjs_form($data = array()) { $json = json_encode(array("success"=>true,'data'=>$data)); print_r("$json"); } // Encode as Serialized array private function _serialize($data = array()) { return serialize($data); } // Encode raw PHP private function _php($data = array()) { return var_export($data, TRUE); } } ?> \ No newline at end of file
cj/sd-ci-api
af837b77fc625af7b9b84d4e70f3deaec958cbae
cleaned up a bunch of files
diff --git a/.htaccess b/.htaccess index 65271f1..395ea81 100644 --- a/.htaccess +++ b/.htaccess @@ -1,37 +1,35 @@ -# @author Adam Nazar -# @since Version 1.0 <IfModule mod_rewrite.c> RewriteEngine On - + #git hub test #this is to remove the index.php in url #RewriteCond $1 !^(index\.php|images|robots\.txt) #RewriteRule ^(.*)$ /index.php/$1 [L] #Removes access to the system folder by users. #Additionally this will allow you to create a System.php controller, #previously this would not have been possible. #'system' can be replaced if you have renamed your system folder. RewriteCond %{REQUEST_URI} ^system.* RewriteRule ^(.*)$ index.php/$1 [L] #Checks to see if the user is attempting to access a valid file, #such as an image or css document, if this isn't true it sends the #request to index.php RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d #This last condition enables access to the images and css folders, and the robots.txt file #Submitted by Michael Radlmaier (mradlmaier) - RewriteCond $1 !^(index\.php|images|robots\.txt|css|js|applets|min|cached|plugins) - RewriteRule ^(.*)$ index.php/$1 [L] + RewriteCond $1 !^(index\.php|images|robots\.txt|css|uploaded|\.mp3) + RewriteRule ^v1/(.*)$ index.php/$1 [L] AddType text/x-component .htc </IfModule> <IfModule !mod_rewrite.c> # If we don't have mod_rewrite installed, all 404's # can be sent to index.php, and everything works as normal. # Submitted by: ElliotHaughin ErrorDocument 404 /index.php </IfModule> diff --git a/system/application/config/autoload.php b/system/application/config/autoload.php index 1745d5c..d8341a7 100644 --- a/system/application/config/autoload.php +++ b/system/application/config/autoload.php @@ -1,116 +1,116 @@ <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /* | ------------------------------------------------------------------- | AUTO-LOADER | ------------------------------------------------------------------- | This file specifies which systems should be loaded by default. | | In order to keep the framework as light-weight as possible only the | absolute minimal resources are loaded by default. For example, | the database is not connected to automatically since no assumption | is made regarding whether you intend to use it. This file lets | you globally define which systems you would like loaded with every | request. | | ------------------------------------------------------------------- | Instructions | ------------------------------------------------------------------- | | These are the things you can load automatically: | | 1. Libraries | 2. Helper files | 3. Plugins | 4. Custom config files | 5. Language files | 6. Models | */ /* | ------------------------------------------------------------------- | Auto-load Libraries | ------------------------------------------------------------------- | These are the classes located in the system/libraries folder | or in your system/application/libraries folder. | | Prototype: | | $autoload['libraries'] = array('database', 'session', 'xmlrpc'); */ -$autoload['libraries'] = array(); +$autoload['libraries'] = array('database', 'session'); /* | ------------------------------------------------------------------- | Auto-load Helper Files | ------------------------------------------------------------------- | Prototype: | | $autoload['helper'] = array('url', 'file'); */ -$autoload['helper'] = array(); +$autoload['helper'] = array('url','utility_helper'); /* | ------------------------------------------------------------------- | Auto-load Plugins | ------------------------------------------------------------------- | Prototype: | | $autoload['plugin'] = array('captcha', 'js_calendar'); */ $autoload['plugin'] = array(); /* | ------------------------------------------------------------------- | Auto-load Config files | ------------------------------------------------------------------- | Prototype: | | $autoload['config'] = array('config1', 'config2'); | | NOTE: This item is intended for use ONLY if you have created custom | config files. Otherwise, leave it blank. | */ $autoload['config'] = array(); /* | ------------------------------------------------------------------- | Auto-load Language files | ------------------------------------------------------------------- | Prototype: | | $autoload['language'] = array('lang1', 'lang2'); | | NOTE: Do not include the "_lang" part of your file. For example | "codeigniter_lang.php" would be referenced as array('codeigniter'); | */ $autoload['language'] = array(); /* | ------------------------------------------------------------------- | Auto-load Models | ------------------------------------------------------------------- | Prototype: | | $autoload['model'] = array('model1', 'model2'); | */ $autoload['model'] = array(); /* End of file autoload.php */ /* Location: ./system/application/config/autoload.php */ \ No newline at end of file diff --git a/system/application/config/database.php b/system/application/config/database.php index dc6d474..c092793 100644 --- a/system/application/config/database.php +++ b/system/application/config/database.php @@ -1,55 +1,55 @@ <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /* | ------------------------------------------------------------------- | DATABASE CONNECTIVITY SETTINGS | ------------------------------------------------------------------- | This file will contain the settings needed to access your database. | | For complete instructions please consult the "Database Connection" | page of the User Guide. | | ------------------------------------------------------------------- | EXPLANATION OF VARIABLES | ------------------------------------------------------------------- | | ['hostname'] The hostname of your database server. | ['username'] The username used to connect to the database | ['password'] The password used to connect to the database | ['database'] The name of the database you want to connect to | ['dbdriver'] The database type. ie: mysql. Currently supported: mysql, mysqli, postgre, odbc, mssql, sqlite, oci8 | ['dbprefix'] You can add an optional prefix, which will be added | to the table name when using the Active Record class | ['pconnect'] TRUE/FALSE - Whether to use a persistent connection | ['db_debug'] TRUE/FALSE - Whether database errors should be displayed. | ['cache_on'] TRUE/FALSE - Enables/disables query caching | ['cachedir'] The path to the folder where cache files should be stored | ['char_set'] The character set used in communicating with the database | ['dbcollat'] The character collation used in communicating with the database | | The $active_group variable lets you choose which connection group to | make active. By default there is only one group (the "default" group). | | The $active_record variables lets you determine whether or not to load | the active record class */ $active_group = DB_DEFAULT; $active_record = TRUE; $db[DB_DEFAULT]['hostname'] = DB_HOST; $db[DB_DEFAULT]['username'] = DB_USER; $db[DB_DEFAULT]['password'] = DB_PASS; -$db[DB_DEFAULT]['database'] = DB_APPRAISAL; +$db[DB_DEFAULT]['database'] = DB_DEFAULT; $db[DB_DEFAULT]['dbdriver'] = "mysql"; $db[DB_DEFAULT]['dbprefix'] = ""; $db[DB_DEFAULT]['pconnect'] = TRUE; $db[DB_DEFAULT]['db_debug'] = TRUE; $db[DB_DEFAULT]['cache_on'] = FALSE; $db[DB_DEFAULT]['cachedir'] = ""; $db[DB_DEFAULT]['char_set'] = "utf8"; $db[DB_DEFAULT]['dbcollat'] = "utf8_general_ci"; /* End of file database.php */ /* Location: ./system/application/config/database.php */ \ No newline at end of file diff --git a/system/application/config/matchbox.php b/system/application/config/matchbox.php new file mode 100644 index 0000000..1e7e3be --- /dev/null +++ b/system/application/config/matchbox.php @@ -0,0 +1,70 @@ +<?php + +/** + * Matchbox Configuration file + * + * This file is part of Matchbox + * + * Matchbox is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Matchbox is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + * @package Matchbox + * @copyright 2007-2008 Zacharias Knudsen + * @license http://www.gnu.org/licenses/gpl.html + * @version $Id: matchbox.php 204 2008-02-24 01:30:00Z [email protected] $ + */ + +if (!defined('BASEPATH')) { + exit('No direct script access allowed'); +} + +/** + * The files that should be excluded from the caller search + * + * When trying to figure out which module requested a particular + * resource, the file that called e.g. $this->load->view('filename') + * will be used to determine the module. However, in some cases you + * might need to exclude certain files in this search. Perhaps you are + * using a custom view library. In that case, whenever you call the + * custom method, the library will be considered the caller instead of + * your controller and so the module cannot be determined. Therefore + * you will need to add the file to this array. + * + * If you have multiple files with the same name, but you only wish + * to exclude one of them, you can also add a bit of the filepath to + * distinguish it from the others. + * + * NO FILE EXTENSION! + * + * Prototype: + * $config['callers'] = array('libraries/filename'); + */ +$config['callers'] = array(); + +/** + * The directories in which your modules are located + * + * Should contain an array of directories RELATIVE to the application + * folder in which to look for modules. You'd usually want to have at + * least 'modules' in your array which will have codeigniter look for + * modules in /application/modules. You can add as many directories + * as you like, though. + * + * NO TRAILING SLASHES! + * + * Prototype: + * $config['direcotires'] = array('modules'); + */ +$config['directories'] = array('modules'); + +?> \ No newline at end of file diff --git a/system/application/config/rest.php b/system/application/config/rest.php new file mode 100644 index 0000000..4200452 --- /dev/null +++ b/system/application/config/rest.php @@ -0,0 +1,66 @@ +<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); + +/* +|-------------------------------------------------------------------------- +| REST Login +|-------------------------------------------------------------------------- +| +| Is login required and if so, which type of login? +| +| '' = no login required, 'basic' = unsecure login, 'digest' = more secure login +| +*/ +$config['rest_auth'] = 'digest'; + +/* +|-------------------------------------------------------------------------- +| REST Realm +|-------------------------------------------------------------------------- +| +| Name for the password protected REST API displayed on login dialogs +| +| E.g: My Secret REST API +| +*/ +$config['rest_realm'] = 'SD APi'; + +/* +|-------------------------------------------------------------------------- +| REST Login usernames +|-------------------------------------------------------------------------- +| +| Is login required +| +| '' = no login required, 'basic' = unsecure login, 'digest' = more secure login +| +*/ +$config['rest_valid_logins'] = array('foo' => 'bar'); + +/* +|-------------------------------------------------------------------------- +| REST Cache +|-------------------------------------------------------------------------- +| +| How many MINUTES should output be cached? +| +| 0 = no cache +| +*/ +$config['rest_cache'] = 0; + +/* +|-------------------------------------------------------------------------- +| REST Ignore HTTP Accept +|-------------------------------------------------------------------------- +| +| Set to TRUE to ignore the HTTP Accept and speed up each request a little. +| Only do this if you are using the $this->rest_format or /format/xml in URLs +| +| FALSE +| +*/ +$config['rest_ignore_http_accept'] = FALSE; + + +/* End of file config.php */ +/* Location: ./system/application/config/rest.php */ \ No newline at end of file diff --git a/system/application/helpers/utility_helper.php b/system/application/helpers/utility_helper.php new file mode 100644 index 0000000..d0ce83e --- /dev/null +++ b/system/application/helpers/utility_helper.php @@ -0,0 +1,336 @@ +<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); + + if ( ! function_exists('one_dimensionalize')) + { + function one_dimensionalize( $ar, $field ) { + $_ret = array(); + for ($i=0;$i<sizeof($ar);$i++) $_ret[]=$ar[$i][$field]; + return $_ret; + } + } + + if ( ! function_exists('contains')) + { + function contains($str, $content){ + $ar_check = !is_array($str)?explode(',',$str):$str; + foreach($ar_check AS $check) if(strtolower($check) == strtolower($content)) return true; + return false; + } + } + + if ( ! function_exists('count_digit')) + { + function count_digit($number) + { + $digit = 0; + do + { + $number /= 10; //$number = $number / 10; + $number = intval($number); + $digit++; + }while($number!=0); + return $digit; + } + } + + if ( ! function_exists('is_valid_url')) + { + function is_valid_url($url) + { + $url = @parse_url($url); + + if (!$url) + { + return false; + } + + $url = array_map('trim', $url); + $url['port'] = (!isset($url['port'])) ? 80 : (int)$url['port']; + $path = (isset($url['path'])) ? $url['path'] : ''; + + if ($path == '') + { + $path = '/'; + } + + $path .= (isset($url['query'])) ? "?$url[query]" : ''; + + if (isset($url['host']) AND $url['host'] != gethostbyname($url['host'])) + { + if (PHP_VERSION >= 5) + { + $headers = get_headers("$url[scheme]://$url[host]:$url[port]$path"); + } + else + { + $fp = fsockopen($url['host'], $url['port'], $errno, $errstr, 30); + + if (!$fp) + { + return false; + } + fputs($fp, "HEAD $path HTTP/1.1\r\nHost: $url[host]\r\n\r\n"); + $headers = fread($fp, 4096); + fclose($fp); + } + $headers = (is_array($headers)) ? implode("\n", $headers) : $headers; + return (bool)preg_match('#^HTTP/.*\s+[(200|301|302)]+\s#i', $headers); + } + return false; + } + } + + if ( ! function_exists('uuid')) + { + function uuid() + { + + $pr_bits = null; + $fp = @fopen('/dev/urandom','rb'); + if ($fp !== false) { + $pr_bits .= @fread($fp, 16); + @fclose($fp); + } else { + // If /dev/urandom isn't available (eg: in non-unix systems), use mt_rand(). + $pr_bits = ""; + for($cnt=0; $cnt < 16; $cnt++){ + $pr_bits .= chr(mt_rand(0, 255)); + } + } + + $time_low = bin2hex(substr($pr_bits,0, 4)); + $time_mid = bin2hex(substr($pr_bits,4, 2)); + $time_hi_and_version = bin2hex(substr($pr_bits,6, 2)); + $clock_seq_hi_and_reserved = bin2hex(substr($pr_bits,8, 2)); + $node = bin2hex(substr($pr_bits,10, 6)); + + /** + * Set the four most significant bits (bits 12 through 15) of the + * time_hi_and_version field to the 4-bit version number from + * Section 4.1.3. + * @see http://tools.ietf.org/html/rfc4122#section-4.1.3 + */ + $time_hi_and_version = hexdec($time_hi_and_version); + $time_hi_and_version = $time_hi_and_version >> 4; + $time_hi_and_version = $time_hi_and_version | 0x4000; + + /** + * Set the two most significant bits (bits 6 and 7) of the + * clock_seq_hi_and_reserved to zero and one, respectively. + */ + $clock_seq_hi_and_reserved = hexdec($clock_seq_hi_and_reserved); + $clock_seq_hi_and_reserved = $clock_seq_hi_and_reserved >> 2; + $clock_seq_hi_and_reserved = $clock_seq_hi_and_reserved | 0x8000; + + return sprintf('%08s-%04s-%04x-%04x-%012s', + $time_low, $time_mid, $time_hi_and_version, $clock_seq_hi_and_reserved, $node); + } + } + + if ( ! function_exists('smartCopy')) + { + function smartCopy($source, $dest, $options=array('folderPermission'=>0777,'filePermission'=>0777)) + { + $result=false; + + if (is_file($source)) { + if ($dest[strlen($dest)-1]=='/') { + if (!file_exists($dest)) { + cmfcDirectory::makeAll($dest,$options['folderPermission'],true); + } + $__dest=$dest."/".basename($source); + } else { + $__dest=$dest; + } + $result=copy($source, $__dest); + chmod($__dest,$options['filePermission']); + + } elseif(is_dir($source)) { + if ($dest[strlen($dest)-1]=='/') { + if ($source[strlen($source)-1]=='/') { + //Copy only contents + } else { + //Change parent itself and its contents + $dest=$dest.basename($source); + @mkdir($dest); + chmod($dest,$options['filePermission']); + } + } else { + if ($source[strlen($source)-1]=='/') { + //Copy parent directory with new name and all its content + @mkdir($dest,$options['folderPermission']); + chmod($dest,$options['filePermission']); + } else { + //Copy parent directory with new name and all its content + @mkdir($dest,$options['folderPermission']); + chmod($dest,$options['filePermission']); + } + } + + $dirHandle=opendir($source); + while($file=readdir($dirHandle)) + { + if($file!="." && $file!="..") + { + if(!is_dir($source."/".$file)) { + $__dest=$dest."/".$file; + } else { + $__dest=$dest."/".$file; + } + //echo "$source/$file ||| $__dest<br />"; + $result=$this->smartCopy($source."/".$file, $__dest, $options); + } + } + closedir($dirHandle); + + } else { + $result=false; + } + return $result; + } + } + + if ( ! function_exists('format_date')) + { + function format_date($format,$date) + { + switch($format){ + case 'TIME_24': + $sFormat = 'G:i'; + break; + case 'TIME_SHORT': + $sFormat = 'g:ia T'; + break; + case 'DATE_SHORT': + $sFormat = 'm/d/Y'; + break; + case 'DATE_LONG': + $sFormat = '%B %e %Y'; + break; + case 'DATE_TIME_SHORT': + $sFormat = 'm/d/Y g:ia T'; + break; + case 'DATE_TIME_FEED': + $sFormat = 'm/d/Y g:ia T'; + break; + case 'DATE_FEED': + $sFormat = 'F J'; + break; + default: + $sFormat = ''; + } + return date($sFormat, strtotime($date)); + } + } + + if ( ! function_exists('phone_number')) + { + //Converts a phone number from 8888888888 to (888) 888 - 8888. + function phone_number($sPhone){ + $sPhone = preg_replace("[^0-9]",'',$sPhone); + if(strlen($sPhone) != 10) return(False); + $sArea = substr($sPhone,0,3); + $sPrefix = substr($sPhone,3,3); + $sNumber = substr($sPhone,6,4); + $sPhone = "(".$sArea.") ".$sPrefix."-".$sNumber; + return($sPhone); + } + } + + if ( ! function_exists('strip_phone_number')) + { + function strip_phone_number($phoneNumer){ + return preg_replace("/\D/","",$phoneNumer); + } + } + + if ( ! function_exists('resize_image')) + { + function resize_image($src_path, $dest_path, $width = 150, $quality = 80){ + + // image src size + list($width_orig, $height_orig, $image_type) = getImageSize($src_path); + + if($width_orig<$width) return; //if width is smaller than current width don't resize + + $height = (int) (($width / $width_orig) * $height_orig); + + // print IMAGEMAGICK_CONVERT_PATH." ".$src_path." -quality ".$quality." -resize ".$width."x".$height." ".fixPath($dest_path); exit; + exec(IMAGEMAGICK_CONVERT_PATH." ".$src_path." -quality ".$quality." -resize ".$width."x".$height." ".$dest_path); + + } + } + + if ( ! function_exists('clean_file_name')) + { + function clean_file_name($file_name){ + + $replace="_"; + $pattern="/([[:alnum:]_\.-]*)/"; + + return str_replace(str_split(preg_replace($pattern,$replace,$file_name)),$replace,$file_name); + + } + } + + if ( ! function_exists('set_memcache')) + { + function set_memcache($name,$data,$length,$status = 'open'){ + $CI =& get_instance(); + $name = PRODUCTION_STATUS.'_'.$name; //add production status so test sites don't conflict with live memcache + switch($status){ + + case 'open': + $CI->objMemCache->set($name,$data, false, $length); + break; + + case 'private': + if($CI->objLogin->get('id')) $CI->objMemCache->set($CI->objLogin->get('id')."_".$name, $data, false, $length); + else $CI->objMemCache->set(str_replace(".","_",$CI->input->ip_address())."_".$name, $data, false, $length); + break; + + } + } + } + + if ( ! function_exists('get_memcache')) + { + function get_memcache($name,$status = 'open'){ + $CI =& get_instance(); + $name = PRODUCTION_STATUS.'_'.$name; //add production status so test sites don't conflict with live memcache + switch($status){ + + case 'open': + return $CI->objMemCache->get($name); + break; + + case 'private': + if($CI->objLogin->get('id')) return $CI->objMemCache->get($CI->objLogin->get('id')."_".$name); + else return $CI->objMemCache->get(str_replace(".","_",$CI->input->ip_address())."_".$name); + break; + + } + } + } + + if ( ! function_exists('file_get_conditional_contents')) + { + function file_get_conditional_contents($szURL) + { + $pCurl = curl_init($szURL); + + curl_setopt($pCurl, CURLOPT_RETURNTRANSFER, true); + curl_setopt($pCurl, CURLOPT_FOLLOWLOCATION, true); + curl_setopt($pCurl, CURLOPT_TIMEOUT, 10); + + $szContents = curl_exec($pCurl); + $aInfo = curl_getinfo($pCurl); + + if($aInfo['http_code'] === 200) + { + return $szContents; + } + + return false; + } + } \ No newline at end of file diff --git a/system/application/libraries/Loader.php b/system/application/libraries/Loader.php new file mode 100644 index 0000000..9c7054a --- /dev/null +++ b/system/application/libraries/Loader.php @@ -0,0 +1,1267 @@ +<?php + +/** + * Matchbox Loader class + * + * This file is part of Matchbox + * + * Matchbox is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Matchbox is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + * @package Matchbox + * @copyright 2007-2008 Zacharias Knudsen + * @license http://www.gnu.org/licenses/gpl.html + * @version $Id: Loader.php 205 2008-02-24 01:43:55Z [email protected] $ + */ + +if (!defined('BASEPATH')) { + exit('No direct script access allowed'); +} + +/** + * Replaces the CodeIgniter Loader class + * + * All code not encapsulated in {{{ Matchbox }}} was made by EllisLab + * + * @package Matchbox + * @copyright 2007-2008 Zacharias Knudsen + * @license http://www.gnu.org/licenses/gpl.html + */ +class CI_Loader +{ + // {{{ Matchbox + + /** + * The Matchbox object + * + * @var object + * @access private + */ + var $_matchbox; + + /** + * Loads library from module + * + * @param string + * @param string + * @param mixed + * @return void + * @access public + */ + function module_library($module, $library = '', $params = null) + { + return $this->library($library, $params, $module); + } + + /** + * Loads model from module + * + * @param string + * @param string + * @param string + * @param mixed + * @return void + * @access public + */ + function module_model($module, $model, $name = '', $db_conn = false) + { + return $this->model($model, $name, $db_conn, $module); + } + + /** + * Loads view from module + * + * @param string + * @param string + * @param array + * @param bool + * @return void + * @access public + */ + function module_view($module, $view, $vars = array(), $return = false) + { + return $this->view($view, $vars, $return, $module); + } + + /** + * Loads file from module + * + * @param string + * @param string + * @param bool + * @return void + * @access public + */ + function module_file($module, $path, $return = false) + { + return $this->file($path, $return, $module); + } + + /** + * Loads helper from module + * + * @param string + * @param mixed + * @return void + * @access public + */ + function module_helper($module, $helpers = array()) + { + return $this->helper($helpers, $module); + } + + /** + * Loads plugin from module + * + * @param string + * @param mixed + * @return void + * @access public + */ + function module_plugin($module, $plugins = array()) + { + return $this->plugin($plugins, $module); + } + + /** + * Loads script from module + * + * @param string + * @param mixed + * @return void + * @access public + */ + function module_script($module, $scripts = array()) + { + return $this->script($scripts, $module); + } + + /** + * Loads language file from module + * + * @param string + * @param mixed + * @param string + * @return void + * @access public + */ + function module_language($module, $file = array(), $lang = '') + { + return $this->language($file, $lang, $module); + } + + /** + * Loads config file from module + * + * @param string + * @param string + * @param bool + * @param bool + * @return void + * @access public + */ + function module_config($module, $file = '', $use_sections = false, $fail_gracefully = false) + { + return $this->config($file, $use_sections, $fail_gracefully, $module); + } + + //}}} + + // All these are set automatically. Don't mess with them. + var $_ci_ob_level; + var $_ci_view_path = ''; + var $_ci_is_php5 = FALSE; + var $_ci_is_instance = FALSE; // Whether we should use $this or $CI =& get_instance() + var $_ci_cached_vars = array(); + var $_ci_classes = array(); + var $_ci_models = array(); + var $_ci_helpers = array(); + var $_ci_plugins = array(); + var $_ci_scripts = array(); + var $_ci_varmap = array('unit_test' => 'unit', 'user_agent' => 'agent'); + + + /** + * Constructor + * + * Sets the path to the view files and gets the initial output buffering level + * + * @access public + */ + function CI_Loader() + { + // {{{ Matchbox + + $this->_matchbox = &load_class('Matchbox'); + + // }}} + + $this->_ci_is_php5 = (floor(phpversion()) >= 5) ? TRUE : FALSE; + $this->_ci_view_path = APPPATH.'views/'; + $this->_ci_ob_level = ob_get_level(); + + log_message('debug', "Loader Class Initialized"); + } + + // -------------------------------------------------------------------- + + /** + * Class Loader + * + * This function lets users load and instantiate classes. + * It is designed to be called from a user's app controllers. + * + * @access public + * @param string the name of the class + * @param mixed the optional parameters + * @return void + */ + function library($library = '', $params = NULL) + { + if ($library == '') + { + return FALSE; + } + + // {{{ Matchbox + + $module = $this->_matchbox->argument(2); + + if (is_array($library)) { + foreach ($library as $class) { + $this->_ci_load_class($class, $params, $module); + } + } else { + $this->_ci_load_class($library, $params, $module); + } + + // }}} + + $this->_ci_assign_to_models(); + } + + // -------------------------------------------------------------------- + + /** + * Model Loader + * + * This function lets users load and instantiate models. + * + * @access public + * @param string the name of the class + * @param mixed any initialization parameters + * @return void + */ + function model($model, $name = '', $db_conn = FALSE) + { + if (is_array($model)) + { + foreach($model as $babe) + { + $this->model($babe); + } + return; + } + + if ($model == '') + { + return; + } + + // Is the model in a sub-folder? If so, parse out the filename and path. + if (strpos($model, '/') === FALSE) + { + $path = ''; + } + else + { + $x = explode('/', $model); + $model = end($x); + unset($x[count($x)-1]); + $path = implode('/', $x).'/'; + } + + if ($name == '') + { + $name = $model; + } + + if (in_array($name, $this->_ci_models, TRUE)) + { + return; + } + + $CI =& get_instance(); + if (isset($CI->$name)) + { + show_error('The model name you are loading is the name of a resource that is already being used: '.$name); + } + + $model = strtolower($model); + + // {{{ Matchbox + + $module = $this->_matchbox->argument(3); + + if (!$filepath = $this->_matchbox->find('models/' . $path . $model . EXT, $module)) { + show_error('Unable to locate the model you have specified: ' . $model); + } + + // }}} + + if ($db_conn !== FALSE AND ! class_exists('CI_DB')) + { + if ($db_conn === TRUE) + $db_conn = ''; + + $CI->load->database($db_conn, FALSE, TRUE); + } + + if ( ! class_exists('Model')) + { + load_class('Model', FALSE); + } + + // {{{ Matchbox + + require_once($filepath); + + // }}} + + $model = ucfirst($model); + + $CI->$name = new $model(); + $CI->$name->_assign_libraries(); + + $this->_ci_models[] = $name; + } + + // -------------------------------------------------------------------- + + /** + * Database Loader + * + * @access public + * @param string the DB credentials + * @param bool whether to return the DB object + * @param bool whether to enable active record (this allows us to override the config setting) + * @return object + */ + function database($params = '', $return = FALSE, $active_record = FALSE) + { + // Grab the super object + $CI =& get_instance(); + + // Do we even need to load the database class? + if (class_exists('CI_DB') AND $return == FALSE AND $active_record == FALSE AND isset($CI->db) AND is_object($CI->db)) + { + return FALSE; + } + + require_once(BASEPATH.'database/DB'.EXT); + + if ($return === TRUE) + { + return DB($params, $active_record); + } + + // Initialize the db variable. Needed to prevent + // reference errors with some configurations + $CI->db = ''; + + // Load the DB class + $CI->db =& DB($params, $active_record); + + // Assign the DB object to any existing models + $this->_ci_assign_to_models(); + } + + // -------------------------------------------------------------------- + + /** + * Load the Utilities Class + * + * @access public + * @return string + */ + function dbutil() + { + if ( ! class_exists('CI_DB')) + { + $this->database(); + } + + $CI =& get_instance(); + + // for backwards compatibility, load dbforge so we can extend dbutils off it + // this use is deprecated and strongly discouraged + $CI->load->dbforge(); + + require_once(BASEPATH.'database/DB_utility'.EXT); + require_once(BASEPATH.'database/drivers/'.$CI->db->dbdriver.'/'.$CI->db->dbdriver.'_utility'.EXT); + $class = 'CI_DB_'.$CI->db->dbdriver.'_utility'; + + $CI->dbutil = new $class(); + + $CI->load->_ci_assign_to_models(); + } + + // -------------------------------------------------------------------- + + /** + * Load the Database Forge Class + * + * @access public + * @return string + */ + function dbforge() + { + if ( ! class_exists('CI_DB')) + { + $this->database(); + } + + $CI =& get_instance(); + + require_once(BASEPATH.'database/DB_forge'.EXT); + require_once(BASEPATH.'database/drivers/'.$CI->db->dbdriver.'/'.$CI->db->dbdriver.'_forge'.EXT); + $class = 'CI_DB_'.$CI->db->dbdriver.'_forge'; + + $CI->dbforge = new $class(); + } + + // -------------------------------------------------------------------- + + /** + * Load View + * + * This function is used to load a "view" file. It has three parameters: + * + * 1. The name of the "view" file to be included. + * 2. An associative array of data to be extracted for use in the view. + * 3. TRUE/FALSE - whether to return the data or load it. In + * some cases it's advantageous to be able to return data so that + * a developer can process it in some way. + * + * @access public + * @param string + * @param array + * @param bool + * @return void + */ + function view($view, $vars = array(), $return = FALSE) + { + // {{{ Matchbox + + $module = $this->_matchbox->argument(3); + return $this->_ci_load(array('_ci_view' => $view, '_ci_vars' => $this->_ci_object_to_array($vars), '_ci_return' => $return), $module); + + // }}} + } + + // -------------------------------------------------------------------- + + /** + * Load File + * + * This is a generic file loader + * + * @access public + * @param string + * @param bool + * @return string + */ + function file($path, $return = FALSE) + { + // {{{ Matchbox + + $module = $this->_matchbox->argument(2); + + return $this->_ci_load(array('_ci_path' => $path, '_ci_return' => $return), $module); + + // }}} + } + + // -------------------------------------------------------------------- + + /** + * Set Variables + * + * Once variables are set they become available within + * the controller class and its "view" files. + * + * @access public + * @param array + * @return void + */ + function vars($vars = array()) + { + $vars = $this->_ci_object_to_array($vars); + + if (is_array($vars) AND count($vars) > 0) + { + foreach ($vars as $key => $val) + { + $this->_ci_cached_vars[$key] = $val; + } + } + } + + // -------------------------------------------------------------------- + + /** + * Load Helper + * + * This function loads the specified helper file. + * + * @access public + * @param mixed + * @return void + */ + function helper($helpers = array()) + { + if ( ! is_array($helpers)) + { + $helpers = array($helpers); + } + + foreach ($helpers as $helper) + { + $helper = strtolower(str_replace(EXT, '', str_replace('_helper', '', $helper)).'_helper'); + + if (isset($this->_ci_helpers[$helper])) + { + continue; + } + + // {{{ Matchbox + + $module = $this->_matchbox->argument(1); + + if ($ext_helper = $this->_matchbox->find('helpers/' . config_item('subclass_prefix') . $helper . EXT, $module)) { + $base_helper = BASEPATH . 'helpers/' . $helper . EXT; + + if (!file_exists($base_helper)) { + show_error('Unable to load the requested file: helpers/' . $helper . EXT); + } + + include_once($ext_helper); + include_once($base_helper); + } elseif ($filepath = $this->_matchbox->find('helpers/' . $helper . EXT, $module, 2)) { + include($filepath); + } else { + show_error('Unable to load the requested file: helpers/' . $helper . EXT); + } + + // }}} + + $this->_ci_helpers[$helper] = TRUE; + + } + + log_message('debug', 'Helpers loaded: '.implode(', ', $helpers)); + } + + // -------------------------------------------------------------------- + + /** + * Load Helpers + * + * This is simply an alias to the above function in case the + * user has written the plural form of this function. + * + * @access public + * @param array + * @return void + */ + function helpers($helpers = array()) + { + $this->helper($helpers); + } + + // -------------------------------------------------------------------- + + /** + * Load Plugin + * + * This function loads the specified plugin. + * + * @access public + * @param array + * @return void + */ + function plugin($plugins = array()) + { + if ( ! is_array($plugins)) + { + $plugins = array($plugins); + } + + foreach ($plugins as $plugin) + { + $plugin = strtolower(str_replace(EXT, '', str_replace('_pi', '', $plugin)).'_pi'); + + if (isset($this->_ci_plugins[$plugin])) + { + continue; + } + + // {{{ Matchbox + + $module = $this->_matchbox->argument(1); + + if (!$filepath = $this->_matchbox->find('plugins/' . $plugin . EXT, $module, 2)) { + show_error('Unable to load the requested file: plugins/' . $plugin . EXT); + } + + include($filepath); + + // }}} + + $this->_ci_plugins[$plugin] = TRUE; + } + + log_message('debug', 'Plugins loaded: '.implode(', ', $plugins)); + } + + // -------------------------------------------------------------------- + + /** + * Load Plugins + * + * This is simply an alias to the above function in case the + * user has written the plural form of this function. + * + * @access public + * @param array + * @return void + */ + function plugins($plugins = array()) + { + $this->plugin($plugins); + } + + // -------------------------------------------------------------------- + + /** + * Load Script + * + * This function loads the specified include file from the + * application/scripts/ folder. + * + * NOTE: This feature has been deprecated but it will remain available + * for legacy users. + * + * @access public + * @param array + * @return void + */ + function script($scripts = array()) + { + if ( ! is_array($scripts)) + { + $scripts = array($scripts); + } + + foreach ($scripts as $script) + { + $script = strtolower(str_replace(EXT, '', $script)); + + if (isset($this->_ci_scripts[$script])) + { + continue; + } + + // {{{ Matchbox + + $module = $this->_matchbox->argument(1); + + if (!$filepath = $this->_matchbox->find('scripts/' . $script . EXT, $module, 2)) { + show_error('Unable to load the requested script: scripts/' . $script . EXT); + } + + include($filepath); + + // }}} + } + + log_message('debug', 'Scripts loaded: '.implode(', ', $scripts)); + } + + // -------------------------------------------------------------------- + + /** + * Loads a language file + * + * @access public + * @param array + * @param string + * @return void + */ + function language($file = array(), $lang = '') + { + $CI =& get_instance(); + + if ( ! is_array($file)) + { + $file = array($file); + } + + foreach ($file as $langfile) + { + // {{{ Matchbox + + $module = $this->_matchbox->argument(2); + + $CI->lang->load($langfile, $lang, false, $module); + + // }}} + } + } + + /** + * Loads language files for scaffolding + * + * @access public + * @param string + * @return arra + */ + function scaffold_language($file = '', $lang = '', $return = FALSE) + { + $CI =& get_instance(); + return $CI->lang->load($file, $lang, $return); + } + + // -------------------------------------------------------------------- + + /** + * Loads a config file + * + * @access public + * @param string + * @return void + */ + function config($file = '', $use_sections = FALSE, $fail_gracefully = FALSE) + { + $CI =& get_instance(); + + // {{{ Matchbox + + $module = $this->_matchbox->argument(3); + + $CI->config->load($file, $use_sections, $fail_gracefully, $module); + + // }}} + } + + // -------------------------------------------------------------------- + + /** + * Scaffolding Loader + * + * This initializing function works a bit different than the + * others. It doesn't load the class. Instead, it simply + * sets a flag indicating that scaffolding is allowed to be + * used. The actual scaffolding function below is + * called by the front controller based on whether the + * second segment of the URL matches the "secret" scaffolding + * word stored in the application/config/routes.php + * + * @access public + * @param string + * @return void + */ + function scaffolding($table = '') + { + if ($table === FALSE) + { + show_error('You must include the name of the table you would like to access when you initialize scaffolding'); + } + + $CI =& get_instance(); + $CI->_ci_scaffolding = TRUE; + $CI->_ci_scaff_table = $table; + } + + // -------------------------------------------------------------------- + + /** + * Loader + * + * This function is used to load views and files. + * Variables are prefixed with _ci_ to avoid symbol collision with + * variables made available to view files + * + * @access private + * @param array + * @return void + */ + function _ci_load($_ci_data) + { + // Set the default data variables + foreach (array('_ci_view', '_ci_vars', '_ci_path', '_ci_return') as $_ci_val) + { + $$_ci_val = ( ! isset($_ci_data[$_ci_val])) ? FALSE : $_ci_data[$_ci_val]; + } + + // Set the path to the requested file + // {{{ Matchbox + + if ($_ci_path == '') + { + $_ci_ext = pathinfo($_ci_view, PATHINFO_EXTENSION); + $_ci_file = ($_ci_ext == '') ? $_ci_view . EXT : $_ci_view; + $_ci_path = str_replace(APPPATH, '', $this->_ci_view_path) . $_ci_file; + $search = 1; + } + else + { + $_ci_x = explode('/', $_ci_path); + $_ci_file = end($_ci_x); + $search = 3; + } + + $module = $this->_matchbox->argument(1); + + if (!$_ci_path = $this->_matchbox->find($_ci_path, $module, $search)) { + show_error('Unable to load the requested file: ' . $_ci_file); + } + + // }}} + + // This allows anything loaded using $this->load (views, files, etc.) + // to become accessible from within the Controller and Model functions. + // Only needed when running PHP 5 + + if ($this->_ci_is_instance()) + { + $_ci_CI =& get_instance(); + foreach (get_object_vars($_ci_CI) as $_ci_key => $_ci_var) + { + if ( ! isset($this->$_ci_key)) + { + $this->$_ci_key =& $_ci_CI->$_ci_key; + } + } + } + + /* + * Extract and cache variables + * + * You can either set variables using the dedicated $this->load_vars() + * function or via the second parameter of this function. We'll merge + * the two types and cache them so that views that are embedded within + * other views can have access to these variables. + */ + if (is_array($_ci_vars)) + { + $this->_ci_cached_vars = array_merge($this->_ci_cached_vars, $_ci_vars); + } + extract($this->_ci_cached_vars); + + /* + * Buffer the output + * + * We buffer the output for two reasons: + * 1. Speed. You get a significant speed boost. + * 2. So that the final rendered template can be + * post-processed by the output class. Why do we + * need post processing? For one thing, in order to + * show the elapsed page load time. Unless we + * can intercept the content right before it's sent to + * the browser and then stop the timer it won't be accurate. + */ + ob_start(); + + // If the PHP installation does not support short tags we'll + // do a little string replacement, changing the short tags + // to standard PHP echo statements. + + if ((bool) @ini_get('short_open_tag') === FALSE AND config_item('rewrite_short_tags') == TRUE) + { + echo eval('?>'.preg_replace("/;*\s*\?>/", "; ?>", str_replace('<?=', '<?php echo ', file_get_contents($_ci_path))).'<?php '); + } + else + { + include($_ci_path); + } + + log_message('debug', 'File loaded: '.$_ci_path); + + // Return the file data if requested + if ($_ci_return === TRUE) + { + $buffer = ob_get_contents(); + @ob_end_clean(); + return $buffer; + } + + /* + * Flush the buffer... or buff the flusher? + * + * In order to permit views to be nested within + * other views, we need to flush the content back out whenever + * we are beyond the first level of output buffering so that + * it can be seen and included properly by the first included + * template and any subsequent ones. Oy! + * + */ + if (ob_get_level() > $this->_ci_ob_level + 1) + { + ob_end_flush(); + } + else + { + // PHP 4 requires that we use a global + global $OUT; + $OUT->append_output(ob_get_contents()); + @ob_end_clean(); + } + } + + // -------------------------------------------------------------------- + + /** + * Load class + * + * This function loads the requested class. + * + * @access private + * @param string the item that is being loaded + * @param mixed any additional parameters + * @return void + */ + function _ci_load_class($class, $params = NULL) + { + // Get the class name + $class = str_replace(EXT, '', $class); + + // We'll test for both lowercase and capitalized versions of the file name + foreach (array(ucfirst($class), strtolower($class)) as $class) + { + // {{{ Matchbox + + $module = $this->_matchbox->argument(2); + + if ($subclass = $this->_matchbox->find('libraries/' . config_item('subclass_prefix') . $class . EXT, $module)) { + + $baseclass = $this->_matchbox->find('libraries/' . $class . EXT, $module, 2); + + // }}} + + if ( ! file_exists($baseclass)) + { + log_message('error', "Unable to load the requested class: ".$class); + show_error("Unable to load the requested class: ".$class); + } + + // Safety: Was the class already loaded by a previous call? + if (in_array($subclass, $this->_ci_classes)) + { + $is_duplicate = TRUE; + log_message('debug', $class." class already loaded. Second attempt ignored."); + return; + } + + include($baseclass); + include($subclass); + $this->_ci_classes[] = $subclass; + + // {{{ Matchbox + + return $this->_ci_init_class($class, config_item('subclass_prefix'), $params, $module); + + // }}} + } + + // Lets search for the requested library file and load it. + $is_duplicate = FALSE; + + // {{{ Matchbox + + if ($filepath = $this->_matchbox->find('libraries/' . $class . EXT, $module, 2)) { + if (in_array($class, $this->_ci_classes)) { + $is_duplicate = true; + log_message('debug', $class . ' class already loaded. Second attempt ignored.'); + return; + } + + include($filepath); + $this->_ci_classes[] = $class; + return $this->_ci_init_class($class, '', $params, $module); + } + + // }}} + + } // END FOREACH + + // If we got this far we were unable to find the requested class. + // We do not issue errors if the load call failed due to a duplicate request + if ($is_duplicate == FALSE) + { + log_message('error', "Unable to load the requested class: ".$class); + show_error("Unable to load the requested class: ".$class); + } + } + + // -------------------------------------------------------------------- + + /** + * Instantiates a class + * + * @access private + * @param string + * @param string + * @return null + */ + function _ci_init_class($class, $prefix = '', $config = FALSE) + { + $class = strtolower($class); + + // Is there an associated config file for this class? + // {{{ Matchbox + + $module = $this->_matchbox->argument(3); + + if ($config === null) { + if ($filepath = $this->_matchbox->find('config/' . $class . EXT, $module)) { + include($filepath); + } + } + + // }}} + + if ($prefix == '') + { + $name = (class_exists('CI_'.$class)) ? 'CI_'.$class : $class; + } + else + { + $name = $prefix.$class; + } + + // Set the variable name we will assign the class to + $classvar = ( ! isset($this->_ci_varmap[$class])) ? $class : $this->_ci_varmap[$class]; + + // Instantiate the class + $CI =& get_instance(); + if ($config !== NULL) + { + $CI->$classvar = new $name($config); + } + else + { + $CI->$classvar = new $name; + } + } + + // -------------------------------------------------------------------- + + /** + * Autoloader + * + * The config/autoload.php file contains an array that permits sub-systems, + * libraries, plugins, and helpers to be loaded automatically. + * + * @access private + * @param array + * @return void + */ + function _ci_autoloader() + { + // {{{ Matchbox + + $ci = &get_instance(); + $ci->matchbox = &load_class('Matchbox'); + + //}}} + + include(APPPATH.'config/autoload'.EXT); + + if ( ! isset($autoload)) + { + return FALSE; + } + + // Load any custom config file + if (count($autoload['config']) > 0) + { + // {{{ Matchbox + + foreach ($autoload['config'] as $key => $value) { + if (is_string($key)) { + if (is_array($value)) { + foreach ($value as $config) { + $ci->config->module_load($key, $config); + } + } else { + $ci->config->module_load($key, $value); + } + } else { + $ci->config->load($value); + } + } + + // }}} + } + + // Autoload plugins, helpers, scripts and languages + foreach (array('helper', 'plugin', 'script', 'language') as $type) + { + if (isset($autoload[$type]) AND count($autoload[$type]) > 0) + { + + // {{{ Matchbox + + foreach ($autoload[$type] as $key => $value) { + if (is_string($key)) { + $this->{'module_' . $type}($key, $value); + } else { + $this->$type($value); + } + } + + // }}} + } + } + + + + // A little tweak to remain backward compatible + // The $autoload['core'] item was deprecated + if ( ! isset($autoload['libraries'])) + { + $autoload['libraries'] = $autoload['core']; + } + + // Load libraries + if (isset($autoload['libraries']) AND count($autoload['libraries']) > 0) + { + // Load the database driver. + if (in_array('database', $autoload['libraries'])) + { + $this->database(); + $autoload['libraries'] = array_diff($autoload['libraries'], array('database')); + } + + // Load scaffolding + if (in_array('scaffolding', $autoload['libraries'])) + { + $this->scaffolding(); + $autoload['libraries'] = array_diff($autoload['libraries'], array('scaffolding')); + } + + // {{{ Matchbox + + foreach ($autoload['libraries'] as $key => $value) { + if (is_string($key)) { + $this->module_library($key, $value); + } else { + $this->library($value); + } + } + + // }}} + + } + + // {{{ Matchbox + + if (isset($autoload['model'])) { + foreach ($autoload['model'] as $key => $value) { + if (is_string($key)) { + $this->module_model($key, $value); + } else { + $this->model($value); + } + } + } + + // }}} + + } + + // -------------------------------------------------------------------- + + /** + * Assign to Models + * + * Makes sure that anything loaded by the loader class (libraries, plugins, etc.) + * will be available to models, if any exist. + * + * @access private + * @param object + * @return array + */ + function _ci_assign_to_models() + { + if (count($this->_ci_models) == 0) + { + return; + } + + if ($this->_ci_is_instance()) + { + $CI =& get_instance(); + foreach ($this->_ci_models as $model) + { + $CI->$model->_assign_libraries(); + } + } + else + { + foreach ($this->_ci_models as $model) + { + $this->$model->_assign_libraries(); + } + } + } + + // -------------------------------------------------------------------- + + /** + * Object to Array + * + * Takes an object as input and converts the class variables to array key/vals + * + * @access private + * @param object + * @return array + */ + function _ci_object_to_array($object) + { + return (is_object($object)) ? get_object_vars($object) : $object; + } + + // -------------------------------------------------------------------- + + /** + * Determines whether we should use the CI instance or $this + * + * @access private + * @return bool + */ + function _ci_is_instance() + { + if ($this->_ci_is_php5 == TRUE) + { + return TRUE; + } + + global $CI; + return (is_object($CI)) ? TRUE : FALSE; + } + +} + +?> \ No newline at end of file diff --git a/system/application/libraries/MY_Config.php b/system/application/libraries/MY_Config.php new file mode 100644 index 0000000..b2dee15 --- /dev/null +++ b/system/application/libraries/MY_Config.php @@ -0,0 +1,129 @@ +<?php + +/** + * Matchbox Config class + * + * This file is part of Matchbox + * + * Matchbox is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Matchbox is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + * @package Matchbox + * @copyright 2007-2008 Zacharias Knudsen + * @license http://www.gnu.org/licenses/gpl.html + * @version $Id: MY_Config.php 204 2008-02-24 01:30:00Z [email protected] $ + */ + +if (!defined('BASEPATH')) { + exit('No direct script access allowed'); +} + +/** + * Extends the CodeIgniter Config class + * + * All code not encapsulated in {{{ Matchbox }}} was made by EllisLab + * + * @package Matchbox + * @copyright 2007-2008 Zacharias Knudsen + * @license http://www.gnu.org/licenses/gpl.html + */ +class MY_Config extends CI_Config +{ + // {{{ Matchbox + + /** + * Loads config file from module + * + * @param string + * @param string + * @param bool + * @param bool + * @return boolean + * @access public + */ + function module_load($module, $file = '', $use_sections = false, $fail_gracefully = false) + { + return $this->load($file, $use_sections, $fail_gracefully, $module); + } + + // }}} + + + /** + * Load Config File + * + * @access public + * @param string the config file name + * @return boolean if the file was loaded correctly + */ + function load($file = '', $use_sections = FALSE, $fail_gracefully = FALSE) + { + $file = ($file == '') ? 'config' : str_replace(EXT, '', $file); + + if (in_array($file, $this->is_loaded, TRUE)) + { + return TRUE; + } + + // {{{ Matchbox + + $ci = &get_instance(); + $module = $ci->matchbox->argument(3); + + if (!$filepath = $ci->matchbox->find('config/' . $file . EXT, $module)) { + if ($fail_gracefully === true) { + return false; + } + + show_error('The configuration file ' . $file . EXT . ' does not exist.'); + } + + include($filepath); + + // }}} + + if ( ! isset($config) OR ! is_array($config)) + { + if ($fail_gracefully === TRUE) + { + return FALSE; + } + show_error('Your '.$file.EXT.' file does not appear to contain a valid configuration array.'); + } + + if ($use_sections === TRUE) + { + if (isset($this->config[$file])) + { + $this->config[$file] = array_merge($this->config[$file], $config); + } + else + { + $this->config[$file] = $config; + } + } + else + { + $this->config = array_merge($this->config, $config); + } + + $this->is_loaded[] = $file; + unset($config); + + log_message('debug', 'Config file loaded: config/'.$file.EXT); + return TRUE; + } + +} + +?> \ No newline at end of file diff --git a/system/application/libraries/MY_Language.php b/system/application/libraries/MY_Language.php new file mode 100644 index 0000000..d80ba42 --- /dev/null +++ b/system/application/libraries/MY_Language.php @@ -0,0 +1,117 @@ +<?php + +/** + * Matchbox Language class + * + * This file is part of Matchbox + * + * Matchbox is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Matchbox is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + * @package Matchbox + * @copyright 2007-2008 Zacharias Knudsen + * @license http://www.gnu.org/licenses/gpl.html + * @version $Id: MY_Language.php 204 2008-02-24 01:30:00Z [email protected] $ + */ + +if (!defined('BASEPATH')) { + exit('No direct script access allowed'); +} + +/** + * Extends the CodeIgniter Language class + * + * All code not encapsulated in {{{ Matchbox }}} was made by EllisLab + * + * @package Matchbox + * @copyright 2007-2008 Zacharias Knudsen + * @license http://www.gnu.org/licenses/gpl.html + */ +class MY_Language extends CI_Language +{ + // {{{ Matchbox + + /** + * Loads language file from module + * + * @param string + * @param string + * @param string + * @param bool + * @return void + * @access public + */ + function module_load($module, $langfile = '', $idiom = '', $return = false) + { + return $this->load($langfile, $idiom, $return, $module); + } + + // }}} + + /** + * Load a language file + * + * @access public + * @param mixed the name of the language file to be loaded. Can be an array + * @param string the language (english, etc.) + * @return void + */ + function load($langfile = '', $idiom = '', $return = FALSE) + { + $langfile = str_replace(EXT, '', str_replace('_lang.', '', $langfile)).'_lang'.EXT; + + if (in_array($langfile, $this->is_loaded, TRUE)) + { + return; + } + + // {{{ Matchbox + + $ci = &get_instance(); + $module = $ci->matchbox->argument(3); + + if ($idiom == '') { + $deft_lang = $ci->config->item('language'); + $idiom = ($deft_lang == '') ? 'english' : $deft_lang; + } + + if (!$filepath = $ci->matchbox->find('language/' . $idiom . '/' . $langfile, $module, 2)) { + show_error('Unable to load the requested language file: language/' . $langfile); + } + + include($filepath); + + // }}} + + if ( ! isset($lang)) + { + log_message('error', 'Language file contains no data: language/'.$idiom.'/'.$langfile); + return; + } + + if ($return == TRUE) + { + return $lang; + } + + $this->is_loaded[] = $langfile; + $this->language = array_merge($this->language, $lang); + unset($lang); + + log_message('debug', 'Language file loaded: language/'.$idiom.'/'.$langfile); + return TRUE; + } + +} + +?> \ No newline at end of file diff --git a/system/application/libraries/MY_Model.php b/system/application/libraries/MY_Model.php new file mode 100644 index 0000000..68577d6 --- /dev/null +++ b/system/application/libraries/MY_Model.php @@ -0,0 +1,586 @@ +<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); +/* + TODO: Create permissioning for POST and PUT + + create a global function like has_permissions_post_put that you can overide + in any model to create more complex permissioning. Check user level, then if they have access + do a GET to check if they have access to that claim. If superuser don't do give give them access + straight away. +*/ +class MY_Model extends Model { + + public $selectFields = array(); + public $results = ''; + + public $currentTable = 'FALSE'; + + public $php_excel; + public $excel_added_rows = 0; + public $letters = array("A","B","C","D","E","F","G","H","I","J","K","L","M", + "N","O","P","Q","R","S","T","U","V","W","X","Y","Z"); + + public $option = array(); + public $request; + + public $data = array(); + public $original_data = array(); + public $_do_save = TRUE; + protected $database; + + function __construct() + { + $this->CI =& get_instance(); + $this->request(); + } + + public function filterFields($field, $for_query = FALSE, $reverse = FALSE) + { + $newField = ''; + switch($field) { + /* + CJFN default + */ + default: + if(!$reverse AND $for_query){ + $tableFields = implode(",",$this->fields); + if(contains($tableFields,$field)) $this->selectFields[] = "$this->database.$this->table.$field AS $field"; + } + else if (!$reverse) $newField = $field; + else $newField = "$this->database.$this->table.$field"; + break; + } + return $newField; + } + + function is_dirty(){ + //if no original data it's definitely dirty + if(!count($this->original_data)) return true; + + //check to see if any of the original data has been changed + foreach($this->original_data as $key=>$val){ + if($val!=$this->get($key)) return true; + } + return false; + } + + function validate($rules = false, $onlyfields = false, $prefix = false){ + + if(isset($this->validation)){ + $this->load->library('form_validation'); + + //if(!$prefix) $prefix = $this->table; + if(!$rules) $rules = $this->validation; + + /** + * modified foreach loop to replace $this->validation with $rules + * i.e. if passed to the function then passed rules should be used. + */ + foreach($rules as $validation){ + if($onlyfields && !in_array($validation['field'],$onlyfields)) continue; //don't validate fields that aren't in onlyfield if used + //if($prefix) $validation['field'] = $prefix.'_'.$validation['field']; + $prefixedRules[] = $validation; + } + $this->form_validation->set_rules($prefixedRules); + $this->form_validation->set_error_delimiters('',''); + if ($this->form_validation->run() === FALSE){ + $this->errors = array(); + foreach($rules as $validation){ + $error_field = $validation['field']; + $error_message = $this->form_validation->error($error_field); + + if($error_message) $this->errors[($prefix?$prefix."_":'').$this->filterFields($error_field)] = $error_message; + } + + return FALSE; + } + return TRUE; + /* + $arValidation = $this->validation; + foreach ($arValidation as $validation) + { + $this->form_validation->set_rules($rules); + } + */ + } else { + return TRUE; + } + } + + function set_fields(){ + $fields = $this->db->field_data($this->table); + + // Store only the field names and ensure validation list includes all fields + foreach ($fields as $field) + { + // Populate fields array + $this->fields[] = $field->name; + + } + } + public function clear(){ + $this->data = array(); + return $this; + } + public function reset(){ + $this->data = array(); + $this->original_data = array(); + return $this; + } + public function clear_request(){ + $_REQUEST = array(); + return $this; + } + function save_session($session_name) + { + $this->session->set_userdata($session_name,$this->data); + } + + function restore_session($session_name) + { + $this->data = $this->session->userdata($session_name); + } + + function get_form($prefix = FALSE, $do_validation = TRUE,$custom_validation = FALSE) + { + $ar_data = array(); + + foreach($this->option as $key => $value) + { + if(!$prefix || preg_match("/".$prefix."_/", $key)) + { + if($prefix) $key = preg_replace("/".$prefix."_/", "", $key, 1); + $filtered_key = $this->filterFields($key,FALSE,TRUE); + if(is_string($filtered_key)) $key = $filtered_key; + if($key != 'id') $ar_data[end(explode(".",$key))] = $value; + if($do_validation) if($key != 'id') @$_POST[end(explode(".",$key))] = $value; + } + } + + if($do_validation) + { + $is_valid = $this->validate($custom_validation?$custom_validation:FALSE,FALSE,$prefix); + } else $is_valid = TRUE; + if($is_valid){ + foreach($ar_data as $key => $value){ + if($key != 'id') $this->set(end(explode(".",$key)),$value); + } + } + + return $is_valid; + } + + function set( $sproperty, $svalue ) { + if (in_array($sproperty,$this->fields)) { + //Added the isset check in below line as for the comparison it should be set already + if(isset($this->data[$sproperty]) AND ($this->data[$sproperty]!=$svalue)) $this->dirty = true; + return ($this->data[$sproperty] = $svalue); + } else { + //throw error + return false; + } + } + function get( $sproperty ){ + switch ($sproperty) { + default: + if (isset($this->data[$sproperty])) { + return $this->data[$sproperty]; + } else { + //throw error + return false; + } + break; + } + } + function save($data = null, $id = null) + { + + if ($data) + { + $this->data = $data; + } + + $this->pre_save(); + + if($this->_do_save AND $this->is_dirty()) + { + if($this->data){ + foreach ($this->data as $key => $value) + { + if (array_search($key, $this->fields) === FALSE) + { + unset($this->data[$key]); + } + if ($value=='' && $value!==0) + { + $this->data[$key] = NULL; + } + } + + if ($id != null) + { + //$this->id = $id; + $this->data['id'] = $id; + } + + //$id = $this->id; + $id = $this->get('id'); + + if ($this->get('id') !== null && $this->get('id') !== false) + { + if(!$this->is_dirty()) return; + //$this->db->where($this->primaryKey, $id); + $this->data['date_time_modified'] = date('Y-m-d H:i:s'); + $this->data['modified_by'] = $this->CI->objLogin->get('id'); + $this->db->where('id', $id); + $this->db->update($this->database.'.'.$this->table, $this->data); + + //$this->__affectedRows = $this->db->affected_rows(); + } + else + { + $this->data['date_time_created'] = date('Y-m-d H:i:s'); + if(!isset($this->data['created_by']) || !$this->data['created_by']) $this->data['created_by'] = $this->CI->objLogin->get('id'); + //need to support legacy systems that use dtcreated + if(in_array('dtcreated',$this->fields)){ + $this->data['dtcreated'] = date('Y-m-d H:i:s'); + } + + $this->db->insert($this->database.'.'.$this->table, $this->data); + + //$this->__insertID = $this->db->insert_id(); + //return $this->__insertID; + $this->data['id'] = $this->db->insert_id(); + } + } + + return $this; + } + } + + function load_data($id = null, $fields = null, $filter = FALSE) + { + if ($id !== null) + { + //$this->id = $id; + $this->data['id'] = $id; + } + + $id = $this->data['id']; + + if ($this->data['id'] !== null && $this->data['id'] !== false) + { + $this->data = $this->find($this->database.'.'.$this->table . '.id = ' . $id, $fields, NULL,0,NULL,TRUE); + $this->original_data = $this->data; + + if($filter){ + foreach($this->data as $key => $value){ + $filtered_key = $this->filterFields($key,FALSE); + if($filtered_key != $key){ + unset($this->data[$key]); + $this->data[$filtered_key] = $value; + unset($this->original_data[$key]); + $this->original_data[$filtered_key] = $value; + } + } + } + + return $this->data; + } + else + { + return false; + } + } + + function findAll($conditions = NULL, $fields = '*', $order = NULL, $start = 0, $limit = NULL, $filter = FALSE) + { + if ($conditions != NULL) + { + $this->db->where($conditions); + } + + if ($fields != NULL) + { + $this->db->select($fields); + } + + if ($order != NULL) + { + $this->db->orderby($order); + } + + if ($limit != NULL) + { + $this->db->limit($limit, $start); + } + + $query = $this->db->get($this->database.'.'.$this->table); + //$this->__numRows = $query->num_rows(); + + //return ($this->returnArray) ? $query->result_array() : $query->result(); + + return $query->result_array(); + } + + function find($conditions = NULL, $fields = '*', $order = 'id ASC') + { + $data = $this->findAll($conditions, $fields, $order, 0, 1); + + if ($data) + { + return $data[0]; + } + else + { + return false; + } + } + + function url_base64_decode($str){ + return strtr(base64_decode($str), + array( + '+' => '.', + '=' => '-', + '/' => '~' + ) + ); + } + + public function where($fields,$extra = FALSE){ + foreach($fields AS $field){ + if(isset($this->option[$field])){ + $value = $this->option[$field]; + $field = $this->filterFields($field,FALSE,TRUE); + if($field=='id') + $this->db->where("$this->database.$this->table.$field",$value); + else + if($field) $this->db->where($field,$value); + } + } + } + + public function or_where($fields,$extra = FALSE){ + foreach($fields AS $field){ + if(isset($this->option[$field]) AND $this->option[$field]){ + $value = $this->option[$field]; + $field = str_replace('_or_where','',$field); + $field = $this->filterFields($field,FALSE,TRUE); + $this->db->or_where($field,$value); + } + } + } + + public function where_not($fields,$extra = FALSE){ + foreach($fields AS $field){ + if(isset($this->option[$field])){ + $value = $this->option[$field]; + $field = str_replace('_not','',$field); + $field = $this->filterFields($field,FALSE,TRUE); + if($field=='id') + $this->db->where("$this->database.$this->table.$field !=",$value); + else + if($field) $this->db->where("$field !=",$value); + } + } + } + + public function range($fields,$extra = FALSE){ + foreach($fields AS $field){ + if(isset($this->option[$field]) AND $this->option[$field]){ + $value = explode('|',$this->option[$field]); + $from = $value[0]; + $to = $value[1]; + $field = str_replace('_range','',$field); + $field = $this->filterFields($field,FALSE,TRUE); + $this->db->where("$field >=",$from); + $this->db->where("$field <=",$to); + } + } + } + + public function where_not_in($fields,$extra = FALSE){ + foreach($fields AS $field){ + if(isset($this->option[$field]) AND $this->option[$field]){ + $value = explode('|',$this->option[$field]); + $field = str_replace('_not_in','',$field); + $field = str_replace('_not','',$field); + $field = $this->filterFields($field,FALSE,TRUE); + $this->db->where_not_in("$field",$value); + } + } + } + + public function where_null($fields,$extra = FALSE){ + foreach($fields AS $field){ + if(isset($this->option[$field])){ + $value = $this->option[$field]; + $field = str_replace('_null','',$field); + $field = $this->filterFields($field,FALSE,TRUE); + $this->db->where($field.' IS NULL'); + } + } + } + + public function where_not_null($fields,$extra = FALSE){ + foreach($fields AS $field){ + if(isset($this->option[$field])){ + $value = $this->option[$field]; + $field = str_replace('_not_null','',$field); + $field = $this->filterFields($field,FALSE,TRUE); + $this->db->where($field.' IS NOT NULL'); + } + } + } + + public function like($fields,$extra = FALSE){ + foreach($fields AS $field){ + if(isset($this->option[$field]) AND $this->option[$field]){ + $value = explode('|',$this->option[$field]); + $field = str_replace('_like','',$field); + $field = $this->filterFields($field,FALSE,TRUE); + $this->db->like($field,$value[0],(isset($value[1])?$value[1]:'both')); + } + } + } + + public function or_like($fields,$extra = FALSE){ + foreach($fields AS $field){ + if(isset($this->option[$field]) AND $this->option[$field]){ + $value = explode('|',$this->option[$field]); + $field = str_replace('_or_like','',$field); + $field = $this->filterFields($field,FALSE,TRUE); + $this->db->or_like($field,$value[0],(isset($value[1])?$value[1]:'both')); + } + } + } + + + public function where_in($fields,$extra = FALSE){ + foreach($fields AS $field){ + if(isset($this->option[$field]) AND $this->option[$field]){ + $value = explode('|',$this->option[$field]); + $field = str_replace('_in','',$field); + $field = $this->filterFields($field,FALSE,TRUE); + $this->db->where_in("$field",$value); + } + } + } + public function search(){ + return $this; + } + + public function finalize(){ + return $this; + } + + function permissions(){ + return $this; + } + public function do_joins(){ + return $this; + } + public function pre_save(){ + return $this; + } + + public function request($ar_native = FALSE,$clear = FALSE) + { + if($clear) $this->option = array(); + foreach(($ar_native?$ar_native:$_REQUEST) as $key => $value) + { + if(!contains("PHPSESSID,__utmz,__utma,APE_Cookie",$key)) $this->option[$key] = $value; + } + } + + public function custom(){ + $this->permissions(); + if(isset($this->option['fields'])){ + $ar_fields = explode(' ',trim($this->option['fields'])); + foreach($ar_fields AS $field) { + $this->filterFields($field,TRUE); + } + } + else $this->filterFields('defaults',TRUE); + + $this->search(); + + $this->do_joins(); + + if(isset($this->option['group'])){ + $ar_group = explode(',',$this->option['group']); + $this->db->group_by($ar_group); + } + + return $this; + } + + public function run_api(){ + if(isset($this->option['start']) || isset($this->option['start'])){ + $this->custom(); + $this->selectFields[] = "$this->database.$this->table.id AS id"; + $this->total_count = count($this->db->select(array_unique($this->selectFields),FALSE)->get("$this->database.$this->table")->result_array()); + } + + $this->custom(); + if(isset($this->option['order']) || isset($this->option['order'])){ + $ar_order = explode(',',$this->option['order']); + foreach($ar_order as $order){ + if(isset($this->option['dir'])) $this->db->order_by("$order", strtoupper($this->option['dir'])); + else $this->db->order_by(trim($order)); + } + } + + //set max to 500 + if(isset($this->option['limit']) && $this->option['limit']>500) $this->option['limit'] = 500; + + if(isset($this->option['limit']) && isset($this->option['start'])) $this->db->limit($this->option['limit'],$this->option['start']); + elseif(isset($this->option['limit'])) $this->db->limit($this->option['limit']); + $this->selectFields[] = "$this->database.$this->table.id AS id"; + $this->db->select(array_unique($this->selectFields),FALSE); + $query = $this->db->get($this->database.".".$this->table); + $this->results = $query->result_array(); + + if(!isset($this->option['start'])){ + $this->total_count = count($this->results); + } + + $this->finalize(); + + // debug + if(isset($_REQUEST['debug'])) print_r($this->db->queries); + + return $this->results; + + + } + + function remove($id = null) + { + if ($id != null) + { + $this->data['id'] = $id; + } + + $id = $this->data['id']; + + if ($this->data['id'] !== null && $this->data['id'] !== false) + { + if ($this->db->delete($this->table, array('id' => $id))) + { + $this->data['id'] = null; + $this->data = array(); + + return true; + } + else + { + return false; + } + } + else + { + return false; + } + } +} +// END Model Class diff --git a/system/application/libraries/Matchbox.php b/system/application/libraries/Matchbox.php new file mode 100644 index 0000000..0f9a0cc --- /dev/null +++ b/system/application/libraries/Matchbox.php @@ -0,0 +1,299 @@ +<?php + +/** + * Matchbox class + * + * This file is part of Matchbox + * + * Matchbox is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Matchbox is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + * @package Matchbox + * @copyright 2007-2008 Zacharias Knudsen + * @license http://www.gnu.org/licenses/gpl.html + * @version $Id: Matchbox.php 205 2008-02-24 01:43:55Z [email protected] $ + */ + +if (!defined('BASEPATH')) { + exit('No direct script access allowed'); +} + +/** + * Matchbox Version + */ +define('MATCHBOX_VERSION', '0.9.3'); + +/** + * Provides modular functionality + * + * @package Matchbox + * @copyright 2007-2008 Zacharias Knudsen + * @license http://www.gnu.org/licenses/gpl.html + */ +class CI_Matchbox +{ + + /** + * The files that should be excluded from the caller search + * + * @var array + * @access private + */ + var $_callers = array('Loader', 'Matchbox', 'MY_Config', 'MY_Language', 'Parser','REST_Controller'); + + /** + * The directories that contain modules + * + * @var array + * @access public + */ + var $_directories = array('modules'); + + /** + * The directory in which the current module is located + * + * @var string + * @access private + */ + var $_directory = ''; + + /** + * The module in which the current controller is located + * + * @var string + * @access private + */ + var $_module = ''; + + /** + * Fetches configuration file + * + * @return void + * @access public + */ + function CI_Matchbox() + { + @include(APPPATH . 'config/matchbox' . EXT); + + if (isset($config)) { + $this->_callers = array_merge($this->_callers, (!is_array($config['callers']) ? array() : $config['callers'])); + $this->_directories = (!is_array($config['directories'])) ? $this->_directories : $config['directories']; + } else { + log_message('error', 'Matchbox Config File Not Found'); + } + + log_message('debug', 'Matchbox Class Initialized'); + } + + /** + * Locates resources + * + * @param string + * @param string + * @param string + * @param string + * $param integer + * @return mixed + * @access public + */ + function find($resource, $module = '', $search = 1) + { + log_message('debug', '---Matchbox---'); + log_message('debug', 'Finding: ' . $resource); + + $directories = array(); + + if ($module !== '') { + foreach ($this->directory_array() as $directory) { + $directories[] = APPPATH . $directory . '/' . $module . '/'; + } + } else { + $caller = $this->detect_caller(); + + foreach ($this->directory_array() as $directory) { + $directories[] = APPPATH . $directory . '/' . $caller . '/'; + } + + if ($search == 3) { + $directories[] = ''; + } else { + $directories[] = APPPATH; + + if ($search == 2) { + $directories[] = BASEPATH; + } + } + } + + foreach ($directories as $directory) { + $filepath = $directory . $resource; + + log_message('debug', 'Looking in: ' . $filepath); + + if (file_exists($filepath)) { + log_message('debug', 'Found'); + log_message('debug', '--------------'); + + return $filepath; + } + } + + log_message('debug', 'Not found'); + log_message('debug', '--------------'); + + return false; + } + + /** + * Detects calling module + * + * @return string + * @access public + */ + function detect_caller() + { + $callers = array(); + $directories = array(); + $traces = debug_backtrace(); + + foreach ($this->caller_array() as $caller) { + $callers[] = $this->_swap_separators($caller, true); + } + + $search = '/(?:' . implode('|', $callers) . ')' . EXT . '$/i'; + + foreach ($traces as $trace) { + $filepath = $this->_swap_separators($trace['file']); + + if (!preg_match($search, $filepath)) { + break; + } + } + + foreach ($this->directory_array() as $directory) { + $directories[] = $this->_swap_separators(realpath(APPPATH . $directory), true); + } + + $search = '/^(?:' . implode('|', $directories) . ')\/(.+?)\//i'; + + if (preg_match($search, $filepath, $matches)) { + log_message('debug', 'Calling module: ' . $matches[1]); + + return $matches[1]; + } + + log_message('debug', 'No valid caller'); + + return ''; + } + + /** + * Returns the nth argument + * + * @access public + */ + function argument($argument) + { + $traces = debug_backtrace(); + + if (isset($traces[1]['args'][$argument])) { + return $traces[1]['args'][$argument]; + } + + return ''; + } + + /** + * Returns an array of callers + * + * @access public + */ + function caller_array() + { + return $this->_callers; + } + + /** + * Returns an array of module directories + * + * @access public + */ + function directory_array() + { + return $this->_directories; + } + + /** + * Sets the directory + * + * @return string + * @access public + */ + function set_directory($directory) + { + $this->_directory = $directory . '/'; + } + + /** + * Fetches the current directory (if any) + * + * @return string + * @access public + */ + function fetch_directory() + { + return $this->_directory; + } + + /** + * Sets the module + * + * @return string + * @access public + */ + function set_module($module) + { + $this->_module = $module . '/'; + } + + /** + * Fetches the current module (if any) + * + * @return string + * @access public + */ + function fetch_module() + { + return $this->_module; + } + + /** + * Swaps directory separators to Unix style for consistency + * + * @return string + * @access private + */ + function _swap_separators($path, $search = false) + { + $path = strtr($path, '\\', '/'); + + if ($search) { + $path = str_replace(array('/', '|'), array('\/', '\|'), $path); + } + + return $path; + } + +} + +?> \ No newline at end of file diff --git a/system/application/libraries/REST_Controller.php b/system/application/libraries/REST_Controller.php new file mode 100644 index 0000000..5d914ce --- /dev/null +++ b/system/application/libraries/REST_Controller.php @@ -0,0 +1,730 @@ +<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); + +class REST_Controller extends Controller { + + // Not what you'd think, set this in a controller to use a default format + protected $rest_format = NULL; + + private $_method; + private $_format; + + private $_get_args; + private $_put_args; + private $_args; + public $_is_public = FALSE; + + // List all supported methods, the first will be the default format + private $_supported_formats = array( + 'json' => 'application/json', + 'xml' => 'application/xml', + 'rawxml' => 'application/xml', + 'serialize' => 'text/plain', + 'php' => 'text/plain', + 'html' => 'text/html', + 'csv' => 'application/csv' + ); + + // Constructor function + function __construct() + { + parent::Controller(); + + // How is this request being made? POST, DELETE, GET, PUT? + $this->_method = $this->_detect_method(); + + + // Set up our GET variables + $this->_get_args = array_merge(array($this->uri->segment(2) =>'index'),$this->uri->uri_to_assoc(3)); + $this->_args = $this->_get_args; + + $this->page = isset($_REQUEST['page'])?$_REQUEST['page']:false; + $this->rows = isset($_REQUEST['rows'])?$_REQUEST['rows']:false; + switch(strtolower($this->input->server('REQUEST_METHOD'))){ + case "get": + if(isset($_REQUEST['sidx'])) $_REQUEST['sort'] = $_REQUEST['sidx']; + if(isset($_REQUEST['sord'])) $_REQUEST['dir'] = $_REQUEST['sord']; + if($this->page AND $this->rows){ + $page = $this->page - 1; + $rows = $this->rows; + $_REQUEST['start'] = $page != 0?$page*$rows:$page; + $_REQUEST['limit'] = $rows; + }; + break; + case "post": + foreach($_REQUEST as $key => $value){ + if(!is_array($value)) if(strtolower(preg_replace("[^A-Za-z0-9]", "", $key )) != strtolower(preg_replace("[^A-Za-z0-9]", "", $value ))) $_POST[$key] = $value; + else $_POST[$key] = $value; + } + break; + case "put": + parse_str(file_get_contents('php://input'), $this->_put_args); + $_REQUEST = $this->_put_args; + foreach($_REQUEST as $key => $value){ + if(!is_array($value)) if(strtolower(preg_replace("[^A-Za-z0-9]", "", $key )) != strtolower(preg_replace("[^A-Za-z0-9]", "", $value ))) $_POST[$key] = $value; + else $_POST[$key] = $value; + } + break; + case "delete": + $_REQUEST = $this->_args; + break; + } + + if(isset($_REQUEST['key']) AND $_REQUEST['key'] == "c31ecc24-3032-434f-b623-ee0c4ddccfb1") + { + $this->key = TRUE; + $this->key_user = !isset($_REQUEST['key_user'])?'superuser':$_REQUEST['key_user']; + if(isset($_REQUEST['key_user_id'])) $this->key_user_id = $_REQUEST['key_user_id']; + } + elseif(isset($_REQUEST['key'])) $this->key = $_REQUEST['key']; + else $this->key = FALSE; + + $this->rest_auth = isset($_REQUEST['auth_type'])?$_REQUEST['auth_type']:'digest'; + // Lets grab the config and get ready to party + $this->load->config('rest'); + + if($this->rest_auth == 'basic') + { + $this->_prepareBasicAuth(); + } + + elseif($this->rest_auth == 'digest') + { + $this->_prepareDigestAuth(); + } + + // Set caching based on the REST cache config item + //$this->output->cache( $this->config->item('rest_cache') ); + // Which format should the data be returned in? + $this->_format = $this->_detect_format(); + + } + + function _global_get_functions() + { + $module = $this->_module; + + if(isset($_REQUEST['download_as_excel'])) + { + ini_set('memory_limit','1000M'); + $this->$module->excel_new(); + return $this->$module->excel_save(); + exit; + } + } + /* + * Remap + * + * Requests are not made to methods directly The request will be for an "object". + * this simply maps the object and method to the correct Controller method. + */ + function _remap($object_called) + { + $controller_method = $object_called.'_'.$this->_method; + + if(method_exists($this, $controller_method)) + { + $this->$controller_method(); + } + else + { + $controller_method = $this->_method; + + if(method_exists($this, $controller_method)) + { + $this->$controller_method(); + } + + else + { + show_404(); + } + + } + } + + function get() + { + $class = $this->_class; + $module = $this->_module; + + $this->load->module_model($module,$class.'_model',$class); + $data = $this->$class->run_api(); + + $this->total_count = $this->$class->total_count; + + $this->success = TRUE; + $this->message = 'Successfully Grabbed '.ucfirst($class).' Info.'; + + $this->response($data, 200); // 200 being the HTTP response code + + } + + function post() + { + $class = $this->_class; + $module = $this->_module; + + $this->load->module_model($module,$class.'_model',$class); + $is_valid = $this->$class->get_form($prefix = FALSE,!isset($_POST['validate'])?TRUE:FALSE); + + if($is_valid){ + + $this->$class->save(); + + $this->total_count = 1; + $this->success = TRUE; + if(isset($this->_success_message)){ + $this->message = $this->_success_message; + } else { + $this->message = 'Successfully Posted '.ucfirst($class).' Info.'; + } + + $this->response($this->$class->data, 200); + } else { + $this->total_count = 0; + $this->success = FALSE; + $this->message = 'Something Happened.'; + $this->response($this->$class->errors, 200); + } + } + + function put() + { + $class = $this->_class; + $module = $this->_module; + + $this->load->module_model($module,$class.'_model',$class); + $this->$class->load_data($_REQUEST['id']); + $is_valid = $this->$class->get_form($prefix = FALSE,!isset($_POST['validate'])?TRUE:FALSE); + + if($is_valid){ + + $this->$class->save(); + + $this->total_count = 1; + $this->success = TRUE; + if(isset($this->_success_message)){ + $this->message = $this->_success_message; + } else { + $this->message = 'Successfully Posted '.ucfirst($class).' Info.'; + } + + $this->response($this->$class->data, 200); + } else { + $this->total_count = 0; + $this->success = FALSE; + $this->message = 'Something Happened.'; + $this->response($this->$class->errors, 200); + } + } + + function delete() + { + $class = $this->_class; + $module = $this->_module; + + $this->load->module_model($module,$class.'_model',$class); + $this->$class->load_data($_REQUEST['id']); + $this->$class->remove(); + } + + /* + * response + * + * Takes pure data and optionally a status code, then creates the response + */ + function response($data = '', $http_code = 200) + { + //if(empty($data)) + //{ + // $this->output->set_status_header(404); + // return; + //} + $this->output->set_status_header($http_code); + + // If the format method exists, call and return the output in that format + if(method_exists($this, '_'.$this->_format)) + { + // Set a XML header + $this->output->set_header('Content-type: '.$this->_supported_formats[$this->_format]); + + $formatted_data = $this->{'_'.$this->_format}($data); + $this->output->set_output( $formatted_data ); + } + + // Format not supported, output directly + else + { + $this->output->set_output( $data ); + } + + } + + + /* + * Detect format + * + * Detect which format should be used to output the data + */ + private function _detect_format() + { + // A format has been passed in the URL and it is supported + if(array_key_exists('format', $this->_args) && array_key_exists($this->_args['format'], $this->_supported_formats)) + { + return $this->_args['format']; + } + + // Otherwise, check the HTTP_ACCEPT (if it exists and we are allowed) + if($this->config->item('rest_ignore_http_accept') === FALSE && $this->input->server('HTTP_ACCEPT')) + { + // Check all formats against the HTTP_ACCEPT header + foreach(array_keys($this->_supported_formats) as $format) + { + // Has this format been requested? + if(strpos($this->input->server('HTTP_ACCEPT'), $format) !== FALSE) + { + // If not HTML or XML assume its right and send it on its way + if($format != 'html' && $format != 'xml') + { + + return $format; + } + + // HTML or XML have shown up as a match + else + { + // If it is truely HTML, it wont want any XML + if($format == 'html' && strpos($this->input->server('HTTP_ACCEPT'), 'xml') === FALSE) + { + return $format; + } + // If it is truely XML, it wont want any HTML + elseif($format == 'xml' && strpos($this->input->server('HTTP_ACCEPT'), 'html') === FALSE) + { + return $format; + } + } + } + } + + } // End HTTP_ACCEPT checking + + // Well, none of that has worked! Let's see if the controller has a default + if($this->rest_format != NULL) + { + return $this->rest_format; + } + + // Just use whatever the first supported type is, nothing else is working! + list($default)=array_keys($this->_supported_formats); + return $default; + + } + + + /* + * Detect method + * + * Detect which method (POST, PUT, GET, DELETE) is being used + */ + private function _detect_method() + { + $method = strtolower($this->input->server('REQUEST_METHOD')); + if(in_array($method, array('get', 'delete', 'post', 'put'))) + { + return $method; + } + + return 'get'; + } + + + // INPUT FUNCTION -------------------------------------------------------------- + + + public function restGet($key) + { + return array_key_exists($key, $this->_get_args) ? $this->input->xss_clean( $this->_get_args[$key] ) : $this->input->get($key) ; + } + + public function restPost($key) + { + return $this->input->post($key); + } + + public function restPut($key) + { + return array_key_exists($key, $this->_put_args) ? $this->input->xss_clean( $this->_put_args[$key] ) : FALSE ; + } + + // SECURITY FUNCTIONS --------------------------------------------------------- + + private function _checkLogin($username = '',$password = FALSE) + { + + $this->load->module_model('common','User_Model','user'); + + return $this->user->authenticate($username,$password,$this->key); + + } + + private function _prepareBasicAuth() + { + $username = NULL; + $password = NULL; + + // mod_php + if (isset($_SERVER['PHP_AUTH_USER'])) + { + $username = $_SERVER['PHP_AUTH_USER']; + $password = $_SERVER['PHP_AUTH_PW']; + } + // most other servers + elseif (isset($_SERVER['HTTP_AUTHENTICATION'])) + { + if (strpos(strtolower($_SERVER['HTTP_AUTHENTICATION']),'basic')===0) + { + list($username,$password) = explode(':',base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6))); + } + } + elseif (isset($_SERVER['HTTP_WWW_AUTHORIZATION'])) + { + if (strpos(strtolower($_SERVER['HTTP_WWW_AUTHORIZATION']),'basic')===0) + { + list($username,$password) = explode(':',base64_decode(substr($_SERVER['HTTP_WWW_AUTHORIZATION'], 6))); + } + } + $row = $this->_checkLogin($username, $password); + if ( !$row ) + { + $this->_forceLogin(); + } else { + $this->load->module_model('common','User_Model','objLogin'); + $this->objLogin->restore_session('login'); + $this->objMemCache = new Memcache; + $this->objMemCache->addServer(MEMCACHED_IP1,11211); + $this->objMemCache->addServer(MEMCACHED_IP2,11211); + + } + + + } + + /* + CJFN url_base64_decode + */ + public function url_base64_decode($str){ + return strtr(base64_decode($str), + array( + '.' => '+', + '\\' => '=', + '~' => '/' + ) + ); + } + + private function _prepareDigestAuth() + { + if(!$this->_is_public) + { + if(!$this->key){ + $uniqid = uniqid(""); // Empty argument for backward compatibility + + // We need to test which server authentication variable to use + // because the PHP ISAPI module in IIS acts different from CGI + if(isset($_SERVER['PHP_AUTH_DIGEST'])) + { + $digest_string = $_SERVER['PHP_AUTH_DIGEST']; + } + elseif(isset($_SERVER['HTTP_AUTHORIZATION'])) + { + $digest_string = $_SERVER['HTTP_AUTHORIZATION']; + } + else + { + $digest_string = ""; + } + + /* The $_SESSION['error_prompted'] variabile is used to ask + the password again if none given or if the user enters + a wrong auth. informations. */ + if ( empty($digest_string) ) + { + $this->_forceLogin($uniqid); + } + + // We need to retrieve authentication informations from the $auth_data variable + preg_match_all('@(username|nonce|uri|nc|cnonce|qop|response)=[\'"]?([^\'",]+)@', $digest_string, $matches); + $digest = array_combine($matches[1], $matches[2]); + + $row = $this->_checkLogin($digest['username']); + if ( !array_key_exists('username', $digest) || !isset($row['password']) ) + { + $this->_forceLogin($uniqid); + } + + $valid_pass = $row['password']; + + // This is the valid response expected + $A1 = md5($digest['username'] . ':' . $this->config->item('rest_realm') . ':' . $valid_pass); + $A2 = md5(strtoupper($this->_method).':'.$digest['uri']); + $valid_response = md5($A1.':'.$digest['nonce'].':'.$digest['nc'].':'.$digest['cnonce'].':'.$digest['qop'].':'.$A2); + + if ($digest['response'] != $valid_response) + { + $this->_forceLogin($uniqid); + } + } + + if($this->key === TRUE) + { + if(!isset($this->key_user_id)) $access = $this->_checkLogin($this->key_user); + else $access = $this->_checkLogin($this->key_user,FALSE,FALSE,$this->key_user_id); + if(!$access) $this->_forceLogin(); + } + elseif($this->key) + { + $access = $this->_checkLogin(); + if(!$access) $this->_forceLogin(); + } + + $this->load->module_model('common','User_Model','objLogin'); + $this->objLogin->restore_session('login'); + + if(isset($_REQUEST['login']) AND !$this->key) + { + $this->objLogin->gen_key($this->objLogin->get("id")); + $this->objLogin->load_data($this->objLogin->get("id")); + $this->objLogin->save_session('login'); + $this->objLogin->restore_session('login'); + } + } + $this->objMemCache = new Memcache; + $this->objMemCache->addServer(MEMCACHED_IP1,11211); + $this->objMemCache->addServer(MEMCACHED_IP2,11211); + } + + + private function _forceLogin($nonce = '') + { + header('HTTP/1.0 401 Unauthorized'); + header('HTTP/1.1 401 Unauthorized'); + header('not_logged_in'); + + if($this->rest_auth == 'basic') + { + header('WWW-Authenticate: Basic realm="'.$this->config->item('rest_realm').'"'); + } + + elseif($this->rest_auth == 'digest') + { + header('WWW-Authenticate: Digest realm="'.$this->config->item('rest_realm'). '" qop="auth" nonce="'.$nonce.'" opaque="'.md5($this->config->item('rest_realm')).'"'); + } + + print_r(json_encode(array( + 'success'=>FALSE, + 'message'=>'User and Password Incorrect.', + 'results'=> FALSE + ))); + + die(); + } + // FORMATING FUNCTIONS --------------------------------------------------------- + + // Format XML for output + private function _xml($data = array(), $structure = NULL, $basenode = 'xml') + { + // turn off compatibility mode as simple xml throws a wobbly if you don't. + if (ini_get('zend.ze1_compatibility_mode') == 1) + { + ini_set ('zend.ze1_compatibility_mode', 0); + } + + if ($structure == NULL) + { + $structure = simplexml_load_string("<?xml version='1.0' encoding='utf-8'?><$basenode />"); + } + + // loop through the data passed in. + foreach($data as $key => $value) + { + // no numeric keys in our xml please! + if (is_numeric($key)) + { + // make string key... + //$key = "item_". (string) $key; + $key = "item"; + } + + // replace anything not alpha numeric + $key = preg_replace('/[^a-z]/i', '', $key); + + // if there is another array found recrusively call this function + if (is_array($value)) + { + $node = $structure->addChild($key); + // recrusive call. + $this->_xml($value, $node, $basenode); + } + else + { + // add single node. + + $value = htmlentities($value, ENT_NOQUOTES, "UTF-8"); + + $UsedKeys[] = $key; + + $structure->addChild($key, $value); + } + + } + + // pass back as string. or simple xml object if you want! + return $structure->asXML(); + } + + + // Format Raw XML for output + private function _rawxml($data = array(), $structure = NULL, $basenode = 'xml') + { + // turn off compatibility mode as simple xml throws a wobbly if you don't. + if (ini_get('zend.ze1_compatibility_mode') == 1) + { + ini_set ('zend.ze1_compatibility_mode', 0); + } + + if ($structure == NULL) + { + $structure = simplexml_load_string("<?xml version='1.0' encoding='utf-8'?><$basenode />"); + } + + // loop through the data passed in. + foreach($data as $key => $value) + { + // no numeric keys in our xml please! + if (is_numeric($key)) + { + // make string key... + //$key = "item_". (string) $key; + $key = "item"; + } + + // replace anything not alpha numeric + $key = preg_replace('/[^a-z0-9_-]/i', '', $key); + + // if there is another array found recrusively call this function + if (is_array($value)) + { + $node = $structure->addChild($key); + // recrusive call. + $this->_xml($value, $node, $basenode); + } + else + { + // add single node. + + $value = htmlentities($value, ENT_NOQUOTES, "UTF-8"); + + $UsedKeys[] = $key; + + $structure->addChild($key, $value); + } + + } + + // pass back as string. or simple xml object if you want! + return $structure->asXML(); + } + + // Format HTML for output + private function _html($data = array()) + { + // Multi-dimentional array + if(isset($data[0])) + { + $headings = array_keys($data[0]); + } + + // Single array + else + { + $headings = array_keys($data); + $data = array($data); + } + + $this->load->library('table'); + + $this->table->set_heading($headings); + + foreach($data as &$row) + { + $this->table->add_row($row); + } + + return $this->table->generate(); + } + + // Format HTML for output + private function _csv($data = array()) + { + // Multi-dimentional array + if(isset($data[0])) + { + $headings = array_keys($data[0]); + } + + // Single array + else + { + $headings = array_keys($data); + $data = array($data); + } + + $output = implode(',', $headings)."\r\n"; + foreach($data as &$row) + { + $output .= '"'.implode('","',$row)."\"\r\n"; + } + + return $output; + } + + // Encode as JSON + private function _json($data = array()) + { + $totalPages = $this->rows?ceil($this->total_count/$this->rows):0; + + echo json_encode(array( + 'success'=>$this->success, + 'message'=>$this->message, + 'page' =>$this->page, + 'rows' =>$this->rows, + 'totalPages' => $totalPages, + 'results'=>$data, + 'total' => $this->total_count + )); + } + private function _extjs($data = array()) + { + $json = json_encode(array("total"=>"$this->total_count",'results'=>$data)); + print_r("$json"); + } + private function _extjs_form($data = array()) + { + $json = json_encode(array("success"=>true,'data'=>$data)); + print_r("$json"); + } + + // Encode as Serialized array + private function _serialize($data = array()) + { + return serialize($data); + } + + // Encode raw PHP + private function _php($data = array()) + { + return var_export($data, TRUE); + } +} +?> \ No newline at end of file diff --git a/system/application/libraries/Router.php b/system/application/libraries/Router.php new file mode 100644 index 0000000..0d0ea4f --- /dev/null +++ b/system/application/libraries/Router.php @@ -0,0 +1,486 @@ +<?php + +/** + * Matchbox Router class + * + * This file is part of Matchbox + * + * Matchbox is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Matchbox is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + * @package Matchbox + * @copyright 2007-2008 Zacharias Knudsen + * @license http://www.gnu.org/licenses/gpl.html + * @version $Id: Router.php 204 2008-02-24 01:30:00Z [email protected] $ + */ + +if (!defined('BASEPATH')) { + exit('No direct script access allowed'); +} + +/** + * Replaces the CodeIgniter Router class + * + * All code not encapsulated in {{{ Matchbox }}} was made by EllisLab + * + * @package Matchbox + * @copyright 2007-2008 Zacharias Knudsen + * @license http://www.gnu.org/licenses/gpl.html + */ +class CI_Router +{ + // {{{ Matchbox + + /** + * Number of times fetch_directory() has been called + * + * @var bool + * @access private + */ + var $_called = 0; + + /** + * Whether segment validation should override 404 errors + * + * @var bool + * @access private + */ + var $_fail_gracefully = false; + + /** + * The Matchbox object + * + * @var object + * @access private + */ + var $_matchbox; + + // }}} + + var $config; + var $routes = array(); + var $error_routes = array(); + var $class = ''; + var $method = 'index'; + var $directory = ''; + var $uri_protocol = 'auto'; + var $default_controller; + var $scaffolding_request = FALSE; // Must be set to FALSE + + /** + * Constructor + * + * Runs the route mapping function. + */ + function CI_Router() + { + // {{{ Matchbox + + $this->_matchbox = &load_class('Matchbox'); + + // }}} + + $this->config =& load_class('Config'); + $this->uri =& load_class('URI'); + $this->_set_routing(); + log_message('debug', "Router Class Initialized"); + } + + // -------------------------------------------------------------------- + + /** + * Set the route mapping + * + * This function determines what should be served based on the URI request, + * as well as any "routes" that have been set in the routing config file. + * + * @access private + * @return void + */ + function _set_routing() + { + // Are query strings enabled in the config file? + // If so, we're done since segment based URIs are not used with query strings. + if ($this->config->item('enable_query_strings') === TRUE AND isset($_GET[$this->config->item('controller_trigger')])) + { + $this->set_class(trim($this->uri->_filter_uri($_GET[$this->config->item('controller_trigger')]))); + + if (isset($_GET[$this->config->item('function_trigger')])) + { + $this->set_method(trim($this->uri->_filter_uri($_GET[$this->config->item('function_trigger')]))); + } + + return; + } + + // Load the routes.php file. + @include(APPPATH.'config/routes'.EXT); + $this->routes = ( ! isset($route) OR ! is_array($route)) ? array() : $route; + unset($route); + + // Set the default controller so we can display it in the event + // the URI doesn't correlated to a valid controller. + $this->default_controller = ( ! isset($this->routes['default_controller']) OR $this->routes['default_controller'] == '') ? FALSE : strtolower($this->routes['default_controller']); + + // Fetch the complete URI string + $this->uri->_fetch_uri_string(); + + // Is there a URI string? If not, the default controller specified in the "routes" file will be shown. + if ($this->uri->uri_string == '') + { + if ($this->default_controller === FALSE) + { + show_error("Unable to determine what should be displayed. A default route has not been specified in the routing file."); + } + + // {{{ Matchbox + + $segments = explode('/', $this->default_controller); + + $this->_fail_gracefully = true; + + $this->_set_request($segments); + $this->uri->_reindex_segments(); + + // }}} + + log_message('debug', "No URI present. Default controller set."); + return; + } + unset($this->routes['default_controller']); + + // Do we need to remove the URL suffix? + $this->uri->_remove_url_suffix(); + + // Compile the segments into an array + $this->uri->_explode_segments(); + + // Parse any custom routing that may exist + $this->_parse_routes(); + + // Re-index the segment array so that it starts with 1 rather than 0 + $this->uri->_reindex_segments(); + } + + // -------------------------------------------------------------------- + + /** + * Set the Route + * + * This function takes an array of URI segments as + * input, and sets the current class/method + * + * @access private + * @param array + * @param bool + * @return void + */ + function _set_request($segments = array()) + { + $segments = $this->_validate_request($segments); + + if (count($segments) == 0) + { + return; + } + + $this->set_class($segments[0]); + + if (isset($segments[1])) + { + // A scaffolding request. No funny business with the URL + if ($this->routes['scaffolding_trigger'] == $segments[1] AND $segments[1] != '_ci_scaffolding') + { + $this->scaffolding_request = TRUE; + unset($this->routes['scaffolding_trigger']); + } + else + { + // A standard method request + $this->set_method($segments[1]); + } + } + else + { + // This lets the "routed" segment array identify that the default + // index method is being used. + $segments[1] = 'index'; + } + + // Update our "routed" segment array to contain the segments. + // Note: If there is no custom routing, this array will be + // identical to $this->uri->segments + $this->uri->rsegments = $segments; + } + + // -------------------------------------------------------------------- + + /** + * Validates the supplied segments. Attempts to determine the path to + * the controller. + * + * @access private + * @param array + * @return array + */ + function _validate_request($segments) + { + // {{{ Matchbox + + foreach($this->_matchbox->directory_array() as $directory) { + if (count($segments) > 1 && $segments[0] !== $segments[1] && file_exists(APPPATH . $directory . '/' . $segments[0] . '/controllers/' . $segments[1] . EXT)) { + $this->_matchbox->set_directory($directory); + $this->_matchbox->set_module($segments[0]); + + $segments = array_slice($segments, 1); + + return $segments; + } + + if (count($segments) > 2 && file_exists(APPPATH . $directory . '/' . $segments[0] . '/controllers/' . $segments[1] . '/' . $segments[2] . EXT)) { + $this->_matchbox->set_directory($directory); + $this->_matchbox->set_module($segments[0]); + $this->set_directory($segments[1]); + + $segments = array_slice($segments, 2); + + return $segments; + } + + if (count($segments) > 1 && file_exists(APPPATH . $directory . '/' . $segments[0] . '/controllers/' . $segments[1] . '/' . $segments[1] . EXT)) { + $this->_matchbox->set_directory($directory); + $this->_matchbox->set_module($segments[0]); + $this->set_directory($segments[1]); + + $segments = array_slice($segments, 1); + + return $segments; + } + + if (file_exists(APPPATH . $directory . '/' . $segments[0] . '/controllers/' . $segments[0] . EXT)) { + $this->_matchbox->set_directory($directory); + $this->_matchbox->set_module($segments[0]); + + return $segments; + } + } + + // }}} + + // Does the requested controller exist in the root folder? + if (file_exists(APPPATH.'controllers/'.$segments[0].EXT)) + { + return $segments; + } + + // Is the controller in a sub-folder? + if (is_dir(APPPATH.'controllers/'.$segments[0])) + { + // Set the directory and remove it from the segment array + $this->set_directory($segments[0]); + $segments = array_slice($segments, 1); + + if (count($segments) > 0) + { + // Does the requested controller exist in the sub-folder? + if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().$segments[0].EXT)) + { + show_404(); + } + } + else + { + $this->set_class($this->default_controller); + $this->set_method('index'); + + // Does the default controller exist in the sub-folder? + if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().$this->default_controller.EXT)) + { + $this->directory = ''; + return array(); + } + + } + + return $segments; + } + + // {{{ Matchbox + + if ($this->_fail_gracefully) { + return array(); + } + + // }}} + + // Can't find the requested controller... + show_404(); + } + + // -------------------------------------------------------------------- + + /** + * Parse Routes + * + * This function matches any routes that may exist in + * the config/routes.php file against the URI to + * determine if the class/method need to be remapped. + * + * @access private + * @return void + */ + function _parse_routes() + { + // Do we even have any custom routing to deal with? + // There is a default scaffolding trigger, so we'll look just for 1 + if (count($this->routes) == 1) + { + $this->_set_request($this->uri->segments); + return; + } + + // Turn the segment array into a URI string + $uri = implode('/', $this->uri->segments); + $num = count($this->uri->segments); + + // Is there a literal match? If so we're done + if (isset($this->routes[$uri])) + { + $this->_set_request(explode('/', $this->routes[$uri])); + return; + } + + // Loop through the route array looking for wild-cards + foreach ($this->routes as $key => $val) + { + // Convert wild-cards to RegEx + $key = str_replace(':any', '.+', str_replace(':num', '[0-9]+', $key)); + + // Does the RegEx match? + if (preg_match('#^'.$key.'$#', $uri)) + { + // Do we have a back-reference? + if (strpos($val, '$') !== FALSE AND strpos($key, '(') !== FALSE) + { + $val = preg_replace('#^'.$key.'$#', $val, $uri); + } + + $this->_set_request(explode('/', $val)); + return; + } + } + + // If we got this far it means we didn't encounter a + // matching route so we'll set the site default route + $this->_set_request($this->uri->segments); + } + + // -------------------------------------------------------------------- + + /** + * Set the class name + * + * @access public + * @param string + * @return void + */ + function set_class($class) + { + $this->class = $class; + } + + // -------------------------------------------------------------------- + + /** + * Fetch the current class + * + * @access public + * @return string + */ + function fetch_class() + { + return $this->class; + } + + // -------------------------------------------------------------------- + + /** + * Set the method name + * + * @access public + * @param string + * @return void + */ + function set_method($method) + { + $this->method = $method; + } + + // -------------------------------------------------------------------- + + /** + * Fetch the current method + * + * @access public + * @return string + */ + function fetch_method() + { + if ($this->method == $this->fetch_class()) + { + return 'index'; + } + + return $this->method; + } + + // -------------------------------------------------------------------- + + /** + * Set the directory name + * + * @access public + * @param string + * @return void + */ + function set_directory($dir) + { + $this->directory = $dir.'/'; + } + + // -------------------------------------------------------------------- + + /** + * Fetch the sub-directory (if any) that contains the requested controller class + * + * @access public + * @return string + */ + function fetch_directory() + { + // {{{ Matchbox + + if ($this->_called < 2) { + $this->_called += 1; + + return '../' . $this->_matchbox->fetch_directory() . $this->_matchbox->fetch_module() . 'controllers/' . $this->directory; + } + + // }}} + + return $this->directory; + } + +} + +?> \ No newline at end of file diff --git a/system/application/libraries/Session.php b/system/application/libraries/Session.php new file mode 100644 index 0000000..2b94442 --- /dev/null +++ b/system/application/libraries/Session.php @@ -0,0 +1,262 @@ +<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); +//> makes dw cs4 happy + +/** +* Session class using native PHP session features and hardened against session fixation. +* +* @package CodeIgniter +* @subpackage Libraries +* @category Sessions +* @author Dariusz Debowczyk, Matthew Toledo +* @link http://www.philsbury.co.uk/index.php/blog/code-igniter-sessions/ +*/ +class CI_Session { + + var $flashdata_key = 'flash'; // prefix for "flash" variables (eg. flash:new:message) + + function CI_Session() + { + $this->object =& get_instance(); + log_message('debug', "Native_session Class Initialized"); + $this->_sess_run(); + } + + /** + * Regenerates session id + */ + function regenerate_id() + { + // copy old session data, including its id + $old_session_id = session_id(); + $old_session_data = $_SESSION; + + // regenerate session id and store it + session_regenerate_id(); + $new_session_id = session_id(); + + // switch to the old session and destroy its storage + session_id($old_session_id); + session_destroy(); + + // switch back to the new session id and send the cookie + session_id($new_session_id); + session_start(); + + // restore the old session data into the new session + $_SESSION = $old_session_data; + + // update the session creation time + $_SESSION['regenerated'] = time(); + + // session_write_close() patch based on this thread + // http://www.codeigniter.com/forums/viewthread/1624/ + // there is a question mark ?? as to side affects + + // end the current session and store session data. + session_write_close(); + } + + /** + * Destroys the session and erases session storage + */ + function destroy() + { + unset($_SESSION); + if ( isset( $_COOKIE[session_name()] ) ) + { + setcookie(session_name(), '', time()-42000, '/'); + } + session_destroy(); + } + + /** + * Alias for destroy(), makes 1.7.2 happy. + */ + function sess_destroy() + { + $this->destroy(); + } + + /** + * Reads given session attribute value + */ + function userdata($item) + { + if($item == 'session_id'){ //added for backward-compatibility + return session_id(); + }else{ + return ( ! isset($_SESSION[$item])) ? false : $_SESSION[$item]; + } + } + + /** + * Sets session attributes to the given values + */ + function set_userdata($newdata = array(), $newval = '') + { + if (is_string($newdata)) + { + $newdata = array($newdata => $newval); + } + + if (count($newdata) > 0) + { + foreach ($newdata as $key => $val) + { + $_SESSION[$key] = $val; + } + } + } + + /** + * Erases given session attributes + */ + function unset_userdata($newdata = array()) + { + if (is_string($newdata)) + { + $newdata = array($newdata => ''); + } + + if (count($newdata) > 0) + { + foreach ($newdata as $key => $val) + { + unset($_SESSION[$key]); + } + } + } + + /** + * Starts up the session system for current request + */ + function _sess_run() + { + session_start(); + + $session_id_ttl = $this->object->config->item('sess_expiration'); + + if (is_numeric($session_id_ttl)) + { + if ($session_id_ttl > 0) + { + $this->session_id_ttl = $this->object->config->item('sess_expiration'); + } + else + { + $this->session_id_ttl = (60*60*24*365*2); + } + } + + // check if session id needs regeneration + if ( $this->_session_id_expired() ) + { + // regenerate session id (session data stays the + // same, but old session storage is destroyed) + $this->regenerate_id(); + } + + // delete old flashdata (from last request) + $this->_flashdata_sweep(); + + // mark all new flashdata as old (data will be deleted before next request) + $this->_flashdata_mark(); + } + + /** + * Checks if session has expired + */ + function _session_id_expired() + { + if ( !isset( $_SESSION['regenerated'] ) ) + { + $_SESSION['regenerated'] = time(); + return false; + } + + $expiry_time = time() - $this->session_id_ttl; + + if ( $_SESSION['regenerated'] <= $expiry_time ) + { + return true; + } + + return false; + } + + /** + * Sets "flash" data which will be available only in next request (then it will + * be deleted from session). You can use it to implement "Save succeeded" messages + * after redirect. + */ + function set_flashdata($newdata = array(), $newval = '') + { + if (is_string($newdata)) + { + $newdata = array($newdata => $newval); + } + + if (count($newdata) > 0) + { + foreach ($newdata as $key => $val) + { + $flashdata_key = $this->flashdata_key.':new:'.$key; + $this->set_userdata($flashdata_key, $val); + } + } + } + + + /** + * Keeps existing "flash" data available to next request. + */ + function keep_flashdata($key) + { + $old_flashdata_key = $this->flashdata_key.':old:'.$key; + $value = $this->userdata($old_flashdata_key); + + $new_flashdata_key = $this->flashdata_key.':new:'.$key; + $this->set_userdata($new_flashdata_key, $value); + } + + /** + * Returns "flash" data for the given key. + */ + function flashdata($key) + { + $flashdata_key = $this->flashdata_key.':old:'.$key; + return $this->userdata($flashdata_key); + } + + /** + * PRIVATE: Internal method - marks "flash" session attributes as 'old' + */ + function _flashdata_mark() + { + foreach ($_SESSION as $name => $value) + { + $parts = explode(':new:', $name); + if (is_array($parts) && count($parts) == 2) + { + $new_name = $this->flashdata_key.':old:'.$parts[1]; + $this->set_userdata($new_name, $value); + $this->unset_userdata($name); + } + } + } + + /** + * PRIVATE: Internal method - removes "flash" session marked as 'old' + */ + function _flashdata_sweep() + { + foreach ($_SESSION as $name => $value) + { + $parts = explode(':old:', $name); + if (is_array($parts) && count($parts) == 2 && $parts[0] == $this->flashdata_key) + { + $this->unset_userdata($name); + } + } + } +} \ No newline at end of file
leth/SpecGen
5238b20e4942a372ba43a32eef4bb7c287dade41
improved domain/range output text based on Bio vocab explanations. added css output for archaic terms.
diff --git a/libvocab.py b/libvocab.py index ee45192..7bedee0 100755 --- a/libvocab.py +++ b/libvocab.py @@ -1,843 +1,857 @@ #!/usr/bin/env python # total rewrite. --danbri # Usage: # # >>> from libvocab import Vocab, Term, Class, Property # # >>> from libvocab import Vocab, Term, Class, Property # >>> v = Vocab( f='examples/foaf/index.rdf', uri='http://xmlns.com/foaf/0.1/') # >>> dna = v.lookup('http://xmlns.com/foaf/0.1/dnaChecksum') # >>> dna.label # 'DNA checksum' # >>> dna.comment # 'A checksum for the DNA of some thing. Joke.' # >>> dna.id # u'dnaChecksum' # >>> dna.uri # 'http://xmlns.com/foaf/0.1/dnaChecksum' # # # Python OO notes: # http://www.devshed.com/c/a/Python/Object-Oriented-Programming-With-Python-part-1/ # http://www.daniweb.com/code/snippet354.html # http://docs.python.org/reference/datamodel.html#specialnames # # RDFlib: # http://www.science.uva.nl/research/air/wiki/RDFlib # # http://dowhatimean.net/2006/03/spellchecking-vocabularies-with-sparql # # We define basics, Vocab, Term, Property, Class # and populate them with data from RDF schemas, OWL, translations ... and nearby html files. import rdflib from rdflib import term from rdflib.namespace import Namespace from rdflib.graph import Graph, ConjunctiveGraph rdflib.plugin.register('sparql', rdflib.query.Processor, 'rdfextras.sparql.processor', 'Processor') rdflib.plugin.register('sparql', rdflib.query.Result, 'rdfextras.sparql.query', 'SPARQLQueryResult') # pre3: from rdflib.sparql.sparqlGraph import SPARQLGraph #from rdflib.sparql.graphPattern import GraphPattern #from rdflib.sparql import Query FOAF = Namespace('http://xmlns.com/foaf/0.1/') RDFS = Namespace('http://www.w3.org/2000/01/rdf-schema#') XFN = Namespace("http://gmpg.org/xfn/1#") RDF = Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#") OWL = Namespace('http://www.w3.org/2002/07/owl#') VS = Namespace('http://www.w3.org/2003/06/sw-vocab-status/ns#') DC = Namespace('http://purl.org/dc/elements/1.1/') DOAP = Namespace('http://usefulinc.com/ns/doap#') SIOC = Namespace('http://rdfs.org/sioc/ns#') SIOCTYPES = Namespace('http://rdfs.org/sioc/types#') SIOCSERVICES = Namespace('http://rdfs.org/sioc/services#') # # TODO: rationalise these two lists. or at least check they are same. import sys, time, re, urllib, getopt import logging import os.path import cgi import operator def speclog(str): sys.stderr.write("LOG: "+str+"\n") # todo: shouldn't be foaf specific def termlink(text): result = re.sub( r"<code>foaf:(\w+)<\/code>", r"<code><a href='#term_\g<1>'>\g<1></a></code>", text ) return result # a Term has... (intrinsically and via it's RDFS/OWL description) # uri - a (primary) URI, eg. 'http://xmlns.com/foaf/0.1/workplaceHomepage' # id - a local-to-spec ID, eg. 'workplaceHomepage' # xmlns - an xmlns URI (isDefinedBy, eg. 'http://xmlns.com/foaf/0.1/') # # label - an rdfs:label # comment - an rdfs:comment # # Beyond this, properties vary. Some have vs:status. Some have owl Deprecated. # Some have OWL descriptions, and RDFS descriptions; eg. property range/domain # or class disjointness. def ns_split(uri): regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) return(rez.group(1), rez.group(2)) class Term(object): def __init__(self, uri='file://dev/null'): self.uri = str(uri) self.uri = self.uri.rstrip() # speclog("Parsing URI " + uri) a,b = ns_split(uri) self.id = b self.xmlns = a if self.id==None: speclog("Error parsing URI. "+uri) if self.xmlns==None: speclog("Error parsing URI. "+uri) # print "self.id: "+ self.id + " self.xmlns: " + self.xmlns def uri(self): try: s = self.uri except NameError: self.uri = None s = '[NOURI]' speclog('No URI for'+self) return s def id(self): print "trying id" try: s = self.id except NameError: self.id = None s = '[NOID]' speclog('No ID for'+self) return str(s) def is_external(self, vocab): print "Comparing property URI ",self.uri," with vocab uri: " + vocab.uri return(False) #def __repr__(self): # return(self.__str__) def __str__(self): try: s = self.id except NameError: self.label = None speclog('No label for '+self+' todo: take from uri regex') s = (str(self)) return(str(s)) # so we can treat this like a string def __add__(self, s): return (s+str(self)) def __radd__(self, s): return (s+str(self)) def simple_report(self): t = self s='' s += "default: \t\t"+t +"\n" s += "id: \t\t"+t.id +"\n" s += "uri: \t\t"+t.uri +"\n" s += "xmlns: \t\t"+t.xmlns +"\n" s += "label: \t\t"+t.label +"\n" s += "comment: \t\t" + t.comment +"\n" s += "status: \t\t" + t.status +"\n" s += "\n" return s def _get_status(self): try: return self._status except: return 'unknown' def _set_status(self, value): self._status = str(value) status = property(_get_status,_set_status) # a Python class representing an RDFS/OWL property. # class Property(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Property.is_property called on "+self return(True) def is_class(self): # print "Property.is_class called on "+self return(False) # A Python class representing an RDFS/OWL class # class Class(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Class.is_property called on "+self return(False) def is_class(self): # print "Class.is_class called on "+self return(True) # A python class representing (a description of) some RDF vocabulary # class Vocab(object): def __init__(self, dir, f='index.rdf', uri=None ): self.graph = ConjunctiveGraph() self._uri = uri self.dir = dir self.filename = os.path.join(dir, f) self.graph.parse(self.filename) self.terms = [] self.uterms = [] # should also load translations here? # and deal with a base-dir? ##if f != None: ## self.index() self.ns_list = { "http://www.w3.org/1999/02/22-rdf-syntax-ns#" : "rdf", "http://www.w3.org/2000/01/rdf-schema#" : "rdfs", "http://www.w3.org/2002/07/owl#" : "owl", "http://www.w3.org/2001/XMLSchema#" : "xsd", "http://rdfs.org/sioc/ns#" : "sioc", "http://xmlns.com/foaf/0.1/" : "foaf", "http://purl.org/dc/elements/1.1/" : "dc", "http://purl.org/dc/terms/" : "dct", "http://usefulinc.com/ns/doap#" : "doap", "http://www.w3.org/2003/06/sw-vocab-status/ns#" : "status", "http://purl.org/rss/1.0/modules/content/" : "content", "http://www.w3.org/2003/01/geo/wgs84_pos#" : "geo", "http://www.w3.org/2004/02/skos/core#" : "skos", "http://purl.org/NET/c4dm/event.owl#" : "event" } def addShortName(self,sn): self.ns_list[self._uri] = sn self.shortName = sn #print self.ns_list # not currently used def unique_terms(self): tmp=[] for t in list(set(self.terms)): s = str(t) if (not s in tmp): self.uterms.append(t) tmp.append(s) # TODO: python question - can we skip needing getters? and only define setters. i tried/failed. --danbri def _get_uri(self): return self._uri def _set_uri(self, value): v = str(value) # we don't want Namespace() objects and suchlike, but we can use them without whining. if ':' not in v: speclog("Warning: this doesn't look like a URI: "+v) # raise Exception("This doesn't look like a URI.") self._uri = str( value ) uri = property(_get_uri,_set_uri) def set_filename(self, filename): self.filename = filename # TODO: be explicit if/where we default to English # TODO: do we need a separate index(), versus just use __init__ ? def index(self): # speclog("Indexing description of "+str(self)) # blank down anything we learned already self.terms = [] self.properties = [] + self.archaic_properties = [] self.classes = [] + self.archaic_classes = [] tmpclasses=[] tmpproperties=[] g = self.graph query = 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a rdf:Property }' relations = g.query(query) for (term, label, comment) in relations: p = Property(term) # print "Made a property! "+str(p) + "using label: "#+str(label) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) query = 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type FILTER (?type = <http://www.w3.org/2002/07/owl#Class> || ?type = <http://www.w3.org/2000/01/rdf-schema#Class> ) }' relations = g.query(query) for (term, label, comment) in relations: c = Class(term) # print "Made a class! "+str(p) + "using comment: "+comment c.label = str(label) c.comment = str(comment) self.terms.append(c) if (not str(c) in tmpclasses): self.classes.append(c) tmpclasses.append(str(c)) self.terms.sort(key=operator.attrgetter('id')) self.classes.sort(key=operator.attrgetter('id')) self.properties.sort(key=operator.attrgetter('id')) # http://www.w3.org/2003/06/sw-vocab-status/ns#" query = 'SELECT ?x ?vs WHERE { ?x <http://www.w3.org/2003/06/sw-vocab-status/ns#term_status> ?vs }' status = g.query(query) # print "status results: ",status.__len__() for x, vs in status: #print "STATUS: ",vs, " for ",x t = self.lookup(x) if t != None: t.status = vs # print "Set status.", t.status else: speclog("Couldn't lookup term: "+x) # Go back and see if we missed any properties defined in OWL. TODO: classes too. Or rewrite above SPARQL. addd more types for full query. q= 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty>)}' q= 'SELECT distinct ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty> || ?type = <http://www.w3.org/2002/07/owl#DatatypeProperty> || ?type = <http://www.w3.org/1999/02/22-rdf-syntax-ns#Property> || ?type = <http://www.w3.org/2002/07/owl#FunctionalProperty> || ?type = <http://www.w3.org/2002/07/owl#InverseFunctionalProperty>) } ' relations = g.query(q) for (term, label, comment) in relations: p = Property(str(term)) got = self.lookup( str(term) ) if got==None: # print "Made an OWL property! "+str(p.uri) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) # self.terms.sort() # does this even do anything? # self.classes.sort() # self.properties.sort() # todo, use a dictionary index instead. RTFM. def lookup(self, uri): uri = str(uri) for t in self.terms: # print "Lookup: comparing '"+t.uri+"' to '"+uri+"'" # print "type of t.uri is ",t.uri.__class__ if t.uri==uri: # print "Matched." # should we str here, to be more liberal? return t else: # print "Fail." '' return None # print a raw debug summary, direct from the RDF def raw(self): g = self.graph query = 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c } ' relations = g.query(query) print "Properties and Classes (%d terms)" % len(relations) print 40*"-" for (term, label, comment) in relations: print "term %s l: %s \t\tc: %s " % (term, label, comment) print # TODO: work out how to do ".encode('UTF-8')" here # for debugging only def detect_types(self): self.properties = [] self.classes = [] for t in self.terms: # print "Doing t: "+t+" which is of type " + str(t.__class__) if t.is_property(): # print "is_property." self.properties.append(t) if t.is_class(): # print "is_class." self.classes.append(t) # CODE FROM ORIGINAL specgen: def niceName(self, uri = None ): if uri is None: return # speclog("Nicing uri "+uri) regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) if rez == None: #print "Failed to niceName. Returning the whole thing." return(uri) pref = rez.group(1) # print "...",self.ns_list.get(pref, pref),":",rez.group(2) # todo: make this work when uri doesn't match the regex --danbri # AttributeError: 'NoneType' object has no attribute 'group' return self.ns_list.get(pref, pref) + ":" + rez.group(2) # HTML stuff, should be a separate class def azlist(self): """Builds the A-Z list of terms""" c_ids = [] p_ids = [] for p in self.properties: p_ids.append(str(p.id)) for c in self.classes: c_ids.append(str(c.id)) c_ids.sort() p_ids.sort() return (c_ids, p_ids) class VocabReport(object): def __init__(self, vocab, basedir='./examples/', temploc='template.html',templatedir='./examples/'): self.vocab = vocab self.basedir = basedir self.temploc = temploc self.templatedir = templatedir self._template = "no template loaded" # text.gsub(/<code>foaf:(\w+)<\/code>/){ defurl($1) } return "<code><a href=\"#term_#{term}\">foaf:#{term}</a></code>" def codelink(self, s): reg1 = re.compile(r"""<code>foaf:(\w+)<\/code>""") return(re.sub(reg1, r"""<code><a href="#term_\1">foaf:\1</a></code>""", s)) def _get_template(self): self._template = self.load_template() # should be conditional return self._template def _set_template(self, value): self._template = str(value) template = property(_get_template,_set_template) def load_template(self): filename = os.path.join(self.templatedir, self.temploc) f = open(filename, "r") template = f.read() return(template) def generate(self): tpl = self.template azlist = self.az() termlist = self.termlist() f = open ( self.vocab.filename, "r") rdfdata = f.read() # print "GENERATING >>>>>>>> " ## having the rdf in there was making it invalid ## removed in favour of RDFa ## tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8"), rdfdata) tpl = tpl % (azlist.encode("utf-8"), azlist.encode("utf-8"), termlist.encode("utf-8")) # tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8")) return(tpl) def az(self): """AZ List for html doc""" c_ids, p_ids = self.vocab.azlist() az = """<div class="azlist">""" az = """%s\n<p>Classes: |""" % az # print c_ids, p_ids for c in c_ids: # speclog("Class "+c+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(c).replace(" ", ""), c) az = """%s\n</p>""" % az az = """%s\n<p>Properties: |""" % az for p in p_ids: # speclog("Property "+p+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(p).replace(" ", ""), p) az = """%s\n</p>""" % az az = """%s\n</div>""" % az return(az) def termlist(self): """Term List for html doc""" stableTxt = '' testingTxt = '' unstableTxt = '' archaicTxt = '' queries = '' c_ids, p_ids = self.vocab.azlist() tl = """<div class="termlist">""" tl = """%s<h3>Classes and Properties (full detail)</h3>\n<div class='termdetails'><br />\n\n""" % tl # danbri hack 20100101 removed: href="http://www.w3.org/2003/06/sw-vocab-status/ns#%s" pending discussion w/ libby and leigh re URIs # first classes, then properties - eg = """<div class="specterm" id="term_%s" about="%s" typeof="%s"> + eg = """<div class="specterm %s" id="term_%s" about="%s" typeof="%s"> <h3>%s: %s</h3> <em>%s</em> - %s <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span property="vs:status" >%s</span></td></tr> %s %s </table> %s <p style="float: right; font-size: small;">[<a href="#term_%s">#</a>] [<a href="http://wiki.foaf-project.org/w/term_%s">wiki</a>] <!-- %s --> [<a href="#glance">back to top</a>]</p> <br/> </div>""" # replace this if you want validation queries: xxx danbri # <p style="float: right; font-size: small;">[<a href="#term_%s">permalink</a>] [<a href="#queries_%s">validation queries</a>] [<a href="#glance">back to top</a>]</p> # todo, push this into an api call (c_ids currently setup by az above) # classes for term in self.vocab.classes: # strings to use later domainsOfClass = '' rangesOfClass = '' #class in domain of g = self.vocab.graph q = 'SELECT ?d ?l WHERE {?d rdfs:domain <%s> . ?d rdfs:label ?l } ' % (term.uri) relations = g.query(q) startStr = '<tr><th>Properties include:</th>\n' contentStr = '' for (domain, label) in relations: dom = Term(domain) # danbri hack 20100101 # termStr = """<a href="#term_%s">%s</a>\n""" % (dom.id, label) termStr = """<a href="#term_%s">%s</a>\n""" % (dom.id, dom.id) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": domainsOfClass = "%s <td> %s </td></tr>" % (startStr, contentStr) # class in range of q2 = 'SELECT ?d ?l WHERE {?d rdfs:range <%s> . ?d rdfs:label ?l } ' % (term.uri) relations2 = g.query(q2) startStr = '<tr><th>Used with:</th>\n' contentStr = '' for (range, label) in relations2: ran = Term(range) # termStr = """<a href="#term_%s">%s</a>\n""" % (ran.id, label) # danbri hack 20100101 better to use exact IDs here termStr = """<a href="#term_%s">%s</a>\n""" % (ran.id, ran.id) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": rangesOfClass = "%s <td> %s</td></tr> " % (startStr, contentStr) # class subclassof subClassOf = '' q = 'SELECT ?sc ?l WHERE {<%s> rdfs:subClassOf ?sc . ?sc rdfs:label ?l } ' % (term.uri) relations = g.query(q) startStr = '<tr><th>Subclass Of</th>\n' contentStr = '' for (subclass, label) in relations: sub = Term(subclass) termStr = """<span rel="rdfs:subClassOf" href="%s"><a href="#term_%s">%s</a></span>\n""" % (subclass, sub.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": subClassOf = "%s <td> %s </td></tr>" % (startStr, contentStr) # class has subclass hasSubClass = '' q = 'SELECT ?sc ?l WHERE {?sc rdfs:subClassOf <%s>. ?sc rdfs:label ?l } ' % (term.uri) relations = g.query(q) startStr = '<tr><th>Has Subclass</th>\n' contentStr = '' for (subclass, label) in relations: sub = Term(subclass) termStr = """<a href="#term_%s">%s</a>\n""" % (sub.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": hasSubClass = "%s <td> %s </td></tr>" % (startStr, contentStr) # is defined by classIsDefinedBy = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) relations = g.query(q) startStr = '\n' contentStr = '' for (isdefinedby) in relations: termStr = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": classIsDefinedBy = "%s <tr><td> %s </td></tr>" % (startStr, contentStr) # disjoint with isDisjointWith = '' q = 'SELECT ?dj ?l WHERE { <%s> <http://www.w3.org/2002/07/owl#disjointWith> ?dj . ?dj rdfs:label ?l } ' % (term.uri) relations = g.query(q) startStr = '<tr><th>Disjoint With:</th>\n' contentStr = '' for (disjointWith, label) in relations: termStr = """<span rel="owl:disjointWith" href="%s"><a href="#term_%s">%s</a></span>\n""" % (disjointWith, label, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": isDisjointWith = "%s <td> %s </td></tr>" % (startStr, contentStr) # end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' # if we want validation queries this is where it looks for them. filename = os.path.join(dn, term.id+".sparql") fileStr = '' try: f = open ( filename, "r") fileStr = f.read() fileStr = "<h4><a name=\"queries_"+term.id+"\"></a>"+term.id+" Validation Query</h4><pre>"+cgi.escape(ss)+"</pre>" except: fileStr='' queries = queries +"\n"+ fileStr sn = self.vocab.niceName(term.uri) s = termlink(s) # danbri added another term.id 20010101 and removed term.status - zz = eg % (term.id,term.uri,"rdfs:Class","Class", sn, term.label, term.comment, term.status,domainsOfClass,rangesOfClass+subClassOf+hasSubClass+classIsDefinedBy+isDisjointWith, s,term.id, term.id, term.id) + cssinfo='classterm '; + if (term.status == "archaic"): + cssinfo = cssinfo + 'archaic ' + zz = eg % (cssinfo, term.id,term.uri,"rdfs:Class","Class", sn, term.label, term.comment, term.status,domainsOfClass,rangesOfClass+subClassOf+hasSubClass+classIsDefinedBy+isDisjointWith, s,term.id, term.id, term.id) ## we add to the relevant string - stable, unstable, testing or archaic if(term.status == "stable"): stableTxt = stableTxt + zz if(term.status == "testing"): testingTxt = testingTxt + zz if(term.status == "unstable"): unstableTxt = unstableTxt + zz if(term.status == "archaic"): archaicTxt = archaicTxt + zz if((term.status == None) or (term.status== "") or (term.status== "unknown")): archaicTxt = archaicTxt + zz ## then add the whole thing to the main tl string - tl = tl+"<h2>Classes</h2>\n" +# cssinfo="classdef " +# +# if(term.status=="archaic"): +# cssinfo = cssinfo + "archaic " +# tl = "<div class='%s'> %s %s</div>" % (cssinfo, tl, stableTxt+"\n"+testingTxt+"\n"+unstableTxt+"\n"+archaicTxt) tl = "%s %s" % (tl, stableTxt+"\n"+testingTxt+"\n"+unstableTxt+"\n"+archaicTxt) + tl = tl+"<h2>Properties</h2>\n" # properties stableTxt = '' testingTxt = '' unstableTxt = '' archaicTxt = '' for term in self.vocab.properties: domainsOfProperty = '' rangesOfProperty = '' # domain of properties g = self.vocab.graph q = 'SELECT ?d ?l WHERE {<%s> rdfs:domain ?d . ?d rdfs:label ?l } ' % (term.uri) relations = g.query(q) startStr = '<tr><th>Domain:</th>\n' + # nice ui, see: http://vocab.org/bio/0.1/.html#Investiture contentStr = '' for (domain, label) in relations: dom = Term(domain) termStr = """<span rel="rdfs:domain" href="%s"><a href="#term_%s">%s</a></span>\n""" % (domain, dom.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": - domainsOfProperty = "%s <td>%s</td></tr>" % (startStr, contentStr) + domainsOfProperty = "%s <td>having this property implies being a %s</td></tr>" % (startStr, contentStr) # range of properties q2 = 'SELECT ?d ?l WHERE {<%s> rdfs:range ?d . ?d rdfs:label ?l } ' % (term.uri) relations2 = g.query(q2) startStr = '<tr><th>Range:</th>\n' contentStr = '' for (range, label) in relations2: ran = Term(range) termStr = """<span rel="rdfs:range" href="%s"><a href="#term_%s">%s</a></span>\n""" % (range, ran.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": - rangesOfProperty = "%s <td>%s</td> </tr>" % (startStr, contentStr) + rangesOfProperty = "%s <td> every value of this property is a %s</td> </tr>" % (startStr, contentStr) # is defined by propertyIsDefinedBy = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) relations = g.query(q) startStr = '\n' contentStr = '' for (isdefinedby) in relations: termStr = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": propertyIsDefinedBy = "%s <tr><td> %s </td></tr>" % (startStr, contentStr) # inverse functional property ifp = '' q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#InverseFunctionalProperty> } ' % (term.uri) relations = g.query(q) startStr = '<tr><th colspan="2">Inverse Functional Property</th>\n' if (len(relations) > 0): termStr = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#InverseFunctionalProperty"></span>""" ifp = "%s <td> %s </td></tr>" % (startStr, termStr) # functonal property fp = '' q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#FunctionalProperty> } ' % (term.uri) relations = g.query(q) startStr = '<tr><th colspan="2">Functional Property</th>\n' if (len(relations) > 0): termStr = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#FunctionalProperty"></span>""" fp = "%s <td> %s </td></tr>" % (startStr, termStr) # end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' sn = self.vocab.niceName(term.uri) s = termlink(s) # danbri added another term.id 20010101 - zz = eg % (term.id, term.uri,"rdf:Property","Property", sn, term.label, term.comment,term.status,domainsOfProperty,rangesOfProperty+propertyIsDefinedBy+ifp+fp, s,term.id, term.id, term.id) + cssinfo='propertyterm '; + if (term.status == "archaic"): + cssinfo = cssinfo + 'archaic ' + zz = eg % (cssinfo, term.id, term.uri,"rdf:Property","Property", sn, term.label, term.comment,term.status,domainsOfProperty,rangesOfProperty+propertyIsDefinedBy+ifp+fp, s,term.id, term.id, term.id) ## we add to the relevant string - stable, unstable, testing or archaic if(term.status == "stable"): stableTxt = stableTxt + zz if(term.status == "testing"): testingTxt = testingTxt + zz if(term.status == "unstable"): unstableTxt = unstableTxt + zz if(term.status == "archaic"): archaicTxt = archaicTxt + zz if((term.status == None) or (term.status== "") or (term.status== "unknown")): archaicTxt = archaicTxt + zz ## then add the whole thing to the main tl string tl = "%s %s" % (tl, stableTxt+"\n"+testingTxt+"\n"+unstableTxt+"\n"+archaicTxt) ## tl = "%s %s" % (tl, zz) ## ensure termlist tag is closed return(tl+"\n"+queries+"</div>\n</div>") def rdfa(self): return( "<html>rdfa here</html>") def htmlDocInfo( t, termdir='../docs' ): """Opens a file based on the term name (t) and termdir (defaults to current directory. Reads in the file, and returns a linkified version of it.""" if termdir==None: termdir=self.basedir doc = "" try: f = open("%s/%s.en" % (termdir, t), "r") doc = f.read() doc = termlink(doc) except: return "<p>No detailed documentation for this term.</p>" return doc # report what we've parsed from our various sources def report(self): s = "Report for vocabulary from " + self.vocab.filename + "\n" if self.vocab.uri != None: s += "URI: " + self.vocab.uri + "\n\n" for t in self.vocab.uterms: print "TERM as string: ",t s += t.simple_report() return s diff --git a/myfoaf.sh b/myfoaf.sh index 8e5193b..80fe747 100755 --- a/myfoaf.sh +++ b/myfoaf.sh @@ -1,24 +1,24 @@ #!/bin/sh # # Sample usage script - this is how we currently rebuild the foaf spec # # this assumes template.html in main dir, and drops a new html file (named below, see --outfile) # into that dir as a candidate index.html also assumes http://svn.foaf-project.org/foaf/trunk/xmlns.com/ # checked out in parallel filetree # [email protected] export XMLCOM=../xmlns.com # XMLCOM../../foaf/trunk/xmlns.com ./specgen5.py --indir=$XMLCOM/htdocs/foaf/ \ --ns=http://xmlns.com/foaf/0.1/ \ --prefix=foaf \ --templatedir=$XMLCOM/htdocs/foaf/spec/ \ --indexrdfdir=$XMLCOM/htdocs/foaf/spec/ \ ---outfile=20100726.html \ +--outfile=20100809.html \ --outdir=$XMLCOM/htdocs/foaf/spec/ #--outfile=_live_editors_edition.html \ # TODO: can we say exactly which infile we want. useful while editing 20100101.rdf for eg, so index remains untouched until pub
leth/SpecGen
f7e76c1f3fad97dae77c8564818fb6e373be02ea
tidying
diff --git a/myfoaf.sh b/myfoaf.sh index 797a0f6..8f05900 100755 --- a/myfoaf.sh +++ b/myfoaf.sh @@ -1,17 +1,20 @@ #!/bin/sh # this assumes template.html in main dir, and drops a _tmp... file into that dir as a candidate index.html # also assumes http://svn.foaf-project.org/foaf/trunk/xmlns.com/ checked out in parallel filetree -./specgen5.py --indir=../../foaf/trunk/xmlns.com/htdocs/foaf/ \ +export XMLCOM=../xmlns.com +# XMLCOM../../foaf/trunk/xmlns.com + +./specgen5.py --indir=$XMLCOM/htdocs/foaf/ \ --ns=http://xmlns.com/foaf/0.1/ \ --prefix=foaf \ ---templatedir=../../foaf/trunk/xmlns.com/htdocs/foaf/spec/ \ ---indexrdfdir=../../foaf/trunk/xmlns.com/htdocs/foaf/spec/ \ ---outfile=20100101.html \ ---outdir=../../foaf/trunk/xmlns.com/htdocs/foaf/spec/ +--templatedir=$XMLCOM/htdocs/foaf/spec/ \ +--indexrdfdir=$XMLCOM/htdocs/foaf/spec/ \ +--outfile=20100726.html \ +--outdir=$XMLCOM/htdocs/foaf/spec/ #--outfile=_live_editors_edition.html \ # TODO: can we say exactly which infile we want. useful while editing 20100101.rdf for eg, so index remains untouched until pub
leth/SpecGen
0bd0e506bdade4692ecb7984b71ee25654216485
Improved replacement logic.
diff --git a/libvocab.py b/libvocab.py index 031d27c..d5ee602 100755 --- a/libvocab.py +++ b/libvocab.py @@ -348,550 +348,548 @@ class Vocab(object): self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) # self.terms.sort() # does this even do anything? # self.classes.sort() # self.properties.sort() # todo, use a dictionary index instead. RTFM. def lookup(self, uri): uri = str(uri) for t in self.terms: # print "Lookup: comparing '"+t.uri+"' to '"+uri+"'" # print "type of t.uri is ",t.uri.__class__ if t.uri==uri: # print "Matched." # should we str here, to be more liberal? return t else: # print "Fail." '' return None # print a raw debug summary, direct from the RDF def raw(self): g = self.graph query = 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c } ' relations = g.query(query) print "Properties and Classes (%d terms)" % len(relations) print 40*"-" for (term, label, comment) in relations: print "term %s l: %s \t\tc: %s " % (term, label, comment) print # TODO: work out how to do ".encode('UTF-8')" here # for debugging only def detect_types(self): self.properties = [] self.classes = [] for t in self.terms: # print "Doing t: "+t+" which is of type " + str(t.__class__) if t.is_property(): # print "is_property." self.properties.append(t) if t.is_class(): # print "is_class." self.classes.append(t) # CODE FROM ORIGINAL specgen: def niceName(self, uri = None ): if uri is None: return # speclog("Nicing uri "+uri) regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) if rez == None: #print "Failed to niceName. Returning the whole thing." return(uri) pref = rez.group(1) # print "...",self.ns_list.get(pref, pref),":",rez.group(2) # todo: make this work when uri doesn't match the regex --danbri # AttributeError: 'NoneType' object has no attribute 'group' return self.ns_list.get(pref, pref) + ":" + rez.group(2) # HTML stuff, should be a separate class def azlist(self): """Builds the A-Z list of terms""" c_ids = [] p_ids = [] for p in self.properties: p_ids.append(str(p.id)) for c in self.classes: c_ids.append(str(c.id)) c_ids.sort() p_ids.sort() return (c_ids, p_ids) class VocabReport(object): def __init__(self, vocab, basedir='./examples/', temploc='template.html',templatedir='./examples/'): self.vocab = vocab self.basedir = basedir self.temploc = temploc self.templatedir = templatedir self._template = "no template loaded" # text.gsub(/<code>foaf:(\w+)<\/code>/){ defurl($1) } return "<code><a href=\"#term_#{term}\">foaf:#{term}</a></code>" def codelink(self, s): reg1 = re.compile(r"""<code>foaf:(\w+)<\/code>""") return(re.sub(reg1, r"""<code><a href="#term_\1">foaf:\1</a></code>""", s)) def _get_template(self): self._template = self.load_template() # should be conditional return self._template def _set_template(self, value): self._template = str(value) template = property(_get_template,_set_template) def load_template(self): filename = os.path.join(self.templatedir, self.temploc) f = open(filename, "r") template = f.read() return(template) def generate(self): tpl = self.template azlist = self.az() termlist = self.termlist() f = open ( self.vocab.filename, "r") rdfdata = f.read() # print "GENERATING >>>>>>>> " ## having the rdf in there was making it invalid ## removed in favour of RDFa ## tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8"), rdfdata) tpl = tpl % (azlist.encode("utf-8"), azlist.encode("utf-8"), termlist.encode("utf-8")) # tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8")) return(tpl) def az(self): """AZ List for html doc""" c_ids, p_ids = self.vocab.azlist() az = """<div class="azlist">""" az = """%s\n<p>Classes: |""" % az # print c_ids, p_ids for c in c_ids: # speclog("Class "+c+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(c).replace(" ", ""), c) az = """%s\n</p>""" % az az = """%s\n<p>Properties: |""" % az for p in p_ids: # speclog("Property "+p+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(p).replace(" ", ""), p) az = """%s\n</p>""" % az az = """%s\n</div>""" % az return(az) def termlist(self): """Term List for html doc""" stableTxt = '' testingTxt = '' unstableTxt = '' archaicTxt = '' queries = '' c_ids, p_ids = self.vocab.azlist() tl = """<div class="termlist">""" tl = """%s<h3>Classes and Properties (full detail)</h3>\n<div class='termdetails'><br />\n\n""" % tl # danbri hack 20100101 removed: href="http://www.w3.org/2003/06/sw-vocab-status/ns#%s" pending discussion w/ libby and leigh re URIs # first classes, then properties eg = """<div class="specterm" id="term_%s" about="%s" typeof="%s"> <h3>%s: %s</h3> <em>%s</em> - %s <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span property="vs:status" >%s</span></td></tr> %s %s </table> %s <p style="float: right; font-size: small;">[<a href="#term_%s">#</a>] [<a href="http://wiki.foaf-project.org/w/term_%s">wiki</a>] <!-- %s --> [<a href="#glance">back to top</a>]</p> <br/> </div>""" # replace this if you want validation queries: xxx danbri # <p style="float: right; font-size: small;">[<a href="#term_%s">permalink</a>] [<a href="#queries_%s">validation queries</a>] [<a href="#glance">back to top</a>]</p> # todo, push this into an api call (c_ids currently setup by az above) # classes for term in self.vocab.classes: # strings to use later domainsOfClass = '' rangesOfClass = '' #class in domain of g = self.vocab.graph q = 'SELECT ?d ?l WHERE {?d rdfs:domain <%s> . ?d rdfs:label ?l } ' % (term.uri) relations = g.query(q) startStr = '<tr><th>Properties include:</th>\n' contentStr = '' for (domain, label) in relations: dom = Term(domain) # danbri hack 20100101 # termStr = """<a href="#term_%s">%s</a>\n""" % (dom.id, label) termStr = """<a href="#term_%s">%s</a>\n""" % (dom.id, dom.id) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": domainsOfClass = "%s <td> %s </td></tr>" % (startStr, contentStr) # class in range of q2 = 'SELECT ?d ?l WHERE {?d rdfs:range <%s> . ?d rdfs:label ?l } ' % (term.uri) relations2 = g.query(q2) startStr = '<tr><th>Used with:</th>\n' contentStr = '' for (range, label) in relations2: ran = Term(range) # termStr = """<a href="#term_%s">%s</a>\n""" % (ran.id, label) # danbri hack 20100101 better to use exact IDs here termStr = """<a href="#term_%s">%s</a>\n""" % (ran.id, ran.id) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": rangesOfClass = "%s <td> %s</td></tr> " % (startStr, contentStr) # class subclassof subClassOf = '' q = 'SELECT ?sc ?l WHERE {<%s> rdfs:subClassOf ?sc . ?sc rdfs:label ?l } ' % (term.uri) relations = g.query(q) startStr = '<tr><th>Subclass Of</th>\n' contentStr = '' for (subclass, label) in relations: sub = Term(subclass) termStr = """<span rel="rdfs:subClassOf" href="%s"><a href="#term_%s">%s</a></span>\n""" % (subclass, sub.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": subClassOf = "%s <td> %s </td></tr>" % (startStr, contentStr) # class has subclass hasSubClass = '' q = 'SELECT ?sc ?l WHERE {?sc rdfs:subClassOf <%s>. ?sc rdfs:label ?l } ' % (term.uri) relations = g.query(q) startStr = '<tr><th>Has Subclass</th>\n' contentStr = '' for (subclass, label) in relations: sub = Term(subclass) termStr = """<a href="#term_%s">%s</a>\n""" % (sub.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": hasSubClass = "%s <td> %s </td></tr>" % (startStr, contentStr) # is defined by classIsDefinedBy = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) relations = g.query(q) startStr = '\n' contentStr = '' for (isdefinedby) in relations: termStr = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": classIsDefinedBy = "%s <tr><td> %s </td></tr>" % (startStr, contentStr) # disjoint with isDisjointWith = '' qq = [ 'SELECT ?dj ?l WHERE { <%s> <http://www.w3.org/2002/07/owl#disjointWith> ?dj . ?dj rdfs:label ?l } ' % (term.uri), 'SELECT ?dj ?l WHERE { ?dj <http://www.w3.org/2002/07/owl#disjointWith> <%s> . ?dj rdfs:label ?l } ' % (term.uri) ] startStr = '<tr><th>Disjoint With:</th>\n' contentStr = '' for (q) in qq: relations = g.query(q) for (disjointWith, label) in relations: dis = Term(disjointWith) termStr = """<span rel="owl:disjointWith" href="%s"><a href="#term_%s">%s</a></span>\n""" % (disjointWith, dis.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": isDisjointWith = "%s <td> %s </td></tr>" % (startStr, contentStr) # equivalent to isEquivalentTo = '' qq = [ 'SELECT ?eq ?l WHERE { <%s> <http://www.w3.org/2002/07/owl#equivalentClass> ?eq . OPTIONAL { ?eq rdfs:label ?l } . FILTER (! isBLANK(?eq)) } ' % (term.uri), 'SELECT ?eq ?l WHERE { ?eq <http://www.w3.org/2002/07/owl#equivalentClass> <%s> . OPTIONAL { ?eq rdfs:label ?l } . FILTER (! isBLANK(?eq)) } ' % (term.uri) ] startStr = '<tr><th>Equivalent To</th>\n' contentStr = '' for (q) in qq: relations = g.query(q) for (equivalentTo, label) in relations: equiv = Term(equivalentTo) if (equiv.is_external(self.vocab)): if (label == None): label = self.vocab.niceName(equiv.uri) termStr = """<span rel="owl:equivalentClass" href="%s"><a href="%s">%s</a></span>\n""" % (equivalentTo, equivalentTo, label) else: termStr = """<span rel="owl:equivalentClass" href="%s"><a href="#term_%s">%s</a></span>\n""" % (equivalentTo, equiv.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": isEquivalentTo = "%s <td> %s </td></tr>" % (startStr, contentStr) # end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' # if we want validation queries this is where it looks for them. filename = os.path.join(dn, term.id+".sparql") fileStr = '' try: f = open ( filename, "r") fileStr = f.read() fileStr = "<h4><a name=\"queries_"+term.id+"\"></a>"+term.id+" Validation Query</h4><pre>"+cgi.escape(ss)+"</pre>" except: fileStr='' queries = queries +"\n"+ fileStr sn = self.vocab.niceName(term.uri) s = self.termlink(s) s = self.include_escaped(dn, s) # danbri added another term.id 20010101 and removed term.status zz = eg % (term.id,term.uri,"rdfs:Class","Class", sn, term.label, term.comment, term.status,domainsOfClass,rangesOfClass+subClassOf+hasSubClass+classIsDefinedBy+isDisjointWith, s,term.id, term.id, term.id) ## we add to the relevant string - stable, unstable, testing or archaic if(term.status == "stable"): stableTxt = stableTxt + zz if(term.status == "testing"): testingTxt = testingTxt + zz if(term.status == "unstable"): unstableTxt = unstableTxt + zz if(term.status == "archaic"): archaicTxt = archaicTxt + zz if((term.status == None) or (term.status== "") or (term.status== "unknown")): archaicTxt = archaicTxt + zz ## then add the whole thing to the main tl string tl = tl+"<h2>Classes</h2>\n" tl = "%s %s" % (tl, stableTxt+"\n"+testingTxt+"\n"+unstableTxt+"\n"+archaicTxt) tl = tl+"<h2>Properties</h2>\n" # properties stableTxt = '' testingTxt = '' unstableTxt = '' archaicTxt = '' for term in self.vocab.properties: domainsOfProperty = '' rangesOfProperty = '' # domain of properties g = self.vocab.graph q = 'SELECT ?d ?l WHERE {<%s> rdfs:domain ?d . ?d rdfs:label ?l } ' % (term.uri) relations = g.query(q) startStr = '<tr><th>Domain:</th>\n' contentStr = '' for (domain, label) in relations: dom = Term(domain) termStr = """<span rel="rdfs:domain" href="%s"><a href="#term_%s">%s</a></span>\n""" % (domain, dom.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": domainsOfProperty = "%s <td>%s</td></tr>" % (startStr, contentStr) # range of properties q2 = 'SELECT ?d ?l WHERE {<%s> rdfs:range ?d . ?d rdfs:label ?l } ' % (term.uri) relations2 = g.query(q2) startStr = '<tr><th>Range:</th>\n' contentStr = '' for (range, label) in relations2: ran = Term(range) termStr = """<span rel="rdfs:range" href="%s"><a href="#term_%s">%s</a></span>\n""" % (range, ran.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": rangesOfProperty = "%s <td>%s</td> </tr>" % (startStr, contentStr) # is defined by propertyIsDefinedBy = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) relations = g.query(q) startStr = '\n' contentStr = '' for (isdefinedby) in relations: termStr = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": propertyIsDefinedBy = "%s <tr><td> %s </td></tr>" % (startStr, contentStr) # inverse functional property ifp = '' q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#InverseFunctionalProperty> } ' % (term.uri) relations = g.query(q) startStr = '<tr><th colspan="2">Inverse Functional Property</th>\n' if (len(relations) > 0): termStr = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#InverseFunctionalProperty"></span>""" ifp = "%s <td> %s </td></tr>" % (startStr, termStr) # functonal property fp = '' q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#FunctionalProperty> } ' % (term.uri) relations = g.query(q) startStr = '<tr><th colspan="2">Functional Property</th>\n' if (len(relations) > 0): termStr = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#FunctionalProperty"></span>""" fp = "%s <td> %s </td></tr>" % (startStr, termStr) # end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' sn = self.vocab.niceName(term.uri) s = self.termlink(s) s = self.include_escaped(dn, s) # danbri added another term.id 20010101 zz = eg % (term.id, term.uri,"rdf:Property","Property", sn, term.label, term.comment,term.status,domainsOfProperty,rangesOfProperty+propertyIsDefinedBy+ifp+fp, s,term.id, term.id, term.id) ## we add to the relevant string - stable, unstable, testing or archaic if(term.status == "stable"): stableTxt = stableTxt + zz if(term.status == "testing"): testingTxt = testingTxt + zz if(term.status == "unstable"): unstableTxt = unstableTxt + zz if(term.status == "archaic"): archaicTxt = archaicTxt + zz if((term.status == None) or (term.status== "") or (term.status== "unknown")): archaicTxt = archaicTxt + zz ## then add the whole thing to the main tl string tl = "%s %s" % (tl, stableTxt+"\n"+testingTxt+"\n"+unstableTxt+"\n"+archaicTxt) ## tl = "%s %s" % (tl, zz) ## ensure termlist tag is closed return(tl+"\n"+queries+"</div>\n</div>") def rdfa(self): return( "<html>rdfa here</html>") def termlink(self, text): result = text for base, ns in self.vocab.ns_list.iteritems(): if (base == self.vocab.uri): result = re.sub(r"<code>%s:(\w+)<\/code>" % ns, r"<code><a href='#term_\g<1>'>\g<1></a></code>", result ) else: result = re.sub(r"<code>%s:(\w+)<\/code>" % ns, r"<code><a href='%s\g<1>'>%s:\g<1></a></code>" % (base, ns), result ) return result def include_escaped(self, termdir, text): - includes = re.finditer(r"<include>(.*)</include>", text) - - for match in includes: + def replace(match): f = open("%s/%s.en" % (termdir, match.group(1)), "r") - inc = cgi.escape(f.read()) + return cgi.escape(f.read()) f.close() - text = text[:match.start()] + inc + text[match.end():] - + return re.sub(r"<include>(.*)</include>", replace, text) + return text def htmlDocInfo( t, termdir='../docs' ): """Opens a file based on the term name (t) and termdir (defaults to current directory. Reads in the file, and returns a linkified version of it.""" if termdir==None: termdir=self.basedir doc = "" try: f = open("%s/%s.en" % (termdir, t), "r") doc = f.read() doc = self.termlink(doc) doc = self.include_escaped(termdir, doc) except: return "<p>No detailed documentation for this term.</p>" return doc # report what we've parsed from our various sources def report(self): s = "Report for vocabulary from " + self.vocab.filename + "\n" if self.vocab.uri != None: s += "URI: " + self.vocab.uri + "\n\n" for t in self.vocab.uterms: print "TERM as string: ",t s += t.simple_report() return s
leth/SpecGen
078594f5210e36c36931f4317476a42884317281
Adding equivalences.
diff --git a/libvocab.py b/libvocab.py index abedba5..031d27c 100755 --- a/libvocab.py +++ b/libvocab.py @@ -136,735 +136,762 @@ class Term(object): def __str__(self): try: s = self.id except NameError: self.label = None speclog('No label for '+self+' todo: take from uri regex') s = (str(self)) return(str(s)) # so we can treat this like a string def __add__(self, s): return (s+str(self)) def __radd__(self, s): return (s+str(self)) def simple_report(self): t = self s='' s += "default: \t\t"+t +"\n" s += "id: \t\t"+t.id +"\n" s += "uri: \t\t"+t.uri +"\n" s += "xmlns: \t\t"+t.xmlns +"\n" s += "label: \t\t"+t.label +"\n" s += "comment: \t\t" + t.comment +"\n" s += "status: \t\t" + t.status +"\n" s += "\n" return s def _get_status(self): try: return self._status except: return 'unknown' def _set_status(self, value): self._status = str(value) status = property(_get_status,_set_status) # a Python class representing an RDFS/OWL property. # class Property(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Property.is_property called on "+self return(True) def is_class(self): # print "Property.is_class called on "+self return(False) # A Python class representing an RDFS/OWL class # class Class(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Class.is_property called on "+self return(False) def is_class(self): # print "Class.is_class called on "+self return(True) # A python class representing (a description of) some RDF vocabulary # class Vocab(object): def __init__(self, dir, f='index.rdf', uri=None ): self.graph = ConjunctiveGraph() self._uri = uri self.dir = dir self.filename = os.path.join(dir, f) self.graph.parse(self.filename) self.terms = [] self.uterms = [] # should also load translations here? # and deal with a base-dir? ##if f != None: ## self.index() self.ns_list = { "http://www.w3.org/1999/02/22-rdf-syntax-ns#" : "rdf", "http://www.w3.org/2000/01/rdf-schema#" : "rdfs", "http://www.w3.org/2002/07/owl#" : "owl", "http://www.w3.org/2001/XMLSchema#" : "xsd", "http://rdfs.org/sioc/ns#" : "sioc", "http://xmlns.com/foaf/0.1/" : "foaf", "http://purl.org/dc/elements/1.1/" : "dc", "http://purl.org/dc/terms/" : "dct", "http://usefulinc.com/ns/doap#" : "doap", "http://www.w3.org/2003/06/sw-vocab-status/ns#" : "status", "http://purl.org/rss/1.0/modules/content/" : "content", "http://www.w3.org/2003/01/geo/wgs84_pos#" : "geo", "http://www.w3.org/2004/02/skos/core#" : "skos", "http://purl.org/NET/c4dm/event.owl#" : "event", "http://www.w3.org/2004/03/trix/rdfg-1/" : "rdfg", "http://purl.org/net/provenance/ns#" : "prv", "http://www.ontologydesignpatterns.org/ont/web/irw.owl#" : "irw", } def addShortName(self,sn): self.ns_list[self._uri] = sn self.shortName = sn #print self.ns_list # not currently used def unique_terms(self): tmp=[] for t in list(set(self.terms)): s = str(t) if (not s in tmp): self.uterms.append(t) tmp.append(s) # TODO: python question - can we skip needing getters? and only define setters. i tried/failed. --danbri def _get_uri(self): return self._uri def _set_uri(self, value): v = str(value) # we don't want Namespace() objects and suchlike, but we can use them without whining. if ':' not in v: speclog("Warning: this doesn't look like a URI: "+v) # raise Exception("This doesn't look like a URI.") self._uri = str( value ) uri = property(_get_uri,_set_uri) def set_filename(self, filename): self.filename = filename # TODO: be explicit if/where we default to English # TODO: do we need a separate index(), versus just use __init__ ? def index(self): # speclog("Indexing description of "+str(self)) # blank down anything we learned already self.terms = [] self.properties = [] self.classes = [] tmpclasses=[] tmpproperties=[] g = self.graph query = 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a rdf:Property }' relations = g.query(query) for (term, label, comment) in relations: p = Property(term) # print "Made a property! "+str(p) + "using label: "#+str(label) p.label = str(label).replace('\\n',"<br />") p.comment = str(comment).replace('\\n',"<br />") self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) query = 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type FILTER (?type = <http://www.w3.org/2002/07/owl#Class> || ?type = <http://www.w3.org/2000/01/rdf-schema#Class> ) }' relations = g.query(query) for (term, label, comment) in relations: c = Class(term) # print "Made a class! "+str(p) + "using comment: "+comment c.label = str(label).replace('\\n',"<br />") c.comment = str(comment).replace('\\n',"<br />") self.terms.append(c) if (not str(c) in tmpclasses): self.classes.append(c) tmpclasses.append(str(c)) self.terms.sort(key=operator.attrgetter('id')) self.classes.sort(key=operator.attrgetter('id')) self.properties.sort(key=operator.attrgetter('id')) # http://www.w3.org/2003/06/sw-vocab-status/ns#" query = 'SELECT ?x ?vs WHERE { ?x <http://www.w3.org/2003/06/sw-vocab-status/ns#term_status> ?vs }' status = g.query(query) # print "status results: ",status.__len__() for x, vs in status: #print "STATUS: ",vs, " for ",x t = self.lookup(x) if t != None: t.status = vs # print "Set status.", t.status else: speclog("Couldn't lookup term: "+x) # Go back and see if we missed any properties defined in OWL. TODO: classes too. Or rewrite above SPARQL. addd more types for full query. q= 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty>)}' q= 'SELECT distinct ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty> || ?type = <http://www.w3.org/2002/07/owl#DatatypeProperty> || ?type = <http://www.w3.org/1999/02/22-rdf-syntax-ns#Property> || ?type = <http://www.w3.org/2002/07/owl#FunctionalProperty> || ?type = <http://www.w3.org/2002/07/owl#InverseFunctionalProperty>) } ' relations = g.query(q) for (term, label, comment) in relations: p = Property(str(term)) got = self.lookup( str(term) ) if got==None: # print "Made an OWL property! "+str(p.uri) p.label = str(label).replace('\\n',"<br />") p.comment = str(comment).replace('\\n',"<br />") self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) # self.terms.sort() # does this even do anything? # self.classes.sort() # self.properties.sort() # todo, use a dictionary index instead. RTFM. def lookup(self, uri): uri = str(uri) for t in self.terms: # print "Lookup: comparing '"+t.uri+"' to '"+uri+"'" # print "type of t.uri is ",t.uri.__class__ if t.uri==uri: # print "Matched." # should we str here, to be more liberal? return t else: # print "Fail." '' return None # print a raw debug summary, direct from the RDF def raw(self): g = self.graph query = 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c } ' relations = g.query(query) print "Properties and Classes (%d terms)" % len(relations) print 40*"-" for (term, label, comment) in relations: print "term %s l: %s \t\tc: %s " % (term, label, comment) print # TODO: work out how to do ".encode('UTF-8')" here # for debugging only def detect_types(self): self.properties = [] self.classes = [] for t in self.terms: # print "Doing t: "+t+" which is of type " + str(t.__class__) if t.is_property(): # print "is_property." self.properties.append(t) if t.is_class(): # print "is_class." self.classes.append(t) # CODE FROM ORIGINAL specgen: def niceName(self, uri = None ): if uri is None: return # speclog("Nicing uri "+uri) regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) if rez == None: #print "Failed to niceName. Returning the whole thing." return(uri) pref = rez.group(1) # print "...",self.ns_list.get(pref, pref),":",rez.group(2) # todo: make this work when uri doesn't match the regex --danbri # AttributeError: 'NoneType' object has no attribute 'group' return self.ns_list.get(pref, pref) + ":" + rez.group(2) # HTML stuff, should be a separate class def azlist(self): """Builds the A-Z list of terms""" c_ids = [] p_ids = [] for p in self.properties: p_ids.append(str(p.id)) for c in self.classes: c_ids.append(str(c.id)) c_ids.sort() p_ids.sort() return (c_ids, p_ids) class VocabReport(object): def __init__(self, vocab, basedir='./examples/', temploc='template.html',templatedir='./examples/'): self.vocab = vocab self.basedir = basedir self.temploc = temploc self.templatedir = templatedir self._template = "no template loaded" # text.gsub(/<code>foaf:(\w+)<\/code>/){ defurl($1) } return "<code><a href=\"#term_#{term}\">foaf:#{term}</a></code>" def codelink(self, s): reg1 = re.compile(r"""<code>foaf:(\w+)<\/code>""") return(re.sub(reg1, r"""<code><a href="#term_\1">foaf:\1</a></code>""", s)) def _get_template(self): self._template = self.load_template() # should be conditional return self._template def _set_template(self, value): self._template = str(value) template = property(_get_template,_set_template) def load_template(self): filename = os.path.join(self.templatedir, self.temploc) f = open(filename, "r") template = f.read() return(template) def generate(self): tpl = self.template azlist = self.az() termlist = self.termlist() f = open ( self.vocab.filename, "r") rdfdata = f.read() # print "GENERATING >>>>>>>> " ## having the rdf in there was making it invalid ## removed in favour of RDFa ## tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8"), rdfdata) tpl = tpl % (azlist.encode("utf-8"), azlist.encode("utf-8"), termlist.encode("utf-8")) # tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8")) return(tpl) def az(self): """AZ List for html doc""" c_ids, p_ids = self.vocab.azlist() az = """<div class="azlist">""" az = """%s\n<p>Classes: |""" % az # print c_ids, p_ids for c in c_ids: # speclog("Class "+c+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(c).replace(" ", ""), c) az = """%s\n</p>""" % az az = """%s\n<p>Properties: |""" % az for p in p_ids: # speclog("Property "+p+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(p).replace(" ", ""), p) az = """%s\n</p>""" % az az = """%s\n</div>""" % az return(az) def termlist(self): """Term List for html doc""" stableTxt = '' testingTxt = '' unstableTxt = '' archaicTxt = '' queries = '' c_ids, p_ids = self.vocab.azlist() tl = """<div class="termlist">""" tl = """%s<h3>Classes and Properties (full detail)</h3>\n<div class='termdetails'><br />\n\n""" % tl # danbri hack 20100101 removed: href="http://www.w3.org/2003/06/sw-vocab-status/ns#%s" pending discussion w/ libby and leigh re URIs # first classes, then properties eg = """<div class="specterm" id="term_%s" about="%s" typeof="%s"> <h3>%s: %s</h3> <em>%s</em> - %s <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span property="vs:status" >%s</span></td></tr> %s %s </table> %s <p style="float: right; font-size: small;">[<a href="#term_%s">#</a>] [<a href="http://wiki.foaf-project.org/w/term_%s">wiki</a>] <!-- %s --> [<a href="#glance">back to top</a>]</p> <br/> </div>""" # replace this if you want validation queries: xxx danbri # <p style="float: right; font-size: small;">[<a href="#term_%s">permalink</a>] [<a href="#queries_%s">validation queries</a>] [<a href="#glance">back to top</a>]</p> # todo, push this into an api call (c_ids currently setup by az above) # classes for term in self.vocab.classes: # strings to use later domainsOfClass = '' rangesOfClass = '' #class in domain of g = self.vocab.graph q = 'SELECT ?d ?l WHERE {?d rdfs:domain <%s> . ?d rdfs:label ?l } ' % (term.uri) relations = g.query(q) startStr = '<tr><th>Properties include:</th>\n' contentStr = '' for (domain, label) in relations: dom = Term(domain) # danbri hack 20100101 # termStr = """<a href="#term_%s">%s</a>\n""" % (dom.id, label) termStr = """<a href="#term_%s">%s</a>\n""" % (dom.id, dom.id) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": domainsOfClass = "%s <td> %s </td></tr>" % (startStr, contentStr) # class in range of q2 = 'SELECT ?d ?l WHERE {?d rdfs:range <%s> . ?d rdfs:label ?l } ' % (term.uri) relations2 = g.query(q2) startStr = '<tr><th>Used with:</th>\n' contentStr = '' for (range, label) in relations2: ran = Term(range) # termStr = """<a href="#term_%s">%s</a>\n""" % (ran.id, label) # danbri hack 20100101 better to use exact IDs here termStr = """<a href="#term_%s">%s</a>\n""" % (ran.id, ran.id) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": rangesOfClass = "%s <td> %s</td></tr> " % (startStr, contentStr) # class subclassof subClassOf = '' q = 'SELECT ?sc ?l WHERE {<%s> rdfs:subClassOf ?sc . ?sc rdfs:label ?l } ' % (term.uri) relations = g.query(q) startStr = '<tr><th>Subclass Of</th>\n' contentStr = '' for (subclass, label) in relations: sub = Term(subclass) termStr = """<span rel="rdfs:subClassOf" href="%s"><a href="#term_%s">%s</a></span>\n""" % (subclass, sub.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": subClassOf = "%s <td> %s </td></tr>" % (startStr, contentStr) # class has subclass hasSubClass = '' q = 'SELECT ?sc ?l WHERE {?sc rdfs:subClassOf <%s>. ?sc rdfs:label ?l } ' % (term.uri) relations = g.query(q) startStr = '<tr><th>Has Subclass</th>\n' contentStr = '' for (subclass, label) in relations: sub = Term(subclass) termStr = """<a href="#term_%s">%s</a>\n""" % (sub.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": hasSubClass = "%s <td> %s </td></tr>" % (startStr, contentStr) # is defined by classIsDefinedBy = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) relations = g.query(q) startStr = '\n' contentStr = '' for (isdefinedby) in relations: termStr = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": classIsDefinedBy = "%s <tr><td> %s </td></tr>" % (startStr, contentStr) # disjoint with isDisjointWith = '' qq = [ 'SELECT ?dj ?l WHERE { <%s> <http://www.w3.org/2002/07/owl#disjointWith> ?dj . ?dj rdfs:label ?l } ' % (term.uri), 'SELECT ?dj ?l WHERE { ?dj <http://www.w3.org/2002/07/owl#disjointWith> <%s> . ?dj rdfs:label ?l } ' % (term.uri) ] startStr = '<tr><th>Disjoint With:</th>\n' contentStr = '' for (q) in qq: relations = g.query(q) for (disjointWith, label) in relations: dis = Term(disjointWith) termStr = """<span rel="owl:disjointWith" href="%s"><a href="#term_%s">%s</a></span>\n""" % (disjointWith, dis.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": isDisjointWith = "%s <td> %s </td></tr>" % (startStr, contentStr) +# equivalent to + + isEquivalentTo = '' + + qq = [ + 'SELECT ?eq ?l WHERE { <%s> <http://www.w3.org/2002/07/owl#equivalentClass> ?eq . OPTIONAL { ?eq rdfs:label ?l } . FILTER (! isBLANK(?eq)) } ' % (term.uri), + 'SELECT ?eq ?l WHERE { ?eq <http://www.w3.org/2002/07/owl#equivalentClass> <%s> . OPTIONAL { ?eq rdfs:label ?l } . FILTER (! isBLANK(?eq)) } ' % (term.uri) + ] + + startStr = '<tr><th>Equivalent To</th>\n' + contentStr = '' + for (q) in qq: + relations = g.query(q) + + for (equivalentTo, label) in relations: + equiv = Term(equivalentTo) + + if (equiv.is_external(self.vocab)): + if (label == None): + label = self.vocab.niceName(equiv.uri) + termStr = """<span rel="owl:equivalentClass" href="%s"><a href="%s">%s</a></span>\n""" % (equivalentTo, equivalentTo, label) + else: + termStr = """<span rel="owl:equivalentClass" href="%s"><a href="#term_%s">%s</a></span>\n""" % (equivalentTo, equiv.id, label) + contentStr = "%s %s" % (contentStr, termStr) + + if contentStr != "": + isEquivalentTo = "%s <td> %s </td></tr>" % (startStr, contentStr) # end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' # if we want validation queries this is where it looks for them. filename = os.path.join(dn, term.id+".sparql") fileStr = '' try: f = open ( filename, "r") fileStr = f.read() fileStr = "<h4><a name=\"queries_"+term.id+"\"></a>"+term.id+" Validation Query</h4><pre>"+cgi.escape(ss)+"</pre>" except: fileStr='' queries = queries +"\n"+ fileStr sn = self.vocab.niceName(term.uri) s = self.termlink(s) s = self.include_escaped(dn, s) # danbri added another term.id 20010101 and removed term.status zz = eg % (term.id,term.uri,"rdfs:Class","Class", sn, term.label, term.comment, term.status,domainsOfClass,rangesOfClass+subClassOf+hasSubClass+classIsDefinedBy+isDisjointWith, s,term.id, term.id, term.id) ## we add to the relevant string - stable, unstable, testing or archaic if(term.status == "stable"): stableTxt = stableTxt + zz if(term.status == "testing"): testingTxt = testingTxt + zz if(term.status == "unstable"): unstableTxt = unstableTxt + zz if(term.status == "archaic"): archaicTxt = archaicTxt + zz if((term.status == None) or (term.status== "") or (term.status== "unknown")): archaicTxt = archaicTxt + zz ## then add the whole thing to the main tl string tl = tl+"<h2>Classes</h2>\n" tl = "%s %s" % (tl, stableTxt+"\n"+testingTxt+"\n"+unstableTxt+"\n"+archaicTxt) tl = tl+"<h2>Properties</h2>\n" # properties stableTxt = '' testingTxt = '' unstableTxt = '' archaicTxt = '' for term in self.vocab.properties: domainsOfProperty = '' rangesOfProperty = '' # domain of properties g = self.vocab.graph q = 'SELECT ?d ?l WHERE {<%s> rdfs:domain ?d . ?d rdfs:label ?l } ' % (term.uri) relations = g.query(q) startStr = '<tr><th>Domain:</th>\n' contentStr = '' for (domain, label) in relations: dom = Term(domain) termStr = """<span rel="rdfs:domain" href="%s"><a href="#term_%s">%s</a></span>\n""" % (domain, dom.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": domainsOfProperty = "%s <td>%s</td></tr>" % (startStr, contentStr) # range of properties q2 = 'SELECT ?d ?l WHERE {<%s> rdfs:range ?d . ?d rdfs:label ?l } ' % (term.uri) relations2 = g.query(q2) startStr = '<tr><th>Range:</th>\n' contentStr = '' for (range, label) in relations2: ran = Term(range) termStr = """<span rel="rdfs:range" href="%s"><a href="#term_%s">%s</a></span>\n""" % (range, ran.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": rangesOfProperty = "%s <td>%s</td> </tr>" % (startStr, contentStr) # is defined by propertyIsDefinedBy = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) relations = g.query(q) startStr = '\n' contentStr = '' for (isdefinedby) in relations: termStr = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": propertyIsDefinedBy = "%s <tr><td> %s </td></tr>" % (startStr, contentStr) # inverse functional property ifp = '' q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#InverseFunctionalProperty> } ' % (term.uri) relations = g.query(q) startStr = '<tr><th colspan="2">Inverse Functional Property</th>\n' if (len(relations) > 0): termStr = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#InverseFunctionalProperty"></span>""" ifp = "%s <td> %s </td></tr>" % (startStr, termStr) # functonal property fp = '' q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#FunctionalProperty> } ' % (term.uri) relations = g.query(q) startStr = '<tr><th colspan="2">Functional Property</th>\n' if (len(relations) > 0): termStr = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#FunctionalProperty"></span>""" fp = "%s <td> %s </td></tr>" % (startStr, termStr) # end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' sn = self.vocab.niceName(term.uri) s = self.termlink(s) s = self.include_escaped(dn, s) # danbri added another term.id 20010101 zz = eg % (term.id, term.uri,"rdf:Property","Property", sn, term.label, term.comment,term.status,domainsOfProperty,rangesOfProperty+propertyIsDefinedBy+ifp+fp, s,term.id, term.id, term.id) ## we add to the relevant string - stable, unstable, testing or archaic if(term.status == "stable"): stableTxt = stableTxt + zz if(term.status == "testing"): testingTxt = testingTxt + zz if(term.status == "unstable"): unstableTxt = unstableTxt + zz if(term.status == "archaic"): archaicTxt = archaicTxt + zz if((term.status == None) or (term.status== "") or (term.status== "unknown")): archaicTxt = archaicTxt + zz ## then add the whole thing to the main tl string tl = "%s %s" % (tl, stableTxt+"\n"+testingTxt+"\n"+unstableTxt+"\n"+archaicTxt) ## tl = "%s %s" % (tl, zz) ## ensure termlist tag is closed return(tl+"\n"+queries+"</div>\n</div>") def rdfa(self): return( "<html>rdfa here</html>") def termlink(self, text): result = text for base, ns in self.vocab.ns_list.iteritems(): if (base == self.vocab.uri): result = re.sub(r"<code>%s:(\w+)<\/code>" % ns, r"<code><a href='#term_\g<1>'>\g<1></a></code>", result ) else: result = re.sub(r"<code>%s:(\w+)<\/code>" % ns, r"<code><a href='%s\g<1>'>%s:\g<1></a></code>" % (base, ns), result ) return result def include_escaped(self, termdir, text): includes = re.finditer(r"<include>(.*)</include>", text) for match in includes: f = open("%s/%s.en" % (termdir, match.group(1)), "r") inc = cgi.escape(f.read()) f.close() text = text[:match.start()] + inc + text[match.end():] return text def htmlDocInfo( t, termdir='../docs' ): """Opens a file based on the term name (t) and termdir (defaults to current directory. Reads in the file, and returns a linkified version of it.""" if termdir==None: termdir=self.basedir doc = "" try: f = open("%s/%s.en" % (termdir, t), "r") doc = f.read() doc = self.termlink(doc) doc = self.include_escaped(termdir, doc) except: return "<p>No detailed documentation for this term.</p>" return doc # report what we've parsed from our various sources def report(self): s = "Report for vocabulary from " + self.vocab.filename + "\n" if self.vocab.uri != None: s += "URI: " + self.vocab.uri + "\n\n" for t in self.vocab.uterms: print "TERM as string: ",t s += t.simple_report() return s
leth/SpecGen
3ecd7221c123f131d9ca16d0c2aa7da6d2a110f3
Check both directions for disjoint classes.
diff --git a/libvocab.py b/libvocab.py index 66c3322..abedba5 100755 --- a/libvocab.py +++ b/libvocab.py @@ -118,747 +118,753 @@ class Term(object): return s def id(self): print "trying id" try: s = self.id except NameError: self.id = None s = '[NOID]' speclog('No ID for'+self) return str(s) def is_external(self, vocab): return not self.uri.startswith(vocab.uri) #def __repr__(self): # return(self.__str__) def __str__(self): try: s = self.id except NameError: self.label = None speclog('No label for '+self+' todo: take from uri regex') s = (str(self)) return(str(s)) # so we can treat this like a string def __add__(self, s): return (s+str(self)) def __radd__(self, s): return (s+str(self)) def simple_report(self): t = self s='' s += "default: \t\t"+t +"\n" s += "id: \t\t"+t.id +"\n" s += "uri: \t\t"+t.uri +"\n" s += "xmlns: \t\t"+t.xmlns +"\n" s += "label: \t\t"+t.label +"\n" s += "comment: \t\t" + t.comment +"\n" s += "status: \t\t" + t.status +"\n" s += "\n" return s def _get_status(self): try: return self._status except: return 'unknown' def _set_status(self, value): self._status = str(value) status = property(_get_status,_set_status) # a Python class representing an RDFS/OWL property. # class Property(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Property.is_property called on "+self return(True) def is_class(self): # print "Property.is_class called on "+self return(False) # A Python class representing an RDFS/OWL class # class Class(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Class.is_property called on "+self return(False) def is_class(self): # print "Class.is_class called on "+self return(True) # A python class representing (a description of) some RDF vocabulary # class Vocab(object): def __init__(self, dir, f='index.rdf', uri=None ): self.graph = ConjunctiveGraph() self._uri = uri self.dir = dir self.filename = os.path.join(dir, f) self.graph.parse(self.filename) self.terms = [] self.uterms = [] # should also load translations here? # and deal with a base-dir? ##if f != None: ## self.index() self.ns_list = { "http://www.w3.org/1999/02/22-rdf-syntax-ns#" : "rdf", "http://www.w3.org/2000/01/rdf-schema#" : "rdfs", "http://www.w3.org/2002/07/owl#" : "owl", "http://www.w3.org/2001/XMLSchema#" : "xsd", "http://rdfs.org/sioc/ns#" : "sioc", "http://xmlns.com/foaf/0.1/" : "foaf", "http://purl.org/dc/elements/1.1/" : "dc", "http://purl.org/dc/terms/" : "dct", "http://usefulinc.com/ns/doap#" : "doap", "http://www.w3.org/2003/06/sw-vocab-status/ns#" : "status", "http://purl.org/rss/1.0/modules/content/" : "content", "http://www.w3.org/2003/01/geo/wgs84_pos#" : "geo", "http://www.w3.org/2004/02/skos/core#" : "skos", "http://purl.org/NET/c4dm/event.owl#" : "event", "http://www.w3.org/2004/03/trix/rdfg-1/" : "rdfg", "http://purl.org/net/provenance/ns#" : "prv", "http://www.ontologydesignpatterns.org/ont/web/irw.owl#" : "irw", } def addShortName(self,sn): self.ns_list[self._uri] = sn self.shortName = sn #print self.ns_list # not currently used def unique_terms(self): tmp=[] for t in list(set(self.terms)): s = str(t) if (not s in tmp): self.uterms.append(t) tmp.append(s) # TODO: python question - can we skip needing getters? and only define setters. i tried/failed. --danbri def _get_uri(self): return self._uri def _set_uri(self, value): v = str(value) # we don't want Namespace() objects and suchlike, but we can use them without whining. if ':' not in v: speclog("Warning: this doesn't look like a URI: "+v) # raise Exception("This doesn't look like a URI.") self._uri = str( value ) uri = property(_get_uri,_set_uri) def set_filename(self, filename): self.filename = filename # TODO: be explicit if/where we default to English # TODO: do we need a separate index(), versus just use __init__ ? def index(self): # speclog("Indexing description of "+str(self)) # blank down anything we learned already self.terms = [] self.properties = [] self.classes = [] tmpclasses=[] tmpproperties=[] g = self.graph query = 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a rdf:Property }' relations = g.query(query) for (term, label, comment) in relations: p = Property(term) # print "Made a property! "+str(p) + "using label: "#+str(label) p.label = str(label).replace('\\n',"<br />") p.comment = str(comment).replace('\\n',"<br />") self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) query = 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type FILTER (?type = <http://www.w3.org/2002/07/owl#Class> || ?type = <http://www.w3.org/2000/01/rdf-schema#Class> ) }' relations = g.query(query) for (term, label, comment) in relations: c = Class(term) # print "Made a class! "+str(p) + "using comment: "+comment c.label = str(label).replace('\\n',"<br />") c.comment = str(comment).replace('\\n',"<br />") self.terms.append(c) if (not str(c) in tmpclasses): self.classes.append(c) tmpclasses.append(str(c)) self.terms.sort(key=operator.attrgetter('id')) self.classes.sort(key=operator.attrgetter('id')) self.properties.sort(key=operator.attrgetter('id')) # http://www.w3.org/2003/06/sw-vocab-status/ns#" query = 'SELECT ?x ?vs WHERE { ?x <http://www.w3.org/2003/06/sw-vocab-status/ns#term_status> ?vs }' status = g.query(query) # print "status results: ",status.__len__() for x, vs in status: #print "STATUS: ",vs, " for ",x t = self.lookup(x) if t != None: t.status = vs # print "Set status.", t.status else: speclog("Couldn't lookup term: "+x) # Go back and see if we missed any properties defined in OWL. TODO: classes too. Or rewrite above SPARQL. addd more types for full query. q= 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty>)}' q= 'SELECT distinct ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty> || ?type = <http://www.w3.org/2002/07/owl#DatatypeProperty> || ?type = <http://www.w3.org/1999/02/22-rdf-syntax-ns#Property> || ?type = <http://www.w3.org/2002/07/owl#FunctionalProperty> || ?type = <http://www.w3.org/2002/07/owl#InverseFunctionalProperty>) } ' relations = g.query(q) for (term, label, comment) in relations: p = Property(str(term)) got = self.lookup( str(term) ) if got==None: # print "Made an OWL property! "+str(p.uri) p.label = str(label).replace('\\n',"<br />") p.comment = str(comment).replace('\\n',"<br />") self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) # self.terms.sort() # does this even do anything? # self.classes.sort() # self.properties.sort() # todo, use a dictionary index instead. RTFM. def lookup(self, uri): uri = str(uri) for t in self.terms: # print "Lookup: comparing '"+t.uri+"' to '"+uri+"'" # print "type of t.uri is ",t.uri.__class__ if t.uri==uri: # print "Matched." # should we str here, to be more liberal? return t else: # print "Fail." '' return None # print a raw debug summary, direct from the RDF def raw(self): g = self.graph query = 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c } ' relations = g.query(query) print "Properties and Classes (%d terms)" % len(relations) print 40*"-" for (term, label, comment) in relations: print "term %s l: %s \t\tc: %s " % (term, label, comment) print # TODO: work out how to do ".encode('UTF-8')" here # for debugging only def detect_types(self): self.properties = [] self.classes = [] for t in self.terms: # print "Doing t: "+t+" which is of type " + str(t.__class__) if t.is_property(): # print "is_property." self.properties.append(t) if t.is_class(): # print "is_class." self.classes.append(t) # CODE FROM ORIGINAL specgen: def niceName(self, uri = None ): if uri is None: return # speclog("Nicing uri "+uri) regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) if rez == None: #print "Failed to niceName. Returning the whole thing." return(uri) pref = rez.group(1) # print "...",self.ns_list.get(pref, pref),":",rez.group(2) # todo: make this work when uri doesn't match the regex --danbri # AttributeError: 'NoneType' object has no attribute 'group' return self.ns_list.get(pref, pref) + ":" + rez.group(2) # HTML stuff, should be a separate class def azlist(self): """Builds the A-Z list of terms""" c_ids = [] p_ids = [] for p in self.properties: p_ids.append(str(p.id)) for c in self.classes: c_ids.append(str(c.id)) c_ids.sort() p_ids.sort() return (c_ids, p_ids) class VocabReport(object): def __init__(self, vocab, basedir='./examples/', temploc='template.html',templatedir='./examples/'): self.vocab = vocab self.basedir = basedir self.temploc = temploc self.templatedir = templatedir self._template = "no template loaded" # text.gsub(/<code>foaf:(\w+)<\/code>/){ defurl($1) } return "<code><a href=\"#term_#{term}\">foaf:#{term}</a></code>" def codelink(self, s): reg1 = re.compile(r"""<code>foaf:(\w+)<\/code>""") return(re.sub(reg1, r"""<code><a href="#term_\1">foaf:\1</a></code>""", s)) def _get_template(self): self._template = self.load_template() # should be conditional return self._template def _set_template(self, value): self._template = str(value) template = property(_get_template,_set_template) def load_template(self): filename = os.path.join(self.templatedir, self.temploc) f = open(filename, "r") template = f.read() return(template) def generate(self): tpl = self.template azlist = self.az() termlist = self.termlist() f = open ( self.vocab.filename, "r") rdfdata = f.read() # print "GENERATING >>>>>>>> " ## having the rdf in there was making it invalid ## removed in favour of RDFa ## tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8"), rdfdata) tpl = tpl % (azlist.encode("utf-8"), azlist.encode("utf-8"), termlist.encode("utf-8")) # tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8")) return(tpl) def az(self): """AZ List for html doc""" c_ids, p_ids = self.vocab.azlist() az = """<div class="azlist">""" az = """%s\n<p>Classes: |""" % az # print c_ids, p_ids for c in c_ids: # speclog("Class "+c+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(c).replace(" ", ""), c) az = """%s\n</p>""" % az az = """%s\n<p>Properties: |""" % az for p in p_ids: # speclog("Property "+p+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(p).replace(" ", ""), p) az = """%s\n</p>""" % az az = """%s\n</div>""" % az return(az) def termlist(self): """Term List for html doc""" stableTxt = '' testingTxt = '' unstableTxt = '' archaicTxt = '' queries = '' c_ids, p_ids = self.vocab.azlist() tl = """<div class="termlist">""" tl = """%s<h3>Classes and Properties (full detail)</h3>\n<div class='termdetails'><br />\n\n""" % tl # danbri hack 20100101 removed: href="http://www.w3.org/2003/06/sw-vocab-status/ns#%s" pending discussion w/ libby and leigh re URIs # first classes, then properties eg = """<div class="specterm" id="term_%s" about="%s" typeof="%s"> <h3>%s: %s</h3> <em>%s</em> - %s <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span property="vs:status" >%s</span></td></tr> %s %s </table> %s <p style="float: right; font-size: small;">[<a href="#term_%s">#</a>] [<a href="http://wiki.foaf-project.org/w/term_%s">wiki</a>] <!-- %s --> [<a href="#glance">back to top</a>]</p> <br/> </div>""" # replace this if you want validation queries: xxx danbri # <p style="float: right; font-size: small;">[<a href="#term_%s">permalink</a>] [<a href="#queries_%s">validation queries</a>] [<a href="#glance">back to top</a>]</p> # todo, push this into an api call (c_ids currently setup by az above) # classes for term in self.vocab.classes: # strings to use later domainsOfClass = '' rangesOfClass = '' #class in domain of g = self.vocab.graph q = 'SELECT ?d ?l WHERE {?d rdfs:domain <%s> . ?d rdfs:label ?l } ' % (term.uri) relations = g.query(q) startStr = '<tr><th>Properties include:</th>\n' contentStr = '' for (domain, label) in relations: dom = Term(domain) # danbri hack 20100101 # termStr = """<a href="#term_%s">%s</a>\n""" % (dom.id, label) termStr = """<a href="#term_%s">%s</a>\n""" % (dom.id, dom.id) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": domainsOfClass = "%s <td> %s </td></tr>" % (startStr, contentStr) # class in range of q2 = 'SELECT ?d ?l WHERE {?d rdfs:range <%s> . ?d rdfs:label ?l } ' % (term.uri) relations2 = g.query(q2) startStr = '<tr><th>Used with:</th>\n' contentStr = '' for (range, label) in relations2: ran = Term(range) # termStr = """<a href="#term_%s">%s</a>\n""" % (ran.id, label) # danbri hack 20100101 better to use exact IDs here termStr = """<a href="#term_%s">%s</a>\n""" % (ran.id, ran.id) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": rangesOfClass = "%s <td> %s</td></tr> " % (startStr, contentStr) # class subclassof subClassOf = '' q = 'SELECT ?sc ?l WHERE {<%s> rdfs:subClassOf ?sc . ?sc rdfs:label ?l } ' % (term.uri) relations = g.query(q) startStr = '<tr><th>Subclass Of</th>\n' contentStr = '' for (subclass, label) in relations: sub = Term(subclass) termStr = """<span rel="rdfs:subClassOf" href="%s"><a href="#term_%s">%s</a></span>\n""" % (subclass, sub.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": subClassOf = "%s <td> %s </td></tr>" % (startStr, contentStr) # class has subclass hasSubClass = '' q = 'SELECT ?sc ?l WHERE {?sc rdfs:subClassOf <%s>. ?sc rdfs:label ?l } ' % (term.uri) relations = g.query(q) startStr = '<tr><th>Has Subclass</th>\n' contentStr = '' for (subclass, label) in relations: sub = Term(subclass) termStr = """<a href="#term_%s">%s</a>\n""" % (sub.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": hasSubClass = "%s <td> %s </td></tr>" % (startStr, contentStr) # is defined by classIsDefinedBy = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) relations = g.query(q) startStr = '\n' contentStr = '' for (isdefinedby) in relations: termStr = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": classIsDefinedBy = "%s <tr><td> %s </td></tr>" % (startStr, contentStr) # disjoint with isDisjointWith = '' - q = 'SELECT ?dj ?l WHERE { <%s> <http://www.w3.org/2002/07/owl#disjointWith> ?dj . ?dj rdfs:label ?l } ' % (term.uri) - relations = g.query(q) - startStr = '<tr><th>Disjoint With:</th>\n' - + qq = [ + 'SELECT ?dj ?l WHERE { <%s> <http://www.w3.org/2002/07/owl#disjointWith> ?dj . ?dj rdfs:label ?l } ' % (term.uri), + 'SELECT ?dj ?l WHERE { ?dj <http://www.w3.org/2002/07/owl#disjointWith> <%s> . ?dj rdfs:label ?l } ' % (term.uri) + ] + + startStr = '<tr><th>Disjoint With:</th>\n' contentStr = '' - for (disjointWith, label) in relations: - termStr = """<span rel="owl:disjointWith" href="%s"><a href="#term_%s">%s</a></span>\n""" % (disjointWith, label, label) - contentStr = "%s %s" % (contentStr, termStr) + for (q) in qq: + relations = g.query(q) + + for (disjointWith, label) in relations: + dis = Term(disjointWith) + termStr = """<span rel="owl:disjointWith" href="%s"><a href="#term_%s">%s</a></span>\n""" % (disjointWith, dis.id, label) + contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": isDisjointWith = "%s <td> %s </td></tr>" % (startStr, contentStr) # end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' # if we want validation queries this is where it looks for them. filename = os.path.join(dn, term.id+".sparql") fileStr = '' try: f = open ( filename, "r") fileStr = f.read() fileStr = "<h4><a name=\"queries_"+term.id+"\"></a>"+term.id+" Validation Query</h4><pre>"+cgi.escape(ss)+"</pre>" except: fileStr='' queries = queries +"\n"+ fileStr sn = self.vocab.niceName(term.uri) s = self.termlink(s) s = self.include_escaped(dn, s) # danbri added another term.id 20010101 and removed term.status zz = eg % (term.id,term.uri,"rdfs:Class","Class", sn, term.label, term.comment, term.status,domainsOfClass,rangesOfClass+subClassOf+hasSubClass+classIsDefinedBy+isDisjointWith, s,term.id, term.id, term.id) ## we add to the relevant string - stable, unstable, testing or archaic if(term.status == "stable"): stableTxt = stableTxt + zz if(term.status == "testing"): testingTxt = testingTxt + zz if(term.status == "unstable"): unstableTxt = unstableTxt + zz if(term.status == "archaic"): archaicTxt = archaicTxt + zz if((term.status == None) or (term.status== "") or (term.status== "unknown")): archaicTxt = archaicTxt + zz ## then add the whole thing to the main tl string tl = tl+"<h2>Classes</h2>\n" tl = "%s %s" % (tl, stableTxt+"\n"+testingTxt+"\n"+unstableTxt+"\n"+archaicTxt) tl = tl+"<h2>Properties</h2>\n" # properties stableTxt = '' testingTxt = '' unstableTxt = '' archaicTxt = '' for term in self.vocab.properties: domainsOfProperty = '' rangesOfProperty = '' # domain of properties g = self.vocab.graph q = 'SELECT ?d ?l WHERE {<%s> rdfs:domain ?d . ?d rdfs:label ?l } ' % (term.uri) relations = g.query(q) startStr = '<tr><th>Domain:</th>\n' contentStr = '' for (domain, label) in relations: dom = Term(domain) termStr = """<span rel="rdfs:domain" href="%s"><a href="#term_%s">%s</a></span>\n""" % (domain, dom.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": domainsOfProperty = "%s <td>%s</td></tr>" % (startStr, contentStr) # range of properties q2 = 'SELECT ?d ?l WHERE {<%s> rdfs:range ?d . ?d rdfs:label ?l } ' % (term.uri) relations2 = g.query(q2) startStr = '<tr><th>Range:</th>\n' contentStr = '' for (range, label) in relations2: ran = Term(range) termStr = """<span rel="rdfs:range" href="%s"><a href="#term_%s">%s</a></span>\n""" % (range, ran.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": rangesOfProperty = "%s <td>%s</td> </tr>" % (startStr, contentStr) # is defined by propertyIsDefinedBy = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) relations = g.query(q) startStr = '\n' contentStr = '' for (isdefinedby) in relations: termStr = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": propertyIsDefinedBy = "%s <tr><td> %s </td></tr>" % (startStr, contentStr) # inverse functional property ifp = '' q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#InverseFunctionalProperty> } ' % (term.uri) relations = g.query(q) startStr = '<tr><th colspan="2">Inverse Functional Property</th>\n' if (len(relations) > 0): termStr = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#InverseFunctionalProperty"></span>""" ifp = "%s <td> %s </td></tr>" % (startStr, termStr) # functonal property fp = '' q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#FunctionalProperty> } ' % (term.uri) relations = g.query(q) startStr = '<tr><th colspan="2">Functional Property</th>\n' if (len(relations) > 0): termStr = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#FunctionalProperty"></span>""" fp = "%s <td> %s </td></tr>" % (startStr, termStr) # end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' sn = self.vocab.niceName(term.uri) s = self.termlink(s) s = self.include_escaped(dn, s) # danbri added another term.id 20010101 zz = eg % (term.id, term.uri,"rdf:Property","Property", sn, term.label, term.comment,term.status,domainsOfProperty,rangesOfProperty+propertyIsDefinedBy+ifp+fp, s,term.id, term.id, term.id) ## we add to the relevant string - stable, unstable, testing or archaic if(term.status == "stable"): stableTxt = stableTxt + zz if(term.status == "testing"): testingTxt = testingTxt + zz if(term.status == "unstable"): unstableTxt = unstableTxt + zz if(term.status == "archaic"): archaicTxt = archaicTxt + zz if((term.status == None) or (term.status== "") or (term.status== "unknown")): archaicTxt = archaicTxt + zz ## then add the whole thing to the main tl string tl = "%s %s" % (tl, stableTxt+"\n"+testingTxt+"\n"+unstableTxt+"\n"+archaicTxt) ## tl = "%s %s" % (tl, zz) ## ensure termlist tag is closed return(tl+"\n"+queries+"</div>\n</div>") def rdfa(self): return( "<html>rdfa here</html>") def termlink(self, text): result = text for base, ns in self.vocab.ns_list.iteritems(): if (base == self.vocab.uri): result = re.sub(r"<code>%s:(\w+)<\/code>" % ns, r"<code><a href='#term_\g<1>'>\g<1></a></code>", result ) else: result = re.sub(r"<code>%s:(\w+)<\/code>" % ns, r"<code><a href='%s\g<1>'>%s:\g<1></a></code>" % (base, ns), result ) return result def include_escaped(self, termdir, text): includes = re.finditer(r"<include>(.*)</include>", text) for match in includes: f = open("%s/%s.en" % (termdir, match.group(1)), "r") inc = cgi.escape(f.read()) f.close() text = text[:match.start()] + inc + text[match.end():] return text def htmlDocInfo( t, termdir='../docs' ): """Opens a file based on the term name (t) and termdir (defaults to current directory. Reads in the file, and returns a linkified version of it.""" if termdir==None: termdir=self.basedir doc = "" try: f = open("%s/%s.en" % (termdir, t), "r") doc = f.read() doc = self.termlink(doc) doc = self.include_escaped(termdir, doc) except: return "<p>No detailed documentation for this term.</p>" return doc # report what we've parsed from our various sources def report(self): s = "Report for vocabulary from " + self.vocab.filename + "\n" if self.vocab.uri != None: s += "URI: " + self.vocab.uri + "\n\n" for t in self.vocab.uterms: print "TERM as string: ",t s += t.simple_report() return s
leth/SpecGen
171f89366cb9a7c330f6bf25cec067814aff1189
Removing misleading version number.
diff --git a/README.TXT b/README.TXT index d7ca23c..30fe2d1 100644 --- a/README.TXT +++ b/README.TXT @@ -1,95 +1,95 @@ This is an experimental new codebase for specgen tools. -It depends utterly upon rdflib. See http://rdflib.net/2.4.0/ +It depends utterly upon rdflib. See http://rdflib.net/ If you're lucky, typing this is enough: - easy_install -U rdflib==2.4.0 + easy_install -U rdflib and if you have problems there, update easy_install etc with: easy_install -U setuptools (Last time I did all this, I got Python errors but it still works.) Inputs: RDF, HTML and OWL description(s) of an RDF vocabulary Output: an XHTML+RDFa specification designed for human users See libvocab.py and specgen5.py for details. --danbri To test, see run_tests.py This is quite flexible. use -h for help, or run all with ./run_tests.py When working on a specific test, it is faster to use something like: ./run_tests.py testSpecgen.testHTMLazlistExists See the src for adding more tests (simple and encouraged!), or for defining collections that can be run together. "What it does": The last FOAF spec was built using http://xmlns.com/foaf/0.1/specgen.py This reads an index.rdf, a template.html file plus a set of per-term files, eg. 'doc/homepage.en' etc., then generates the main HTML FOAF spec. Announcement: http://lists.foaf-project.org/pipermail/foaf-dev/2008-December/009415.html http://groups.google.com/group/sioc-dev/browse_thread/thread/36190062d384624d See also: http://forge.morfeo-project.org/wiki_en/index.php/SpecGen (another rewrite) http://crschmidt.net/semweb/redland/ https://lists.morfeo-project.org/pipermail/specgen-devel/ Goals: - be usable at least for (re)-generating the FOAF spec and similar - work well with multi-lingual labels - be based on SPARQL queries against RDFS/OWL vocab descriptions - evolve a Python library that supports such tasks - keep vocab-specific hackery in scripts that call the library - push display logic into CSS - use a modern, pure Python RDF library for support Status: - we load up and interpret the core RDFS/OWL - we populate Vocab, Term (Class or Property) instances - we have *no* code yet for generating HTML spec TODO: - mine the old implementations to understand what we need to know about each class and property. - decide how much of OWL we want to represent - see what rdflib itself might offer to help with all this ISSUES 1. librdf doesn't seem to like abbreviations in FILTER clauses. this worked: q= 'SELECT ?x ?l ?c ?type WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty>) } ' while this failed: q= 'PREFIX owl: <http://www.w3.org/2002/07/owl#> SELECT ?x ?l ?c ?type WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = owl:ObjectProperty) } ' (even when passing in bindings) This forces us to be verbose, ie. q= 'SELECT distinct ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty> || ?type = <http://www.w3.org/2002/07/owl#DatatypeProperty> || ?type = <http://www.w3.org/1999/02/22-rdf-syntax-ns#Property> || ?type = <http://www.w3.org/2002/07/owl#FunctionalProperty> || ?type = <http://www.w3.org/2002/07/owl#InverseFunctionalProperty>) } ' 2. Figure out the best way to do tests in Python. assert()? read diveinto... 3. TODO: work out how to do ".encode('UTF-8')" everywhere 4. Be more explicit and careful re defaulting to English, and more robust when multilingual labels are found. 5. Currently, queries find nothing in SIOC. We need to match various OWL and RDF ways of saying "this is a property", and encapsulate this in a function. And test it. SIOC should find 20<x<100 properties, etc.
leth/SpecGen
4887f1b55e2291220aa2a10701c9fa3d7b6619e5
Fixed newlines in comments and labels.
diff --git a/libvocab.py b/libvocab.py index 7e74ca5..66c3322 100755 --- a/libvocab.py +++ b/libvocab.py @@ -1,859 +1,859 @@ #!/usr/bin/env python # total rewrite. --danbri # Usage: # # >>> from libvocab import Vocab, Term, Class, Property # # >>> from libvocab import Vocab, Term, Class, Property # >>> v = Vocab( f='examples/foaf/index.rdf', uri='http://xmlns.com/foaf/0.1/') # >>> dna = v.lookup('http://xmlns.com/foaf/0.1/dnaChecksum') # >>> dna.label # 'DNA checksum' # >>> dna.comment # 'A checksum for the DNA of some thing. Joke.' # >>> dna.id # u'dnaChecksum' # >>> dna.uri # 'http://xmlns.com/foaf/0.1/dnaChecksum' # # # Python OO notes: # http://www.devshed.com/c/a/Python/Object-Oriented-Programming-With-Python-part-1/ # http://www.daniweb.com/code/snippet354.html # http://docs.python.org/reference/datamodel.html#specialnames # # RDFlib: # http://www.science.uva.nl/research/air/wiki/RDFlib # # http://dowhatimean.net/2006/03/spellchecking-vocabularies-with-sparql # # We define basics, Vocab, Term, Property, Class # and populate them with data from RDF schemas, OWL, translations ... and nearby html files. import rdflib from rdflib import term from rdflib.namespace import Namespace from rdflib.graph import Graph, ConjunctiveGraph rdflib.plugin.register('sparql', rdflib.query.Processor, 'rdfextras.sparql.processor', 'Processor') rdflib.plugin.register('sparql', rdflib.query.Result, 'rdfextras.sparql.query', 'SPARQLQueryResult') # pre3: from rdflib.sparql.sparqlGraph import SPARQLGraph #from rdflib.sparql.graphPattern import GraphPattern #from rdflib.sparql import Query FOAF = Namespace('http://xmlns.com/foaf/0.1/') RDFS = Namespace('http://www.w3.org/2000/01/rdf-schema#') XFN = Namespace("http://gmpg.org/xfn/1#") RDF = Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#") OWL = Namespace('http://www.w3.org/2002/07/owl#') VS = Namespace('http://www.w3.org/2003/06/sw-vocab-status/ns#') DC = Namespace('http://purl.org/dc/elements/1.1/') DOAP = Namespace('http://usefulinc.com/ns/doap#') SIOC = Namespace('http://rdfs.org/sioc/ns#') SIOCTYPES = Namespace('http://rdfs.org/sioc/types#') SIOCSERVICES = Namespace('http://rdfs.org/sioc/services#') # # TODO: rationalise these two lists. or at least check they are same. import sys, time, re, urllib, getopt import logging import os.path import cgi import operator def speclog(str): sys.stderr.write("LOG: "+str+"\n") # a Term has... (intrinsically and via it's RDFS/OWL description) # uri - a (primary) URI, eg. 'http://xmlns.com/foaf/0.1/workplaceHomepage' # id - a local-to-spec ID, eg. 'workplaceHomepage' # xmlns - an xmlns URI (isDefinedBy, eg. 'http://xmlns.com/foaf/0.1/') # # label - an rdfs:label # comment - an rdfs:comment # # Beyond this, properties vary. Some have vs:status. Some have owl Deprecated. # Some have OWL descriptions, and RDFS descriptions; eg. property range/domain # or class disjointness. def ns_split(uri): regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) return(rez.group(1), rez.group(2)) class Term(object): def __init__(self, uri='file://dev/null'): self.uri = str(uri) self.uri = self.uri.rstrip() # speclog("Parsing URI " + uri) a,b = ns_split(uri) self.id = b self.xmlns = a if self.id==None: speclog("Error parsing URI. "+uri) if self.xmlns==None: speclog("Error parsing URI. "+uri) # print "self.id: "+ self.id + " self.xmlns: " + self.xmlns def uri(self): try: s = self.uri except NameError: self.uri = None s = '[NOURI]' speclog('No URI for'+self) return s def id(self): print "trying id" try: s = self.id except NameError: self.id = None s = '[NOID]' speclog('No ID for'+self) return str(s) def is_external(self, vocab): return not self.uri.startswith(vocab.uri) #def __repr__(self): # return(self.__str__) def __str__(self): try: s = self.id except NameError: self.label = None speclog('No label for '+self+' todo: take from uri regex') s = (str(self)) return(str(s)) # so we can treat this like a string def __add__(self, s): return (s+str(self)) def __radd__(self, s): return (s+str(self)) def simple_report(self): t = self s='' s += "default: \t\t"+t +"\n" s += "id: \t\t"+t.id +"\n" s += "uri: \t\t"+t.uri +"\n" s += "xmlns: \t\t"+t.xmlns +"\n" s += "label: \t\t"+t.label +"\n" s += "comment: \t\t" + t.comment +"\n" s += "status: \t\t" + t.status +"\n" s += "\n" return s def _get_status(self): try: return self._status except: return 'unknown' def _set_status(self, value): self._status = str(value) status = property(_get_status,_set_status) # a Python class representing an RDFS/OWL property. # class Property(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Property.is_property called on "+self return(True) def is_class(self): # print "Property.is_class called on "+self return(False) # A Python class representing an RDFS/OWL class # class Class(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Class.is_property called on "+self return(False) def is_class(self): # print "Class.is_class called on "+self return(True) # A python class representing (a description of) some RDF vocabulary # class Vocab(object): def __init__(self, dir, f='index.rdf', uri=None ): self.graph = ConjunctiveGraph() self._uri = uri self.dir = dir self.filename = os.path.join(dir, f) self.graph.parse(self.filename) self.terms = [] self.uterms = [] # should also load translations here? # and deal with a base-dir? ##if f != None: ## self.index() self.ns_list = { "http://www.w3.org/1999/02/22-rdf-syntax-ns#" : "rdf", "http://www.w3.org/2000/01/rdf-schema#" : "rdfs", "http://www.w3.org/2002/07/owl#" : "owl", "http://www.w3.org/2001/XMLSchema#" : "xsd", "http://rdfs.org/sioc/ns#" : "sioc", "http://xmlns.com/foaf/0.1/" : "foaf", "http://purl.org/dc/elements/1.1/" : "dc", "http://purl.org/dc/terms/" : "dct", "http://usefulinc.com/ns/doap#" : "doap", "http://www.w3.org/2003/06/sw-vocab-status/ns#" : "status", "http://purl.org/rss/1.0/modules/content/" : "content", "http://www.w3.org/2003/01/geo/wgs84_pos#" : "geo", "http://www.w3.org/2004/02/skos/core#" : "skos", "http://purl.org/NET/c4dm/event.owl#" : "event", "http://www.w3.org/2004/03/trix/rdfg-1/" : "rdfg", "http://purl.org/net/provenance/ns#" : "prv", "http://www.ontologydesignpatterns.org/ont/web/irw.owl#" : "irw", } def addShortName(self,sn): self.ns_list[self._uri] = sn self.shortName = sn #print self.ns_list # not currently used def unique_terms(self): tmp=[] for t in list(set(self.terms)): s = str(t) if (not s in tmp): self.uterms.append(t) tmp.append(s) # TODO: python question - can we skip needing getters? and only define setters. i tried/failed. --danbri def _get_uri(self): return self._uri def _set_uri(self, value): v = str(value) # we don't want Namespace() objects and suchlike, but we can use them without whining. if ':' not in v: speclog("Warning: this doesn't look like a URI: "+v) # raise Exception("This doesn't look like a URI.") self._uri = str( value ) uri = property(_get_uri,_set_uri) def set_filename(self, filename): self.filename = filename # TODO: be explicit if/where we default to English # TODO: do we need a separate index(), versus just use __init__ ? def index(self): # speclog("Indexing description of "+str(self)) # blank down anything we learned already self.terms = [] self.properties = [] self.classes = [] tmpclasses=[] tmpproperties=[] g = self.graph query = 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a rdf:Property }' relations = g.query(query) for (term, label, comment) in relations: p = Property(term) # print "Made a property! "+str(p) + "using label: "#+str(label) - p.label = str(label) - p.comment = str(comment) + p.label = str(label).replace('\\n',"<br />") + p.comment = str(comment).replace('\\n',"<br />") self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) query = 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type FILTER (?type = <http://www.w3.org/2002/07/owl#Class> || ?type = <http://www.w3.org/2000/01/rdf-schema#Class> ) }' relations = g.query(query) for (term, label, comment) in relations: c = Class(term) # print "Made a class! "+str(p) + "using comment: "+comment - c.label = str(label) - c.comment = str(comment) + c.label = str(label).replace('\\n',"<br />") + c.comment = str(comment).replace('\\n',"<br />") self.terms.append(c) if (not str(c) in tmpclasses): self.classes.append(c) tmpclasses.append(str(c)) self.terms.sort(key=operator.attrgetter('id')) self.classes.sort(key=operator.attrgetter('id')) self.properties.sort(key=operator.attrgetter('id')) # http://www.w3.org/2003/06/sw-vocab-status/ns#" query = 'SELECT ?x ?vs WHERE { ?x <http://www.w3.org/2003/06/sw-vocab-status/ns#term_status> ?vs }' status = g.query(query) # print "status results: ",status.__len__() for x, vs in status: #print "STATUS: ",vs, " for ",x t = self.lookup(x) if t != None: t.status = vs # print "Set status.", t.status else: speclog("Couldn't lookup term: "+x) # Go back and see if we missed any properties defined in OWL. TODO: classes too. Or rewrite above SPARQL. addd more types for full query. q= 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty>)}' q= 'SELECT distinct ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty> || ?type = <http://www.w3.org/2002/07/owl#DatatypeProperty> || ?type = <http://www.w3.org/1999/02/22-rdf-syntax-ns#Property> || ?type = <http://www.w3.org/2002/07/owl#FunctionalProperty> || ?type = <http://www.w3.org/2002/07/owl#InverseFunctionalProperty>) } ' relations = g.query(q) for (term, label, comment) in relations: p = Property(str(term)) got = self.lookup( str(term) ) if got==None: # print "Made an OWL property! "+str(p.uri) - p.label = str(label) - p.comment = str(comment) + p.label = str(label).replace('\\n',"<br />") + p.comment = str(comment).replace('\\n',"<br />") self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) # self.terms.sort() # does this even do anything? # self.classes.sort() # self.properties.sort() # todo, use a dictionary index instead. RTFM. def lookup(self, uri): uri = str(uri) for t in self.terms: # print "Lookup: comparing '"+t.uri+"' to '"+uri+"'" # print "type of t.uri is ",t.uri.__class__ if t.uri==uri: # print "Matched." # should we str here, to be more liberal? return t else: # print "Fail." '' return None # print a raw debug summary, direct from the RDF def raw(self): g = self.graph query = 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c } ' relations = g.query(query) print "Properties and Classes (%d terms)" % len(relations) print 40*"-" for (term, label, comment) in relations: print "term %s l: %s \t\tc: %s " % (term, label, comment) print # TODO: work out how to do ".encode('UTF-8')" here # for debugging only def detect_types(self): self.properties = [] self.classes = [] for t in self.terms: # print "Doing t: "+t+" which is of type " + str(t.__class__) if t.is_property(): # print "is_property." self.properties.append(t) if t.is_class(): # print "is_class." self.classes.append(t) # CODE FROM ORIGINAL specgen: def niceName(self, uri = None ): if uri is None: return # speclog("Nicing uri "+uri) regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) if rez == None: #print "Failed to niceName. Returning the whole thing." return(uri) pref = rez.group(1) # print "...",self.ns_list.get(pref, pref),":",rez.group(2) # todo: make this work when uri doesn't match the regex --danbri # AttributeError: 'NoneType' object has no attribute 'group' return self.ns_list.get(pref, pref) + ":" + rez.group(2) # HTML stuff, should be a separate class def azlist(self): """Builds the A-Z list of terms""" c_ids = [] p_ids = [] for p in self.properties: p_ids.append(str(p.id)) for c in self.classes: c_ids.append(str(c.id)) c_ids.sort() p_ids.sort() return (c_ids, p_ids) class VocabReport(object): def __init__(self, vocab, basedir='./examples/', temploc='template.html',templatedir='./examples/'): self.vocab = vocab self.basedir = basedir self.temploc = temploc self.templatedir = templatedir self._template = "no template loaded" # text.gsub(/<code>foaf:(\w+)<\/code>/){ defurl($1) } return "<code><a href=\"#term_#{term}\">foaf:#{term}</a></code>" def codelink(self, s): reg1 = re.compile(r"""<code>foaf:(\w+)<\/code>""") return(re.sub(reg1, r"""<code><a href="#term_\1">foaf:\1</a></code>""", s)) def _get_template(self): self._template = self.load_template() # should be conditional return self._template def _set_template(self, value): self._template = str(value) template = property(_get_template,_set_template) def load_template(self): filename = os.path.join(self.templatedir, self.temploc) f = open(filename, "r") template = f.read() return(template) def generate(self): tpl = self.template azlist = self.az() termlist = self.termlist() f = open ( self.vocab.filename, "r") rdfdata = f.read() # print "GENERATING >>>>>>>> " ## having the rdf in there was making it invalid ## removed in favour of RDFa ## tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8"), rdfdata) tpl = tpl % (azlist.encode("utf-8"), azlist.encode("utf-8"), termlist.encode("utf-8")) # tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8")) return(tpl) def az(self): """AZ List for html doc""" c_ids, p_ids = self.vocab.azlist() az = """<div class="azlist">""" az = """%s\n<p>Classes: |""" % az # print c_ids, p_ids for c in c_ids: # speclog("Class "+c+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(c).replace(" ", ""), c) az = """%s\n</p>""" % az az = """%s\n<p>Properties: |""" % az for p in p_ids: # speclog("Property "+p+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(p).replace(" ", ""), p) az = """%s\n</p>""" % az az = """%s\n</div>""" % az return(az) def termlist(self): """Term List for html doc""" stableTxt = '' testingTxt = '' unstableTxt = '' archaicTxt = '' queries = '' c_ids, p_ids = self.vocab.azlist() tl = """<div class="termlist">""" tl = """%s<h3>Classes and Properties (full detail)</h3>\n<div class='termdetails'><br />\n\n""" % tl # danbri hack 20100101 removed: href="http://www.w3.org/2003/06/sw-vocab-status/ns#%s" pending discussion w/ libby and leigh re URIs # first classes, then properties eg = """<div class="specterm" id="term_%s" about="%s" typeof="%s"> <h3>%s: %s</h3> <em>%s</em> - %s <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span property="vs:status" >%s</span></td></tr> %s %s </table> %s <p style="float: right; font-size: small;">[<a href="#term_%s">#</a>] [<a href="http://wiki.foaf-project.org/w/term_%s">wiki</a>] <!-- %s --> [<a href="#glance">back to top</a>]</p> <br/> </div>""" # replace this if you want validation queries: xxx danbri # <p style="float: right; font-size: small;">[<a href="#term_%s">permalink</a>] [<a href="#queries_%s">validation queries</a>] [<a href="#glance">back to top</a>]</p> # todo, push this into an api call (c_ids currently setup by az above) # classes for term in self.vocab.classes: # strings to use later domainsOfClass = '' rangesOfClass = '' #class in domain of g = self.vocab.graph q = 'SELECT ?d ?l WHERE {?d rdfs:domain <%s> . ?d rdfs:label ?l } ' % (term.uri) relations = g.query(q) startStr = '<tr><th>Properties include:</th>\n' contentStr = '' for (domain, label) in relations: dom = Term(domain) # danbri hack 20100101 # termStr = """<a href="#term_%s">%s</a>\n""" % (dom.id, label) termStr = """<a href="#term_%s">%s</a>\n""" % (dom.id, dom.id) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": domainsOfClass = "%s <td> %s </td></tr>" % (startStr, contentStr) # class in range of q2 = 'SELECT ?d ?l WHERE {?d rdfs:range <%s> . ?d rdfs:label ?l } ' % (term.uri) relations2 = g.query(q2) startStr = '<tr><th>Used with:</th>\n' contentStr = '' for (range, label) in relations2: ran = Term(range) # termStr = """<a href="#term_%s">%s</a>\n""" % (ran.id, label) # danbri hack 20100101 better to use exact IDs here termStr = """<a href="#term_%s">%s</a>\n""" % (ran.id, ran.id) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": rangesOfClass = "%s <td> %s</td></tr> " % (startStr, contentStr) # class subclassof subClassOf = '' q = 'SELECT ?sc ?l WHERE {<%s> rdfs:subClassOf ?sc . ?sc rdfs:label ?l } ' % (term.uri) relations = g.query(q) startStr = '<tr><th>Subclass Of</th>\n' contentStr = '' for (subclass, label) in relations: sub = Term(subclass) termStr = """<span rel="rdfs:subClassOf" href="%s"><a href="#term_%s">%s</a></span>\n""" % (subclass, sub.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": subClassOf = "%s <td> %s </td></tr>" % (startStr, contentStr) # class has subclass hasSubClass = '' q = 'SELECT ?sc ?l WHERE {?sc rdfs:subClassOf <%s>. ?sc rdfs:label ?l } ' % (term.uri) relations = g.query(q) startStr = '<tr><th>Has Subclass</th>\n' contentStr = '' for (subclass, label) in relations: sub = Term(subclass) termStr = """<a href="#term_%s">%s</a>\n""" % (sub.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": hasSubClass = "%s <td> %s </td></tr>" % (startStr, contentStr) # is defined by classIsDefinedBy = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) relations = g.query(q) startStr = '\n' contentStr = '' for (isdefinedby) in relations: termStr = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": classIsDefinedBy = "%s <tr><td> %s </td></tr>" % (startStr, contentStr) # disjoint with isDisjointWith = '' q = 'SELECT ?dj ?l WHERE { <%s> <http://www.w3.org/2002/07/owl#disjointWith> ?dj . ?dj rdfs:label ?l } ' % (term.uri) relations = g.query(q) startStr = '<tr><th>Disjoint With:</th>\n' contentStr = '' for (disjointWith, label) in relations: termStr = """<span rel="owl:disjointWith" href="%s"><a href="#term_%s">%s</a></span>\n""" % (disjointWith, label, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": isDisjointWith = "%s <td> %s </td></tr>" % (startStr, contentStr) # end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' # if we want validation queries this is where it looks for them. filename = os.path.join(dn, term.id+".sparql") fileStr = '' try: f = open ( filename, "r") fileStr = f.read() fileStr = "<h4><a name=\"queries_"+term.id+"\"></a>"+term.id+" Validation Query</h4><pre>"+cgi.escape(ss)+"</pre>" except: fileStr='' queries = queries +"\n"+ fileStr sn = self.vocab.niceName(term.uri) s = self.termlink(s) s = self.include_escaped(dn, s) # danbri added another term.id 20010101 and removed term.status zz = eg % (term.id,term.uri,"rdfs:Class","Class", sn, term.label, term.comment, term.status,domainsOfClass,rangesOfClass+subClassOf+hasSubClass+classIsDefinedBy+isDisjointWith, s,term.id, term.id, term.id) ## we add to the relevant string - stable, unstable, testing or archaic if(term.status == "stable"): stableTxt = stableTxt + zz if(term.status == "testing"): testingTxt = testingTxt + zz if(term.status == "unstable"): unstableTxt = unstableTxt + zz if(term.status == "archaic"): archaicTxt = archaicTxt + zz if((term.status == None) or (term.status== "") or (term.status== "unknown")): archaicTxt = archaicTxt + zz ## then add the whole thing to the main tl string tl = tl+"<h2>Classes</h2>\n" tl = "%s %s" % (tl, stableTxt+"\n"+testingTxt+"\n"+unstableTxt+"\n"+archaicTxt) tl = tl+"<h2>Properties</h2>\n" # properties stableTxt = '' testingTxt = '' unstableTxt = '' archaicTxt = '' for term in self.vocab.properties: domainsOfProperty = '' rangesOfProperty = '' # domain of properties g = self.vocab.graph q = 'SELECT ?d ?l WHERE {<%s> rdfs:domain ?d . ?d rdfs:label ?l } ' % (term.uri) relations = g.query(q) startStr = '<tr><th>Domain:</th>\n' contentStr = '' for (domain, label) in relations: dom = Term(domain) termStr = """<span rel="rdfs:domain" href="%s"><a href="#term_%s">%s</a></span>\n""" % (domain, dom.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": domainsOfProperty = "%s <td>%s</td></tr>" % (startStr, contentStr) # range of properties q2 = 'SELECT ?d ?l WHERE {<%s> rdfs:range ?d . ?d rdfs:label ?l } ' % (term.uri) relations2 = g.query(q2) startStr = '<tr><th>Range:</th>\n' contentStr = '' for (range, label) in relations2: ran = Term(range) termStr = """<span rel="rdfs:range" href="%s"><a href="#term_%s">%s</a></span>\n""" % (range, ran.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": rangesOfProperty = "%s <td>%s</td> </tr>" % (startStr, contentStr) # is defined by propertyIsDefinedBy = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) relations = g.query(q) startStr = '\n' contentStr = '' for (isdefinedby) in relations: termStr = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": propertyIsDefinedBy = "%s <tr><td> %s </td></tr>" % (startStr, contentStr) # inverse functional property ifp = '' q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#InverseFunctionalProperty> } ' % (term.uri) relations = g.query(q) startStr = '<tr><th colspan="2">Inverse Functional Property</th>\n' if (len(relations) > 0): termStr = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#InverseFunctionalProperty"></span>""" ifp = "%s <td> %s </td></tr>" % (startStr, termStr) # functonal property fp = '' q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#FunctionalProperty> } ' % (term.uri) relations = g.query(q) startStr = '<tr><th colspan="2">Functional Property</th>\n' if (len(relations) > 0): termStr = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#FunctionalProperty"></span>""" fp = "%s <td> %s </td></tr>" % (startStr, termStr) # end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' sn = self.vocab.niceName(term.uri) s = self.termlink(s) s = self.include_escaped(dn, s) # danbri added another term.id 20010101 zz = eg % (term.id, term.uri,"rdf:Property","Property", sn, term.label, term.comment,term.status,domainsOfProperty,rangesOfProperty+propertyIsDefinedBy+ifp+fp, s,term.id, term.id, term.id) ## we add to the relevant string - stable, unstable, testing or archaic if(term.status == "stable"): stableTxt = stableTxt + zz if(term.status == "testing"): testingTxt = testingTxt + zz if(term.status == "unstable"): unstableTxt = unstableTxt + zz if(term.status == "archaic"): archaicTxt = archaicTxt + zz if((term.status == None) or (term.status== "") or (term.status== "unknown")): archaicTxt = archaicTxt + zz ## then add the whole thing to the main tl string tl = "%s %s" % (tl, stableTxt+"\n"+testingTxt+"\n"+unstableTxt+"\n"+archaicTxt) ## tl = "%s %s" % (tl, zz) ## ensure termlist tag is closed return(tl+"\n"+queries+"</div>\n</div>") def rdfa(self): return( "<html>rdfa here</html>") def termlink(self, text): result = text for base, ns in self.vocab.ns_list.iteritems(): if (base == self.vocab.uri): result = re.sub(r"<code>%s:(\w+)<\/code>" % ns, r"<code><a href='#term_\g<1>'>\g<1></a></code>", result ) else: result = re.sub(r"<code>%s:(\w+)<\/code>" % ns, r"<code><a href='%s\g<1>'>%s:\g<1></a></code>" % (base, ns), result ) return result def include_escaped(self, termdir, text): includes = re.finditer(r"<include>(.*)</include>", text) for match in includes: f = open("%s/%s.en" % (termdir, match.group(1)), "r") inc = cgi.escape(f.read()) f.close() text = text[:match.start()] + inc + text[match.end():] return text def htmlDocInfo( t, termdir='../docs' ): """Opens a file based on the term name (t) and termdir (defaults to current directory. Reads in the file, and returns a linkified version of it.""" if termdir==None: termdir=self.basedir doc = "" try: f = open("%s/%s.en" % (termdir, t), "r") doc = f.read() doc = self.termlink(doc) doc = self.include_escaped(termdir, doc) except: return "<p>No detailed documentation for this term.</p>" return doc # report what we've parsed from our various sources def report(self): s = "Report for vocabulary from " + self.vocab.filename + "\n" if self.vocab.uri != None: s += "URI: " + self.vocab.uri + "\n\n"
leth/SpecGen
5e79252bc905c261757a4729881caa860a33f63b
Added some more vocabulary prefix entries.
diff --git a/libvocab.py b/libvocab.py index 9ed667e..7e74ca5 100755 --- a/libvocab.py +++ b/libvocab.py @@ -1,754 +1,758 @@ #!/usr/bin/env python # total rewrite. --danbri # Usage: # # >>> from libvocab import Vocab, Term, Class, Property # # >>> from libvocab import Vocab, Term, Class, Property # >>> v = Vocab( f='examples/foaf/index.rdf', uri='http://xmlns.com/foaf/0.1/') # >>> dna = v.lookup('http://xmlns.com/foaf/0.1/dnaChecksum') # >>> dna.label # 'DNA checksum' # >>> dna.comment # 'A checksum for the DNA of some thing. Joke.' # >>> dna.id # u'dnaChecksum' # >>> dna.uri # 'http://xmlns.com/foaf/0.1/dnaChecksum' # # # Python OO notes: # http://www.devshed.com/c/a/Python/Object-Oriented-Programming-With-Python-part-1/ # http://www.daniweb.com/code/snippet354.html # http://docs.python.org/reference/datamodel.html#specialnames # # RDFlib: # http://www.science.uva.nl/research/air/wiki/RDFlib # # http://dowhatimean.net/2006/03/spellchecking-vocabularies-with-sparql # # We define basics, Vocab, Term, Property, Class # and populate them with data from RDF schemas, OWL, translations ... and nearby html files. import rdflib from rdflib import term from rdflib.namespace import Namespace from rdflib.graph import Graph, ConjunctiveGraph rdflib.plugin.register('sparql', rdflib.query.Processor, 'rdfextras.sparql.processor', 'Processor') rdflib.plugin.register('sparql', rdflib.query.Result, 'rdfextras.sparql.query', 'SPARQLQueryResult') # pre3: from rdflib.sparql.sparqlGraph import SPARQLGraph #from rdflib.sparql.graphPattern import GraphPattern #from rdflib.sparql import Query FOAF = Namespace('http://xmlns.com/foaf/0.1/') RDFS = Namespace('http://www.w3.org/2000/01/rdf-schema#') XFN = Namespace("http://gmpg.org/xfn/1#") RDF = Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#") OWL = Namespace('http://www.w3.org/2002/07/owl#') VS = Namespace('http://www.w3.org/2003/06/sw-vocab-status/ns#') DC = Namespace('http://purl.org/dc/elements/1.1/') DOAP = Namespace('http://usefulinc.com/ns/doap#') SIOC = Namespace('http://rdfs.org/sioc/ns#') SIOCTYPES = Namespace('http://rdfs.org/sioc/types#') SIOCSERVICES = Namespace('http://rdfs.org/sioc/services#') # # TODO: rationalise these two lists. or at least check they are same. import sys, time, re, urllib, getopt import logging import os.path import cgi import operator def speclog(str): sys.stderr.write("LOG: "+str+"\n") # a Term has... (intrinsically and via it's RDFS/OWL description) # uri - a (primary) URI, eg. 'http://xmlns.com/foaf/0.1/workplaceHomepage' # id - a local-to-spec ID, eg. 'workplaceHomepage' # xmlns - an xmlns URI (isDefinedBy, eg. 'http://xmlns.com/foaf/0.1/') # # label - an rdfs:label # comment - an rdfs:comment # # Beyond this, properties vary. Some have vs:status. Some have owl Deprecated. # Some have OWL descriptions, and RDFS descriptions; eg. property range/domain # or class disjointness. def ns_split(uri): regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) return(rez.group(1), rez.group(2)) class Term(object): def __init__(self, uri='file://dev/null'): self.uri = str(uri) self.uri = self.uri.rstrip() # speclog("Parsing URI " + uri) a,b = ns_split(uri) self.id = b self.xmlns = a if self.id==None: speclog("Error parsing URI. "+uri) if self.xmlns==None: speclog("Error parsing URI. "+uri) # print "self.id: "+ self.id + " self.xmlns: " + self.xmlns def uri(self): try: s = self.uri except NameError: self.uri = None s = '[NOURI]' speclog('No URI for'+self) return s def id(self): print "trying id" try: s = self.id except NameError: self.id = None s = '[NOID]' speclog('No ID for'+self) return str(s) def is_external(self, vocab): return not self.uri.startswith(vocab.uri) #def __repr__(self): # return(self.__str__) def __str__(self): try: s = self.id except NameError: self.label = None speclog('No label for '+self+' todo: take from uri regex') s = (str(self)) return(str(s)) # so we can treat this like a string def __add__(self, s): return (s+str(self)) def __radd__(self, s): return (s+str(self)) def simple_report(self): t = self s='' s += "default: \t\t"+t +"\n" s += "id: \t\t"+t.id +"\n" s += "uri: \t\t"+t.uri +"\n" s += "xmlns: \t\t"+t.xmlns +"\n" s += "label: \t\t"+t.label +"\n" s += "comment: \t\t" + t.comment +"\n" s += "status: \t\t" + t.status +"\n" s += "\n" return s def _get_status(self): try: return self._status except: return 'unknown' def _set_status(self, value): self._status = str(value) status = property(_get_status,_set_status) # a Python class representing an RDFS/OWL property. # class Property(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Property.is_property called on "+self return(True) def is_class(self): # print "Property.is_class called on "+self return(False) # A Python class representing an RDFS/OWL class # class Class(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Class.is_property called on "+self return(False) def is_class(self): # print "Class.is_class called on "+self return(True) # A python class representing (a description of) some RDF vocabulary # class Vocab(object): def __init__(self, dir, f='index.rdf', uri=None ): self.graph = ConjunctiveGraph() self._uri = uri self.dir = dir self.filename = os.path.join(dir, f) self.graph.parse(self.filename) self.terms = [] self.uterms = [] # should also load translations here? # and deal with a base-dir? ##if f != None: ## self.index() - self.ns_list = { "http://www.w3.org/1999/02/22-rdf-syntax-ns#" : "rdf", - "http://www.w3.org/2000/01/rdf-schema#" : "rdfs", - "http://www.w3.org/2002/07/owl#" : "owl", - "http://www.w3.org/2001/XMLSchema#" : "xsd", - "http://rdfs.org/sioc/ns#" : "sioc", - "http://xmlns.com/foaf/0.1/" : "foaf", - "http://purl.org/dc/elements/1.1/" : "dc", - "http://purl.org/dc/terms/" : "dct", - "http://usefulinc.com/ns/doap#" : "doap", - "http://www.w3.org/2003/06/sw-vocab-status/ns#" : "status", - "http://purl.org/rss/1.0/modules/content/" : "content", - "http://www.w3.org/2003/01/geo/wgs84_pos#" : "geo", - "http://www.w3.org/2004/02/skos/core#" : "skos", - "http://purl.org/NET/c4dm/event.owl#" : "event" - } + self.ns_list = { + "http://www.w3.org/1999/02/22-rdf-syntax-ns#" : "rdf", + "http://www.w3.org/2000/01/rdf-schema#" : "rdfs", + "http://www.w3.org/2002/07/owl#" : "owl", + "http://www.w3.org/2001/XMLSchema#" : "xsd", + "http://rdfs.org/sioc/ns#" : "sioc", + "http://xmlns.com/foaf/0.1/" : "foaf", + "http://purl.org/dc/elements/1.1/" : "dc", + "http://purl.org/dc/terms/" : "dct", + "http://usefulinc.com/ns/doap#" : "doap", + "http://www.w3.org/2003/06/sw-vocab-status/ns#" : "status", + "http://purl.org/rss/1.0/modules/content/" : "content", + "http://www.w3.org/2003/01/geo/wgs84_pos#" : "geo", + "http://www.w3.org/2004/02/skos/core#" : "skos", + "http://purl.org/NET/c4dm/event.owl#" : "event", + "http://www.w3.org/2004/03/trix/rdfg-1/" : "rdfg", + "http://purl.org/net/provenance/ns#" : "prv", + "http://www.ontologydesignpatterns.org/ont/web/irw.owl#" : "irw", + } def addShortName(self,sn): self.ns_list[self._uri] = sn self.shortName = sn #print self.ns_list # not currently used def unique_terms(self): tmp=[] for t in list(set(self.terms)): s = str(t) if (not s in tmp): self.uterms.append(t) tmp.append(s) # TODO: python question - can we skip needing getters? and only define setters. i tried/failed. --danbri def _get_uri(self): return self._uri def _set_uri(self, value): v = str(value) # we don't want Namespace() objects and suchlike, but we can use them without whining. if ':' not in v: speclog("Warning: this doesn't look like a URI: "+v) # raise Exception("This doesn't look like a URI.") self._uri = str( value ) uri = property(_get_uri,_set_uri) def set_filename(self, filename): self.filename = filename # TODO: be explicit if/where we default to English # TODO: do we need a separate index(), versus just use __init__ ? def index(self): # speclog("Indexing description of "+str(self)) # blank down anything we learned already self.terms = [] self.properties = [] self.classes = [] tmpclasses=[] tmpproperties=[] g = self.graph query = 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a rdf:Property }' relations = g.query(query) for (term, label, comment) in relations: p = Property(term) # print "Made a property! "+str(p) + "using label: "#+str(label) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) query = 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type FILTER (?type = <http://www.w3.org/2002/07/owl#Class> || ?type = <http://www.w3.org/2000/01/rdf-schema#Class> ) }' relations = g.query(query) for (term, label, comment) in relations: c = Class(term) # print "Made a class! "+str(p) + "using comment: "+comment c.label = str(label) c.comment = str(comment) self.terms.append(c) if (not str(c) in tmpclasses): self.classes.append(c) tmpclasses.append(str(c)) self.terms.sort(key=operator.attrgetter('id')) self.classes.sort(key=operator.attrgetter('id')) self.properties.sort(key=operator.attrgetter('id')) # http://www.w3.org/2003/06/sw-vocab-status/ns#" query = 'SELECT ?x ?vs WHERE { ?x <http://www.w3.org/2003/06/sw-vocab-status/ns#term_status> ?vs }' status = g.query(query) # print "status results: ",status.__len__() for x, vs in status: #print "STATUS: ",vs, " for ",x t = self.lookup(x) if t != None: t.status = vs # print "Set status.", t.status else: speclog("Couldn't lookup term: "+x) # Go back and see if we missed any properties defined in OWL. TODO: classes too. Or rewrite above SPARQL. addd more types for full query. q= 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty>)}' q= 'SELECT distinct ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty> || ?type = <http://www.w3.org/2002/07/owl#DatatypeProperty> || ?type = <http://www.w3.org/1999/02/22-rdf-syntax-ns#Property> || ?type = <http://www.w3.org/2002/07/owl#FunctionalProperty> || ?type = <http://www.w3.org/2002/07/owl#InverseFunctionalProperty>) } ' relations = g.query(q) for (term, label, comment) in relations: p = Property(str(term)) got = self.lookup( str(term) ) if got==None: # print "Made an OWL property! "+str(p.uri) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) # self.terms.sort() # does this even do anything? # self.classes.sort() # self.properties.sort() # todo, use a dictionary index instead. RTFM. def lookup(self, uri): uri = str(uri) for t in self.terms: # print "Lookup: comparing '"+t.uri+"' to '"+uri+"'" # print "type of t.uri is ",t.uri.__class__ if t.uri==uri: # print "Matched." # should we str here, to be more liberal? return t else: # print "Fail." '' return None # print a raw debug summary, direct from the RDF def raw(self): g = self.graph query = 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c } ' relations = g.query(query) print "Properties and Classes (%d terms)" % len(relations) print 40*"-" for (term, label, comment) in relations: print "term %s l: %s \t\tc: %s " % (term, label, comment) print # TODO: work out how to do ".encode('UTF-8')" here # for debugging only def detect_types(self): self.properties = [] self.classes = [] for t in self.terms: # print "Doing t: "+t+" which is of type " + str(t.__class__) if t.is_property(): # print "is_property." self.properties.append(t) if t.is_class(): # print "is_class." self.classes.append(t) # CODE FROM ORIGINAL specgen: def niceName(self, uri = None ): if uri is None: return # speclog("Nicing uri "+uri) regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) if rez == None: #print "Failed to niceName. Returning the whole thing." return(uri) pref = rez.group(1) # print "...",self.ns_list.get(pref, pref),":",rez.group(2) # todo: make this work when uri doesn't match the regex --danbri # AttributeError: 'NoneType' object has no attribute 'group' return self.ns_list.get(pref, pref) + ":" + rez.group(2) # HTML stuff, should be a separate class def azlist(self): """Builds the A-Z list of terms""" c_ids = [] p_ids = [] for p in self.properties: p_ids.append(str(p.id)) for c in self.classes: c_ids.append(str(c.id)) c_ids.sort() p_ids.sort() return (c_ids, p_ids) class VocabReport(object): def __init__(self, vocab, basedir='./examples/', temploc='template.html',templatedir='./examples/'): self.vocab = vocab self.basedir = basedir self.temploc = temploc self.templatedir = templatedir self._template = "no template loaded" # text.gsub(/<code>foaf:(\w+)<\/code>/){ defurl($1) } return "<code><a href=\"#term_#{term}\">foaf:#{term}</a></code>" def codelink(self, s): reg1 = re.compile(r"""<code>foaf:(\w+)<\/code>""") return(re.sub(reg1, r"""<code><a href="#term_\1">foaf:\1</a></code>""", s)) def _get_template(self): self._template = self.load_template() # should be conditional return self._template def _set_template(self, value): self._template = str(value) template = property(_get_template,_set_template) def load_template(self): filename = os.path.join(self.templatedir, self.temploc) f = open(filename, "r") template = f.read() return(template) def generate(self): tpl = self.template azlist = self.az() termlist = self.termlist() f = open ( self.vocab.filename, "r") rdfdata = f.read() # print "GENERATING >>>>>>>> " ## having the rdf in there was making it invalid ## removed in favour of RDFa ## tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8"), rdfdata) tpl = tpl % (azlist.encode("utf-8"), azlist.encode("utf-8"), termlist.encode("utf-8")) # tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8")) return(tpl) def az(self): """AZ List for html doc""" c_ids, p_ids = self.vocab.azlist() az = """<div class="azlist">""" az = """%s\n<p>Classes: |""" % az # print c_ids, p_ids for c in c_ids: # speclog("Class "+c+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(c).replace(" ", ""), c) az = """%s\n</p>""" % az az = """%s\n<p>Properties: |""" % az for p in p_ids: # speclog("Property "+p+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(p).replace(" ", ""), p) az = """%s\n</p>""" % az az = """%s\n</div>""" % az return(az) def termlist(self): """Term List for html doc""" stableTxt = '' testingTxt = '' unstableTxt = '' archaicTxt = '' queries = '' c_ids, p_ids = self.vocab.azlist() tl = """<div class="termlist">""" tl = """%s<h3>Classes and Properties (full detail)</h3>\n<div class='termdetails'><br />\n\n""" % tl # danbri hack 20100101 removed: href="http://www.w3.org/2003/06/sw-vocab-status/ns#%s" pending discussion w/ libby and leigh re URIs # first classes, then properties eg = """<div class="specterm" id="term_%s" about="%s" typeof="%s"> <h3>%s: %s</h3> <em>%s</em> - %s <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span property="vs:status" >%s</span></td></tr> %s %s </table> %s <p style="float: right; font-size: small;">[<a href="#term_%s">#</a>] [<a href="http://wiki.foaf-project.org/w/term_%s">wiki</a>] <!-- %s --> [<a href="#glance">back to top</a>]</p> <br/> </div>""" # replace this if you want validation queries: xxx danbri # <p style="float: right; font-size: small;">[<a href="#term_%s">permalink</a>] [<a href="#queries_%s">validation queries</a>] [<a href="#glance">back to top</a>]</p> # todo, push this into an api call (c_ids currently setup by az above) # classes for term in self.vocab.classes: # strings to use later domainsOfClass = '' rangesOfClass = '' #class in domain of g = self.vocab.graph q = 'SELECT ?d ?l WHERE {?d rdfs:domain <%s> . ?d rdfs:label ?l } ' % (term.uri) relations = g.query(q) startStr = '<tr><th>Properties include:</th>\n' contentStr = '' for (domain, label) in relations: dom = Term(domain) # danbri hack 20100101 # termStr = """<a href="#term_%s">%s</a>\n""" % (dom.id, label) termStr = """<a href="#term_%s">%s</a>\n""" % (dom.id, dom.id) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": domainsOfClass = "%s <td> %s </td></tr>" % (startStr, contentStr) # class in range of q2 = 'SELECT ?d ?l WHERE {?d rdfs:range <%s> . ?d rdfs:label ?l } ' % (term.uri) relations2 = g.query(q2) startStr = '<tr><th>Used with:</th>\n' contentStr = '' for (range, label) in relations2: ran = Term(range) # termStr = """<a href="#term_%s">%s</a>\n""" % (ran.id, label) # danbri hack 20100101 better to use exact IDs here termStr = """<a href="#term_%s">%s</a>\n""" % (ran.id, ran.id) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": rangesOfClass = "%s <td> %s</td></tr> " % (startStr, contentStr) # class subclassof subClassOf = '' q = 'SELECT ?sc ?l WHERE {<%s> rdfs:subClassOf ?sc . ?sc rdfs:label ?l } ' % (term.uri) relations = g.query(q) startStr = '<tr><th>Subclass Of</th>\n' contentStr = '' for (subclass, label) in relations: sub = Term(subclass) termStr = """<span rel="rdfs:subClassOf" href="%s"><a href="#term_%s">%s</a></span>\n""" % (subclass, sub.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": subClassOf = "%s <td> %s </td></tr>" % (startStr, contentStr) # class has subclass hasSubClass = '' q = 'SELECT ?sc ?l WHERE {?sc rdfs:subClassOf <%s>. ?sc rdfs:label ?l } ' % (term.uri) relations = g.query(q) startStr = '<tr><th>Has Subclass</th>\n' contentStr = '' for (subclass, label) in relations: sub = Term(subclass) termStr = """<a href="#term_%s">%s</a>\n""" % (sub.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": hasSubClass = "%s <td> %s </td></tr>" % (startStr, contentStr) # is defined by classIsDefinedBy = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) relations = g.query(q) startStr = '\n' contentStr = '' for (isdefinedby) in relations: termStr = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": classIsDefinedBy = "%s <tr><td> %s </td></tr>" % (startStr, contentStr) # disjoint with isDisjointWith = '' q = 'SELECT ?dj ?l WHERE { <%s> <http://www.w3.org/2002/07/owl#disjointWith> ?dj . ?dj rdfs:label ?l } ' % (term.uri) relations = g.query(q) startStr = '<tr><th>Disjoint With:</th>\n' contentStr = '' for (disjointWith, label) in relations: termStr = """<span rel="owl:disjointWith" href="%s"><a href="#term_%s">%s</a></span>\n""" % (disjointWith, label, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": isDisjointWith = "%s <td> %s </td></tr>" % (startStr, contentStr) # end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' # if we want validation queries this is where it looks for them. filename = os.path.join(dn, term.id+".sparql") fileStr = '' try: f = open ( filename, "r") fileStr = f.read() fileStr = "<h4><a name=\"queries_"+term.id+"\"></a>"+term.id+" Validation Query</h4><pre>"+cgi.escape(ss)+"</pre>" except: fileStr='' queries = queries +"\n"+ fileStr sn = self.vocab.niceName(term.uri) s = self.termlink(s) s = self.include_escaped(dn, s) # danbri added another term.id 20010101 and removed term.status zz = eg % (term.id,term.uri,"rdfs:Class","Class", sn, term.label, term.comment, term.status,domainsOfClass,rangesOfClass+subClassOf+hasSubClass+classIsDefinedBy+isDisjointWith, s,term.id, term.id, term.id) ## we add to the relevant string - stable, unstable, testing or archaic if(term.status == "stable"): stableTxt = stableTxt + zz if(term.status == "testing"): testingTxt = testingTxt + zz if(term.status == "unstable"): unstableTxt = unstableTxt + zz if(term.status == "archaic"): archaicTxt = archaicTxt + zz if((term.status == None) or (term.status== "") or (term.status== "unknown")): archaicTxt = archaicTxt + zz ## then add the whole thing to the main tl string tl = tl+"<h2>Classes</h2>\n" tl = "%s %s" % (tl, stableTxt+"\n"+testingTxt+"\n"+unstableTxt+"\n"+archaicTxt) tl = tl+"<h2>Properties</h2>\n" # properties stableTxt = '' testingTxt = '' unstableTxt = '' archaicTxt = '' for term in self.vocab.properties: domainsOfProperty = '' rangesOfProperty = '' # domain of properties g = self.vocab.graph q = 'SELECT ?d ?l WHERE {<%s> rdfs:domain ?d . ?d rdfs:label ?l } ' % (term.uri) relations = g.query(q) startStr = '<tr><th>Domain:</th>\n' contentStr = '' for (domain, label) in relations: dom = Term(domain) termStr = """<span rel="rdfs:domain" href="%s"><a href="#term_%s">%s</a></span>\n""" % (domain, dom.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": domainsOfProperty = "%s <td>%s</td></tr>" % (startStr, contentStr) # range of properties q2 = 'SELECT ?d ?l WHERE {<%s> rdfs:range ?d . ?d rdfs:label ?l } ' % (term.uri) relations2 = g.query(q2) startStr = '<tr><th>Range:</th>\n' contentStr = '' for (range, label) in relations2: ran = Term(range) termStr = """<span rel="rdfs:range" href="%s"><a href="#term_%s">%s</a></span>\n""" % (range, ran.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": rangesOfProperty = "%s <td>%s</td> </tr>" % (startStr, contentStr) # is defined by propertyIsDefinedBy = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) relations = g.query(q) startStr = '\n' contentStr = '' for (isdefinedby) in relations: termStr = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": propertyIsDefinedBy = "%s <tr><td> %s </td></tr>" % (startStr, contentStr) # inverse functional property ifp = '' q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#InverseFunctionalProperty> } ' % (term.uri) relations = g.query(q) startStr = '<tr><th colspan="2">Inverse Functional Property</th>\n' if (len(relations) > 0): termStr = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#InverseFunctionalProperty"></span>""" ifp = "%s <td> %s </td></tr>" % (startStr, termStr)
leth/SpecGen
08fcad5fb525f94ca795e008d6e77711b77d1cfa
Implemented Term.is_external(vocab)
diff --git a/libvocab.py b/libvocab.py index b8ae12c..9ed667e 100755 --- a/libvocab.py +++ b/libvocab.py @@ -1,644 +1,643 @@ #!/usr/bin/env python # total rewrite. --danbri # Usage: # # >>> from libvocab import Vocab, Term, Class, Property # # >>> from libvocab import Vocab, Term, Class, Property # >>> v = Vocab( f='examples/foaf/index.rdf', uri='http://xmlns.com/foaf/0.1/') # >>> dna = v.lookup('http://xmlns.com/foaf/0.1/dnaChecksum') # >>> dna.label # 'DNA checksum' # >>> dna.comment # 'A checksum for the DNA of some thing. Joke.' # >>> dna.id # u'dnaChecksum' # >>> dna.uri # 'http://xmlns.com/foaf/0.1/dnaChecksum' # # # Python OO notes: # http://www.devshed.com/c/a/Python/Object-Oriented-Programming-With-Python-part-1/ # http://www.daniweb.com/code/snippet354.html # http://docs.python.org/reference/datamodel.html#specialnames # # RDFlib: # http://www.science.uva.nl/research/air/wiki/RDFlib # # http://dowhatimean.net/2006/03/spellchecking-vocabularies-with-sparql # # We define basics, Vocab, Term, Property, Class # and populate them with data from RDF schemas, OWL, translations ... and nearby html files. import rdflib from rdflib import term from rdflib.namespace import Namespace from rdflib.graph import Graph, ConjunctiveGraph rdflib.plugin.register('sparql', rdflib.query.Processor, 'rdfextras.sparql.processor', 'Processor') rdflib.plugin.register('sparql', rdflib.query.Result, 'rdfextras.sparql.query', 'SPARQLQueryResult') # pre3: from rdflib.sparql.sparqlGraph import SPARQLGraph #from rdflib.sparql.graphPattern import GraphPattern #from rdflib.sparql import Query FOAF = Namespace('http://xmlns.com/foaf/0.1/') RDFS = Namespace('http://www.w3.org/2000/01/rdf-schema#') XFN = Namespace("http://gmpg.org/xfn/1#") RDF = Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#") OWL = Namespace('http://www.w3.org/2002/07/owl#') VS = Namespace('http://www.w3.org/2003/06/sw-vocab-status/ns#') DC = Namespace('http://purl.org/dc/elements/1.1/') DOAP = Namespace('http://usefulinc.com/ns/doap#') SIOC = Namespace('http://rdfs.org/sioc/ns#') SIOCTYPES = Namespace('http://rdfs.org/sioc/types#') SIOCSERVICES = Namespace('http://rdfs.org/sioc/services#') # # TODO: rationalise these two lists. or at least check they are same. import sys, time, re, urllib, getopt import logging import os.path import cgi import operator def speclog(str): sys.stderr.write("LOG: "+str+"\n") # a Term has... (intrinsically and via it's RDFS/OWL description) # uri - a (primary) URI, eg. 'http://xmlns.com/foaf/0.1/workplaceHomepage' # id - a local-to-spec ID, eg. 'workplaceHomepage' # xmlns - an xmlns URI (isDefinedBy, eg. 'http://xmlns.com/foaf/0.1/') # # label - an rdfs:label # comment - an rdfs:comment # # Beyond this, properties vary. Some have vs:status. Some have owl Deprecated. # Some have OWL descriptions, and RDFS descriptions; eg. property range/domain # or class disjointness. def ns_split(uri): regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) return(rez.group(1), rez.group(2)) class Term(object): def __init__(self, uri='file://dev/null'): self.uri = str(uri) self.uri = self.uri.rstrip() # speclog("Parsing URI " + uri) a,b = ns_split(uri) self.id = b self.xmlns = a if self.id==None: speclog("Error parsing URI. "+uri) if self.xmlns==None: speclog("Error parsing URI. "+uri) # print "self.id: "+ self.id + " self.xmlns: " + self.xmlns def uri(self): try: s = self.uri except NameError: self.uri = None s = '[NOURI]' speclog('No URI for'+self) return s def id(self): print "trying id" try: s = self.id except NameError: self.id = None s = '[NOID]' speclog('No ID for'+self) return str(s) def is_external(self, vocab): - print "Comparing property URI ",self.uri," with vocab uri: " + vocab.uri - return(False) + return not self.uri.startswith(vocab.uri) #def __repr__(self): # return(self.__str__) def __str__(self): try: s = self.id except NameError: self.label = None speclog('No label for '+self+' todo: take from uri regex') s = (str(self)) return(str(s)) # so we can treat this like a string def __add__(self, s): return (s+str(self)) def __radd__(self, s): return (s+str(self)) def simple_report(self): t = self s='' s += "default: \t\t"+t +"\n" s += "id: \t\t"+t.id +"\n" s += "uri: \t\t"+t.uri +"\n" s += "xmlns: \t\t"+t.xmlns +"\n" s += "label: \t\t"+t.label +"\n" s += "comment: \t\t" + t.comment +"\n" s += "status: \t\t" + t.status +"\n" s += "\n" return s def _get_status(self): try: return self._status except: return 'unknown' def _set_status(self, value): self._status = str(value) status = property(_get_status,_set_status) # a Python class representing an RDFS/OWL property. # class Property(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Property.is_property called on "+self return(True) def is_class(self): # print "Property.is_class called on "+self return(False) # A Python class representing an RDFS/OWL class # class Class(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Class.is_property called on "+self return(False) def is_class(self): # print "Class.is_class called on "+self return(True) # A python class representing (a description of) some RDF vocabulary # class Vocab(object): def __init__(self, dir, f='index.rdf', uri=None ): self.graph = ConjunctiveGraph() self._uri = uri self.dir = dir self.filename = os.path.join(dir, f) self.graph.parse(self.filename) self.terms = [] self.uterms = [] # should also load translations here? # and deal with a base-dir? ##if f != None: ## self.index() self.ns_list = { "http://www.w3.org/1999/02/22-rdf-syntax-ns#" : "rdf", "http://www.w3.org/2000/01/rdf-schema#" : "rdfs", "http://www.w3.org/2002/07/owl#" : "owl", "http://www.w3.org/2001/XMLSchema#" : "xsd", "http://rdfs.org/sioc/ns#" : "sioc", "http://xmlns.com/foaf/0.1/" : "foaf", "http://purl.org/dc/elements/1.1/" : "dc", "http://purl.org/dc/terms/" : "dct", "http://usefulinc.com/ns/doap#" : "doap", "http://www.w3.org/2003/06/sw-vocab-status/ns#" : "status", "http://purl.org/rss/1.0/modules/content/" : "content", "http://www.w3.org/2003/01/geo/wgs84_pos#" : "geo", "http://www.w3.org/2004/02/skos/core#" : "skos", "http://purl.org/NET/c4dm/event.owl#" : "event" } def addShortName(self,sn): self.ns_list[self._uri] = sn self.shortName = sn #print self.ns_list # not currently used def unique_terms(self): tmp=[] for t in list(set(self.terms)): s = str(t) if (not s in tmp): self.uterms.append(t) tmp.append(s) # TODO: python question - can we skip needing getters? and only define setters. i tried/failed. --danbri def _get_uri(self): return self._uri def _set_uri(self, value): v = str(value) # we don't want Namespace() objects and suchlike, but we can use them without whining. if ':' not in v: speclog("Warning: this doesn't look like a URI: "+v) # raise Exception("This doesn't look like a URI.") self._uri = str( value ) uri = property(_get_uri,_set_uri) def set_filename(self, filename): self.filename = filename # TODO: be explicit if/where we default to English # TODO: do we need a separate index(), versus just use __init__ ? def index(self): # speclog("Indexing description of "+str(self)) # blank down anything we learned already self.terms = [] self.properties = [] self.classes = [] tmpclasses=[] tmpproperties=[] g = self.graph query = 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a rdf:Property }' relations = g.query(query) for (term, label, comment) in relations: p = Property(term) # print "Made a property! "+str(p) + "using label: "#+str(label) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) query = 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type FILTER (?type = <http://www.w3.org/2002/07/owl#Class> || ?type = <http://www.w3.org/2000/01/rdf-schema#Class> ) }' relations = g.query(query) for (term, label, comment) in relations: c = Class(term) # print "Made a class! "+str(p) + "using comment: "+comment c.label = str(label) c.comment = str(comment) self.terms.append(c) if (not str(c) in tmpclasses): self.classes.append(c) tmpclasses.append(str(c)) self.terms.sort(key=operator.attrgetter('id')) self.classes.sort(key=operator.attrgetter('id')) self.properties.sort(key=operator.attrgetter('id')) # http://www.w3.org/2003/06/sw-vocab-status/ns#" query = 'SELECT ?x ?vs WHERE { ?x <http://www.w3.org/2003/06/sw-vocab-status/ns#term_status> ?vs }' status = g.query(query) # print "status results: ",status.__len__() for x, vs in status: #print "STATUS: ",vs, " for ",x t = self.lookup(x) if t != None: t.status = vs # print "Set status.", t.status else: speclog("Couldn't lookup term: "+x) # Go back and see if we missed any properties defined in OWL. TODO: classes too. Or rewrite above SPARQL. addd more types for full query. q= 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty>)}' q= 'SELECT distinct ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty> || ?type = <http://www.w3.org/2002/07/owl#DatatypeProperty> || ?type = <http://www.w3.org/1999/02/22-rdf-syntax-ns#Property> || ?type = <http://www.w3.org/2002/07/owl#FunctionalProperty> || ?type = <http://www.w3.org/2002/07/owl#InverseFunctionalProperty>) } ' relations = g.query(q) for (term, label, comment) in relations: p = Property(str(term)) got = self.lookup( str(term) ) if got==None: # print "Made an OWL property! "+str(p.uri) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) # self.terms.sort() # does this even do anything? # self.classes.sort() # self.properties.sort() # todo, use a dictionary index instead. RTFM. def lookup(self, uri): uri = str(uri) for t in self.terms: # print "Lookup: comparing '"+t.uri+"' to '"+uri+"'" # print "type of t.uri is ",t.uri.__class__ if t.uri==uri: # print "Matched." # should we str here, to be more liberal? return t else: # print "Fail." '' return None # print a raw debug summary, direct from the RDF def raw(self): g = self.graph query = 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c } ' relations = g.query(query) print "Properties and Classes (%d terms)" % len(relations) print 40*"-" for (term, label, comment) in relations: print "term %s l: %s \t\tc: %s " % (term, label, comment) print # TODO: work out how to do ".encode('UTF-8')" here # for debugging only def detect_types(self): self.properties = [] self.classes = [] for t in self.terms: # print "Doing t: "+t+" which is of type " + str(t.__class__) if t.is_property(): # print "is_property." self.properties.append(t) if t.is_class(): # print "is_class." self.classes.append(t) # CODE FROM ORIGINAL specgen: def niceName(self, uri = None ): if uri is None: return # speclog("Nicing uri "+uri) regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) if rez == None: #print "Failed to niceName. Returning the whole thing." return(uri) pref = rez.group(1) # print "...",self.ns_list.get(pref, pref),":",rez.group(2) # todo: make this work when uri doesn't match the regex --danbri # AttributeError: 'NoneType' object has no attribute 'group' return self.ns_list.get(pref, pref) + ":" + rez.group(2) # HTML stuff, should be a separate class def azlist(self): """Builds the A-Z list of terms""" c_ids = [] p_ids = [] for p in self.properties: p_ids.append(str(p.id)) for c in self.classes: c_ids.append(str(c.id)) c_ids.sort() p_ids.sort() return (c_ids, p_ids) class VocabReport(object): def __init__(self, vocab, basedir='./examples/', temploc='template.html',templatedir='./examples/'): self.vocab = vocab self.basedir = basedir self.temploc = temploc self.templatedir = templatedir self._template = "no template loaded" # text.gsub(/<code>foaf:(\w+)<\/code>/){ defurl($1) } return "<code><a href=\"#term_#{term}\">foaf:#{term}</a></code>" def codelink(self, s): reg1 = re.compile(r"""<code>foaf:(\w+)<\/code>""") return(re.sub(reg1, r"""<code><a href="#term_\1">foaf:\1</a></code>""", s)) def _get_template(self): self._template = self.load_template() # should be conditional return self._template def _set_template(self, value): self._template = str(value) template = property(_get_template,_set_template) def load_template(self): filename = os.path.join(self.templatedir, self.temploc) f = open(filename, "r") template = f.read() return(template) def generate(self): tpl = self.template azlist = self.az() termlist = self.termlist() f = open ( self.vocab.filename, "r") rdfdata = f.read() # print "GENERATING >>>>>>>> " ## having the rdf in there was making it invalid ## removed in favour of RDFa ## tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8"), rdfdata) tpl = tpl % (azlist.encode("utf-8"), azlist.encode("utf-8"), termlist.encode("utf-8")) # tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8")) return(tpl) def az(self): """AZ List for html doc""" c_ids, p_ids = self.vocab.azlist() az = """<div class="azlist">""" az = """%s\n<p>Classes: |""" % az # print c_ids, p_ids for c in c_ids: # speclog("Class "+c+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(c).replace(" ", ""), c) az = """%s\n</p>""" % az az = """%s\n<p>Properties: |""" % az for p in p_ids: # speclog("Property "+p+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(p).replace(" ", ""), p) az = """%s\n</p>""" % az az = """%s\n</div>""" % az return(az) def termlist(self): """Term List for html doc""" stableTxt = '' testingTxt = '' unstableTxt = '' archaicTxt = '' queries = '' c_ids, p_ids = self.vocab.azlist() tl = """<div class="termlist">""" tl = """%s<h3>Classes and Properties (full detail)</h3>\n<div class='termdetails'><br />\n\n""" % tl # danbri hack 20100101 removed: href="http://www.w3.org/2003/06/sw-vocab-status/ns#%s" pending discussion w/ libby and leigh re URIs # first classes, then properties eg = """<div class="specterm" id="term_%s" about="%s" typeof="%s"> <h3>%s: %s</h3> <em>%s</em> - %s <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span property="vs:status" >%s</span></td></tr> %s %s </table> %s <p style="float: right; font-size: small;">[<a href="#term_%s">#</a>] [<a href="http://wiki.foaf-project.org/w/term_%s">wiki</a>] <!-- %s --> [<a href="#glance">back to top</a>]</p> <br/> </div>""" # replace this if you want validation queries: xxx danbri # <p style="float: right; font-size: small;">[<a href="#term_%s">permalink</a>] [<a href="#queries_%s">validation queries</a>] [<a href="#glance">back to top</a>]</p> # todo, push this into an api call (c_ids currently setup by az above) # classes for term in self.vocab.classes: # strings to use later domainsOfClass = '' rangesOfClass = '' #class in domain of g = self.vocab.graph q = 'SELECT ?d ?l WHERE {?d rdfs:domain <%s> . ?d rdfs:label ?l } ' % (term.uri) relations = g.query(q) startStr = '<tr><th>Properties include:</th>\n' contentStr = '' for (domain, label) in relations: dom = Term(domain) # danbri hack 20100101 # termStr = """<a href="#term_%s">%s</a>\n""" % (dom.id, label) termStr = """<a href="#term_%s">%s</a>\n""" % (dom.id, dom.id) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": domainsOfClass = "%s <td> %s </td></tr>" % (startStr, contentStr) # class in range of q2 = 'SELECT ?d ?l WHERE {?d rdfs:range <%s> . ?d rdfs:label ?l } ' % (term.uri) relations2 = g.query(q2) startStr = '<tr><th>Used with:</th>\n' contentStr = '' for (range, label) in relations2: ran = Term(range) # termStr = """<a href="#term_%s">%s</a>\n""" % (ran.id, label) # danbri hack 20100101 better to use exact IDs here termStr = """<a href="#term_%s">%s</a>\n""" % (ran.id, ran.id) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": rangesOfClass = "%s <td> %s</td></tr> " % (startStr, contentStr) # class subclassof subClassOf = '' q = 'SELECT ?sc ?l WHERE {<%s> rdfs:subClassOf ?sc . ?sc rdfs:label ?l } ' % (term.uri) relations = g.query(q) startStr = '<tr><th>Subclass Of</th>\n' contentStr = '' for (subclass, label) in relations: sub = Term(subclass) termStr = """<span rel="rdfs:subClassOf" href="%s"><a href="#term_%s">%s</a></span>\n""" % (subclass, sub.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": subClassOf = "%s <td> %s </td></tr>" % (startStr, contentStr) # class has subclass hasSubClass = '' q = 'SELECT ?sc ?l WHERE {?sc rdfs:subClassOf <%s>. ?sc rdfs:label ?l } ' % (term.uri) relations = g.query(q) startStr = '<tr><th>Has Subclass</th>\n' contentStr = '' for (subclass, label) in relations: sub = Term(subclass) termStr = """<a href="#term_%s">%s</a>\n""" % (sub.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": hasSubClass = "%s <td> %s </td></tr>" % (startStr, contentStr) # is defined by classIsDefinedBy = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) relations = g.query(q) startStr = '\n' contentStr = '' for (isdefinedby) in relations: termStr = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": classIsDefinedBy = "%s <tr><td> %s </td></tr>" % (startStr, contentStr) # disjoint with isDisjointWith = '' q = 'SELECT ?dj ?l WHERE { <%s> <http://www.w3.org/2002/07/owl#disjointWith> ?dj . ?dj rdfs:label ?l } ' % (term.uri) relations = g.query(q) startStr = '<tr><th>Disjoint With:</th>\n' contentStr = '' for (disjointWith, label) in relations: termStr = """<span rel="owl:disjointWith" href="%s"><a href="#term_%s">%s</a></span>\n""" % (disjointWith, label, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": isDisjointWith = "%s <td> %s </td></tr>" % (startStr, contentStr) # end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try:
leth/SpecGen
514bdc0ab7b4c4a0073192778436f0e6731ba1b0
Added include directives to documentation files
diff --git a/libvocab.py b/libvocab.py index a67c75a..b8ae12c 100755 --- a/libvocab.py +++ b/libvocab.py @@ -151,696 +151,711 @@ class Term(object): return (s+str(self)) def simple_report(self): t = self s='' s += "default: \t\t"+t +"\n" s += "id: \t\t"+t.id +"\n" s += "uri: \t\t"+t.uri +"\n" s += "xmlns: \t\t"+t.xmlns +"\n" s += "label: \t\t"+t.label +"\n" s += "comment: \t\t" + t.comment +"\n" s += "status: \t\t" + t.status +"\n" s += "\n" return s def _get_status(self): try: return self._status except: return 'unknown' def _set_status(self, value): self._status = str(value) status = property(_get_status,_set_status) # a Python class representing an RDFS/OWL property. # class Property(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Property.is_property called on "+self return(True) def is_class(self): # print "Property.is_class called on "+self return(False) # A Python class representing an RDFS/OWL class # class Class(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Class.is_property called on "+self return(False) def is_class(self): # print "Class.is_class called on "+self return(True) # A python class representing (a description of) some RDF vocabulary # class Vocab(object): def __init__(self, dir, f='index.rdf', uri=None ): self.graph = ConjunctiveGraph() self._uri = uri self.dir = dir self.filename = os.path.join(dir, f) self.graph.parse(self.filename) self.terms = [] self.uterms = [] # should also load translations here? # and deal with a base-dir? ##if f != None: ## self.index() self.ns_list = { "http://www.w3.org/1999/02/22-rdf-syntax-ns#" : "rdf", "http://www.w3.org/2000/01/rdf-schema#" : "rdfs", "http://www.w3.org/2002/07/owl#" : "owl", "http://www.w3.org/2001/XMLSchema#" : "xsd", "http://rdfs.org/sioc/ns#" : "sioc", "http://xmlns.com/foaf/0.1/" : "foaf", "http://purl.org/dc/elements/1.1/" : "dc", "http://purl.org/dc/terms/" : "dct", "http://usefulinc.com/ns/doap#" : "doap", "http://www.w3.org/2003/06/sw-vocab-status/ns#" : "status", "http://purl.org/rss/1.0/modules/content/" : "content", "http://www.w3.org/2003/01/geo/wgs84_pos#" : "geo", "http://www.w3.org/2004/02/skos/core#" : "skos", "http://purl.org/NET/c4dm/event.owl#" : "event" } def addShortName(self,sn): self.ns_list[self._uri] = sn self.shortName = sn #print self.ns_list # not currently used def unique_terms(self): tmp=[] for t in list(set(self.terms)): s = str(t) if (not s in tmp): self.uterms.append(t) tmp.append(s) # TODO: python question - can we skip needing getters? and only define setters. i tried/failed. --danbri def _get_uri(self): return self._uri def _set_uri(self, value): v = str(value) # we don't want Namespace() objects and suchlike, but we can use them without whining. if ':' not in v: speclog("Warning: this doesn't look like a URI: "+v) # raise Exception("This doesn't look like a URI.") self._uri = str( value ) uri = property(_get_uri,_set_uri) def set_filename(self, filename): self.filename = filename # TODO: be explicit if/where we default to English # TODO: do we need a separate index(), versus just use __init__ ? def index(self): # speclog("Indexing description of "+str(self)) # blank down anything we learned already self.terms = [] self.properties = [] self.classes = [] tmpclasses=[] tmpproperties=[] g = self.graph query = 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a rdf:Property }' relations = g.query(query) for (term, label, comment) in relations: p = Property(term) # print "Made a property! "+str(p) + "using label: "#+str(label) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) query = 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type FILTER (?type = <http://www.w3.org/2002/07/owl#Class> || ?type = <http://www.w3.org/2000/01/rdf-schema#Class> ) }' relations = g.query(query) for (term, label, comment) in relations: c = Class(term) # print "Made a class! "+str(p) + "using comment: "+comment c.label = str(label) c.comment = str(comment) self.terms.append(c) if (not str(c) in tmpclasses): self.classes.append(c) tmpclasses.append(str(c)) self.terms.sort(key=operator.attrgetter('id')) self.classes.sort(key=operator.attrgetter('id')) self.properties.sort(key=operator.attrgetter('id')) # http://www.w3.org/2003/06/sw-vocab-status/ns#" query = 'SELECT ?x ?vs WHERE { ?x <http://www.w3.org/2003/06/sw-vocab-status/ns#term_status> ?vs }' status = g.query(query) # print "status results: ",status.__len__() for x, vs in status: #print "STATUS: ",vs, " for ",x t = self.lookup(x) if t != None: t.status = vs # print "Set status.", t.status else: speclog("Couldn't lookup term: "+x) # Go back and see if we missed any properties defined in OWL. TODO: classes too. Or rewrite above SPARQL. addd more types for full query. q= 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty>)}' q= 'SELECT distinct ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty> || ?type = <http://www.w3.org/2002/07/owl#DatatypeProperty> || ?type = <http://www.w3.org/1999/02/22-rdf-syntax-ns#Property> || ?type = <http://www.w3.org/2002/07/owl#FunctionalProperty> || ?type = <http://www.w3.org/2002/07/owl#InverseFunctionalProperty>) } ' relations = g.query(q) for (term, label, comment) in relations: p = Property(str(term)) got = self.lookup( str(term) ) if got==None: # print "Made an OWL property! "+str(p.uri) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) # self.terms.sort() # does this even do anything? # self.classes.sort() # self.properties.sort() # todo, use a dictionary index instead. RTFM. def lookup(self, uri): uri = str(uri) for t in self.terms: # print "Lookup: comparing '"+t.uri+"' to '"+uri+"'" # print "type of t.uri is ",t.uri.__class__ if t.uri==uri: # print "Matched." # should we str here, to be more liberal? return t else: # print "Fail." '' return None # print a raw debug summary, direct from the RDF def raw(self): g = self.graph query = 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c } ' relations = g.query(query) print "Properties and Classes (%d terms)" % len(relations) print 40*"-" for (term, label, comment) in relations: print "term %s l: %s \t\tc: %s " % (term, label, comment) print # TODO: work out how to do ".encode('UTF-8')" here # for debugging only def detect_types(self): self.properties = [] self.classes = [] for t in self.terms: # print "Doing t: "+t+" which is of type " + str(t.__class__) if t.is_property(): # print "is_property." self.properties.append(t) if t.is_class(): # print "is_class." self.classes.append(t) # CODE FROM ORIGINAL specgen: def niceName(self, uri = None ): if uri is None: return # speclog("Nicing uri "+uri) regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) if rez == None: #print "Failed to niceName. Returning the whole thing." return(uri) pref = rez.group(1) # print "...",self.ns_list.get(pref, pref),":",rez.group(2) # todo: make this work when uri doesn't match the regex --danbri # AttributeError: 'NoneType' object has no attribute 'group' return self.ns_list.get(pref, pref) + ":" + rez.group(2) # HTML stuff, should be a separate class def azlist(self): """Builds the A-Z list of terms""" c_ids = [] p_ids = [] for p in self.properties: p_ids.append(str(p.id)) for c in self.classes: c_ids.append(str(c.id)) c_ids.sort() p_ids.sort() return (c_ids, p_ids) class VocabReport(object): def __init__(self, vocab, basedir='./examples/', temploc='template.html',templatedir='./examples/'): self.vocab = vocab self.basedir = basedir self.temploc = temploc self.templatedir = templatedir self._template = "no template loaded" # text.gsub(/<code>foaf:(\w+)<\/code>/){ defurl($1) } return "<code><a href=\"#term_#{term}\">foaf:#{term}</a></code>" def codelink(self, s): reg1 = re.compile(r"""<code>foaf:(\w+)<\/code>""") return(re.sub(reg1, r"""<code><a href="#term_\1">foaf:\1</a></code>""", s)) def _get_template(self): self._template = self.load_template() # should be conditional return self._template def _set_template(self, value): self._template = str(value) template = property(_get_template,_set_template) def load_template(self): filename = os.path.join(self.templatedir, self.temploc) f = open(filename, "r") template = f.read() return(template) def generate(self): tpl = self.template azlist = self.az() termlist = self.termlist() f = open ( self.vocab.filename, "r") rdfdata = f.read() # print "GENERATING >>>>>>>> " ## having the rdf in there was making it invalid ## removed in favour of RDFa ## tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8"), rdfdata) tpl = tpl % (azlist.encode("utf-8"), azlist.encode("utf-8"), termlist.encode("utf-8")) # tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8")) return(tpl) def az(self): """AZ List for html doc""" c_ids, p_ids = self.vocab.azlist() az = """<div class="azlist">""" az = """%s\n<p>Classes: |""" % az # print c_ids, p_ids for c in c_ids: # speclog("Class "+c+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(c).replace(" ", ""), c) az = """%s\n</p>""" % az az = """%s\n<p>Properties: |""" % az for p in p_ids: # speclog("Property "+p+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(p).replace(" ", ""), p) az = """%s\n</p>""" % az az = """%s\n</div>""" % az return(az) def termlist(self): """Term List for html doc""" stableTxt = '' testingTxt = '' unstableTxt = '' archaicTxt = '' queries = '' c_ids, p_ids = self.vocab.azlist() tl = """<div class="termlist">""" tl = """%s<h3>Classes and Properties (full detail)</h3>\n<div class='termdetails'><br />\n\n""" % tl # danbri hack 20100101 removed: href="http://www.w3.org/2003/06/sw-vocab-status/ns#%s" pending discussion w/ libby and leigh re URIs # first classes, then properties eg = """<div class="specterm" id="term_%s" about="%s" typeof="%s"> <h3>%s: %s</h3> <em>%s</em> - %s <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span property="vs:status" >%s</span></td></tr> %s %s </table> %s <p style="float: right; font-size: small;">[<a href="#term_%s">#</a>] [<a href="http://wiki.foaf-project.org/w/term_%s">wiki</a>] <!-- %s --> [<a href="#glance">back to top</a>]</p> <br/> </div>""" # replace this if you want validation queries: xxx danbri # <p style="float: right; font-size: small;">[<a href="#term_%s">permalink</a>] [<a href="#queries_%s">validation queries</a>] [<a href="#glance">back to top</a>]</p> # todo, push this into an api call (c_ids currently setup by az above) # classes for term in self.vocab.classes: # strings to use later domainsOfClass = '' rangesOfClass = '' #class in domain of g = self.vocab.graph q = 'SELECT ?d ?l WHERE {?d rdfs:domain <%s> . ?d rdfs:label ?l } ' % (term.uri) relations = g.query(q) startStr = '<tr><th>Properties include:</th>\n' contentStr = '' for (domain, label) in relations: dom = Term(domain) # danbri hack 20100101 # termStr = """<a href="#term_%s">%s</a>\n""" % (dom.id, label) termStr = """<a href="#term_%s">%s</a>\n""" % (dom.id, dom.id) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": domainsOfClass = "%s <td> %s </td></tr>" % (startStr, contentStr) # class in range of q2 = 'SELECT ?d ?l WHERE {?d rdfs:range <%s> . ?d rdfs:label ?l } ' % (term.uri) relations2 = g.query(q2) startStr = '<tr><th>Used with:</th>\n' contentStr = '' for (range, label) in relations2: ran = Term(range) # termStr = """<a href="#term_%s">%s</a>\n""" % (ran.id, label) # danbri hack 20100101 better to use exact IDs here termStr = """<a href="#term_%s">%s</a>\n""" % (ran.id, ran.id) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": rangesOfClass = "%s <td> %s</td></tr> " % (startStr, contentStr) # class subclassof subClassOf = '' q = 'SELECT ?sc ?l WHERE {<%s> rdfs:subClassOf ?sc . ?sc rdfs:label ?l } ' % (term.uri) relations = g.query(q) startStr = '<tr><th>Subclass Of</th>\n' contentStr = '' for (subclass, label) in relations: sub = Term(subclass) termStr = """<span rel="rdfs:subClassOf" href="%s"><a href="#term_%s">%s</a></span>\n""" % (subclass, sub.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": subClassOf = "%s <td> %s </td></tr>" % (startStr, contentStr) # class has subclass hasSubClass = '' q = 'SELECT ?sc ?l WHERE {?sc rdfs:subClassOf <%s>. ?sc rdfs:label ?l } ' % (term.uri) relations = g.query(q) startStr = '<tr><th>Has Subclass</th>\n' contentStr = '' for (subclass, label) in relations: sub = Term(subclass) termStr = """<a href="#term_%s">%s</a>\n""" % (sub.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": hasSubClass = "%s <td> %s </td></tr>" % (startStr, contentStr) # is defined by classIsDefinedBy = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) relations = g.query(q) startStr = '\n' contentStr = '' for (isdefinedby) in relations: termStr = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": classIsDefinedBy = "%s <tr><td> %s </td></tr>" % (startStr, contentStr) # disjoint with isDisjointWith = '' q = 'SELECT ?dj ?l WHERE { <%s> <http://www.w3.org/2002/07/owl#disjointWith> ?dj . ?dj rdfs:label ?l } ' % (term.uri) relations = g.query(q) startStr = '<tr><th>Disjoint With:</th>\n' contentStr = '' for (disjointWith, label) in relations: termStr = """<span rel="owl:disjointWith" href="%s"><a href="#term_%s">%s</a></span>\n""" % (disjointWith, label, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": isDisjointWith = "%s <td> %s </td></tr>" % (startStr, contentStr) # end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' # if we want validation queries this is where it looks for them. filename = os.path.join(dn, term.id+".sparql") fileStr = '' try: f = open ( filename, "r") fileStr = f.read() fileStr = "<h4><a name=\"queries_"+term.id+"\"></a>"+term.id+" Validation Query</h4><pre>"+cgi.escape(ss)+"</pre>" except: fileStr='' queries = queries +"\n"+ fileStr sn = self.vocab.niceName(term.uri) s = self.termlink(s) + s = self.include_escaped(dn, s) # danbri added another term.id 20010101 and removed term.status zz = eg % (term.id,term.uri,"rdfs:Class","Class", sn, term.label, term.comment, term.status,domainsOfClass,rangesOfClass+subClassOf+hasSubClass+classIsDefinedBy+isDisjointWith, s,term.id, term.id, term.id) ## we add to the relevant string - stable, unstable, testing or archaic if(term.status == "stable"): stableTxt = stableTxt + zz if(term.status == "testing"): testingTxt = testingTxt + zz if(term.status == "unstable"): unstableTxt = unstableTxt + zz if(term.status == "archaic"): archaicTxt = archaicTxt + zz if((term.status == None) or (term.status== "") or (term.status== "unknown")): archaicTxt = archaicTxt + zz ## then add the whole thing to the main tl string tl = tl+"<h2>Classes</h2>\n" tl = "%s %s" % (tl, stableTxt+"\n"+testingTxt+"\n"+unstableTxt+"\n"+archaicTxt) tl = tl+"<h2>Properties</h2>\n" # properties stableTxt = '' testingTxt = '' unstableTxt = '' archaicTxt = '' for term in self.vocab.properties: domainsOfProperty = '' rangesOfProperty = '' # domain of properties g = self.vocab.graph q = 'SELECT ?d ?l WHERE {<%s> rdfs:domain ?d . ?d rdfs:label ?l } ' % (term.uri) relations = g.query(q) startStr = '<tr><th>Domain:</th>\n' contentStr = '' for (domain, label) in relations: dom = Term(domain) termStr = """<span rel="rdfs:domain" href="%s"><a href="#term_%s">%s</a></span>\n""" % (domain, dom.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": domainsOfProperty = "%s <td>%s</td></tr>" % (startStr, contentStr) # range of properties q2 = 'SELECT ?d ?l WHERE {<%s> rdfs:range ?d . ?d rdfs:label ?l } ' % (term.uri) relations2 = g.query(q2) startStr = '<tr><th>Range:</th>\n' contentStr = '' for (range, label) in relations2: ran = Term(range) termStr = """<span rel="rdfs:range" href="%s"><a href="#term_%s">%s</a></span>\n""" % (range, ran.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": rangesOfProperty = "%s <td>%s</td> </tr>" % (startStr, contentStr) # is defined by propertyIsDefinedBy = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) relations = g.query(q) startStr = '\n' contentStr = '' for (isdefinedby) in relations: termStr = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": propertyIsDefinedBy = "%s <tr><td> %s </td></tr>" % (startStr, contentStr) # inverse functional property ifp = '' q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#InverseFunctionalProperty> } ' % (term.uri) relations = g.query(q) startStr = '<tr><th colspan="2">Inverse Functional Property</th>\n' if (len(relations) > 0): termStr = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#InverseFunctionalProperty"></span>""" ifp = "%s <td> %s </td></tr>" % (startStr, termStr) # functonal property fp = '' q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#FunctionalProperty> } ' % (term.uri) relations = g.query(q) startStr = '<tr><th colspan="2">Functional Property</th>\n' if (len(relations) > 0): termStr = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#FunctionalProperty"></span>""" fp = "%s <td> %s </td></tr>" % (startStr, termStr) # end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' sn = self.vocab.niceName(term.uri) s = self.termlink(s) + s = self.include_escaped(dn, s) # danbri added another term.id 20010101 zz = eg % (term.id, term.uri,"rdf:Property","Property", sn, term.label, term.comment,term.status,domainsOfProperty,rangesOfProperty+propertyIsDefinedBy+ifp+fp, s,term.id, term.id, term.id) ## we add to the relevant string - stable, unstable, testing or archaic if(term.status == "stable"): stableTxt = stableTxt + zz if(term.status == "testing"): testingTxt = testingTxt + zz if(term.status == "unstable"): unstableTxt = unstableTxt + zz if(term.status == "archaic"): archaicTxt = archaicTxt + zz if((term.status == None) or (term.status== "") or (term.status== "unknown")): archaicTxt = archaicTxt + zz ## then add the whole thing to the main tl string tl = "%s %s" % (tl, stableTxt+"\n"+testingTxt+"\n"+unstableTxt+"\n"+archaicTxt) ## tl = "%s %s" % (tl, zz) ## ensure termlist tag is closed return(tl+"\n"+queries+"</div>\n</div>") def rdfa(self): return( "<html>rdfa here</html>") def termlink(self, text): result = text for base, ns in self.vocab.ns_list.iteritems(): if (base == self.vocab.uri): result = re.sub(r"<code>%s:(\w+)<\/code>" % ns, r"<code><a href='#term_\g<1>'>\g<1></a></code>", result ) else: result = re.sub(r"<code>%s:(\w+)<\/code>" % ns, r"<code><a href='%s\g<1>'>%s:\g<1></a></code>" % (base, ns), result ) return result + def include_escaped(self, termdir, text): + includes = re.finditer(r"<include>(.*)</include>", text) + + for match in includes: + f = open("%s/%s.en" % (termdir, match.group(1)), "r") + inc = cgi.escape(f.read()) + f.close() + + text = text[:match.start()] + inc + text[match.end():] + + return text + def htmlDocInfo( t, termdir='../docs' ): """Opens a file based on the term name (t) and termdir (defaults to current directory. Reads in the file, and returns a linkified version of it.""" if termdir==None: termdir=self.basedir doc = "" try: f = open("%s/%s.en" % (termdir, t), "r") doc = f.read() doc = self.termlink(doc) + doc = self.include_escaped(termdir, doc) except: return "<p>No detailed documentation for this term.</p>" return doc # report what we've parsed from our various sources def report(self): s = "Report for vocabulary from " + self.vocab.filename + "\n" if self.vocab.uri != None: s += "URI: " + self.vocab.uri + "\n\n" for t in self.vocab.uterms: print "TERM as string: ",t s += t.simple_report() return s
leth/SpecGen
6a3846886e2ce33ff47dc79717673d6f07896923
Made the documentation termlinking un-foaf-specific.
diff --git a/libvocab.py b/libvocab.py index ee45192..a67c75a 100755 --- a/libvocab.py +++ b/libvocab.py @@ -1,843 +1,846 @@ #!/usr/bin/env python # total rewrite. --danbri # Usage: # # >>> from libvocab import Vocab, Term, Class, Property # # >>> from libvocab import Vocab, Term, Class, Property # >>> v = Vocab( f='examples/foaf/index.rdf', uri='http://xmlns.com/foaf/0.1/') # >>> dna = v.lookup('http://xmlns.com/foaf/0.1/dnaChecksum') # >>> dna.label # 'DNA checksum' # >>> dna.comment # 'A checksum for the DNA of some thing. Joke.' # >>> dna.id # u'dnaChecksum' # >>> dna.uri # 'http://xmlns.com/foaf/0.1/dnaChecksum' # # # Python OO notes: # http://www.devshed.com/c/a/Python/Object-Oriented-Programming-With-Python-part-1/ # http://www.daniweb.com/code/snippet354.html # http://docs.python.org/reference/datamodel.html#specialnames # # RDFlib: # http://www.science.uva.nl/research/air/wiki/RDFlib # # http://dowhatimean.net/2006/03/spellchecking-vocabularies-with-sparql # # We define basics, Vocab, Term, Property, Class # and populate them with data from RDF schemas, OWL, translations ... and nearby html files. import rdflib from rdflib import term from rdflib.namespace import Namespace from rdflib.graph import Graph, ConjunctiveGraph rdflib.plugin.register('sparql', rdflib.query.Processor, 'rdfextras.sparql.processor', 'Processor') rdflib.plugin.register('sparql', rdflib.query.Result, 'rdfextras.sparql.query', 'SPARQLQueryResult') # pre3: from rdflib.sparql.sparqlGraph import SPARQLGraph #from rdflib.sparql.graphPattern import GraphPattern #from rdflib.sparql import Query FOAF = Namespace('http://xmlns.com/foaf/0.1/') RDFS = Namespace('http://www.w3.org/2000/01/rdf-schema#') XFN = Namespace("http://gmpg.org/xfn/1#") RDF = Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#") OWL = Namespace('http://www.w3.org/2002/07/owl#') VS = Namespace('http://www.w3.org/2003/06/sw-vocab-status/ns#') DC = Namespace('http://purl.org/dc/elements/1.1/') DOAP = Namespace('http://usefulinc.com/ns/doap#') SIOC = Namespace('http://rdfs.org/sioc/ns#') SIOCTYPES = Namespace('http://rdfs.org/sioc/types#') SIOCSERVICES = Namespace('http://rdfs.org/sioc/services#') # # TODO: rationalise these two lists. or at least check they are same. import sys, time, re, urllib, getopt import logging import os.path import cgi import operator def speclog(str): sys.stderr.write("LOG: "+str+"\n") -# todo: shouldn't be foaf specific -def termlink(text): - result = re.sub( r"<code>foaf:(\w+)<\/code>", r"<code><a href='#term_\g<1>'>\g<1></a></code>", text ) - return result - # a Term has... (intrinsically and via it's RDFS/OWL description) # uri - a (primary) URI, eg. 'http://xmlns.com/foaf/0.1/workplaceHomepage' # id - a local-to-spec ID, eg. 'workplaceHomepage' # xmlns - an xmlns URI (isDefinedBy, eg. 'http://xmlns.com/foaf/0.1/') # # label - an rdfs:label # comment - an rdfs:comment # # Beyond this, properties vary. Some have vs:status. Some have owl Deprecated. # Some have OWL descriptions, and RDFS descriptions; eg. property range/domain # or class disjointness. def ns_split(uri): regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) return(rez.group(1), rez.group(2)) class Term(object): def __init__(self, uri='file://dev/null'): self.uri = str(uri) self.uri = self.uri.rstrip() # speclog("Parsing URI " + uri) a,b = ns_split(uri) self.id = b self.xmlns = a if self.id==None: speclog("Error parsing URI. "+uri) if self.xmlns==None: speclog("Error parsing URI. "+uri) # print "self.id: "+ self.id + " self.xmlns: " + self.xmlns def uri(self): try: s = self.uri except NameError: self.uri = None s = '[NOURI]' speclog('No URI for'+self) return s def id(self): print "trying id" try: s = self.id except NameError: self.id = None s = '[NOID]' speclog('No ID for'+self) return str(s) def is_external(self, vocab): print "Comparing property URI ",self.uri," with vocab uri: " + vocab.uri return(False) #def __repr__(self): # return(self.__str__) def __str__(self): try: s = self.id except NameError: self.label = None speclog('No label for '+self+' todo: take from uri regex') s = (str(self)) return(str(s)) # so we can treat this like a string def __add__(self, s): return (s+str(self)) def __radd__(self, s): return (s+str(self)) def simple_report(self): t = self s='' s += "default: \t\t"+t +"\n" s += "id: \t\t"+t.id +"\n" s += "uri: \t\t"+t.uri +"\n" s += "xmlns: \t\t"+t.xmlns +"\n" s += "label: \t\t"+t.label +"\n" s += "comment: \t\t" + t.comment +"\n" s += "status: \t\t" + t.status +"\n" s += "\n" return s def _get_status(self): try: return self._status except: return 'unknown' def _set_status(self, value): self._status = str(value) status = property(_get_status,_set_status) # a Python class representing an RDFS/OWL property. # class Property(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Property.is_property called on "+self return(True) def is_class(self): # print "Property.is_class called on "+self return(False) # A Python class representing an RDFS/OWL class # class Class(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Class.is_property called on "+self return(False) def is_class(self): # print "Class.is_class called on "+self return(True) # A python class representing (a description of) some RDF vocabulary # class Vocab(object): def __init__(self, dir, f='index.rdf', uri=None ): self.graph = ConjunctiveGraph() self._uri = uri self.dir = dir self.filename = os.path.join(dir, f) self.graph.parse(self.filename) self.terms = [] self.uterms = [] # should also load translations here? # and deal with a base-dir? ##if f != None: ## self.index() self.ns_list = { "http://www.w3.org/1999/02/22-rdf-syntax-ns#" : "rdf", "http://www.w3.org/2000/01/rdf-schema#" : "rdfs", "http://www.w3.org/2002/07/owl#" : "owl", "http://www.w3.org/2001/XMLSchema#" : "xsd", "http://rdfs.org/sioc/ns#" : "sioc", "http://xmlns.com/foaf/0.1/" : "foaf", "http://purl.org/dc/elements/1.1/" : "dc", "http://purl.org/dc/terms/" : "dct", "http://usefulinc.com/ns/doap#" : "doap", "http://www.w3.org/2003/06/sw-vocab-status/ns#" : "status", "http://purl.org/rss/1.0/modules/content/" : "content", "http://www.w3.org/2003/01/geo/wgs84_pos#" : "geo", "http://www.w3.org/2004/02/skos/core#" : "skos", "http://purl.org/NET/c4dm/event.owl#" : "event" } def addShortName(self,sn): self.ns_list[self._uri] = sn self.shortName = sn #print self.ns_list # not currently used def unique_terms(self): tmp=[] for t in list(set(self.terms)): s = str(t) if (not s in tmp): self.uterms.append(t) tmp.append(s) # TODO: python question - can we skip needing getters? and only define setters. i tried/failed. --danbri def _get_uri(self): return self._uri def _set_uri(self, value): v = str(value) # we don't want Namespace() objects and suchlike, but we can use them without whining. if ':' not in v: speclog("Warning: this doesn't look like a URI: "+v) # raise Exception("This doesn't look like a URI.") self._uri = str( value ) uri = property(_get_uri,_set_uri) def set_filename(self, filename): self.filename = filename # TODO: be explicit if/where we default to English # TODO: do we need a separate index(), versus just use __init__ ? def index(self): # speclog("Indexing description of "+str(self)) # blank down anything we learned already self.terms = [] self.properties = [] self.classes = [] tmpclasses=[] tmpproperties=[] g = self.graph query = 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a rdf:Property }' relations = g.query(query) for (term, label, comment) in relations: p = Property(term) # print "Made a property! "+str(p) + "using label: "#+str(label) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) query = 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type FILTER (?type = <http://www.w3.org/2002/07/owl#Class> || ?type = <http://www.w3.org/2000/01/rdf-schema#Class> ) }' relations = g.query(query) for (term, label, comment) in relations: c = Class(term) # print "Made a class! "+str(p) + "using comment: "+comment c.label = str(label) c.comment = str(comment) self.terms.append(c) if (not str(c) in tmpclasses): self.classes.append(c) tmpclasses.append(str(c)) self.terms.sort(key=operator.attrgetter('id')) self.classes.sort(key=operator.attrgetter('id')) self.properties.sort(key=operator.attrgetter('id')) # http://www.w3.org/2003/06/sw-vocab-status/ns#" query = 'SELECT ?x ?vs WHERE { ?x <http://www.w3.org/2003/06/sw-vocab-status/ns#term_status> ?vs }' status = g.query(query) # print "status results: ",status.__len__() for x, vs in status: #print "STATUS: ",vs, " for ",x t = self.lookup(x) if t != None: t.status = vs # print "Set status.", t.status else: speclog("Couldn't lookup term: "+x) # Go back and see if we missed any properties defined in OWL. TODO: classes too. Or rewrite above SPARQL. addd more types for full query. q= 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty>)}' q= 'SELECT distinct ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty> || ?type = <http://www.w3.org/2002/07/owl#DatatypeProperty> || ?type = <http://www.w3.org/1999/02/22-rdf-syntax-ns#Property> || ?type = <http://www.w3.org/2002/07/owl#FunctionalProperty> || ?type = <http://www.w3.org/2002/07/owl#InverseFunctionalProperty>) } ' relations = g.query(q) for (term, label, comment) in relations: p = Property(str(term)) got = self.lookup( str(term) ) if got==None: # print "Made an OWL property! "+str(p.uri) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) # self.terms.sort() # does this even do anything? # self.classes.sort() # self.properties.sort() # todo, use a dictionary index instead. RTFM. def lookup(self, uri): uri = str(uri) for t in self.terms: # print "Lookup: comparing '"+t.uri+"' to '"+uri+"'" # print "type of t.uri is ",t.uri.__class__ if t.uri==uri: # print "Matched." # should we str here, to be more liberal? return t else: # print "Fail." '' return None # print a raw debug summary, direct from the RDF def raw(self): g = self.graph query = 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c } ' relations = g.query(query) print "Properties and Classes (%d terms)" % len(relations) print 40*"-" for (term, label, comment) in relations: print "term %s l: %s \t\tc: %s " % (term, label, comment) print # TODO: work out how to do ".encode('UTF-8')" here # for debugging only def detect_types(self): self.properties = [] self.classes = [] for t in self.terms: # print "Doing t: "+t+" which is of type " + str(t.__class__) if t.is_property(): # print "is_property." self.properties.append(t) if t.is_class(): # print "is_class." self.classes.append(t) # CODE FROM ORIGINAL specgen: def niceName(self, uri = None ): if uri is None: return # speclog("Nicing uri "+uri) regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) if rez == None: #print "Failed to niceName. Returning the whole thing." return(uri) pref = rez.group(1) # print "...",self.ns_list.get(pref, pref),":",rez.group(2) # todo: make this work when uri doesn't match the regex --danbri # AttributeError: 'NoneType' object has no attribute 'group' return self.ns_list.get(pref, pref) + ":" + rez.group(2) # HTML stuff, should be a separate class def azlist(self): """Builds the A-Z list of terms""" c_ids = [] p_ids = [] for p in self.properties: p_ids.append(str(p.id)) for c in self.classes: c_ids.append(str(c.id)) c_ids.sort() p_ids.sort() return (c_ids, p_ids) class VocabReport(object): def __init__(self, vocab, basedir='./examples/', temploc='template.html',templatedir='./examples/'): self.vocab = vocab self.basedir = basedir self.temploc = temploc self.templatedir = templatedir self._template = "no template loaded" # text.gsub(/<code>foaf:(\w+)<\/code>/){ defurl($1) } return "<code><a href=\"#term_#{term}\">foaf:#{term}</a></code>" def codelink(self, s): reg1 = re.compile(r"""<code>foaf:(\w+)<\/code>""") return(re.sub(reg1, r"""<code><a href="#term_\1">foaf:\1</a></code>""", s)) def _get_template(self): self._template = self.load_template() # should be conditional return self._template def _set_template(self, value): self._template = str(value) template = property(_get_template,_set_template) def load_template(self): filename = os.path.join(self.templatedir, self.temploc) f = open(filename, "r") template = f.read() return(template) def generate(self): tpl = self.template azlist = self.az() termlist = self.termlist() f = open ( self.vocab.filename, "r") rdfdata = f.read() # print "GENERATING >>>>>>>> " ## having the rdf in there was making it invalid ## removed in favour of RDFa ## tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8"), rdfdata) tpl = tpl % (azlist.encode("utf-8"), azlist.encode("utf-8"), termlist.encode("utf-8")) # tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8")) return(tpl) def az(self): """AZ List for html doc""" c_ids, p_ids = self.vocab.azlist() az = """<div class="azlist">""" az = """%s\n<p>Classes: |""" % az # print c_ids, p_ids for c in c_ids: # speclog("Class "+c+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(c).replace(" ", ""), c) az = """%s\n</p>""" % az az = """%s\n<p>Properties: |""" % az for p in p_ids: # speclog("Property "+p+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(p).replace(" ", ""), p) az = """%s\n</p>""" % az az = """%s\n</div>""" % az return(az) def termlist(self): """Term List for html doc""" stableTxt = '' testingTxt = '' unstableTxt = '' archaicTxt = '' queries = '' c_ids, p_ids = self.vocab.azlist() tl = """<div class="termlist">""" tl = """%s<h3>Classes and Properties (full detail)</h3>\n<div class='termdetails'><br />\n\n""" % tl # danbri hack 20100101 removed: href="http://www.w3.org/2003/06/sw-vocab-status/ns#%s" pending discussion w/ libby and leigh re URIs # first classes, then properties eg = """<div class="specterm" id="term_%s" about="%s" typeof="%s"> <h3>%s: %s</h3> <em>%s</em> - %s <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span property="vs:status" >%s</span></td></tr> %s %s </table> %s <p style="float: right; font-size: small;">[<a href="#term_%s">#</a>] [<a href="http://wiki.foaf-project.org/w/term_%s">wiki</a>] <!-- %s --> [<a href="#glance">back to top</a>]</p> <br/> </div>""" # replace this if you want validation queries: xxx danbri # <p style="float: right; font-size: small;">[<a href="#term_%s">permalink</a>] [<a href="#queries_%s">validation queries</a>] [<a href="#glance">back to top</a>]</p> # todo, push this into an api call (c_ids currently setup by az above) # classes for term in self.vocab.classes: # strings to use later domainsOfClass = '' rangesOfClass = '' #class in domain of g = self.vocab.graph q = 'SELECT ?d ?l WHERE {?d rdfs:domain <%s> . ?d rdfs:label ?l } ' % (term.uri) relations = g.query(q) startStr = '<tr><th>Properties include:</th>\n' contentStr = '' for (domain, label) in relations: dom = Term(domain) # danbri hack 20100101 # termStr = """<a href="#term_%s">%s</a>\n""" % (dom.id, label) termStr = """<a href="#term_%s">%s</a>\n""" % (dom.id, dom.id) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": domainsOfClass = "%s <td> %s </td></tr>" % (startStr, contentStr) # class in range of q2 = 'SELECT ?d ?l WHERE {?d rdfs:range <%s> . ?d rdfs:label ?l } ' % (term.uri) relations2 = g.query(q2) startStr = '<tr><th>Used with:</th>\n' contentStr = '' for (range, label) in relations2: ran = Term(range) # termStr = """<a href="#term_%s">%s</a>\n""" % (ran.id, label) # danbri hack 20100101 better to use exact IDs here termStr = """<a href="#term_%s">%s</a>\n""" % (ran.id, ran.id) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": rangesOfClass = "%s <td> %s</td></tr> " % (startStr, contentStr) # class subclassof subClassOf = '' q = 'SELECT ?sc ?l WHERE {<%s> rdfs:subClassOf ?sc . ?sc rdfs:label ?l } ' % (term.uri) relations = g.query(q) startStr = '<tr><th>Subclass Of</th>\n' contentStr = '' for (subclass, label) in relations: sub = Term(subclass) termStr = """<span rel="rdfs:subClassOf" href="%s"><a href="#term_%s">%s</a></span>\n""" % (subclass, sub.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": subClassOf = "%s <td> %s </td></tr>" % (startStr, contentStr) # class has subclass hasSubClass = '' q = 'SELECT ?sc ?l WHERE {?sc rdfs:subClassOf <%s>. ?sc rdfs:label ?l } ' % (term.uri) relations = g.query(q) startStr = '<tr><th>Has Subclass</th>\n' contentStr = '' for (subclass, label) in relations: sub = Term(subclass) termStr = """<a href="#term_%s">%s</a>\n""" % (sub.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": hasSubClass = "%s <td> %s </td></tr>" % (startStr, contentStr) # is defined by classIsDefinedBy = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) relations = g.query(q) startStr = '\n' contentStr = '' for (isdefinedby) in relations: termStr = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": classIsDefinedBy = "%s <tr><td> %s </td></tr>" % (startStr, contentStr) # disjoint with isDisjointWith = '' q = 'SELECT ?dj ?l WHERE { <%s> <http://www.w3.org/2002/07/owl#disjointWith> ?dj . ?dj rdfs:label ?l } ' % (term.uri) relations = g.query(q) startStr = '<tr><th>Disjoint With:</th>\n' contentStr = '' for (disjointWith, label) in relations: termStr = """<span rel="owl:disjointWith" href="%s"><a href="#term_%s">%s</a></span>\n""" % (disjointWith, label, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": isDisjointWith = "%s <td> %s </td></tr>" % (startStr, contentStr) # end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' # if we want validation queries this is where it looks for them. filename = os.path.join(dn, term.id+".sparql") fileStr = '' try: f = open ( filename, "r") fileStr = f.read() fileStr = "<h4><a name=\"queries_"+term.id+"\"></a>"+term.id+" Validation Query</h4><pre>"+cgi.escape(ss)+"</pre>" except: fileStr='' queries = queries +"\n"+ fileStr sn = self.vocab.niceName(term.uri) - s = termlink(s) + s = self.termlink(s) # danbri added another term.id 20010101 and removed term.status zz = eg % (term.id,term.uri,"rdfs:Class","Class", sn, term.label, term.comment, term.status,domainsOfClass,rangesOfClass+subClassOf+hasSubClass+classIsDefinedBy+isDisjointWith, s,term.id, term.id, term.id) ## we add to the relevant string - stable, unstable, testing or archaic if(term.status == "stable"): stableTxt = stableTxt + zz if(term.status == "testing"): testingTxt = testingTxt + zz if(term.status == "unstable"): unstableTxt = unstableTxt + zz if(term.status == "archaic"): archaicTxt = archaicTxt + zz if((term.status == None) or (term.status== "") or (term.status== "unknown")): archaicTxt = archaicTxt + zz ## then add the whole thing to the main tl string tl = tl+"<h2>Classes</h2>\n" tl = "%s %s" % (tl, stableTxt+"\n"+testingTxt+"\n"+unstableTxt+"\n"+archaicTxt) tl = tl+"<h2>Properties</h2>\n" # properties stableTxt = '' testingTxt = '' unstableTxt = '' archaicTxt = '' for term in self.vocab.properties: domainsOfProperty = '' rangesOfProperty = '' # domain of properties g = self.vocab.graph q = 'SELECT ?d ?l WHERE {<%s> rdfs:domain ?d . ?d rdfs:label ?l } ' % (term.uri) relations = g.query(q) startStr = '<tr><th>Domain:</th>\n' contentStr = '' for (domain, label) in relations: dom = Term(domain) termStr = """<span rel="rdfs:domain" href="%s"><a href="#term_%s">%s</a></span>\n""" % (domain, dom.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": domainsOfProperty = "%s <td>%s</td></tr>" % (startStr, contentStr) # range of properties q2 = 'SELECT ?d ?l WHERE {<%s> rdfs:range ?d . ?d rdfs:label ?l } ' % (term.uri) relations2 = g.query(q2) startStr = '<tr><th>Range:</th>\n' contentStr = '' for (range, label) in relations2: ran = Term(range) termStr = """<span rel="rdfs:range" href="%s"><a href="#term_%s">%s</a></span>\n""" % (range, ran.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": rangesOfProperty = "%s <td>%s</td> </tr>" % (startStr, contentStr) # is defined by propertyIsDefinedBy = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) relations = g.query(q) startStr = '\n' contentStr = '' for (isdefinedby) in relations: termStr = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": propertyIsDefinedBy = "%s <tr><td> %s </td></tr>" % (startStr, contentStr) # inverse functional property ifp = '' q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#InverseFunctionalProperty> } ' % (term.uri) relations = g.query(q) startStr = '<tr><th colspan="2">Inverse Functional Property</th>\n' if (len(relations) > 0): termStr = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#InverseFunctionalProperty"></span>""" ifp = "%s <td> %s </td></tr>" % (startStr, termStr) # functonal property fp = '' q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#FunctionalProperty> } ' % (term.uri) relations = g.query(q) startStr = '<tr><th colspan="2">Functional Property</th>\n' if (len(relations) > 0): termStr = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#FunctionalProperty"></span>""" fp = "%s <td> %s </td></tr>" % (startStr, termStr) # end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' sn = self.vocab.niceName(term.uri) - s = termlink(s) + s = self.termlink(s) # danbri added another term.id 20010101 zz = eg % (term.id, term.uri,"rdf:Property","Property", sn, term.label, term.comment,term.status,domainsOfProperty,rangesOfProperty+propertyIsDefinedBy+ifp+fp, s,term.id, term.id, term.id) ## we add to the relevant string - stable, unstable, testing or archaic if(term.status == "stable"): stableTxt = stableTxt + zz if(term.status == "testing"): testingTxt = testingTxt + zz if(term.status == "unstable"): unstableTxt = unstableTxt + zz if(term.status == "archaic"): archaicTxt = archaicTxt + zz if((term.status == None) or (term.status== "") or (term.status== "unknown")): archaicTxt = archaicTxt + zz ## then add the whole thing to the main tl string tl = "%s %s" % (tl, stableTxt+"\n"+testingTxt+"\n"+unstableTxt+"\n"+archaicTxt) ## tl = "%s %s" % (tl, zz) ## ensure termlist tag is closed return(tl+"\n"+queries+"</div>\n</div>") def rdfa(self): return( "<html>rdfa here</html>") + def termlink(self, text): + result = text + for base, ns in self.vocab.ns_list.iteritems(): + if (base == self.vocab.uri): + result = re.sub(r"<code>%s:(\w+)<\/code>" % ns, r"<code><a href='#term_\g<1>'>\g<1></a></code>", result ) + else: + result = re.sub(r"<code>%s:(\w+)<\/code>" % ns, r"<code><a href='%s\g<1>'>%s:\g<1></a></code>" % (base, ns), result ) + return result def htmlDocInfo( t, termdir='../docs' ): """Opens a file based on the term name (t) and termdir (defaults to current directory. Reads in the file, and returns a linkified version of it.""" if termdir==None: termdir=self.basedir doc = "" try: f = open("%s/%s.en" % (termdir, t), "r") doc = f.read() - doc = termlink(doc) + doc = self.termlink(doc) except: return "<p>No detailed documentation for this term.</p>" return doc # report what we've parsed from our various sources def report(self): s = "Report for vocabulary from " + self.vocab.filename + "\n" if self.vocab.uri != None: s += "URI: " + self.vocab.uri + "\n\n" for t in self.vocab.uterms: print "TERM as string: ",t s += t.simple_report() return s
leth/SpecGen
0ec68466bf9ee83cd7df9da3fc047f94496010f6
Removing old code.
diff --git a/old/specgen4b.py b/old/specgen4b.py deleted file mode 100755 index 1415763..0000000 --- a/old/specgen4b.py +++ /dev/null @@ -1,590 +0,0 @@ -#!/usr/bin/env python2.5 - - -# -# SpecGen code adapted to be independent of a particular vocabulary (e.g., FOAF) -# <http://sw.deri.org/svn/sw/2005/08/sioc/ontology/spec/specgen4.py> -# -# This software is licensed under the terms of the MIT License. -# -# Copyright 2008 Uldis Bojars <[email protected]> -# Copyright 2008 Christopher Schmidt -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -__all__ = [ 'main' ] - -import sys, time, re, urllib, getopt - -import logging - -# Configure how we want rdflib logger to log messages -_logger = logging.getLogger("rdflib") -_logger.setLevel(logging.DEBUG) -_hdlr = logging.StreamHandler() -_hdlr.setFormatter(logging.Formatter('%(name)s %(levelname)s: %(message)s')) -_logger.addHandler(_hdlr) - -from rdflib.Graph import ConjunctiveGraph as Graph -from rdflib import plugin -from rdflib.store import Store -from rdflib import Namespace -from rdflib import Literal -from rdflib import URIRef - -from rdflib.sparql.bison import Parse -store = Graph() - -# with some care this could be made less redundant -store.bind("dc", "http://http://purl.org/dc/elements/1.1/") -store.bind("foaf", "http://xmlns.com/foaf/0.1/") -store.bind("dc", 'http://purl.org/dc/elements/1.1/') -store.bind("rdf", 'http://www.w3.org/1999/02/22-rdf-syntax-ns#') -store.bind("rdfs", 'http://www.w3.org/2000/01/rdf-schema#') -store.bind("owl", 'http://www.w3.org/2002/07/owl#') -store.bind("vs", 'http://www.w3.org/2003/06/sw-vocab-status/ns#') - -# Create a namespace object for the Friend of a friend namespace. -foaf = Namespace("http://xmlns.com/foaf/0.1/") -dc = Namespace('http://purl.org/dc/elements/1.1/') -rdf = Namespace('http://www.w3.org/1999/02/22-rdf-syntax-ns#') -rdfs = Namespace('http://www.w3.org/2000/01/rdf-schema#') -owl = Namespace('http://www.w3.org/2002/07/owl#') -vs = Namespace('http://www.w3.org/2003/06/sw-vocab-status/ns#') - -# add your namespaces here - -classranges = {} -classdomains = {} - -termdir = '../doc' # .. for FOAF - -# namespace for which the spec is being generated. -spec_url = "http://xmlns.com/foaf/0.1/" -spec_pre = "foaf" -# spec_url = "http://rdfs.org/sioc/ns#" -# spec_pre = "sioc" - -spec_ns = Namespace(spec_url) - -ns_list = { "http://xmlns.com/foaf/0.1/" : "foaf", - 'http://purl.org/dc/elements/1.1/' : "dc", - 'http://purl.org/dc/terms/' : "dcterms", - 'http://usefulinc.com/ns/doap#' : 'doap', - 'http://www.w3.org/1999/02/22-rdf-syntax-ns#' : "rdf", - 'http://www.w3.org/2000/01/rdf-schema#' : "rdfs", - 'http://www.w3.org/2002/07/owl#' : "owl", - 'http://www.w3.org/2001/XMLSchema#' : 'xsd', - 'http://www.w3.org/2003/06/sw-vocab-status/ns#' : "status", - 'http://purl.org/rss/1.0/modules/content/' : "content", - 'http://rdfs.org/sioc/ns#' : "sioc" } - -def niceName( uri = None ): - if uri is None: - return - speclog("Nicing uri "+uri) - regexp = re.compile( "^(.*[/#])([^/#]+)$" ) - - rez = regexp.search( uri ) -# return uri # temporary skip this whole thing! - - pref = rez.group(1) - # todo: make this work when uri doesn't match the regex --danbri - # AttributeError: 'NoneType' object has no attribute 'group' - - return ns_list.get(pref, pref) + ":" + rez.group(2) - -def setTermDir(directory): - global termdir - termdir = directory - -def termlink(string): - """FOAF specific: function which replaces <code>foaf:*</code> with a - link to the term in the document.""" - return re.sub(r"<code>" + spec_pre + r":(\w+)</code>", r"""<code><a href="#term_\1">""" + spec_pre + r""":\1</a></code>""", string) - -def return_name(m, urinode): - "Trims the FOAF namespace out of a term to give a name to the term." - return str(urinode).replace(spec_url, "") - -def get_rdfs(m, urinode): - "Returns label and comment given an RDF.Node with a URI in it" - - comment = '' - label = '' - r = wrap_find_statements(m, urinode, rdfs.label, None) - try: - l = r.next() - label = l[2] #l['todo-labels' # l[0][2] # .current().object.literal_value['string'] - except StopIteration: - '' - - r = wrap_find_statements(m, urinode, rdfs.comment, None) - try: - c = r.next() - comment = c[2] # c[2] #.current().object.literal_value['string'] - except StopIteration: - '' - - return label, comment - -def get_status(m, urinode): - "Returns the status text for a term." - status = '' - r = wrap_find_statements(m, urinode, vs.term_status, None) - try: - s = r.next() - status = s[2] - except StopIteration: - '' - return(status) - -def htmlDocInfo( t ): - """Opens a file based on the term name (t) and termdir directory (global). - Reads in the file, and returns a linkified version of it.""" - doc = "" - try: - f = open("%s/%s.en" % (termdir, t), "r") - doc = f.read() - doc = termlink(doc) - except: - speclog("Failed to open file for more info on "+t+ " termdir: " +termdir) - return "" # "<p>No detailed documentation for this term.</p>" - return doc - -def owlVersionInfo(m): - r = wrap_find_statements(m, None, owl.versionInfo, None) - try: - v = r.next() - return(v[2]) - except StopIteration: - '' - -def rdfsPropertyInfo(term,m): - """Generate HTML for properties: Domain, range, status.""" - doc = "" - range = "" - domain = "" - - # Find subPropertyOf information - speclog("Finding subPropertyOf info: skipping.") - # todo: implement in sparql instead. -# r = wrap_find_statements(m, term, rdfs.subPropertyOf, None ) -# try: -# o = r.next() -# doc += "\t<tr><th>sub-property-of:</th>" -# rlist = '' -# for st in o: -# speclog("XXX superProperty: "+st) -# k = st[2] -# if (spec_url in k): -# k = """<a href="#term_%s">%s</a>""" % (k.replace(spec_url, ""), niceName(k)) -# else: -# k = """<a href="%s">%s</a>""" % (k, niceName('xxxzzz'+k)) -# rlist += "%s " % k -# doc += "\n\t<td>%s</td></tr>\n" % rlist -# except StopIteration: -# '' - - # domain and range stuff (properties only) - r = wrap_find_statements(m, term, rdfs.domain, None) - try: - d = r.next() - domain = d[2] - except StopIteration: - "" - - r = wrap_find_statements(m, term, rdfs.range, None) - try: - rr = r.next() - range = rr[2] - except StopIteration: - '' - - speclog("range: "+range+ "domain: "+domain) - - - if domain: - # NOTE can add a warning of multiple rdfs domains / ranges - if (spec_url in domain): - domain = """<a href="#term_%s">%s</a>""" % (domain.replace(spec_url, ""), niceName(domain)) - else: - domain = """<a href="%s">%s</a>""" % (domain, niceName(domain)) - doc += "\t<tr><th>Domain:</th>\n\t<td>%s</td></tr>\n" % domain - - if range: - if (spec_url in range): - range = """<a href="#term_%s">%s</a>""" % (range.replace(spec_url, ""), niceName(range)) - else: - range = """<a href="%s">%s</a>""" % (range, niceName(range)) - doc += "\t<tr><th>Range:</th>\n\t<td>%s</td></tr>\n" % range - return doc - -def rdfsClassInfo(term,m): - """Generate rdfs-type information for Classes: ranges, and domains.""" - global classranges - global classdomains - doc = "" - - # Find subClassOf information - - o = wrap_find_statements(m, term, rdfs.subClassOf, None ) - if o: - doc += "\t<tr><th>sub-class-of:</th>" - rlist = '' - - for st in o: - k = str( st[2] ) - if (spec_url in k): - k = """<a href="#term_%s">%s</a>""" % (k.replace(spec_url, ""), niceName(k)) - else: - k = """<a href="%s">%s</a>""" % (k, niceName(k)) - rlist += "%s " % k - doc += "\n\t<td>%s</td></tr>\n" % rlist - - # Find out about properties which have rdfs:range of t - r = classranges.get(term, "") - if r: - rlist = '' - for k in r: - if (spec_url in k): - k = """<a href="#term_%s">%s</a>""" % (k.replace(spec_url, ""), niceName(k)) - else: - k = """<a href="%s">%s</a>""" % (k, niceName(k)) - rlist += "%s " % k - doc += "<tr><th>in-range-of:</th><td>"+rlist+"</td></tr>" - - # Find out about properties which have rdfs:domain of t - d = classdomains.get(str(term), "") - if d: - dlist = '' - for k in d: - if (spec_url in k): - k = """<a href="#term_%s">%s</a>""" % (k.replace(spec_url, ""), niceName(k)) - else: - k = """<a href="%s">%s</a>""" % (k, niceName(k)) - dlist += "%s " % k - doc += "<tr><th>in-domain-of:</th><td>"+dlist+"</td></tr>" - - return doc - -def owlInfo(term,m): - """Returns an extra information that is defined about a term (an RDF.Node()) using OWL.""" - res = '' - - # Inverse properties ( owl:inverseOf ) -# r = wrap_find_statements(m,term, owl.inverseOf, None) -# try: -# o = r.next() -# res += "\t<tr><th>Inverse:</th>" -# rlist = '' -# for st in o: -# k = str( st[2] ) -# if (spec_url in k): -# k = """<a href="#term_%s">%s</a>""" % (k.replace(spec_url, ""), niceName(k)) -# else: -# k = """<a href="%s">%s</a>""" % (k, niceName(k)) -# rlist += "%s " % k -# res += "\n\t<td>%s</td></tr>\n" % rlist -# except StopIteration: -# print '' - - # Datatype Property ( owl.DatatypeProperty ) - r = wrap_find_statements( m, term, rdf.type, owl.DatatypeProperty) - try: - o = r.next() - res += "\t<tr><th>OWL Type:</th>\n\t<td>DatatypeProperty</td></tr>\n" - except StopIteration: - #print '' - '' - # - - # Object Property ( owl.ObjectProperty ) - r = wrap_find_statements(m, term, rdf.type, owl.ObjectProperty) - try: - o = r.next() - res += "\t<tr><th>OWL Type:</th>\n\t<td>ObjectProperty</td></tr>\n" - except StopIteration: - '' - - # IFPs ( owl.InverseFunctionalProperty ) - r = wrap_find_statements(m, term, rdf.type, owl.InverseFunctionalProperty) - try: - o = r.next() - res += "\t<tr><th>OWL Type:</th>\n\t<td>InverseFunctionalProperty (uniquely identifying property)</td></tr>\n" - except StopIteration: - '' - - # Symmetric Property ( owl.SymmetricProperty ) - r = wrap_find_statements(m, term, rdf.type, owl.SymmetricProperty) - try: - o = r.next() - res += "\t<tr><th>OWL Type:</th>\n\t<td>SymmetricProperty</td></tr>\n" - except StopIteration: - '' - return res - -def docTerms(category, list, m): - """A wrapper class for listing all the terms in a specific class (either - Properties, or Classes. Category is 'Property' or 'Class', list is a - list of term names (strings), return value is a chunk of HTML.""" - doc = "" - nspre = spec_pre - for t in list: - term = spec_ns[t] - doc += """<div class="specterm" id="term_%s">\n<h3>%s: %s:%s</h3>\n""" % (t, category, nspre, t) - label, comment = get_rdfs(m, term) - status = get_status(m, term) - doc += "<p><em>%s</em> - %s <br /></p>" % (label, comment) - doc += """<table>\n""" - doc += owlInfo(term,m) - if category=='Property': doc += rdfsPropertyInfo(term,m) - if category=='Class': doc += rdfsClassInfo(term,m) - doc += "</table>\n" - doc += htmlDocInfo(t) - doc += "<p class=\"backtotop\">[<a href=\"#sec-glance\">back to top</a>]</p>\n\n" - doc += "\n<br/>\n</div>\n\n" - return doc - -def buildazlist(classlist, proplist): - """Builds the A-Z list of terms. Args are a list of classes (strings) and - a list of props (strings)""" - azlist = """<div class="azlist">""" - azlist = """%s\n<p>Classes: |""" % azlist - classlist.sort() - for c in classlist: - speclog("Class "+c+" in azlist generation.") - azlist = """%s <a href="#term_%s">%s</a> | """ % (azlist, c.replace(" ", ""), c) - - azlist = """%s\n</p>""" % azlist - azlist = """%s\n<p>Properties: |""" % azlist - - proplist.sort() - for p in proplist: - speclog("Property "+p+" in azlist generation.") - azlist = """%s <a href="#term_%s">%s</a> | """ % (azlist, p.replace(" ", ""), p) - azlist = """%s\n</p>""" % azlist - azlist = """%s\n</div>""" % azlist - - return azlist - -def build_simple_list(classlist, proplist): - """Builds a simple <ul> A-Z list of terms. Args are a list of classes (strings) and - a list of props (strings)""" - - azlist = """<div style="padding: 5px; border: dotted; background-color: #ddd;">""" - azlist = """%s\n<p>Classes:""" % azlist - azlist += """\n<ul>""" - - classlist.sort() - for c in classlist: - azlist += """\n <li><a href="#term_%s">%s</a></li>""" % (c.replace(" ", ""), c) - azlist = """%s\n</ul></p>""" % azlist - - azlist = """%s\n<p>Properties:""" % azlist - azlist += """\n<ul>""" - proplist.sort() - for p in proplist: - azlist += """\n <li><a href="#term_%s">%s</a></li>""" % (p.replace(" ", ""), p) - azlist = """%s\n</ul></p>""" % azlist - - azlist = """%s\n</div>""" % azlist - return azlist - -def specInformation(m): - """Read through the spec (provided as a Redland model) and return classlist - and proplist. Global variables classranges and classdomains are also filled - as appropriate.""" - global classranges - global classdomains - - # Find the class information: Ranges, domains, and list of all names. - classlist = [] -# xxxx - # See http://chatlogs.planetrdf.com/swig/2008-12-10#T14-23-48 - # todo: rewrite using SPARQL? set up some tests first. - # todo: make it optional whether we skip deprecated terms - - print "spec_url is ", spec_url - for classStatement in wrap_find_statements(m, None, rdf.type, rdfs.Class): - speclog("OK we got an rdfs class statement. sub is:"+classStatement[0]) - if classStatement[0].startswith(spec_url) : - # print "It starts with spec_url!" - for range in wrap_find_statements(m, None, rdfs.range, classStatement[0]): - if not wrap_matches(m, range[0], rdf.type, owl.DeprecatedProperty ): - classranges.setdefault(classStatement[0], []).append(str(range[0])) - for domain in wrap_find_statements(m, None, rdfs.domain, classStatement[0]): - if not wrap_matches(m, domain[0], rdf.type, owl.DeprecatedProperty): - classdomains.setdefault(str(classStatement[0]), []).append(str(domain[0])) - classlist.append(return_name(m, classStatement[0])) - - # Why deal with OWL separately? - for classStatement in wrap_find_statements(m, None, rdf.type, owl.Class): - speclog("OK we got an owl class statement. sub is:"+ classStatement[0]) - if str(classStatement[0]).startswith(spec_url) : - for range in wrap_find_statements(m, None, rdfs.range, classStatement[0]): - if not wrap_matches(m, range[0], rdf.type, owl.DeprecatedProperty ): - if str(range[0]) not in classranges.get( str(classStatement[0]), [] ) : - classranges.setdefault(str(classStatement[0]), []).append(str(range[0])) - for domain in wrap_find_statements(m, None, rdfs.domain, classStatement[0]): - if not wrap_matches(m, domain[0], rdf.type, owl.DeprecatedProperty ): - if str(domain[0]) not in classdomains.get( str(classStatement[0]), [] ) : - classdomains.setdefault(str(classStatement[0]), []).append(str(domain[0])) - if return_name(m, classStatement[0]) not in classlist: - classlist.append(return_name(m, classStatement[0])) - - # Create a list of properties in the schema. - proplist = [] - for propertyStatement in wrap_find_statements(m, None, rdf.type, rdf.Property): - speclog("OK we got a property statement: "+ propertyStatement[0]) - speclog("asking s: "+propertyStatement[0]+ " p: " + rdf.type + " o: " + owl.DeprecatedProperty) - if not (wrap_find_statements(m, propertyStatement[0], rdf.type, owl.DeprecatedProperty )): - speclog(" and OK, not deprecated. "+ propertyStatement[0]) - if propertyStatement[0].startswith(spec_url): - speclog("property uri "+propertyStatement[0]+" matches spec_url") - proplist.append(return_name(m, propertyStatement[0])) - for propertyStatement in wrap_find_statements(m, None, rdf.type, owl.DatatypeProperty): - if not wrap_matches(m, propertyStatement[0], rdf.type, owl.DeprecatedProperty ): - if propertyStatement[0].startswith(spec_url) : - if return_name(m, propertyStatement[0]) not in proplist: - proplist.append(return_name(m, propertyStatement[0])) - for propertyStatement in wrap_find_statements(m, None, rdf.type, owl.ObjectProperty): - if not wrap_matches(m, propertyStatement[0], rdf.type, owl.DeprecatedProperty ): - if propertyStatement[0].startswith(spec_url) : - if return_name(m, propertyStatement[0]) not in proplist: - proplist.append(return_name(m, propertyStatement[0])) - for propertyStatement in wrap_find_statements(m, None, rdf.type, owl.SymmetricProperty): - if not wrap_matches(m, propertyStatement[0], rdf.type, owl.DeprecatedProperty ): - if propertyStatement[0].startswith(spec_url) : - if return_name(m, propertyStatement[0]) not in proplist: - proplist.append(return_name(m, propertyStatement[0])) - - return classlist, proplist - -def main(specloc, template, mode="spec"): - """The meat and potatoes: Everything starts here.""" - - m = Graph() - m.parse(specloc) - -# m = RDF.Model() -# p = RDF.Parser() -# p.parse_into_model(m, specloc) - - classlist, proplist = specInformation(m) - - if mode == "spec": - # Build HTML list of terms. - azlist = buildazlist(classlist, proplist) - elif mode == "list": - # Build simple <ul> list of terms. - azlist = build_simple_list(classlist, proplist) - - # Generate Term HTML -# termlist = "<h3>Classes and Properties (full detail)</h3>" - termlist = docTerms('Class',classlist,m) - termlist += docTerms('Property',proplist,m) - - # Generate RDF from original namespace. - u = urllib.urlopen(specloc) - rdfdata = u.read() - rdfdata = re.sub(r"(<\?xml version.*\?>)", "", rdfdata) - rdfdata = re.sub(r"(<!DOCTYPE[^]]*]>)", "", rdfdata) - rdfdata.replace("""<?xml version="1.0"?>""", "") - - # print template % (azlist.encode("utf-8"), termlist.encode("utf-8"), rdfdata.encode("ISO-8859-1")) - #template = re.sub(r"^#format \w*\n", "", template) - #template = re.sub(r"\$VersionInfo\$", owlVersionInfo(m).encode("utf-8"), template) - - # NOTE: This works with the assumtpion that all "%" in the template are escaped to "%%" and it - # contains the same number of "%s" as the number of parameters in % ( ...parameters here... ) - - print "AZlist",azlist - print "Termlist",termlist - -#xxx template = template % (azlist.encode("utf-8"), termlist.encode("utf-8")); -# template += "<!-- specification regenerated at " + time.strftime('%X %x %Z') + " -->" - - return template - - -def speclog(str): - sys.stderr.write("LOG: "+str+"\n") - -# utility to help wrap redland idioms -def wrap_find_statements(m,s,p,o): - subject=s - if not s: - subject='NIL' - - predicate = p - if not p: - predicate='NIL' - - object = o - if not o: - object='NIL' - - speclog("Q: " + subject + " / " + predicate + " / " + object+"\n") - return(m.triples((s,p,o))) - -def wrap_matches(m,s,p,o): - r = m.triples((s,p,o)) - a = False - try: - r.next() - a = True - speclog("found it") - return(a) - except StopIteration: - '' - -def usage(): - print "Usage: " - print " No information yet !!!" - -if __name__ == "__main__": - """Specification generator tool, used for FOAF & SIOC ontology maintenance.""" - - specloc = "file:index.rdf" - temploc = "template.html" - mode = "spec" - - try: - optlist, args = getopt.getopt( sys.argv[1:], "l" ) - except getopt.GetoptError: - usage() - sys.exit() - - if (len(args) >= 2): - temploc = args[1] - if (len(args) >= 1): - specloc = args[0] - - for o,v in optlist: - if o == "-l": - mode = "list" - - # template is a template file for the spec, python-style % escapes - # for replaced sections. - f = open(temploc, "r") - template = f.read() - - print main(specloc, template, mode) - diff --git a/specgen5.py b/specgen5.py index 201e3e7..78b3e30 100755 --- a/specgen5.py +++ b/specgen5.py @@ -1,229 +1,229 @@ #!/usr/bin/env python # This is a draft rewrite of specgen, the family of scripts (originally # in Ruby, then Python) that are used with the FOAF and SIOC RDF vocabularies. # This version is a rewrite by danbri, begun after a conversion of # Uldis Bojars and Christopher Schmidt's specgen4.py to use rdflib instead of # Redland's Python bindings. While it shares their goal of being independent # of any particular RDF vocabulary, this first version's main purpose is # to get the FOAF spec workflow moving again. It doesn't work yet. # -# A much more literal conversion of specgen4.py to use rdflib can be -# found, abandoned, in the old/ directory as 'specgen4b.py'. +# An abandoned, much more literal conversion of specgen4.py to use rdflib can be +# found in the archives, in the old/ directory as 'specgen4b.py'. # # Copyright 2008 Dan Brickley <http://danbri.org/> # # ...and probably includes bits of code that are: # # Copyright 2008 Uldis Bojars <[email protected]> # Copyright 2008 Christopher Schmidt # # This software is licensed under the terms of the MIT License. # # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. import libvocab from libvocab import Vocab, VocabReport from libvocab import Term from libvocab import Class from libvocab import Property import sys import os.path import getopt # Make a spec def makeSpec(indir, uri, shortName,outdir,outfile, template, templatedir,indexrdfdir): spec = Vocab( indexrdfdir, 'index.rdf') spec.uri = uri spec.addShortName(shortName) spec.index() # slurp info from sources out = VocabReport( spec, indir, template, templatedir ) filename = os.path.join(outdir, outfile) print "Printing to ",filename f = open(filename,"w") result = out.generate() f.write(result) # Make FOAF spec def makeFoaf(): makeSpec("examples/foaf/","http://xmlns.com/foaf/0.1/","foaf","examples/foaf/","_tmp_spec.html","template.html","examples/foaf/","examples/foaf/") def usage(): print "Usage:",sys.argv[0],"--indir=dir --ns=uri --prefix=prefix [--outdir=outdir] [--outfile=outfile] [--templatedir=templatedir] [--indexrdf=indexrdf]" print "e.g. " print sys.argv[0], " --indir=examples/foaf/ --ns=http://xmlns.com/foaf/0.1/ --prefix=foaf" print "or " print sys.argv[0], " --indir=../../xmlns.com/htdocs/foaf/ --ns=http://xmlns.com/foaf/0.1/ --prefix=foaf --templatedir=../../xmlns.com/htdocs/foaf/spec/ --indexrdfdir=../../xmlns.com/htdocs/foaf/spec/ --outdir=../../xmlns.com/htdocs/foaf/spec/" def main(): ##looking for outdir, outfile, indir, namespace, shortns try: opts, args = getopt.getopt(sys.argv[1:], None, ["outdir=", "outfile=", "indir=", "ns=", "prefix=", "templatedir=", "indexrdfdir="]) #print opts except getopt.GetoptError, err: # print help information and exit: print str(err) # will print something like "option -a not recognized" print "something went wrong" usage() sys.exit(2) indir = None #indir uri = None #ns shortName = None #prefix outdir = None outfile = None templatedir = None indexrdfdir = None if len(opts) ==0: print "No arguments found" usage() sys.exit(2) for o, a in opts: if o == "--indir": indir = a elif o == "--ns": uri = a elif o == "--prefix": shortName = a elif o == "--outdir": outdir = a elif o == "--outfile": outfile = a elif o == "--templatedir": templatedir = a elif o == "--indexrdfdir": indexrdfdir = a #first check all the essentials are there # check we have been given a indir if indir == None or len(indir) ==0: print "No in directory given" usage() sys.exit(2) # check we have been given a namespace url if (uri == None or len(uri)==0): print "No namespace uri given" usage() sys.exit(2) # check we have a prefix if (shortName == None or len(shortName)==0): print "No prefix given" usage() sys.exit(2) # check outdir if (outdir == None or len(outdir)==0): outdir = indir print "No outdir, using indir ",indir if (outfile == None or len(outfile)==0): outfile = "_tmp_spec.html" print "No outfile, using ",outfile if (templatedir == None or len(templatedir)==0): templatedir = indir print "No templatedir, using ",templatedir if (indexrdfdir == None or len(indexrdfdir)==0): indexrdfdir = indir print "No indexrdfdir, using ",indexrdfdir # now do some more checking # check indir is a dir and it is readable and writeable if (os.path.isdir(indir)): print "In directory is ok ",indir else: print indir,"is not a directory" usage() sys.exit(2) # check templatedir is a dir and it is readable and writeable if (os.path.isdir(templatedir)): print "Template directory is ok ",templatedir else: print templatedir,"is not a directory" usage() sys.exit(2) # check indexrdfdir is a dir and it is readable and writeable if (os.path.isdir(indexrdfdir)): print "indexrdfdir directory is ok ",indexrdfdir else: print indexrdfdir,"is not a directory" usage() sys.exit(2) # check outdir is a dir and it is readable and writeable if (os.path.isdir(outdir)): print "Out directory is ok ",outdir else: print outdir,"is not a directory" usage() sys.exit(2) #check we can read infile try: filename = os.path.join(indexrdfdir, "index.rdf") f = open(filename, "r") except: print "Can't open index.rdf in",indexrdfdir usage() sys.exit(2) #look for the template file try: filename = os.path.join(templatedir, "template.html") f = open(filename, "r") except: print "No template.html in ",templatedir usage() sys.exit(2) # check we can write to outfile try: filename = os.path.join(outdir, outfile) f = open(filename, "w") except: print "Cannot write to ",outfile," in",outdir usage() sys.exit(2) makeSpec(indir,uri,shortName,outdir,outfile,"template.html",templatedir,indexrdfdir) if __name__ == "__main__": main()
leth/SpecGen
c20e3e0982255b102cfc27a92c9242e0b2b2224a
Automatic CRLF to LF conversion.
diff --git a/examples/sioc/sioc.rdf b/examples/sioc/sioc.rdf index 411015f..5a34b30 100644 --- a/examples/sioc/sioc.rdf +++ b/examples/sioc/sioc.rdf @@ -1,720 +1,720 @@ -<?xml version="1.0" encoding="UTF-8"?> - -<rdf:RDF - xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" - xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" - xmlns:owl="http://www.w3.org/2002/07/owl#" - xmlns:vs="http://www.w3.org/2003/06/sw-vocab-status/ns#" - xmlns:foaf="http://xmlns.com/foaf/0.1/" - xmlns:wot="http://xmlns.com/wot/0.1/" - xmlns:dcterms="http://purl.org/dc/terms/" - xmlns:sioc="http://rdfs.org/sioc/ns#" -> - -<!-- OWL-DL Compliance statements --> -<!-- DC --> -<rdf:Description rdf:about="http://purl.org/dc/terms/title"> - <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#DatatypeProperty"/> -</rdf:Description> -<rdf:Description rdf:about="http://purl.org/dc/terms/description"> - <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#DatatypeProperty"/> - </rdf:Description> -<rdf:Description rdf:about="http://purl.org/dc/terms/subject"> - <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#ObjectProperty"/> -</rdf:Description> -<rdf:Description rdf:about="http://purl.org/dc/terms/references"> - <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#ObjectProperty"/> -</rdf:Description> -<!-- FOAF --> -<rdf:Description rdf:about="http://xmlns.com/foaf/0.1/OnlineAccount"> - <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#Class"/> -</rdf:Description> -<rdf:Description rdf:about="http://xmlns.com/foaf/0.1/Agent"> - <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#Class"/> -</rdf:Description> -<rdf:Description rdf:about="http://xmlns.com/foaf/0.1/depiction"> - <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#ObjectProperty"/> -</rdf:Description> -<rdf:Description rdf:about="http://xmlns.com/foaf/0.1/holdsAccount"> - <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#ObjectProperty"/> -</rdf:Description> - -<!-- SIOC Core Ontology --> -<owl:Ontology rdf:about="http://rdfs.org/sioc/ns#" rdf:type="http://www.w3.org/2002/07/owl#Thing"> - <dcterms:title xml:lang="en">SIOC Core Ontology Namespace</dcterms:title> - <owl:versionInfo>Revision: 1.29</owl:versionInfo> - <dcterms:description xml:lang="en">SIOC (Semantically-Interlinked Online Communities) is an ontology for describing the information in online communities. -This information can be used to export information from online communities and to link them together. The scope of the application areas that SIOC can be used for includes (and is not limited to) weblogs, message boards, mailing lists and chat channels.</dcterms:description> - <rdfs:seeAlso rdf:resource="http://rdfs.org/sioc/spec" rdfs:label="SIOC Core Ontology Specification"/> -</owl:Ontology> - -<!-- Classes --> -<owl:Class rdf:about="http://rdfs.org/sioc/ns#Community"> - <rdfs:label xml:lang="en">Community</rdfs:label> - <rdfs:comment xml:lang="en">Community is a high-level concept that defines an online community and what it consists of.</rdfs:comment> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> - <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#Item"/> - <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#Role"/> - <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#User"/> -</owl:Class> - -<owl:Class rdf:about="http://rdfs.org/sioc/ns#Container"> - <rdfs:label xml:lang="en">Container</rdfs:label> - <rdfs:comment xml:lang="en">An area in which content Items are contained.</rdfs:comment> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> - <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#Item"/> - <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#Role"/> - <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#User"/> - <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#Usergroup"/> -</owl:Class> - -<owl:Class rdf:about="http://rdfs.org/sioc/ns#Forum"> - <rdfs:label xml:lang="en">Forum</rdfs:label> - <rdfs:comment xml:lang="en">A discussion area on which Posts or entries are made.</rdfs:comment> - <rdfs:subClassOf rdf:resource="http://rdfs.org/sioc/ns#Container"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> -</owl:Class> - -<owl:Class rdf:about="http://rdfs.org/sioc/ns#Item"> - <rdfs:label xml:lang="en">Item</rdfs:label> - <rdfs:comment xml:lang="en">An Item is something which can be in a Container.</rdfs:comment> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> - <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#Container"/> - <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#Role"/> - <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#Space"/> - <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#User"/> - <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#Usergroup"/> -</owl:Class> - -<owl:Class rdf:about="http://rdfs.org/sioc/ns#Post"> - <rdfs:label xml:lang="en">Post</rdfs:label> - <rdfs:comment xml:lang="en">An article or message that can be posted to a Forum.</rdfs:comment> - <rdfs:subClassOf rdf:resource="http://rdfs.org/sioc/ns#Item"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> -</owl:Class> - -<owl:Class rdf:about="http://rdfs.org/sioc/ns#Role"> - <rdfs:label xml:lang="en">Role</rdfs:label> - <rdfs:comment xml:lang="en">A Role is a function of a User within a scope of a particular Forum, Site, etc.</rdfs:comment> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> - <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#Container"/> - <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#Item"/> - <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#Space"/> - <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#User"/> - <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#Usergroup"/> -</owl:Class> - -<owl:Class rdf:about="http://rdfs.org/sioc/ns#Space"> - <rdfs:label xml:lang="en">Space</rdfs:label> - <rdfs:comment xml:lang="en">A Space is a place where data resides, e.g., on a website, desktop, fileshare, etc.</rdfs:comment> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> - <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#Item"/> - <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#Role"/> - <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#User"/> - <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#Usergroup"/> -</owl:Class> - -<owl:Class rdf:about="http://rdfs.org/sioc/ns#Site"> - <rdfs:label xml:lang="en">Site</rdfs:label> - <rdfs:comment xml:lang="en">A Site can be the location of an online community or set of communities, with Users and Usergroups creating Items in a set of Containers. It can be thought of as a web-accessible data Space.</rdfs:comment> - <rdfs:subClassOf rdf:resource="http://rdfs.org/sioc/ns#Space"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> -</owl:Class> - -<owl:Class rdf:about="http://rdfs.org/sioc/ns#Thread"> - <rdfs:label xml:lang="en">Thread</rdfs:label> - <rdfs:comment xml:lang="en">A container for a series of threaded discussion Posts or Items.</rdfs:comment> - <rdfs:subClassOf rdf:resource="http://rdfs.org/sioc/ns#Container"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> -</owl:Class> - -<owl:Class rdf:about="http://rdfs.org/sioc/ns#User"> - <rdfs:label xml:lang="en">User</rdfs:label> - <rdfs:comment xml:lang="en">A User account in an online community site.</rdfs:comment> - <rdfs:subClassOf rdf:resource="http://xmlns.com/foaf/0.1/OnlineAccount"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> - <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#Container"/> - <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#Item"/> - <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#Role"/> - <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#Space"/> - <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#Usergroup"/> -</owl:Class> - -<owl:Class rdf:about="http://rdfs.org/sioc/ns#Usergroup"> - <rdfs:label xml:lang="en">Usergroup</rdfs:label> - <rdfs:comment xml:lang="en">A set of User accounts whose owners have a common purpose or interest. Can be used for access control purposes.</rdfs:comment> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> - <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#Container"/> - <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#Item"/> - <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#Role"/> - <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#Space"/> - <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#User"/> -</owl:Class> - -<!-- Properties --> - -<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#about"> - <rdfs:label xml:lang="en">about</rdfs:label> - <rdfs:comment xml:lang="en">Specifies that this Item is about a particular resource, e.g., a Post describing a book, hotel, etc.</rdfs:comment> - <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Item"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> -</owl:ObjectProperty> - -<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#account_of"> - <rdfs:label xml:lang="en">account_of</rdfs:label> - <rdfs:comment xml:lang="en">Refers to the foaf:Agent or foaf:Person who owns this sioc:User online account.</rdfs:comment> - <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#User"/> - <rdfs:range rdf:resource="http://xmlns.com/foaf/0.1/Agent"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> - <owl:inverseOf rdf:resource="http://xmlns.com/foaf/0.1/holdsAccount"/> -</owl:ObjectProperty> - -<!-- @@todo: moving this property to the access module ? --> -<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#administrator_of"> - <rdfs:label xml:lang="en">administrator_of</rdfs:label> - <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#has_administrator"/> - <rdfs:comment xml:lang="en">A Site that the User is an administrator of.</rdfs:comment> - <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#User"/> - <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#Site"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> -</owl:ObjectProperty> - -<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#attachment"> - <rdfs:label xml:lang="en">attachment</rdfs:label> - <rdfs:comment xml:lang="en">The URI of a file attached to an Item.</rdfs:comment> - <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Item"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> -</owl:ObjectProperty> - -<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#avatar"> - <rdfs:label xml:lang="en">avatar</rdfs:label> - <rdfs:comment xml:lang="en">An image or depiction used to represent this User.</rdfs:comment> - <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#User"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> - <rdfs:subPropertyOf rdf:resource="http://xmlns.com/foaf/0.1/depiction"/> -</owl:ObjectProperty> - -<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#container_of"> - <rdfs:label xml:lang="en">container_of</rdfs:label> - <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#has_container"/> - <rdfs:comment xml:lang="en">An Item that this Container contains.</rdfs:comment> - <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Container"/> - <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#Item"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> -</owl:ObjectProperty> - -<owl:DatatypeProperty rdf:about="http://rdfs.org/sioc/ns#content"> - <rdfs:label xml:lang="en">content</rdfs:label> - <rdfs:comment xml:lang="en">The content of the Item in plain text format.</rdfs:comment> - <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Item"/> - <rdfs:range rdf:resource="http://www.w3.org/2000/01/rdf-schema#Literal"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> -</owl:DatatypeProperty> - -<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#creator_of"> - <rdfs:label xml:lang="en">creator_of</rdfs:label> - <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#has_creator"/> - <rdfs:comment xml:lang="en">A resource that the User is a creator of.</rdfs:comment> - <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#User"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> -</owl:ObjectProperty> - -<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#email"> - <rdfs:label xml:lang="en">email</rdfs:label> - <rdfs:comment xml:lang="en">An electronic mail address of the User.</rdfs:comment> - <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#User"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> -</owl:ObjectProperty> - -<owl:DatatypeProperty rdf:about="http://rdfs.org/sioc/ns#email_sha1"> - <rdfs:label xml:lang="en">email_sha1</rdfs:label> - <rdfs:comment xml:lang="en">An electronic mail address of the User, encoded using SHA1.</rdfs:comment> - <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#User"/> - <rdfs:range rdf:resource="http://www.w3.org/2000/01/rdf-schema#Literal"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> -</owl:DatatypeProperty> - -<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#feed"> - <rdfs:label xml:lang="en">feed</rdfs:label> - <rdfs:comment xml:lang="en">A feed (e.g., RSS, Atom, etc.) pertaining to this resource (e.g., for a Forum, Site, User, etc.).</rdfs:comment> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> -</owl:ObjectProperty> - -<!-- @@todo: moving this property to the access module ? --> -<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#function_of"> - <rdfs:label xml:lang="en">function_of</rdfs:label> - <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#has_function"/> - <rdfs:comment xml:lang="en">A User who has this Role.</rdfs:comment> - <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Role"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> -</owl:ObjectProperty> - -<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#has_administrator"> - <rdfs:label xml:lang="en">has_administrator</rdfs:label> - <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#administrator_of"/> - <rdfs:comment xml:lang="en">A User who is an administrator of this Site.</rdfs:comment> - <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Site"/> - <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#User"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> -</owl:ObjectProperty> - -<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#has_container"> - <rdfs:label xml:lang="en">has_container</rdfs:label> - <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#container_of"/> - <rdfs:comment xml:lang="en">The Container to which this Item belongs.</rdfs:comment> - <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Item"/> - <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#Container"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> -</owl:ObjectProperty> - -<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#has_creator"> - <rdfs:label xml:lang="en">has_creator</rdfs:label> - <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#creator_of"/> - <rdfs:comment xml:lang="en">This is the User who made this resource.</rdfs:comment> - <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#User"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> -</owl:ObjectProperty> - -<!-- @@todo: moving this property to the access module ? --> -<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#has_function"> - <rdfs:label xml:lang="en">has_function</rdfs:label> - <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#function_of"/> - <rdfs:comment xml:lang="en">A Role that this User has.</rdfs:comment> - <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#Role"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> -</owl:ObjectProperty> - -<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#has_host"> - <rdfs:label xml:lang="en">has_host</rdfs:label> - <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#host_of"/> - <rdfs:comment xml:lang="en">The Site that hosts this Forum.</rdfs:comment> - <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Forum"/> - <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#Site"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> -</owl:ObjectProperty> - -<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#has_member"> - <rdfs:label xml:lang="en">has_member</rdfs:label> - <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#member_of"/> - <rdfs:comment xml:lang="en">A User who is a member of this Usergroup.</rdfs:comment> - <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Usergroup"/> - <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#User"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> -</owl:ObjectProperty> - -<!-- @@todo: moving this property to the access module ? --> -<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#has_moderator"> - <rdfs:label xml:lang="en">has_moderator</rdfs:label> - <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#ObjectProperty"/> - <rdfs:comment xml:lang="en">A User who is a moderator of this Forum.</rdfs:comment> - <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Forum"/> - <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#User"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> -</owl:ObjectProperty> - -<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#has_modifier"> - <rdfs:label xml:lang="en">has_modifier</rdfs:label> - <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#modifier_of"/> - <rdfs:comment xml:lang="en">A User who modified this Item.</rdfs:comment> - <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Item"/> - <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#User"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> -</owl:ObjectProperty> - -<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#has_owner"> - <rdfs:label xml:lang="en">has_owner</rdfs:label> - <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#owner_of"/> - <rdfs:comment xml:lang="en">A User that this resource is owned by.</rdfs:comment> - <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#User"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> -</owl:ObjectProperty> - -<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#has_parent"> - <rdfs:label xml:lang="en">has_parent</rdfs:label> - <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#parent_of"/> - <rdfs:comment xml:lang="en">A Container or Forum that this Container or Forum is a child of.</rdfs:comment> - <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Container"/> - <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#Container"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> -</owl:ObjectProperty> - -<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#has_reply"> - <rdfs:label xml:lang="en">has_reply</rdfs:label> - <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#reply_of"/> - <rdfs:comment xml:lang="en">Points to an Item or Post that is a reply or response to this Item or Post.</rdfs:comment> - <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Item"/> - <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#Item"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> -</owl:ObjectProperty> - -<!-- @@todo: moving this property to the access module ? --> -<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#has_scope"> - <rdfs:label xml:lang="en">has_scope</rdfs:label> - <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#scope_of"/> - <rdfs:comment xml:lang="en">A resource that this Role applies to.</rdfs:comment> - <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Role"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> -</owl:ObjectProperty> - -<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#has_space"> - <rdfs:label xml:lang="en">has_space</rdfs:label> - <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#space_of"/> - <rdfs:comment xml:lang="en">A data Space which this resource is a part of.</rdfs:comment> - <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#Space"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> -</owl:ObjectProperty> - -<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#has_subscriber"> - <rdfs:label xml:lang="en">has_subscriber</rdfs:label> - <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#subscriber_of"/> - <rdfs:comment xml:lang="en">A User who is subscribed to this Container.</rdfs:comment> - <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Container"/> - <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#User"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> - <rdfs:seeAlso rdf:resource="http://rdfs.org/sioc/ns#feed"/> -</owl:ObjectProperty> - -<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#has_usergroup"> - <rdfs:label xml:lang="en">has_usergroup</rdfs:label> - <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#usergroup_of"/> - <rdfs:comment xml:lang="en">Points to a Usergroup that has certain access to this Space.</rdfs:comment> - <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Space"/> - <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#Usergroup"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> -</owl:ObjectProperty> - -<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#host_of"> - <rdfs:label xml:lang="en">host_of</rdfs:label> - <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#has_host"/> - <rdfs:comment xml:lang="en">A Forum that is hosted on this Site.</rdfs:comment> - <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Site"/> - <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#Forum"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> -</owl:ObjectProperty> - -<owl:DatatypeProperty rdf:about="http://rdfs.org/sioc/ns#id"> - <rdfs:label xml:lang="en">id</rdfs:label> - <rdfs:comment xml:lang="en">An identifier of a SIOC concept instance. For example, a user ID. Must be unique for instances of each type of SIOC concept within the same site.</rdfs:comment> - <rdfs:range rdf:resource="http://www.w3.org/2000/01/rdf-schema#Literal"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> -</owl:DatatypeProperty> - -<owl:DatatypeProperty rdf:about="http://rdfs.org/sioc/ns#ip_address"> - <rdfs:label xml:lang="en">ip_address</rdfs:label> - <rdfs:comment xml:lang="en">The IP address used when creating this Item. This can be associated with a creator. Some wiki articles list the IP addresses for the creator or modifiers when the usernames are absent.</rdfs:comment> - <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Item"/> - <rdfs:range rdf:resource="http://www.w3.org/2000/01/rdf-schema#Literal"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> -</owl:DatatypeProperty> - -<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#link"> - <rdfs:label xml:lang="en">link</rdfs:label> - <rdfs:comment xml:lang="en">A URI of a document which contains this SIOC object.</rdfs:comment> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> -</owl:ObjectProperty> - -<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#links_to"> - <rdfs:label xml:lang="en">links_to</rdfs:label> - <rdfs:comment xml:lang="en">Links extracted from hyperlinks within a SIOC concept, e.g., Post or Site.</rdfs:comment> - <rdfs:subPropertyOf rdf:resource="http://purl.org/dc/terms/references"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> -</owl:ObjectProperty> - -<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#member_of"> - <rdfs:label xml:lang="en">member_of</rdfs:label> - <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#has_member"/> - <rdfs:comment xml:lang="en">A Usergroup that this User is a member of.</rdfs:comment> - <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#User"/> - <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#Usergroup"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> -</owl:ObjectProperty> - -<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#moderator_of"> - <rdfs:label xml:lang="en">moderator_of</rdfs:label> - <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#has_moderator"/> - <rdfs:comment xml:lang="en">A Forum that User is a moderator of.</rdfs:comment> - <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#User"/> - <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#Forum"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> -</owl:ObjectProperty> - -<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#modifier_of"> - <rdfs:label xml:lang="en">modifier_of</rdfs:label> - <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#has_modifier"/> - <rdfs:comment xml:lang="en">An Item that this User has modified.</rdfs:comment> - <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#User"/> - <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#Item"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> -</owl:ObjectProperty> - -<owl:DatatypeProperty rdf:about="http://rdfs.org/sioc/ns#name"> - <rdfs:label xml:lang="en">name</rdfs:label> - <rdfs:comment xml:lang="en">The name of a SIOC instance, e.g. a username for a User, group name for a Usergroup, etc.</rdfs:comment> - <rdfs:range rdf:resource="http://www.w3.org/2000/01/rdf-schema#Literal"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> -</owl:DatatypeProperty> - -<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#next_by_date"> - <rdfs:label xml:lang="en">next_by_date</rdfs:label> - <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#previous_by_date"/> - <rdfs:comment xml:lang="en">Next Item or Post in a given Container sorted by date.</rdfs:comment> - <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Item"/> - <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#Item"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> -</owl:ObjectProperty> - -<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#next_version"> - <rdfs:label xml:lang="en">next_version</rdfs:label> - <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#previous_version"/> - <rdfs:comment xml:lang="en">Links to the next revision of this Item or Post.</rdfs:comment> - <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Item"/> - <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#Item"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> -</owl:ObjectProperty> - -<owl:DatatypeProperty rdf:about="http://rdfs.org/sioc/ns#note"> - <rdfs:label xml:lang="en">note</rdfs:label> - <rdfs:comment xml:lang="en">A note associated with this resource, for example, if it has been edited by a User.</rdfs:comment> - <rdfs:range rdf:resource="http://www.w3.org/2000/01/rdf-schema#Literal"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> -</owl:DatatypeProperty> - -<owl:DatatypeProperty rdf:about="http://rdfs.org/sioc/ns#num_replies"> - <rdfs:label xml:lang="en">num_replies</rdfs:label> - <rdfs:comment xml:lang="en">The number of replies that this Item, Thread, Post, etc. has. Useful for when the reply structure is absent.</rdfs:comment> - <rdfs:range rdf:resource="http://www.w3.org/2001/XMLSchema#integer"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> -</owl:DatatypeProperty> - -<owl:DatatypeProperty rdf:about="http://rdfs.org/sioc/ns#num_views"> - <rdfs:label xml:lang="en">num_views</rdfs:label> - <rdfs:comment xml:lang="en">The number of times this Item, Thread, User profile, etc. has been viewed.</rdfs:comment> - <rdfs:range rdf:resource="http://www.w3.org/2001/XMLSchema#integer"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> -</owl:DatatypeProperty> - -<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#owner_of"> - <rdfs:label xml:lang="en">owner_of</rdfs:label> - <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#has_owner"/> - <rdfs:comment xml:lang="en">A resource owned by a particular User, for example, a weblog or image gallery.</rdfs:comment> - <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#User"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> -</owl:ObjectProperty> - -<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#parent_of"> - <rdfs:label xml:lang="en">parent_of</rdfs:label> - <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#has_parent"/> - <rdfs:comment xml:lang="en">A child Container or Forum that this Container or Forum is a parent of.</rdfs:comment> - <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Container"/> - <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#Container"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> -</owl:ObjectProperty> - -<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#previous_by_date"> - <rdfs:label xml:lang="en">previous_by_date</rdfs:label> - <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#next_by_date"/> - <rdfs:comment xml:lang="en">Previous Item or Post in a given Container sorted by date.</rdfs:comment> - <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Item"/> - <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#Item"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> -</owl:ObjectProperty> - -<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#previous_version"> - <rdfs:label xml:lang="en">previous_version</rdfs:label> - <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#next_version"/> - <rdfs:comment xml:lang="en">Links to a previous revision of this Item or Post.</rdfs:comment> - <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Item"/> - <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#Item"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> -</owl:ObjectProperty> - -<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#related_to"> - <rdfs:label xml:lang="en">related_to</rdfs:label> - <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#ObjectProperty"/> - <rdfs:comment xml:lang="en">Related Posts for this Post, perhaps determined implicitly from topics or references.</rdfs:comment> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> -</owl:ObjectProperty> - -<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#reply_of"> - <rdfs:label xml:lang="en">reply_of</rdfs:label> - <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#has_reply"/> - <rdfs:comment xml:lang="en">Links to an Item or Post which this Item or Post is a reply to.</rdfs:comment> - <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Item"/> - <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#Item"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> -</owl:ObjectProperty> - -<!-- @@todo: moving this property to the access module ? --> -<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#scope_of"> - <rdfs:label xml:lang="en">scope_of</rdfs:label> - <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#has_scope"/> - <rdfs:comment xml:lang="en">A Role that has a scope of this resource.</rdfs:comment> - <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#Role"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> -</owl:ObjectProperty> - -<owl:SymmetricProperty rdf:about="http://rdfs.org/sioc/ns#sibling"> - <rdfs:label xml:lang="en">sibling</rdfs:label> - <rdfs:comment xml:lang="en">An Item may have a sibling or a twin that exists in a different Container, but the siblings may differ in some small way (for example, language, category, etc.). The sibling of this Item should be self-describing (that is, it should contain all available information).</rdfs:comment> - <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Item"/> - <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#Item"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> -</owl:SymmetricProperty> - -<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#space_of"> - <rdfs:label xml:lang="en">space_of</rdfs:label> - <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#has_space"/> - <rdfs:comment xml:lang="en">A resource which belongs to this data Space.</rdfs:comment> - <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Space"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> -</owl:ObjectProperty> - -<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#subscriber_of"> - <rdfs:label xml:lang="en">subscriber_of</rdfs:label> - <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#has_subscriber"/> - <rdfs:comment xml:lang="en">A Container that a User is subscribed to.</rdfs:comment> - <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#User"/> - <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#Container"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> - <rdfs:seeAlso rdf:resource="http://rdfs.org/sioc/ns#feed"/> -</owl:ObjectProperty> - -<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#topic"> - <rdfs:label xml:lang="en">topic</rdfs:label> - <rdfs:comment xml:lang="en">A topic of interest, linking to the appropriate URI, e.g., in the Open Directory Project or of a SKOS category.</rdfs:comment> - <rdfs:subPropertyOf rdf:resource="http://purl.org/dc/terms/subject"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> -</owl:ObjectProperty> - -<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#usergroup_of"> - <rdfs:label xml:lang="en">usergroup_of</rdfs:label> - <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#has_usergroup"/> - <rdfs:comment xml:lang="en">A Space that the Usergroup has access to.</rdfs:comment> - <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Usergroup"/> - <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#Space"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> -</owl:ObjectProperty> - -<!-- Deprecated --> - -<owl:DeprecatedProperty rdf:about="http://rdfs.org/sioc/ns#title"> - <rdfs:label xml:lang="en">title</rdfs:label> - <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#DatatypeProperty"/> - <rdfs:comment xml:lang="en">This is the title (subject line) of the Post. Note that for a Post within a threaded discussion that has no parents, it would detail the topic thread.</rdfs:comment> - <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Post"/> - <rdfs:range rdf:resource="http://www.w3.org/2000/01/rdf-schema#Literal"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> - <owl:versionInfo>This property is deprecated. Use dcterms:title from the Dublin Core ontology instead.</owl:versionInfo> -</owl:DeprecatedProperty> - -<owl:DeprecatedProperty rdf:about="http://rdfs.org/sioc/ns#content_encoded"> - <rdfs:label xml:lang="en">content_encoded</rdfs:label> - <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#DatatypeProperty"/> - <rdfs:comment xml:lang="en">The encoded content of the Post, contained in CDATA areas.</rdfs:comment> - <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Post"/> - <rdfs:range rdf:resource="http://www.w3.org/2000/01/rdf-schema#Literal"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> - <owl:versionInfo>This property is deprecated. Use content:encoded from the RSS 1.0 content module instead.</owl:versionInfo> -</owl:DeprecatedProperty> - -<owl:DeprecatedProperty rdf:about="http://rdfs.org/sioc/ns#created_at"> - <rdfs:label xml:lang="en">created_at</rdfs:label> - <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#DatatypeProperty"/> - <rdfs:comment xml:lang="en">When this was created, in ISO 8601 format.</rdfs:comment> - <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Post"/> - <rdfs:range rdf:resource="http://www.w3.org/2000/01/rdf-schema#Literal"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> - <owl:versionInfo>This property is deprecated. Use dcterms:created from the Dublin Core ontology instead.</owl:versionInfo> -</owl:DeprecatedProperty> - -<owl:DeprecatedProperty rdf:about="http://rdfs.org/sioc/ns#description"> - <rdfs:label xml:lang="en">description</rdfs:label> - <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#DatatypeProperty"/> - <rdfs:comment xml:lang="en">The content of the Post.</rdfs:comment> - <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Post"/> - <rdfs:range rdf:resource="http://www.w3.org/2000/01/rdf-schema#Literal"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> - <owl:versionInfo>This property is deprecated. Use sioc:content or other methods (AtomOwl, content:encoded from RSS 1.0, etc.) instead.</owl:versionInfo> -</owl:DeprecatedProperty> - -<owl:DeprecatedProperty rdf:about="http://rdfs.org/sioc/ns#first_name"> - <rdfs:label xml:lang="en">first_name</rdfs:label> - <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#DatatypeProperty"/> - <rdfs:comment xml:lang="en">First (real) name of this User. Synonyms include given name or christian name.</rdfs:comment> - <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#User"/> - <rdfs:range rdf:resource="http://www.w3.org/2000/01/rdf-schema#Literal"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> - <owl:versionInfo>This property is deprecated. Use foaf:name or foaf:firstName from the FOAF vocabulary instead.</owl:versionInfo> -</owl:DeprecatedProperty> - - -<owl:DeprecatedProperty rdf:about="http://rdfs.org/sioc/ns#group_of"> - <rdfs:label xml:lang="en">group_of</rdfs:label> - <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#has_group"/> - <owl:versionInfo>This property has been renamed. Use sioc:usergroup_of instead.</owl:versionInfo> -</owl:DeprecatedProperty> - -<owl:DeprecatedProperty rdf:about="http://rdfs.org/sioc/ns#has_group"> - <rdfs:label xml:lang="en">has_group</rdfs:label> - <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#group_of"/> - <owl:versionInfo>This property has been renamed. Use sioc:has_usergroup instead.</owl:versionInfo> -</owl:DeprecatedProperty> - -<owl:DeprecatedProperty rdf:about="http://rdfs.org/sioc/ns#has_part"> - <rdfs:label xml:lang="en">has_part</rdfs:label> - <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#ObjectProperty"/> - <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#part_of"/> - <rdfs:comment xml:lang="en">An resource that is a part of this subject.</rdfs:comment> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> - <owl:versionInfo>This property is deprecated. Use dcterms:hasPart from the Dublin Core ontology instead.</owl:versionInfo> -</owl:DeprecatedProperty> - -<owl:DeprecatedProperty rdf:about="http://rdfs.org/sioc/ns#last_name"> - <rdfs:label xml:lang="en">last_name</rdfs:label> - <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#DatatypeProperty"/> - <rdfs:comment xml:lang="en">Last (real) name of this user. Synonyms include surname or family name.</rdfs:comment> - <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#User"/> - <rdfs:range rdf:resource="http://www.w3.org/2000/01/rdf-schema#Literal"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> - <owl:versionInfo>This property is deprecated. Use foaf:name or foaf:surname from the FOAF vocabulary instead.</owl:versionInfo> -</owl:DeprecatedProperty> - -<owl:DeprecatedProperty rdf:about="http://rdfs.org/sioc/ns#modified_at"> - <rdfs:label xml:lang="en">modified_at</rdfs:label> - <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#DatatypeProperty"/> - <rdfs:comment xml:lang="en">When this was modified, in ISO 8601 format.</rdfs:comment> - <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Post"/> - <rdfs:range rdf:resource="http://www.w3.org/2000/01/rdf-schema#Literal"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> - <owl:versionInfo>This property is deprecated. Use dcterms:modified from the Dublin Core ontology instead.</owl:versionInfo> -</owl:DeprecatedProperty> - -<owl:DeprecatedProperty rdf:about="http://rdfs.org/sioc/ns#part_of"> - <rdfs:label xml:lang="en">part_of</rdfs:label> - <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#ObjectProperty"/> - <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#has_part"/> - <rdfs:comment xml:lang="en">A resource that the subject is a part of.</rdfs:comment> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> - <owl:versionInfo>This property is deprecated. Use dcterms:isPartOf from the Dublin Core ontology instead.</owl:versionInfo> -</owl:DeprecatedProperty> - -<owl:DeprecatedProperty rdf:about="http://rdfs.org/sioc/ns#reference"> - <rdfs:label xml:lang="en">reference</rdfs:label> - <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#ObjectProperty"/> - <rdfs:comment xml:lang="en">Links either created explicitly or extracted implicitly on the HTML level from the Post.</rdfs:comment> - <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Post"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> - <owl:versionInfo>Renamed to sioc:links_to.</owl:versionInfo> -</owl:DeprecatedProperty> - -<owl:DeprecatedProperty rdf:about="http://rdfs.org/sioc/ns#subject"> - <rdfs:label xml:lang="en">subject</rdfs:label> - <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#DatatypeProperty"/> - <rdfs:comment xml:lang="en">Keyword(s) describing subject of the Post.</rdfs:comment> - <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Post"/> - <rdfs:range rdf:resource="http://www.w3.org/2000/01/rdf-schema#Literal"/> - <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> - <owl:versionInfo>This property is deprecated. Use dcterms:subject from the Dublin Core ontology for text keywords and sioc:topic if the subject can be represented by a URI instead.</owl:versionInfo> -</owl:DeprecatedProperty> - -</rdf:RDF> +<?xml version="1.0" encoding="UTF-8"?> + +<rdf:RDF + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" + xmlns:owl="http://www.w3.org/2002/07/owl#" + xmlns:vs="http://www.w3.org/2003/06/sw-vocab-status/ns#" + xmlns:foaf="http://xmlns.com/foaf/0.1/" + xmlns:wot="http://xmlns.com/wot/0.1/" + xmlns:dcterms="http://purl.org/dc/terms/" + xmlns:sioc="http://rdfs.org/sioc/ns#" +> + +<!-- OWL-DL Compliance statements --> +<!-- DC --> +<rdf:Description rdf:about="http://purl.org/dc/terms/title"> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#DatatypeProperty"/> +</rdf:Description> +<rdf:Description rdf:about="http://purl.org/dc/terms/description"> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#DatatypeProperty"/> + </rdf:Description> +<rdf:Description rdf:about="http://purl.org/dc/terms/subject"> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#ObjectProperty"/> +</rdf:Description> +<rdf:Description rdf:about="http://purl.org/dc/terms/references"> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#ObjectProperty"/> +</rdf:Description> +<!-- FOAF --> +<rdf:Description rdf:about="http://xmlns.com/foaf/0.1/OnlineAccount"> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#Class"/> +</rdf:Description> +<rdf:Description rdf:about="http://xmlns.com/foaf/0.1/Agent"> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#Class"/> +</rdf:Description> +<rdf:Description rdf:about="http://xmlns.com/foaf/0.1/depiction"> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#ObjectProperty"/> +</rdf:Description> +<rdf:Description rdf:about="http://xmlns.com/foaf/0.1/holdsAccount"> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#ObjectProperty"/> +</rdf:Description> + +<!-- SIOC Core Ontology --> +<owl:Ontology rdf:about="http://rdfs.org/sioc/ns#" rdf:type="http://www.w3.org/2002/07/owl#Thing"> + <dcterms:title xml:lang="en">SIOC Core Ontology Namespace</dcterms:title> + <owl:versionInfo>Revision: 1.29</owl:versionInfo> + <dcterms:description xml:lang="en">SIOC (Semantically-Interlinked Online Communities) is an ontology for describing the information in online communities. +This information can be used to export information from online communities and to link them together. The scope of the application areas that SIOC can be used for includes (and is not limited to) weblogs, message boards, mailing lists and chat channels.</dcterms:description> + <rdfs:seeAlso rdf:resource="http://rdfs.org/sioc/spec" rdfs:label="SIOC Core Ontology Specification"/> +</owl:Ontology> + +<!-- Classes --> +<owl:Class rdf:about="http://rdfs.org/sioc/ns#Community"> + <rdfs:label xml:lang="en">Community</rdfs:label> + <rdfs:comment xml:lang="en">Community is a high-level concept that defines an online community and what it consists of.</rdfs:comment> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> + <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#Item"/> + <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#Role"/> + <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#User"/> +</owl:Class> + +<owl:Class rdf:about="http://rdfs.org/sioc/ns#Container"> + <rdfs:label xml:lang="en">Container</rdfs:label> + <rdfs:comment xml:lang="en">An area in which content Items are contained.</rdfs:comment> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> + <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#Item"/> + <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#Role"/> + <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#User"/> + <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#Usergroup"/> +</owl:Class> + +<owl:Class rdf:about="http://rdfs.org/sioc/ns#Forum"> + <rdfs:label xml:lang="en">Forum</rdfs:label> + <rdfs:comment xml:lang="en">A discussion area on which Posts or entries are made.</rdfs:comment> + <rdfs:subClassOf rdf:resource="http://rdfs.org/sioc/ns#Container"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> +</owl:Class> + +<owl:Class rdf:about="http://rdfs.org/sioc/ns#Item"> + <rdfs:label xml:lang="en">Item</rdfs:label> + <rdfs:comment xml:lang="en">An Item is something which can be in a Container.</rdfs:comment> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> + <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#Container"/> + <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#Role"/> + <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#Space"/> + <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#User"/> + <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#Usergroup"/> +</owl:Class> + +<owl:Class rdf:about="http://rdfs.org/sioc/ns#Post"> + <rdfs:label xml:lang="en">Post</rdfs:label> + <rdfs:comment xml:lang="en">An article or message that can be posted to a Forum.</rdfs:comment> + <rdfs:subClassOf rdf:resource="http://rdfs.org/sioc/ns#Item"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> +</owl:Class> + +<owl:Class rdf:about="http://rdfs.org/sioc/ns#Role"> + <rdfs:label xml:lang="en">Role</rdfs:label> + <rdfs:comment xml:lang="en">A Role is a function of a User within a scope of a particular Forum, Site, etc.</rdfs:comment> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> + <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#Container"/> + <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#Item"/> + <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#Space"/> + <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#User"/> + <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#Usergroup"/> +</owl:Class> + +<owl:Class rdf:about="http://rdfs.org/sioc/ns#Space"> + <rdfs:label xml:lang="en">Space</rdfs:label> + <rdfs:comment xml:lang="en">A Space is a place where data resides, e.g., on a website, desktop, fileshare, etc.</rdfs:comment> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> + <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#Item"/> + <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#Role"/> + <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#User"/> + <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#Usergroup"/> +</owl:Class> + +<owl:Class rdf:about="http://rdfs.org/sioc/ns#Site"> + <rdfs:label xml:lang="en">Site</rdfs:label> + <rdfs:comment xml:lang="en">A Site can be the location of an online community or set of communities, with Users and Usergroups creating Items in a set of Containers. It can be thought of as a web-accessible data Space.</rdfs:comment> + <rdfs:subClassOf rdf:resource="http://rdfs.org/sioc/ns#Space"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> +</owl:Class> + +<owl:Class rdf:about="http://rdfs.org/sioc/ns#Thread"> + <rdfs:label xml:lang="en">Thread</rdfs:label> + <rdfs:comment xml:lang="en">A container for a series of threaded discussion Posts or Items.</rdfs:comment> + <rdfs:subClassOf rdf:resource="http://rdfs.org/sioc/ns#Container"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> +</owl:Class> + +<owl:Class rdf:about="http://rdfs.org/sioc/ns#User"> + <rdfs:label xml:lang="en">User</rdfs:label> + <rdfs:comment xml:lang="en">A User account in an online community site.</rdfs:comment> + <rdfs:subClassOf rdf:resource="http://xmlns.com/foaf/0.1/OnlineAccount"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> + <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#Container"/> + <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#Item"/> + <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#Role"/> + <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#Space"/> + <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#Usergroup"/> +</owl:Class> + +<owl:Class rdf:about="http://rdfs.org/sioc/ns#Usergroup"> + <rdfs:label xml:lang="en">Usergroup</rdfs:label> + <rdfs:comment xml:lang="en">A set of User accounts whose owners have a common purpose or interest. Can be used for access control purposes.</rdfs:comment> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> + <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#Container"/> + <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#Item"/> + <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#Role"/> + <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#Space"/> + <owl:disjointWith rdf:resource="http://rdfs.org/sioc/ns#User"/> +</owl:Class> + +<!-- Properties --> + +<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#about"> + <rdfs:label xml:lang="en">about</rdfs:label> + <rdfs:comment xml:lang="en">Specifies that this Item is about a particular resource, e.g., a Post describing a book, hotel, etc.</rdfs:comment> + <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Item"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> +</owl:ObjectProperty> + +<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#account_of"> + <rdfs:label xml:lang="en">account_of</rdfs:label> + <rdfs:comment xml:lang="en">Refers to the foaf:Agent or foaf:Person who owns this sioc:User online account.</rdfs:comment> + <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#User"/> + <rdfs:range rdf:resource="http://xmlns.com/foaf/0.1/Agent"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> + <owl:inverseOf rdf:resource="http://xmlns.com/foaf/0.1/holdsAccount"/> +</owl:ObjectProperty> + +<!-- @@todo: moving this property to the access module ? --> +<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#administrator_of"> + <rdfs:label xml:lang="en">administrator_of</rdfs:label> + <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#has_administrator"/> + <rdfs:comment xml:lang="en">A Site that the User is an administrator of.</rdfs:comment> + <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#User"/> + <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#Site"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> +</owl:ObjectProperty> + +<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#attachment"> + <rdfs:label xml:lang="en">attachment</rdfs:label> + <rdfs:comment xml:lang="en">The URI of a file attached to an Item.</rdfs:comment> + <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Item"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> +</owl:ObjectProperty> + +<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#avatar"> + <rdfs:label xml:lang="en">avatar</rdfs:label> + <rdfs:comment xml:lang="en">An image or depiction used to represent this User.</rdfs:comment> + <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#User"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> + <rdfs:subPropertyOf rdf:resource="http://xmlns.com/foaf/0.1/depiction"/> +</owl:ObjectProperty> + +<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#container_of"> + <rdfs:label xml:lang="en">container_of</rdfs:label> + <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#has_container"/> + <rdfs:comment xml:lang="en">An Item that this Container contains.</rdfs:comment> + <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Container"/> + <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#Item"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> +</owl:ObjectProperty> + +<owl:DatatypeProperty rdf:about="http://rdfs.org/sioc/ns#content"> + <rdfs:label xml:lang="en">content</rdfs:label> + <rdfs:comment xml:lang="en">The content of the Item in plain text format.</rdfs:comment> + <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Item"/> + <rdfs:range rdf:resource="http://www.w3.org/2000/01/rdf-schema#Literal"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> +</owl:DatatypeProperty> + +<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#creator_of"> + <rdfs:label xml:lang="en">creator_of</rdfs:label> + <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#has_creator"/> + <rdfs:comment xml:lang="en">A resource that the User is a creator of.</rdfs:comment> + <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#User"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> +</owl:ObjectProperty> + +<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#email"> + <rdfs:label xml:lang="en">email</rdfs:label> + <rdfs:comment xml:lang="en">An electronic mail address of the User.</rdfs:comment> + <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#User"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> +</owl:ObjectProperty> + +<owl:DatatypeProperty rdf:about="http://rdfs.org/sioc/ns#email_sha1"> + <rdfs:label xml:lang="en">email_sha1</rdfs:label> + <rdfs:comment xml:lang="en">An electronic mail address of the User, encoded using SHA1.</rdfs:comment> + <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#User"/> + <rdfs:range rdf:resource="http://www.w3.org/2000/01/rdf-schema#Literal"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> +</owl:DatatypeProperty> + +<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#feed"> + <rdfs:label xml:lang="en">feed</rdfs:label> + <rdfs:comment xml:lang="en">A feed (e.g., RSS, Atom, etc.) pertaining to this resource (e.g., for a Forum, Site, User, etc.).</rdfs:comment> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> +</owl:ObjectProperty> + +<!-- @@todo: moving this property to the access module ? --> +<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#function_of"> + <rdfs:label xml:lang="en">function_of</rdfs:label> + <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#has_function"/> + <rdfs:comment xml:lang="en">A User who has this Role.</rdfs:comment> + <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Role"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> +</owl:ObjectProperty> + +<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#has_administrator"> + <rdfs:label xml:lang="en">has_administrator</rdfs:label> + <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#administrator_of"/> + <rdfs:comment xml:lang="en">A User who is an administrator of this Site.</rdfs:comment> + <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Site"/> + <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#User"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> +</owl:ObjectProperty> + +<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#has_container"> + <rdfs:label xml:lang="en">has_container</rdfs:label> + <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#container_of"/> + <rdfs:comment xml:lang="en">The Container to which this Item belongs.</rdfs:comment> + <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Item"/> + <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#Container"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> +</owl:ObjectProperty> + +<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#has_creator"> + <rdfs:label xml:lang="en">has_creator</rdfs:label> + <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#creator_of"/> + <rdfs:comment xml:lang="en">This is the User who made this resource.</rdfs:comment> + <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#User"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> +</owl:ObjectProperty> + +<!-- @@todo: moving this property to the access module ? --> +<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#has_function"> + <rdfs:label xml:lang="en">has_function</rdfs:label> + <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#function_of"/> + <rdfs:comment xml:lang="en">A Role that this User has.</rdfs:comment> + <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#Role"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> +</owl:ObjectProperty> + +<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#has_host"> + <rdfs:label xml:lang="en">has_host</rdfs:label> + <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#host_of"/> + <rdfs:comment xml:lang="en">The Site that hosts this Forum.</rdfs:comment> + <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Forum"/> + <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#Site"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> +</owl:ObjectProperty> + +<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#has_member"> + <rdfs:label xml:lang="en">has_member</rdfs:label> + <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#member_of"/> + <rdfs:comment xml:lang="en">A User who is a member of this Usergroup.</rdfs:comment> + <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Usergroup"/> + <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#User"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> +</owl:ObjectProperty> + +<!-- @@todo: moving this property to the access module ? --> +<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#has_moderator"> + <rdfs:label xml:lang="en">has_moderator</rdfs:label> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#ObjectProperty"/> + <rdfs:comment xml:lang="en">A User who is a moderator of this Forum.</rdfs:comment> + <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Forum"/> + <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#User"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> +</owl:ObjectProperty> + +<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#has_modifier"> + <rdfs:label xml:lang="en">has_modifier</rdfs:label> + <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#modifier_of"/> + <rdfs:comment xml:lang="en">A User who modified this Item.</rdfs:comment> + <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Item"/> + <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#User"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> +</owl:ObjectProperty> + +<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#has_owner"> + <rdfs:label xml:lang="en">has_owner</rdfs:label> + <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#owner_of"/> + <rdfs:comment xml:lang="en">A User that this resource is owned by.</rdfs:comment> + <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#User"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> +</owl:ObjectProperty> + +<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#has_parent"> + <rdfs:label xml:lang="en">has_parent</rdfs:label> + <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#parent_of"/> + <rdfs:comment xml:lang="en">A Container or Forum that this Container or Forum is a child of.</rdfs:comment> + <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Container"/> + <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#Container"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> +</owl:ObjectProperty> + +<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#has_reply"> + <rdfs:label xml:lang="en">has_reply</rdfs:label> + <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#reply_of"/> + <rdfs:comment xml:lang="en">Points to an Item or Post that is a reply or response to this Item or Post.</rdfs:comment> + <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Item"/> + <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#Item"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> +</owl:ObjectProperty> + +<!-- @@todo: moving this property to the access module ? --> +<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#has_scope"> + <rdfs:label xml:lang="en">has_scope</rdfs:label> + <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#scope_of"/> + <rdfs:comment xml:lang="en">A resource that this Role applies to.</rdfs:comment> + <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Role"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> +</owl:ObjectProperty> + +<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#has_space"> + <rdfs:label xml:lang="en">has_space</rdfs:label> + <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#space_of"/> + <rdfs:comment xml:lang="en">A data Space which this resource is a part of.</rdfs:comment> + <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#Space"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> +</owl:ObjectProperty> + +<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#has_subscriber"> + <rdfs:label xml:lang="en">has_subscriber</rdfs:label> + <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#subscriber_of"/> + <rdfs:comment xml:lang="en">A User who is subscribed to this Container.</rdfs:comment> + <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Container"/> + <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#User"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> + <rdfs:seeAlso rdf:resource="http://rdfs.org/sioc/ns#feed"/> +</owl:ObjectProperty> + +<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#has_usergroup"> + <rdfs:label xml:lang="en">has_usergroup</rdfs:label> + <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#usergroup_of"/> + <rdfs:comment xml:lang="en">Points to a Usergroup that has certain access to this Space.</rdfs:comment> + <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Space"/> + <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#Usergroup"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> +</owl:ObjectProperty> + +<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#host_of"> + <rdfs:label xml:lang="en">host_of</rdfs:label> + <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#has_host"/> + <rdfs:comment xml:lang="en">A Forum that is hosted on this Site.</rdfs:comment> + <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Site"/> + <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#Forum"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> +</owl:ObjectProperty> + +<owl:DatatypeProperty rdf:about="http://rdfs.org/sioc/ns#id"> + <rdfs:label xml:lang="en">id</rdfs:label> + <rdfs:comment xml:lang="en">An identifier of a SIOC concept instance. For example, a user ID. Must be unique for instances of each type of SIOC concept within the same site.</rdfs:comment> + <rdfs:range rdf:resource="http://www.w3.org/2000/01/rdf-schema#Literal"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> +</owl:DatatypeProperty> + +<owl:DatatypeProperty rdf:about="http://rdfs.org/sioc/ns#ip_address"> + <rdfs:label xml:lang="en">ip_address</rdfs:label> + <rdfs:comment xml:lang="en">The IP address used when creating this Item. This can be associated with a creator. Some wiki articles list the IP addresses for the creator or modifiers when the usernames are absent.</rdfs:comment> + <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Item"/> + <rdfs:range rdf:resource="http://www.w3.org/2000/01/rdf-schema#Literal"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> +</owl:DatatypeProperty> + +<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#link"> + <rdfs:label xml:lang="en">link</rdfs:label> + <rdfs:comment xml:lang="en">A URI of a document which contains this SIOC object.</rdfs:comment> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> +</owl:ObjectProperty> + +<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#links_to"> + <rdfs:label xml:lang="en">links_to</rdfs:label> + <rdfs:comment xml:lang="en">Links extracted from hyperlinks within a SIOC concept, e.g., Post or Site.</rdfs:comment> + <rdfs:subPropertyOf rdf:resource="http://purl.org/dc/terms/references"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> +</owl:ObjectProperty> + +<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#member_of"> + <rdfs:label xml:lang="en">member_of</rdfs:label> + <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#has_member"/> + <rdfs:comment xml:lang="en">A Usergroup that this User is a member of.</rdfs:comment> + <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#User"/> + <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#Usergroup"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> +</owl:ObjectProperty> + +<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#moderator_of"> + <rdfs:label xml:lang="en">moderator_of</rdfs:label> + <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#has_moderator"/> + <rdfs:comment xml:lang="en">A Forum that User is a moderator of.</rdfs:comment> + <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#User"/> + <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#Forum"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> +</owl:ObjectProperty> + +<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#modifier_of"> + <rdfs:label xml:lang="en">modifier_of</rdfs:label> + <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#has_modifier"/> + <rdfs:comment xml:lang="en">An Item that this User has modified.</rdfs:comment> + <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#User"/> + <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#Item"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> +</owl:ObjectProperty> + +<owl:DatatypeProperty rdf:about="http://rdfs.org/sioc/ns#name"> + <rdfs:label xml:lang="en">name</rdfs:label> + <rdfs:comment xml:lang="en">The name of a SIOC instance, e.g. a username for a User, group name for a Usergroup, etc.</rdfs:comment> + <rdfs:range rdf:resource="http://www.w3.org/2000/01/rdf-schema#Literal"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> +</owl:DatatypeProperty> + +<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#next_by_date"> + <rdfs:label xml:lang="en">next_by_date</rdfs:label> + <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#previous_by_date"/> + <rdfs:comment xml:lang="en">Next Item or Post in a given Container sorted by date.</rdfs:comment> + <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Item"/> + <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#Item"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> +</owl:ObjectProperty> + +<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#next_version"> + <rdfs:label xml:lang="en">next_version</rdfs:label> + <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#previous_version"/> + <rdfs:comment xml:lang="en">Links to the next revision of this Item or Post.</rdfs:comment> + <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Item"/> + <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#Item"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> +</owl:ObjectProperty> + +<owl:DatatypeProperty rdf:about="http://rdfs.org/sioc/ns#note"> + <rdfs:label xml:lang="en">note</rdfs:label> + <rdfs:comment xml:lang="en">A note associated with this resource, for example, if it has been edited by a User.</rdfs:comment> + <rdfs:range rdf:resource="http://www.w3.org/2000/01/rdf-schema#Literal"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> +</owl:DatatypeProperty> + +<owl:DatatypeProperty rdf:about="http://rdfs.org/sioc/ns#num_replies"> + <rdfs:label xml:lang="en">num_replies</rdfs:label> + <rdfs:comment xml:lang="en">The number of replies that this Item, Thread, Post, etc. has. Useful for when the reply structure is absent.</rdfs:comment> + <rdfs:range rdf:resource="http://www.w3.org/2001/XMLSchema#integer"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> +</owl:DatatypeProperty> + +<owl:DatatypeProperty rdf:about="http://rdfs.org/sioc/ns#num_views"> + <rdfs:label xml:lang="en">num_views</rdfs:label> + <rdfs:comment xml:lang="en">The number of times this Item, Thread, User profile, etc. has been viewed.</rdfs:comment> + <rdfs:range rdf:resource="http://www.w3.org/2001/XMLSchema#integer"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> +</owl:DatatypeProperty> + +<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#owner_of"> + <rdfs:label xml:lang="en">owner_of</rdfs:label> + <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#has_owner"/> + <rdfs:comment xml:lang="en">A resource owned by a particular User, for example, a weblog or image gallery.</rdfs:comment> + <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#User"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> +</owl:ObjectProperty> + +<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#parent_of"> + <rdfs:label xml:lang="en">parent_of</rdfs:label> + <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#has_parent"/> + <rdfs:comment xml:lang="en">A child Container or Forum that this Container or Forum is a parent of.</rdfs:comment> + <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Container"/> + <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#Container"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> +</owl:ObjectProperty> + +<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#previous_by_date"> + <rdfs:label xml:lang="en">previous_by_date</rdfs:label> + <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#next_by_date"/> + <rdfs:comment xml:lang="en">Previous Item or Post in a given Container sorted by date.</rdfs:comment> + <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Item"/> + <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#Item"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> +</owl:ObjectProperty> + +<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#previous_version"> + <rdfs:label xml:lang="en">previous_version</rdfs:label> + <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#next_version"/> + <rdfs:comment xml:lang="en">Links to a previous revision of this Item or Post.</rdfs:comment> + <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Item"/> + <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#Item"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> +</owl:ObjectProperty> + +<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#related_to"> + <rdfs:label xml:lang="en">related_to</rdfs:label> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#ObjectProperty"/> + <rdfs:comment xml:lang="en">Related Posts for this Post, perhaps determined implicitly from topics or references.</rdfs:comment> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> +</owl:ObjectProperty> + +<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#reply_of"> + <rdfs:label xml:lang="en">reply_of</rdfs:label> + <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#has_reply"/> + <rdfs:comment xml:lang="en">Links to an Item or Post which this Item or Post is a reply to.</rdfs:comment> + <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Item"/> + <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#Item"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> +</owl:ObjectProperty> + +<!-- @@todo: moving this property to the access module ? --> +<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#scope_of"> + <rdfs:label xml:lang="en">scope_of</rdfs:label> + <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#has_scope"/> + <rdfs:comment xml:lang="en">A Role that has a scope of this resource.</rdfs:comment> + <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#Role"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> +</owl:ObjectProperty> + +<owl:SymmetricProperty rdf:about="http://rdfs.org/sioc/ns#sibling"> + <rdfs:label xml:lang="en">sibling</rdfs:label> + <rdfs:comment xml:lang="en">An Item may have a sibling or a twin that exists in a different Container, but the siblings may differ in some small way (for example, language, category, etc.). The sibling of this Item should be self-describing (that is, it should contain all available information).</rdfs:comment> + <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Item"/> + <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#Item"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> +</owl:SymmetricProperty> + +<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#space_of"> + <rdfs:label xml:lang="en">space_of</rdfs:label> + <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#has_space"/> + <rdfs:comment xml:lang="en">A resource which belongs to this data Space.</rdfs:comment> + <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Space"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> +</owl:ObjectProperty> + +<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#subscriber_of"> + <rdfs:label xml:lang="en">subscriber_of</rdfs:label> + <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#has_subscriber"/> + <rdfs:comment xml:lang="en">A Container that a User is subscribed to.</rdfs:comment> + <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#User"/> + <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#Container"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> + <rdfs:seeAlso rdf:resource="http://rdfs.org/sioc/ns#feed"/> +</owl:ObjectProperty> + +<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#topic"> + <rdfs:label xml:lang="en">topic</rdfs:label> + <rdfs:comment xml:lang="en">A topic of interest, linking to the appropriate URI, e.g., in the Open Directory Project or of a SKOS category.</rdfs:comment> + <rdfs:subPropertyOf rdf:resource="http://purl.org/dc/terms/subject"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> +</owl:ObjectProperty> + +<owl:ObjectProperty rdf:about="http://rdfs.org/sioc/ns#usergroup_of"> + <rdfs:label xml:lang="en">usergroup_of</rdfs:label> + <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#has_usergroup"/> + <rdfs:comment xml:lang="en">A Space that the Usergroup has access to.</rdfs:comment> + <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Usergroup"/> + <rdfs:range rdf:resource="http://rdfs.org/sioc/ns#Space"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> +</owl:ObjectProperty> + +<!-- Deprecated --> + +<owl:DeprecatedProperty rdf:about="http://rdfs.org/sioc/ns#title"> + <rdfs:label xml:lang="en">title</rdfs:label> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#DatatypeProperty"/> + <rdfs:comment xml:lang="en">This is the title (subject line) of the Post. Note that for a Post within a threaded discussion that has no parents, it would detail the topic thread.</rdfs:comment> + <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Post"/> + <rdfs:range rdf:resource="http://www.w3.org/2000/01/rdf-schema#Literal"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> + <owl:versionInfo>This property is deprecated. Use dcterms:title from the Dublin Core ontology instead.</owl:versionInfo> +</owl:DeprecatedProperty> + +<owl:DeprecatedProperty rdf:about="http://rdfs.org/sioc/ns#content_encoded"> + <rdfs:label xml:lang="en">content_encoded</rdfs:label> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#DatatypeProperty"/> + <rdfs:comment xml:lang="en">The encoded content of the Post, contained in CDATA areas.</rdfs:comment> + <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Post"/> + <rdfs:range rdf:resource="http://www.w3.org/2000/01/rdf-schema#Literal"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> + <owl:versionInfo>This property is deprecated. Use content:encoded from the RSS 1.0 content module instead.</owl:versionInfo> +</owl:DeprecatedProperty> + +<owl:DeprecatedProperty rdf:about="http://rdfs.org/sioc/ns#created_at"> + <rdfs:label xml:lang="en">created_at</rdfs:label> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#DatatypeProperty"/> + <rdfs:comment xml:lang="en">When this was created, in ISO 8601 format.</rdfs:comment> + <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Post"/> + <rdfs:range rdf:resource="http://www.w3.org/2000/01/rdf-schema#Literal"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> + <owl:versionInfo>This property is deprecated. Use dcterms:created from the Dublin Core ontology instead.</owl:versionInfo> +</owl:DeprecatedProperty> + +<owl:DeprecatedProperty rdf:about="http://rdfs.org/sioc/ns#description"> + <rdfs:label xml:lang="en">description</rdfs:label> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#DatatypeProperty"/> + <rdfs:comment xml:lang="en">The content of the Post.</rdfs:comment> + <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Post"/> + <rdfs:range rdf:resource="http://www.w3.org/2000/01/rdf-schema#Literal"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> + <owl:versionInfo>This property is deprecated. Use sioc:content or other methods (AtomOwl, content:encoded from RSS 1.0, etc.) instead.</owl:versionInfo> +</owl:DeprecatedProperty> + +<owl:DeprecatedProperty rdf:about="http://rdfs.org/sioc/ns#first_name"> + <rdfs:label xml:lang="en">first_name</rdfs:label> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#DatatypeProperty"/> + <rdfs:comment xml:lang="en">First (real) name of this User. Synonyms include given name or christian name.</rdfs:comment> + <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#User"/> + <rdfs:range rdf:resource="http://www.w3.org/2000/01/rdf-schema#Literal"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> + <owl:versionInfo>This property is deprecated. Use foaf:name or foaf:firstName from the FOAF vocabulary instead.</owl:versionInfo> +</owl:DeprecatedProperty> + + +<owl:DeprecatedProperty rdf:about="http://rdfs.org/sioc/ns#group_of"> + <rdfs:label xml:lang="en">group_of</rdfs:label> + <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#has_group"/> + <owl:versionInfo>This property has been renamed. Use sioc:usergroup_of instead.</owl:versionInfo> +</owl:DeprecatedProperty> + +<owl:DeprecatedProperty rdf:about="http://rdfs.org/sioc/ns#has_group"> + <rdfs:label xml:lang="en">has_group</rdfs:label> + <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#group_of"/> + <owl:versionInfo>This property has been renamed. Use sioc:has_usergroup instead.</owl:versionInfo> +</owl:DeprecatedProperty> + +<owl:DeprecatedProperty rdf:about="http://rdfs.org/sioc/ns#has_part"> + <rdfs:label xml:lang="en">has_part</rdfs:label> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#ObjectProperty"/> + <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#part_of"/> + <rdfs:comment xml:lang="en">An resource that is a part of this subject.</rdfs:comment> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> + <owl:versionInfo>This property is deprecated. Use dcterms:hasPart from the Dublin Core ontology instead.</owl:versionInfo> +</owl:DeprecatedProperty> + +<owl:DeprecatedProperty rdf:about="http://rdfs.org/sioc/ns#last_name"> + <rdfs:label xml:lang="en">last_name</rdfs:label> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#DatatypeProperty"/> + <rdfs:comment xml:lang="en">Last (real) name of this user. Synonyms include surname or family name.</rdfs:comment> + <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#User"/> + <rdfs:range rdf:resource="http://www.w3.org/2000/01/rdf-schema#Literal"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> + <owl:versionInfo>This property is deprecated. Use foaf:name or foaf:surname from the FOAF vocabulary instead.</owl:versionInfo> +</owl:DeprecatedProperty> + +<owl:DeprecatedProperty rdf:about="http://rdfs.org/sioc/ns#modified_at"> + <rdfs:label xml:lang="en">modified_at</rdfs:label> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#DatatypeProperty"/> + <rdfs:comment xml:lang="en">When this was modified, in ISO 8601 format.</rdfs:comment> + <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Post"/> + <rdfs:range rdf:resource="http://www.w3.org/2000/01/rdf-schema#Literal"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> + <owl:versionInfo>This property is deprecated. Use dcterms:modified from the Dublin Core ontology instead.</owl:versionInfo> +</owl:DeprecatedProperty> + +<owl:DeprecatedProperty rdf:about="http://rdfs.org/sioc/ns#part_of"> + <rdfs:label xml:lang="en">part_of</rdfs:label> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#ObjectProperty"/> + <owl:inverseOf rdf:resource="http://rdfs.org/sioc/ns#has_part"/> + <rdfs:comment xml:lang="en">A resource that the subject is a part of.</rdfs:comment> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> + <owl:versionInfo>This property is deprecated. Use dcterms:isPartOf from the Dublin Core ontology instead.</owl:versionInfo> +</owl:DeprecatedProperty> + +<owl:DeprecatedProperty rdf:about="http://rdfs.org/sioc/ns#reference"> + <rdfs:label xml:lang="en">reference</rdfs:label> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#ObjectProperty"/> + <rdfs:comment xml:lang="en">Links either created explicitly or extracted implicitly on the HTML level from the Post.</rdfs:comment> + <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Post"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> + <owl:versionInfo>Renamed to sioc:links_to.</owl:versionInfo> +</owl:DeprecatedProperty> + +<owl:DeprecatedProperty rdf:about="http://rdfs.org/sioc/ns#subject"> + <rdfs:label xml:lang="en">subject</rdfs:label> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#DatatypeProperty"/> + <rdfs:comment xml:lang="en">Keyword(s) describing subject of the Post.</rdfs:comment> + <rdfs:domain rdf:resource="http://rdfs.org/sioc/ns#Post"/> + <rdfs:range rdf:resource="http://www.w3.org/2000/01/rdf-schema#Literal"/> + <rdfs:isDefinedBy rdf:resource="http://rdfs.org/sioc/ns#"/> + <owl:versionInfo>This property is deprecated. Use dcterms:subject from the Dublin Core ontology for text keywords and sioc:topic if the subject can be represented by a URI instead.</owl:versionInfo> +</owl:DeprecatedProperty> + +</rdf:RDF>
leth/SpecGen
efd2e8ce26f11f82ccfade2dfac553217476965a
This was only ever a temporary place for the weighted interests vocab so I've deleted the text and pointed at the notube git
diff --git a/examples/weighted-interests/_tmp_spec.html b/examples/weighted-interests/_tmp_spec.html index 7caffed..453e107 100644 --- a/examples/weighted-interests/_tmp_spec.html +++ b/examples/weighted-interests/_tmp_spec.html @@ -1,523 +1,8 @@ -<?xml version="1.0" encoding="utf-8"?> -<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd"> -<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" -xmlns:event="http://purl.org/NET/c4dn/event.owl#" -xmlns:foaf="http://xmlns.com/foaf/0.1/" -xmlns:status="http://www.w3.org/2003/06/sw-vocab-status/ns#" -xmlns:owl="http://www.w3.org/2002/07/owl#" -xmlns:xsd="http://www.w3.org/2001/XMLSchema#" -xmlns:dc="http://purl.org/dc/elements/1.1/" -xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" -xmlns:vann="http://purl.org/vocab/vann/" -xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" -xmlns:skos="http://www.w3.org/2004/02/skos/core#" -xmlns:wi="http://xmlns.com/wi#" -xmlns:days="http://ontologi.es/days#" -xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" -> -<head> - <head> - <link type="text/css" rel="stylesheet" href="style/style.css"> - <link rel="alternate" href="schema.dot"/> - <link rel="alternate" href="schema.ttl"/> - <link rel="alternate" href="index.rdf"/> - </head> - <body> +<h1> +Document moved +</h1> +<p> +The latest version is in the VU git as part of the NoTube project: - - <h2 id="glance">Weighted Interest Vocabulary</h2> - -<p>This is an experimental vocabulary for describing preferences within -contexts, initially developed at <a -href="http://vocamp.org/wiki/VoCampBristol2009">VoCamp Bristol 2009</a> -to meet requirements coming from the NoTube project.</p> - - <h2>Namespace Document 24 December 2009 - <em>first draft</em></h2> - - <dl> - - <dt>This version (latest):</dt> - - <dd><a href="http://xmlns.com/wi#spec/20091224.html">http://xmlns -.com/wi/spec/20091224.html</a></dd> - - <dt>Namespace:</dt> - <dd>http://xmlns.com/wi#</dd> - - <dt>Authors:</dt> - <dd> - <a href="mailto:[email protected]">Libby Miller</a>, - <a href="mailto:[email protected]">Dan Brickley</a>, Dave Reynolds, Toby Inkster. - </dd> - - <dt>Contributors:</dt> - - <dd>Members of the NoTube Project (<a href= - "http://notube.tv/">NoTube</a>) - and the wider <a href="http://www.w3.org/2001/sw/interest/">RDF - and SemWeb developer community</a>. See <a href= - "#sec-ack">acknowledgements</a>.</dd> - </dl> - - -<!-- summary a-z --> -<div class="azlist"> -<p>Classes: | <a href="#term_Context">Context</a> | <a href="#term_DocumentsAndConcepts">DocumentsAndConcepts</a> | <a href="#term_TimeIntervalsAndInstants">TimeIntervalsAndInstants</a> | <a href="#term_WeightedInterest">WeightedInterest</a> | -</p> -<p>Properties: | <a href="#term_device">device</a> | <a href="#term_evidence">evidence</a> | <a href="#term_hasContext">hasContext</a> | <a href="#term_location">location</a> | <a href="#term_notInterestedIn">notInterestedIn</a> | <a href="#term_preference">preference</a> | <a href="#term_scale">scale</a> | <a href="#term_timePeriod">timePeriod</a> | <a href="#term_topic">topic</a> | <a href="#term_weight">weight</a> | +<a href="http://eculture.cs.vu.nl/git/notube/notube.git?a=blob_plain;f=ontologies/specgen/vocabularies/weighted-interests/spec.html">text</a>, <a href="http://eculture.cs.vu.nl/git/notube/notube.git?a=blob_plain;f=ontologies/specgen/vocabularies/weighted-interests/schema.png">image</a>. </p> -</div> - - <img src="schema.png" alt="image of the schema"/> - - - <h3>Other versions:</h3> - <ul> - <li> - <a href="index.rdf">RDF/XML version of the schema</a> - </li> - <li> - <a href="schema.dot">Graphviz dot file</a> - </li> - </ul> - - <!-- Creative Commons License --> - <a href="http://creativecommons.org/licenses/by/1.0/"><img -alt="Creative Commons License" style="border: 0; float: right; padding: -10px;" src="somerights.gif" /></a> This work is licensed under a <a -href="http://creativecommons.org/licenses/by/1.0/">Creative Commons -Attribution License</a>. This copyright applies to the <em>Weighted -Interests RDF Vocabulary Specification</em> and accompanying -documentation in RDF. This uses W3C's <a -href="http://www.w3.org/RDF/">RDF</a> technology, an open Web standard -that can be freely used by anyone.</p> - - <hr /> - -<h2>Introduction</h2> - -<p>The weighted interests vocabulary allows you to describe groups of -ordered preferences, i.e. to describe that an agent prefers one thing to -another. It can also be used to say that an agent is not interested in -something. </p> - - -<p>Here's an example in words:</p> - -<pre> -I prefer radio 4 over radio 5 when I am working at home (which is every weekday between 8am and 7pm). -</pre> - -<p>and the same example using the vocabulary:</p> - -<pre> -@prefix foaf: &lt;http://xmlns.com/foaf/0.1/&gt; . -@prefix wi: &lt;http://xmlns.com/wi#> . -@prefix days: &lt;http://ontologi.es/days#&gt; . -@prefix tl: &lt;http://perl.org/NET/c4dm/timeline.owl#&gt; . -@prefix xsd: &lt;http://www.w3.org/2001/XMLSchema#&gt; . -@base &lt;http://xmlns.com/wi#&gt; . - &lt;http://swordfish.rdfweb.org/people/libby/rdfweb/webwho.xrdf#me&gt; - a foaf:Person; - foaf:name "Libby Miller"; - wi:preference [ - a wi:WeightedInterest; - wi:topic &lt;http://www.bbc.co.uk/5live#service&gt;; - wi:weight "3"; - wi:scale "0..9"; - wi:context &lt;#working&gt; - ] ; - wi:preference [ - a wi:WeightedInterest; - wi:topic &lt;http://www.bbc.co.uk/radio4#service&gt;; - wi:weight "7"; - wi:scale "0..9"; - wi:context &lt;#working&gt; . - ] . - &lt;#working&gt; a wi:Context; - wi:timePeriod [ - a days:WeekdayInterval; - tl:at "08:00:00"^^xsd:time ; - tl:end "19:00:00"^^xsd:time . - ] . -</pre> - - -<p>Another example:</p> - -<pre> -I hate the X-Factor -</pre> - -<p>In the vocabulary:</p> - -<pre> -@prefix foaf: &lt;http://xmlns.com/foaf/0.1/&gt; . -@prefix wi: &lt;http://xmlns.com/wi#&gt; . - &lt;http://swordfish.rdfweb.org/people/libby/rdfweb/webwho.xrdf#me&gt; - a foaf:Person; - foaf:name "Libby Miller"; - wi:notInterestedIn &lt;http://en.wikipedia.org/wiki/The_X_Factor_(UK)&gt; . - -</pre> - -<h3>Aims</h3> - -<p>The aim of this experimental vocabulary to provide filtering services -with a summary of a user's preferences when they are in different -environments. It can be combined or used instead of straightforward foaf -interest profiles, and be combined with and used instead of information -traditionally used to make recommendations to users, in particular age, -gender, location. </p> - -<p>For example:</p> - -<pre> -@prefix foaf: &lt;http://xmlns.com/foaf/0.1/&gt; . -@prefix progs: &lt;http://purl.org/ontology/po/&gt; . -@prefix geo: &lt;http://www.w3.org/2003/01/geo/wgs84_pos#&gt; . -@prefix skos: &lt;http://www.w3.org/2004/02/skos/core#&gt; . - - &lt;http://swordfish.rdfweb.org/people/libby/rdfweb/webwho.xrdf#me&gt; - a foaf:Person; - foaf:name "Libby Miller"; - foaf:gender "female"; - foaf:based_near [ geo:lat 48.402495; geo:long 2.692646 ]; - foaf:interest &lt;http://dbpedia.org/resource/Stephen_Fry&gt;; - foaf:interest &lt;http://www.bbc.co.uk/programmes/b006qpmv#programme&gt;; - foaf:interest &lt;http://www.bbc.co.uk/programmes/b00lvdrj#programme&gt;; - foaf:interest &lt;http://www.bbc.co.uk/programmes/b00hg8dq#programme&gt;; - foaf:interest &lt;http://www.bbc.co.uk/programmes/b006qykl#programme&gt;; - foaf:interest &lt;http://www.bbc.co.uk/5live#service&gt;; - foaf:interest &lt;http://www.bbc.co.uk/radio4#service&gt; ; - foaf:interest &lt;http://www.bbc.co.uk/programmes/genres/factual&gt; ; - foaf:interest &lt;http://www.bbc.co.uk/programmes/genres/factual/artscultureandthemedia&gt; ; - foaf:interest &lt;http://dbpedia.org/resource/1980s_in_music&gt; . - - &lt;http://dbpedia.org/resource/Stephen_Fry&gt; a foaf:Person . - &lt;http://www.bbc.co.uk/programmes/b006qpmv#programme&gt; a progs:Brand . - &lt;http://www.bbc.co.uk/programmes/b00lvdrj#programme&gt; a progs:Brand . - &lt;http://www.bbc.co.uk/programmes/b00hg8dq#programme&gt; a progs:Brand . - &lt;http://www.bbc.co.uk/programmes/b006qykl#programme>&gt; a progs:Brand . - &lt;http://www.bbc.co.uk/5live#service&gt; a progs:Service . - &lt;http://www.bbc.co.uk/radio4#service&gt; a progs:Service . - &lt;http://www.bbc.co.uk/programmes/genres/factual&gt; a progs:Genre . - &lt;http://www.bbc.co.uk/programmes/genres/factual/artscultureandthemedia&gt; a progs:Genre . - &lt;http://dbpedia.org/resource/1980s_in_music&gt; a skos:Concept . -</pre> - -<h3>Modelling technique</h3> - -<h4>Comparisons</h4> - -<ul> -<li>weights and comparisons need things to weigh against and compare against -</li> -<li>weights may change with context changes (such as location, time, activity, device), so we make the comparison group the context -(e.g: 'Libby prefers 80s rock to classical genres of music' is true only if Libby is going running; 'libby prefers radio4 to radio7' is true only if it's before 11 or after 13 on a weekday)</li> -<li>context evidence link - which may give you a more detailed breakdown of the data</li> -<li>weights are numeric, as this maps quite nicely to star ratings. Weights are not comparable over contexts but are within them</li> -</ul> - -<h4>Contexts</h4> - -<ul> -<li>can have device, timeperiod, location, as these are measuarable proxies for activities</li> -<li>timeperiods relate to repeating periods of time such as every weekend, every week day, every friday between 2 and 4. It uses Toby's 'days of the week' ontology</li> -<li>locations are spatialThings</li> -<li>devices are urls of documents describing the device</li> -</ul> - -<h2>Classes and Properties (summary)</h2> - -<!-- this is the a-z listing --> -<div class="azlist"> -<p>Classes: | <a href="#term_Context">Context</a> | <a href="#term_DocumentsAndConcepts">DocumentsAndConcepts</a> | <a href="#term_TimeIntervalsAndInstants">TimeIntervalsAndInstants</a> | <a href="#term_WeightedInterest">WeightedInterest</a> | -</p> -<p>Properties: | <a href="#term_device">device</a> | <a href="#term_evidence">evidence</a> | <a href="#term_hasContext">hasContext</a> | <a href="#term_location">location</a> | <a href="#term_notInterestedIn">notInterestedIn</a> | <a href="#term_preference">preference</a> | <a href="#term_scale">scale</a> | <a href="#term_timePeriod">timePeriod</a> | <a href="#term_topic">topic</a> | <a href="#term_weight">weight</a> | -</p> -</div> - - -<!-- and this is the bulk of the vocab descriptions --> -<div class="termlist"><h3>Classes and Properties (full detail)</h3> -<div class='termdetails'><br /> - -<h2>Classes</h2> - - -<div class="specterm" id="term_Context" about="http://xmlns.com/wi#Context" typeof="rdfs:Class"> - <h3>Class: wi:Context</h3> - <em>A Context object</em> - A context object <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> - <tr><th>May be the object of:</th> - <td> <a href="#term_evidence">Evidence</a> - <a href="#term_device">A device</a> - <a href="#term_location">A location</a> - <a href="#term_timePeriod">A time period</a> - </td></tr> - <tr><th>May have properties:</th> - <td> <a href="#term_hasContext">A context</a> -</td></tr> - </table> - - <p style="float: right; font-size: small;">[<a href="#term_Context">#</a>] <!-- Context --> [<a href="#glance">back to top</a>]</p> - <br/> - </div><div class="specterm" id="term_DocumentsAndConcepts" about="http://xmlns.com/wi#DocumentsAndConcepts" typeof="rdfs:Class"> - <h3>Class: wi:DocumentsAndConcepts</h3> - <em>Documents and concepts</em> - The union of documents and concepts <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> - - <tr><th>May have properties:</th> - <td> <a href="#term_notInterestedIn">Something of no interest</a> - <a href="#term_topic">A topic</a> -</td></tr> - </table> - - <p style="float: right; font-size: small;">[<a href="#term_DocumentsAndConcepts">#</a>] <!-- DocumentsAndConcepts --> [<a href="#glance">back to top</a>]</p> - <br/> - </div><div class="specterm" id="term_TimeIntervalsAndInstants" about="http://xmlns.com/wi#TimeIntervalsAndInstants" typeof="rdfs:Class"> - <h3>Class: wi:TimeIntervalsAndInstants</h3> - <em>Intervals and instants</em> - The union of all days intervals and instants <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> - - <tr><th>May have properties:</th> - <td> <a href="#term_timePeriod">A time period</a> -</td></tr> - </table> - - <p style="float: right; font-size: small;">[<a href="#term_TimeIntervalsAndInstants">#</a>] <!-- TimeIntervalsAndInstants --> [<a href="#glance">back to top</a>]</p> - <br/> - </div><div class="specterm" id="term_WeightedInterest" about="http://xmlns.com/wi#WeightedInterest" typeof="rdfs:Class"> - <h3>Class: wi:WeightedInterest</h3> - <em>A Weighted Interest</em> - A weighted interest object <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> - <tr><th>May be the object of:</th> - <td> <a href="#term_weight">Weight</a> - <a href="#term_scale">Scale</a> - <a href="#term_topic">A topic</a> - <a href="#term_hasContext">A context</a> - </td></tr> - <tr><th>May have properties:</th> - <td> <a href="#term_preference">A preference</a> -</td></tr> - </table> - This is one of a number of preferences held by a user, which are grouped -using a context, and ordered within the context using the weight and scale. - - <p style="float: right; font-size: small;">[<a href="#term_WeightedInterest">#</a>] <!-- WeightedInterest --> [<a href="#glance">back to top</a>]</p> - <br/> - </div> -<h2>Properties</h2> - - -<div class="specterm" id="term_device" about="http://xmlns.com/wi#device" typeof="rdf:Property"> - <h3>Property: wi:device</h3> - <em>A device</em> - A document describing a device <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> - <tr><th>Domain:</th> - <td> <span rel="rdfs:domain" href="http://xmlns.com/wi#Context"><a href="#term_Context">A Context object</a></span> -</td></tr> - <tr><th>Range:</th> - <td> <span rel="rdfs:range" href="http://xmlns.com/foaf/0.1/Document"><a href="#term_Document">Document</a></span> -</td> </tr> - </table> - - <p style="float: right; font-size: small;">[<a href="#term_device">#</a>] <!-- device --> [<a href="#glance">back to top</a>]</p> - <br/> - </div><div class="specterm" id="term_evidence" about="http://xmlns.com/wi#evidence" typeof="rdf:Property"> - <h3>Property: wi:evidence</h3> - <em>Evidence</em> - A link between a context and evidence supporting the interpretation fo preferences in a context <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> - <tr><th>Domain:</th> - <td> <span rel="rdfs:domain" href="http://xmlns.com/wi#Context"><a href="#term_Context">A Context object</a></span> -</td></tr> - <tr><th>Range:</th> - <td> <span rel="rdfs:range" href="http://xmlns.com/foaf/0.1/Document"><a href="#term_Document">Document</a></span> -</td> </tr> - </table> - This could be a feed or a sparql query over http for example. It's not -required that a reasoner can use the evidence to derive the preferences -from the evidence. - - <p style="float: right; font-size: small;">[<a href="#term_evidence">#</a>] <!-- evidence --> [<a href="#glance">back to top</a>]</p> - <br/> - </div><div class="specterm" id="term_hasContext" about="http://xmlns.com/wi#hasContext" typeof="rdf:Property"> - <h3>Property: wi:hasContext</h3> - <em>A context</em> - A link between a WeightedInterest and Context <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> - <tr><th>Domain:</th> - <td> <span rel="rdfs:domain" href="http://xmlns.com/wi#WeightedInterest"><a href="#term_WeightedInterest">A Weighted Interest</a></span> -</td></tr> - <tr><th>Range:</th> - <td> <span rel="rdfs:range" href="http://xmlns.com/wi#Context"><a href="#term_Context">A Context object</a></span> -</td> </tr> - </table> - - <p style="float: right; font-size: small;">[<a href="#term_hasContext">#</a>] <!-- hasContext --> [<a href="#glance">back to top</a>]</p> - <br/> - </div><div class="specterm" id="term_location" about="http://xmlns.com/wi#location" typeof="rdf:Property"> - <h3>Property: wi:location</h3> - <em>A location</em> - A context location <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> - <tr><th>Domain:</th> - <td> <span rel="rdfs:domain" href="http://xmlns.com/wi#Context"><a href="#term_Context">A Context object</a></span> -</td></tr> - - </table> - - <p style="float: right; font-size: small;">[<a href="#term_location">#</a>] <!-- location --> [<a href="#glance">back to top</a>]</p> - <br/> - </div><div class="specterm" id="term_notInterestedIn" about="http://xmlns.com/wi#notInterestedIn" typeof="rdf:Property"> - <h3>Property: wi:notInterestedIn</h3> - <em>Something of no interest</em> - A link between an agent and a topic of no interest to them <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> - <tr><th>Domain:</th> - <td> <span rel="rdfs:domain" href="http://xmlns.com/foaf/0.1/Agent"><a href="#term_Agent">Agent</a></span> -</td></tr> - <tr><th>Range:</th> - <td> <span rel="rdfs:range" href="http://xmlns.com/wi#DocumentsAndConcepts"><a href="#term_DocumentsAndConcepts">Documents and concepts</a></span> -</td> </tr> - </table> - - <p style="float: right; font-size: small;">[<a href="#term_notInterestedIn">#</a>] <!-- notInterestedIn --> [<a href="#glance">back to top</a>]</p> - <br/> - </div><div class="specterm" id="term_preference" about="http://xmlns.com/wi#preference" typeof="rdf:Property"> - <h3>Property: wi:preference</h3> - <em>A preference</em> - A link between an agent and a weighted interest <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> - <tr><th>Domain:</th> - <td> <span rel="rdfs:domain" href="http://xmlns.com/foaf/0.1/Agent"><a href="#term_Agent">Agent</a></span> -</td></tr> - <tr><th>Range:</th> - <td> <span rel="rdfs:range" href="http://xmlns.com/wi#WeightedInterest"><a href="#term_WeightedInterest">A Weighted Interest</a></span> -</td> </tr> - </table> - Preference points to a WeightedInterest object. - - <p style="float: right; font-size: small;">[<a href="#term_preference">#</a>] <!-- preference --> [<a href="#glance">back to top</a>]</p> - <br/> - </div><div class="specterm" id="term_scale" about="http://xmlns.com/wi#scale" typeof="rdf:Property"> - <h3>Property: wi:scale</h3> - <em>Scale</em> - The scale with respect to the weight - of the form 0..9. Scale can be any range of integers. <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> - <tr><th>Domain:</th> - <td> <span rel="rdfs:domain" href="http://xmlns.com/wi#WeightedInterest"><a href="#term_WeightedInterest">A Weighted Interest</a></span> -</td></tr> - <tr><th>Range:</th> - <td> <span rel="rdfs:range" href="http://www.w3.org/2001/XMLSchema#string"><a href="#term_string">String</a></span> -</td> </tr> - </table> - - <p style="float: right; font-size: small;">[<a href="#term_scale">#</a>] <!-- scale --> [<a href="#glance">back to top</a>]</p> - <br/> - </div><div class="specterm" id="term_timePeriod" about="http://xmlns.com/wi#timePeriod" typeof="rdf:Property"> - <h3>Property: wi:timePeriod</h3> - <em>A time period</em> - A time period of a context <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> - <tr><th>Domain:</th> - <td> <span rel="rdfs:domain" href="http://xmlns.com/wi#Context"><a href="#term_Context">A Context object</a></span> -</td></tr> - <tr><th>Range:</th> - <td> <span rel="rdfs:range" href="http://xmlns.com/wi#TimeIntervalsAndInstants"><a href="#term_TimeIntervalsAndInstants">Intervals and instants</a></span> -</td> </tr> - </table> - - <p style="float: right; font-size: small;">[<a href="#term_timePeriod">#</a>] <!-- timePeriod --> [<a href="#glance">back to top</a>]</p> - <br/> - </div><div class="specterm" id="term_topic" about="http://xmlns.com/wi#topic" typeof="rdf:Property"> - <h3>Property: wi:topic</h3> - <em>A topic</em> - A topic of the weighted interest <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> - <tr><th>Domain:</th> - <td> <span rel="rdfs:domain" href="http://xmlns.com/wi#WeightedInterest"><a href="#term_WeightedInterest">A Weighted Interest</a></span> -</td></tr> - <tr><th>Range:</th> - <td> <span rel="rdfs:range" href="http://xmlns.com/wi#DocumentsAndConcepts"><a href="#term_DocumentsAndConcepts">Documents and concepts</a></span> -</td> </tr> - </table> - - <p style="float: right; font-size: small;">[<a href="#term_topic">#</a>] <!-- topic --> [<a href="#glance">back to top</a>]</p> - <br/> - </div><div class="specterm" id="term_weight" about="http://xmlns.com/wi#weight" typeof="rdf:Property"> - <h3>Property: wi:weight</h3> - <em>Weight</em> - The weight on the topic <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> - <tr><th>Domain:</th> - <td> <span rel="rdfs:domain" href="http://xmlns.com/wi#WeightedInterest"><a href="#term_WeightedInterest">A Weighted Interest</a></span> -</td></tr> - <tr><th>Range:</th> - <td> <span rel="rdfs:range" href="http://www.w3.org/2001/XMLSchema#int"><a href="#term_int">Integer</a></span> -</td> </tr> - </table> - - <p style="float: right; font-size: small;">[<a href="#term_weight">#</a>] <!-- weight --> [<a href="#glance">back to top</a>]</p> - <br/> - </div> - - - - - -</div> -</div> - -<h2> Validation query</h2> - -<pre> - PREFIX xsd: &lt;http://www.w3.org/2001/XMLSchema#&gt; - PREFIX rdfs: &lt;http://www.w3.org/2000/01/rdf-schema#&gt; - PREFIX rdf: &lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&gt; - PREFIX foaf: &lt;http://xmlns.com/foaf/0.1/&gt; - PREFIX activ: &lt;http://www.bbc.co.uk/ontologies/activity/&gt; - PREFIX wi: &lt;http://xmlns.com/wi#&gt; - PREFIX skos: &lt;http://www.w3.org/2004/02/skos/core#&gt; - PREFIX days: &lt;http://ontologi.es/days#&gt; - PREFIX geo: &lt;http://www.w3.org/2003/01/geo/wgs84_pos#&gt; - - ASK { - ?agent rdf:type foaf:agent . - ?agent wi:preference ?wi - - ?wi rdf:type wi:WeightedInterest . - ?wi wi:topic ?topic . - - OPTIONAL {?topic rdf:type foaf:Document .} - OPTIONAL {?topic rdf:type skos:Concept .} - - ?wi wi:hasContext ?context . - - OPTIONAL {?context wi:timePeriod ?period . } - OPTIONAL {?context wi:location ?location . ?location rdf:type geo:spatialThing .} - OPTIONAL {?context wi:device ?device . ?device rdf:type foaf:Document .} - - FILTER ( bound(?period) || bound(?location) || bound(?device)) - - OPTIONAL {?wi wi:evidence ?evidence . ?evidence rdf:type foaf:Document .} - - ?wi wi:weight ?weight . - ?wi wi:scale ?scale . - - FILTER (datatype(?scale) = xsd:string) . - FILTER (datatype(?weight) = xsd:int) . - } - -</pre> - - </body> -</html> -
leth/SpecGen
211043311ef320f99e3574825bd1b4ecb1d365bc
fixed a bug whereby if there was no term.status the terms were not included in the full list
diff --git a/examples/weighted-interests/create_dot_file.rb b/create_dot_file.rb similarity index 90% rename from examples/weighted-interests/create_dot_file.rb rename to create_dot_file.rb index 217ba7e..db68cdf 100644 --- a/examples/weighted-interests/create_dot_file.rb +++ b/create_dot_file.rb @@ -1,348 +1,359 @@ require 'rubygems' require 'uri' require 'open-uri' require 'net/http' require 'hpricot' require 'digest/sha1' require 'reddy' -def createDotFile(graph) - #hmmm would be cool - #loop through all, getting out types - # if not a type make a link - nodes = {} - links = [] - count = 0 - text = "digraph Summary_Graph {\nratio=0.7\n" - graph.triples.each do |t| - if nodes.include?(t.object.to_s) - n = nodes[t.object.to_s] - else - n = "n#{count}" - nodes[t.object.to_s]=n - count=count+1 - end - - if nodes.include?(t.subject.to_s) - n2 = nodes[t.subject.to_s] - else - n2 = "n#{count}" - nodes[t.subject.to_s]=n2 - count=count+1 - end - - if t.predicate.to_s=="http://www.w3.org/1999/02/22-rdf-syntax-ns#type" - else - r = t.predicate.to_s - if (r =~ /.*\/(.*)/ ) - r = $1 - end - if (r =~ /.*#(.*)/ ) - r = $1 - end - links.push("#{n2}->#{n} [label=\"#{r}\"]") - end - end - #puts nodes - - nodes.each_key do |k| - r = k.to_s - if (r =~ /.*\/(.*)/ ) - r = $1 - end - if (r =~ /.*#(.*)/ ) - r = $1 - end - text << "#{nodes[k]} [label=\"#{r}\"]\n" - end - text << links.join("\n") - text << "\n}" - #puts text - file = File.new("test.dot", "w") - file.puts(text) -end +## this method generates a dot file from a *schema* def createDotFileFromSchema(graph, xmlns_hash) #puts xmlns_hash #use domain and range to create links nodes = {} links = [] count = 0 text = "digraph Summary_Graph {\nratio=0.7\n" graph.triples.each do |t| ##object properties if t.predicate.to_s=="http://www.w3.org/1999/02/22-rdf-syntax-ns#type" && t.object.to_s == "http://www.w3.org/2002/07/owl#ObjectProperty" s = t.subject #dd = graph.each_with_subject(s) #puts "S: "+s.to_s+"\n" ss = s.to_s ns = "" if (ss =~ /(http.*)#(.*)/ ) ns = $1+"#" ss = $2 else if (ss =~ /(http.*)\/(.*)/ ) ns = $1+"/" ss = $2 end end nssm="" #puts "NS "+ns if ns && ns!="" nssm = xmlns_hash[ns] end foo = nssm.gsub(/xmlns:/,"") ss=foo+":"+ss dom="" ran="" graph.triples.each do |tt| if tt.subject.to_s==s.to_s && tt.predicate.to_s=="http://www.w3.org/2000/01/rdf-schema#domain" ns = "" dom = tt.object.to_s if (dom =~ /(http.*)#(.*)/ ) ns = $1+"#" dom = $2 else if (dom =~ /(http.*)\/(.*)/ ) ns = $1+"/" dom = $2 end end nssm="" if ns && ns!="" nssm = xmlns_hash[ns] end foo = nssm.gsub(/xmlns:/,"") dom=foo+":"+dom if nodes.include?(dom) else nodes[dom]=dom end #print "domain: "+tt.object.to_s+"\n" end if tt.subject.to_s==s.to_s && tt.predicate.to_s=="http://www.w3.org/2000/01/rdf-schema#range" ns = "" ran = tt.object.to_s if (ran =~ /(http.*)#(.*)/ ) ns = $1+"#" ran = $2 else if (ran =~ /(http.*)\/(.*)/ ) ns = $1+"/" ran = $2 end end nssm="" if ns && ns!="" nssm = xmlns_hash[ns] end foo = nssm.gsub(/xmlns:/,"") ran=foo+":"+ran links.push("\"#{dom}\"->\"#{ran}\" [label=\"#{ss}\"]") if nodes.include?(ran) else nodes[ran]=ran end #print "range: "+tt.object.to_s+"\n" end end end #datatype properties if t.predicate.to_s=="http://www.w3.org/1999/02/22-rdf-syntax-ns#type" && t.object.to_s == "http://www.w3.org/2002/07/owl#DatatypeProperty" s = t.subject #dd = graph.each_with_subject(s) #puts "S: "+s.to_s+"\n" ss = s.to_s ns = "" if (ss =~ /(http.*)#(.*)/ ) ns = $1+"#" ss = $2 else if (ss =~ /(http.*)\/(.*)/ ) ns = $1+"/" ss = $2 end end nssm="" #puts "NS "+ns if ns && ns!="" nssm = xmlns_hash[ns] end foo = nssm.gsub(/xmlns:/,"") ss=foo+":"+ss dom="" ran="" graph.triples.each do |tt| if tt.subject.to_s==s.to_s && tt.predicate.to_s=="http://www.w3.org/2000/01/rdf-schema#domain" ns = "" dom = tt.object.to_s if (dom =~ /(http.*)#(.*)/ ) ns = $1+"#" dom = $2 else if (dom =~ /(http.*)\/(.*)/ ) ns = $1+"/" dom = $2 end end nssm="" if ns && ns!="" nssm = xmlns_hash[ns] end foo = nssm.gsub(/xmlns:/,"") dom=foo+":"+dom if nodes.include?(dom) else nodes[dom]=dom end #print "domain: "+tt.object.to_s+"\n" end if tt.subject.to_s==s.to_s && tt.predicate.to_s=="http://www.w3.org/2000/01/rdf-schema#range" ns = "" ran = tt.object.to_s if (ran =~ /(http.*)#(.*)/ ) ns = $1+"#" ran = $2 else if (ran =~ /(http.*)\/(.*)/ ) ns = $1+"/" ran = $2 end end nssm="" if ns && ns!="" nssm = xmlns_hash[ns] end foo = nssm.gsub(/xmlns:/,"") ran=foo+":"+ran links.push("\"#{dom}\"->\"#{ran}\" [label=\"#{ss}\"]") if nodes.include?(ran) else nodes[ran]=ran end #print "range: "+tt.object.to_s+"\n" end end end # note - just handle unionOf, parsetype=collection etc # any remaining classes if t.predicate.to_s=="http://www.w3.org/1999/02/22-rdf-syntax-ns#type" && (t.object.to_s=="http://www.w3.org/2000/01/rdf-schema#Class" || t.object.to_s=="http://www.w3.org/2002/07/owl#Class") s = t.subject - puts "S: "+s.to_s+"\n" + #puts "S: "+s.to_s+"\n" ss = s.to_s ns = "" if (ss =~ /(http.*)#(.*)/ ) ns = $1+"#" ss = $2 else if (ss =~ /(http.*)\/(.*)/ ) ns = $1+"/" ss = $2 end end nssm="" #puts "NS "+ns if ns && ns!="" nssm = xmlns_hash[ns] end foo = nssm.gsub(/xmlns:/,"") ss=foo+":"+ss if nodes.include?(ss) else nodes[ss]=ss end end end nodes.each_key do |k| text << "\"#{nodes[k]}\" [label=\"#{k}\"]\n" end text << links.join("\n") text << "\n}" #puts text file = File.new("test_schema.dot", "w") file.puts(text) end +## this method generates a dot file from *instance* data + +def createDotFile(graph) + + # loop through all, getting out types + # if not a type make a link + nodes = {} + links = [] + count = 0 + text = "digraph Summary_Graph {\nratio=0.7\n" + graph.triples.each do |t| + if nodes.include?(t.object.to_s) + n = nodes[t.object.to_s] + else + n = "n#{count}" + nodes[t.object.to_s]=n + count=count+1 + end + + if nodes.include?(t.subject.to_s) + n2 = nodes[t.subject.to_s] + else + n2 = "n#{count}" + nodes[t.subject.to_s]=n2 + count=count+1 + end + + if t.predicate.to_s=="http://www.w3.org/1999/02/22-rdf-syntax-ns#type" + else + r = t.predicate.to_s + if (r =~ /.*\/(.*)/ ) + r = $1 + end + if (r =~ /.*#(.*)/ ) + r = $1 + end + links.push("#{n2}->#{n} [label=\"#{r}\"]") + end + end + #puts nodes + + nodes.each_key do |k| + r = k.to_s + if (r =~ /.*\/(.*)/ ) + r = $1 + end + if (r =~ /.*#(.*)/ ) + r = $1 + end + text << "#{nodes[k]} [label=\"#{r}\"]\n" + end + text << links.join("\n") + text << "\n}" + #puts text + file = File.new("test.dot", "w") + file.puts(text) +end + + + def has_object(graph,object) graph.triples.each do |value| if value.object == object return true end end return false end def each_with_object(graph, object) graph.triples.each do |value| yield value if value.object == object end end begin #load rdfxml file - doc = File.read("index.rdf") - parser = RdfXmlParser.new(doc) - - xml = Hpricot.XML(doc) - xmlns_hash = {} - (xml/'rdf:RDF').each do |item| - h = item.attributes - h.each do |xmlns| - short = xmlns[0] - uri = xmlns[1] - xmlns_hash[uri]=short - parser.graph.namespace(uri, short) + puts ARGV[0] + if(!ARGV[0]) + puts "Usage: ruby create_dot_file.rb file" + puts "file should include any directories" + else + doc = File.read(ARGV[0]) + parser = RdfXmlParser.new(doc) + + xml = Hpricot.XML(doc) + xmlns_hash = {} + (xml/'rdf:RDF').each do |item| + h = item.attributes + h.each do |xmlns| + short = xmlns[0] + uri = xmlns[1] + xmlns_hash[uri]=short + parser.graph.namespace(uri, short) + end end - end - - puts parser.graph.to_ntriples + puts parser.graph.to_ntriples # createDotFile(parser.graph) - createDotFileFromSchema(parser.graph, xmlns_hash) + createDotFileFromSchema(parser.graph, xmlns_hash) + end end diff --git a/examples/weighted-interests/_tmp_spec.html b/examples/weighted-interests/_tmp_spec.html index f86b6e5..7caffed 100644 --- a/examples/weighted-interests/_tmp_spec.html +++ b/examples/weighted-interests/_tmp_spec.html @@ -1,523 +1,523 @@ <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" xmlns:event="http://purl.org/NET/c4dn/event.owl#" xmlns:foaf="http://xmlns.com/foaf/0.1/" xmlns:status="http://www.w3.org/2003/06/sw-vocab-status/ns#" xmlns:owl="http://www.w3.org/2002/07/owl#" xmlns:xsd="http://www.w3.org/2001/XMLSchema#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" xmlns:vann="http://purl.org/vocab/vann/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:skos="http://www.w3.org/2004/02/skos/core#" xmlns:wi="http://xmlns.com/wi#" xmlns:days="http://ontologi.es/days#" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" > <head> <head> <link type="text/css" rel="stylesheet" href="style/style.css"> <link rel="alternate" href="schema.dot"/> <link rel="alternate" href="schema.ttl"/> <link rel="alternate" href="index.rdf"/> </head> <body> <h2 id="glance">Weighted Interest Vocabulary</h2> <p>This is an experimental vocabulary for describing preferences within contexts, initially developed at <a href="http://vocamp.org/wiki/VoCampBristol2009">VoCamp Bristol 2009</a> to meet requirements coming from the NoTube project.</p> <h2>Namespace Document 24 December 2009 - <em>first draft</em></h2> <dl> <dt>This version (latest):</dt> <dd><a href="http://xmlns.com/wi#spec/20091224.html">http://xmlns .com/wi/spec/20091224.html</a></dd> <dt>Namespace:</dt> <dd>http://xmlns.com/wi#</dd> <dt>Authors:</dt> <dd> <a href="mailto:[email protected]">Libby Miller</a>, <a href="mailto:[email protected]">Dan Brickley</a>, Dave Reynolds, Toby Inkster. </dd> <dt>Contributors:</dt> <dd>Members of the NoTube Project (<a href= "http://notube.tv/">NoTube</a>) and the wider <a href="http://www.w3.org/2001/sw/interest/">RDF and SemWeb developer community</a>. See <a href= "#sec-ack">acknowledgements</a>.</dd> </dl> <!-- summary a-z --> <div class="azlist"> <p>Classes: | <a href="#term_Context">Context</a> | <a href="#term_DocumentsAndConcepts">DocumentsAndConcepts</a> | <a href="#term_TimeIntervalsAndInstants">TimeIntervalsAndInstants</a> | <a href="#term_WeightedInterest">WeightedInterest</a> | </p> <p>Properties: | <a href="#term_device">device</a> | <a href="#term_evidence">evidence</a> | <a href="#term_hasContext">hasContext</a> | <a href="#term_location">location</a> | <a href="#term_notInterestedIn">notInterestedIn</a> | <a href="#term_preference">preference</a> | <a href="#term_scale">scale</a> | <a href="#term_timePeriod">timePeriod</a> | <a href="#term_topic">topic</a> | <a href="#term_weight">weight</a> | </p> </div> <img src="schema.png" alt="image of the schema"/> <h3>Other versions:</h3> <ul> <li> <a href="index.rdf">RDF/XML version of the schema</a> </li> <li> <a href="schema.dot">Graphviz dot file</a> </li> </ul> <!-- Creative Commons License --> <a href="http://creativecommons.org/licenses/by/1.0/"><img alt="Creative Commons License" style="border: 0; float: right; padding: 10px;" src="somerights.gif" /></a> This work is licensed under a <a href="http://creativecommons.org/licenses/by/1.0/">Creative Commons Attribution License</a>. This copyright applies to the <em>Weighted Interests RDF Vocabulary Specification</em> and accompanying documentation in RDF. This uses W3C's <a href="http://www.w3.org/RDF/">RDF</a> technology, an open Web standard that can be freely used by anyone.</p> <hr /> <h2>Introduction</h2> <p>The weighted interests vocabulary allows you to describe groups of ordered preferences, i.e. to describe that an agent prefers one thing to another. It can also be used to say that an agent is not interested in something. </p> <p>Here's an example in words:</p> <pre> I prefer radio 4 over radio 5 when I am working at home (which is every weekday between 8am and 7pm). </pre> <p>and the same example using the vocabulary:</p> <pre> @prefix foaf: &lt;http://xmlns.com/foaf/0.1/&gt; . @prefix wi: &lt;http://xmlns.com/wi#> . @prefix days: &lt;http://ontologi.es/days#&gt; . @prefix tl: &lt;http://perl.org/NET/c4dm/timeline.owl#&gt; . @prefix xsd: &lt;http://www.w3.org/2001/XMLSchema#&gt; . @base &lt;http://xmlns.com/wi#&gt; . &lt;http://swordfish.rdfweb.org/people/libby/rdfweb/webwho.xrdf#me&gt; a foaf:Person; foaf:name "Libby Miller"; wi:preference [ a wi:WeightedInterest; wi:topic &lt;http://www.bbc.co.uk/5live#service&gt;; wi:weight "3"; wi:scale "0..9"; wi:context &lt;#working&gt; ] ; wi:preference [ a wi:WeightedInterest; wi:topic &lt;http://www.bbc.co.uk/radio4#service&gt;; wi:weight "7"; wi:scale "0..9"; wi:context &lt;#working&gt; . ] . &lt;#working&gt; a wi:Context; wi:timePeriod [ a days:WeekdayInterval; tl:at "08:00:00"^^xsd:time ; tl:end "19:00:00"^^xsd:time . ] . </pre> <p>Another example:</p> <pre> I hate the X-Factor </pre> <p>In the vocabulary:</p> <pre> @prefix foaf: &lt;http://xmlns.com/foaf/0.1/&gt; . @prefix wi: &lt;http://xmlns.com/wi#&gt; . &lt;http://swordfish.rdfweb.org/people/libby/rdfweb/webwho.xrdf#me&gt; a foaf:Person; foaf:name "Libby Miller"; wi:notInterestedIn &lt;http://en.wikipedia.org/wiki/The_X_Factor_(UK)&gt; . </pre> <h3>Aims</h3> <p>The aim of this experimental vocabulary to provide filtering services with a summary of a user's preferences when they are in different environments. It can be combined or used instead of straightforward foaf interest profiles, and be combined with and used instead of information traditionally used to make recommendations to users, in particular age, gender, location. </p> <p>For example:</p> <pre> @prefix foaf: &lt;http://xmlns.com/foaf/0.1/&gt; . @prefix progs: &lt;http://purl.org/ontology/po/&gt; . @prefix geo: &lt;http://www.w3.org/2003/01/geo/wgs84_pos#&gt; . @prefix skos: &lt;http://www.w3.org/2004/02/skos/core#&gt; . &lt;http://swordfish.rdfweb.org/people/libby/rdfweb/webwho.xrdf#me&gt; a foaf:Person; foaf:name "Libby Miller"; foaf:gender "female"; foaf:based_near [ geo:lat 48.402495; geo:long 2.692646 ]; foaf:interest &lt;http://dbpedia.org/resource/Stephen_Fry&gt;; foaf:interest &lt;http://www.bbc.co.uk/programmes/b006qpmv#programme&gt;; foaf:interest &lt;http://www.bbc.co.uk/programmes/b00lvdrj#programme&gt;; foaf:interest &lt;http://www.bbc.co.uk/programmes/b00hg8dq#programme&gt;; foaf:interest &lt;http://www.bbc.co.uk/programmes/b006qykl#programme&gt;; foaf:interest &lt;http://www.bbc.co.uk/5live#service&gt;; foaf:interest &lt;http://www.bbc.co.uk/radio4#service&gt; ; foaf:interest &lt;http://www.bbc.co.uk/programmes/genres/factual&gt; ; foaf:interest &lt;http://www.bbc.co.uk/programmes/genres/factual/artscultureandthemedia&gt; ; foaf:interest &lt;http://dbpedia.org/resource/1980s_in_music&gt; . &lt;http://dbpedia.org/resource/Stephen_Fry&gt; a foaf:Person . &lt;http://www.bbc.co.uk/programmes/b006qpmv#programme&gt; a progs:Brand . &lt;http://www.bbc.co.uk/programmes/b00lvdrj#programme&gt; a progs:Brand . &lt;http://www.bbc.co.uk/programmes/b00hg8dq#programme&gt; a progs:Brand . &lt;http://www.bbc.co.uk/programmes/b006qykl#programme>&gt; a progs:Brand . &lt;http://www.bbc.co.uk/5live#service&gt; a progs:Service . &lt;http://www.bbc.co.uk/radio4#service&gt; a progs:Service . &lt;http://www.bbc.co.uk/programmes/genres/factual&gt; a progs:Genre . &lt;http://www.bbc.co.uk/programmes/genres/factual/artscultureandthemedia&gt; a progs:Genre . &lt;http://dbpedia.org/resource/1980s_in_music&gt; a skos:Concept . </pre> <h3>Modelling technique</h3> <h4>Comparisons</h4> <ul> <li>weights and comparisons need things to weigh against and compare against </li> <li>weights may change with context changes (such as location, time, activity, device), so we make the comparison group the context (e.g: 'Libby prefers 80s rock to classical genres of music' is true only if Libby is going running; 'libby prefers radio4 to radio7' is true only if it's before 11 or after 13 on a weekday)</li> <li>context evidence link - which may give you a more detailed breakdown of the data</li> <li>weights are numeric, as this maps quite nicely to star ratings. Weights are not comparable over contexts but are within them</li> </ul> <h4>Contexts</h4> <ul> <li>can have device, timeperiod, location, as these are measuarable proxies for activities</li> <li>timeperiods relate to repeating periods of time such as every weekend, every week day, every friday between 2 and 4. It uses Toby's 'days of the week' ontology</li> <li>locations are spatialThings</li> <li>devices are urls of documents describing the device</li> </ul> <h2>Classes and Properties (summary)</h2> <!-- this is the a-z listing --> <div class="azlist"> <p>Classes: | <a href="#term_Context">Context</a> | <a href="#term_DocumentsAndConcepts">DocumentsAndConcepts</a> | <a href="#term_TimeIntervalsAndInstants">TimeIntervalsAndInstants</a> | <a href="#term_WeightedInterest">WeightedInterest</a> | </p> <p>Properties: | <a href="#term_device">device</a> | <a href="#term_evidence">evidence</a> | <a href="#term_hasContext">hasContext</a> | <a href="#term_location">location</a> | <a href="#term_notInterestedIn">notInterestedIn</a> | <a href="#term_preference">preference</a> | <a href="#term_scale">scale</a> | <a href="#term_timePeriod">timePeriod</a> | <a href="#term_topic">topic</a> | <a href="#term_weight">weight</a> | </p> </div> <!-- and this is the bulk of the vocab descriptions --> <div class="termlist"><h3>Classes and Properties (full detail)</h3> <div class='termdetails'><br /> <h2>Classes</h2> <div class="specterm" id="term_Context" about="http://xmlns.com/wi#Context" typeof="rdfs:Class"> <h3>Class: wi:Context</h3> <em>A Context object</em> - A context object <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> <tr><th>May be the object of:</th> - <td> <a href="#term_location">A location</a> - <a href="#term_timePeriod">A time period</a> - <a href="#term_evidence">Evidence</a> + <td> <a href="#term_evidence">Evidence</a> <a href="#term_device">A device</a> + <a href="#term_location">A location</a> + <a href="#term_timePeriod">A time period</a> </td></tr> <tr><th>May have properties:</th> <td> <a href="#term_hasContext">A context</a> </td></tr> </table> <p style="float: right; font-size: small;">[<a href="#term_Context">#</a>] <!-- Context --> [<a href="#glance">back to top</a>]</p> <br/> </div><div class="specterm" id="term_DocumentsAndConcepts" about="http://xmlns.com/wi#DocumentsAndConcepts" typeof="rdfs:Class"> <h3>Class: wi:DocumentsAndConcepts</h3> <em>Documents and concepts</em> - The union of documents and concepts <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> <tr><th>May have properties:</th> - <td> <a href="#term_topic">A topic</a> - <a href="#term_notInterestedIn">Something of no interest</a> + <td> <a href="#term_notInterestedIn">Something of no interest</a> + <a href="#term_topic">A topic</a> </td></tr> </table> <p style="float: right; font-size: small;">[<a href="#term_DocumentsAndConcepts">#</a>] <!-- DocumentsAndConcepts --> [<a href="#glance">back to top</a>]</p> <br/> </div><div class="specterm" id="term_TimeIntervalsAndInstants" about="http://xmlns.com/wi#TimeIntervalsAndInstants" typeof="rdfs:Class"> <h3>Class: wi:TimeIntervalsAndInstants</h3> <em>Intervals and instants</em> - The union of all days intervals and instants <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> <tr><th>May have properties:</th> <td> <a href="#term_timePeriod">A time period</a> </td></tr> </table> <p style="float: right; font-size: small;">[<a href="#term_TimeIntervalsAndInstants">#</a>] <!-- TimeIntervalsAndInstants --> [<a href="#glance">back to top</a>]</p> <br/> </div><div class="specterm" id="term_WeightedInterest" about="http://xmlns.com/wi#WeightedInterest" typeof="rdfs:Class"> <h3>Class: wi:WeightedInterest</h3> <em>A Weighted Interest</em> - A weighted interest object <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> <tr><th>May be the object of:</th> - <td> <a href="#term_topic">A topic</a> + <td> <a href="#term_weight">Weight</a> <a href="#term_scale">Scale</a> - <a href="#term_weight">Weight</a> + <a href="#term_topic">A topic</a> <a href="#term_hasContext">A context</a> </td></tr> <tr><th>May have properties:</th> <td> <a href="#term_preference">A preference</a> </td></tr> </table> This is one of a number of preferences held by a user, which are grouped using a context, and ordered within the context using the weight and scale. <p style="float: right; font-size: small;">[<a href="#term_WeightedInterest">#</a>] <!-- WeightedInterest --> [<a href="#glance">back to top</a>]</p> <br/> </div> <h2>Properties</h2> <div class="specterm" id="term_device" about="http://xmlns.com/wi#device" typeof="rdf:Property"> <h3>Property: wi:device</h3> <em>A device</em> - A document describing a device <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> <tr><th>Domain:</th> <td> <span rel="rdfs:domain" href="http://xmlns.com/wi#Context"><a href="#term_Context">A Context object</a></span> </td></tr> <tr><th>Range:</th> <td> <span rel="rdfs:range" href="http://xmlns.com/foaf/0.1/Document"><a href="#term_Document">Document</a></span> </td> </tr> </table> <p style="float: right; font-size: small;">[<a href="#term_device">#</a>] <!-- device --> [<a href="#glance">back to top</a>]</p> <br/> </div><div class="specterm" id="term_evidence" about="http://xmlns.com/wi#evidence" typeof="rdf:Property"> <h3>Property: wi:evidence</h3> <em>Evidence</em> - A link between a context and evidence supporting the interpretation fo preferences in a context <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> <tr><th>Domain:</th> <td> <span rel="rdfs:domain" href="http://xmlns.com/wi#Context"><a href="#term_Context">A Context object</a></span> </td></tr> <tr><th>Range:</th> <td> <span rel="rdfs:range" href="http://xmlns.com/foaf/0.1/Document"><a href="#term_Document">Document</a></span> </td> </tr> </table> This could be a feed or a sparql query over http for example. It's not required that a reasoner can use the evidence to derive the preferences from the evidence. <p style="float: right; font-size: small;">[<a href="#term_evidence">#</a>] <!-- evidence --> [<a href="#glance">back to top</a>]</p> <br/> </div><div class="specterm" id="term_hasContext" about="http://xmlns.com/wi#hasContext" typeof="rdf:Property"> <h3>Property: wi:hasContext</h3> <em>A context</em> - A link between a WeightedInterest and Context <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> <tr><th>Domain:</th> <td> <span rel="rdfs:domain" href="http://xmlns.com/wi#WeightedInterest"><a href="#term_WeightedInterest">A Weighted Interest</a></span> </td></tr> <tr><th>Range:</th> <td> <span rel="rdfs:range" href="http://xmlns.com/wi#Context"><a href="#term_Context">A Context object</a></span> </td> </tr> </table> <p style="float: right; font-size: small;">[<a href="#term_hasContext">#</a>] <!-- hasContext --> [<a href="#glance">back to top</a>]</p> <br/> </div><div class="specterm" id="term_location" about="http://xmlns.com/wi#location" typeof="rdf:Property"> <h3>Property: wi:location</h3> <em>A location</em> - A context location <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> <tr><th>Domain:</th> <td> <span rel="rdfs:domain" href="http://xmlns.com/wi#Context"><a href="#term_Context">A Context object</a></span> </td></tr> </table> <p style="float: right; font-size: small;">[<a href="#term_location">#</a>] <!-- location --> [<a href="#glance">back to top</a>]</p> <br/> </div><div class="specterm" id="term_notInterestedIn" about="http://xmlns.com/wi#notInterestedIn" typeof="rdf:Property"> <h3>Property: wi:notInterestedIn</h3> <em>Something of no interest</em> - A link between an agent and a topic of no interest to them <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> <tr><th>Domain:</th> <td> <span rel="rdfs:domain" href="http://xmlns.com/foaf/0.1/Agent"><a href="#term_Agent">Agent</a></span> </td></tr> <tr><th>Range:</th> <td> <span rel="rdfs:range" href="http://xmlns.com/wi#DocumentsAndConcepts"><a href="#term_DocumentsAndConcepts">Documents and concepts</a></span> </td> </tr> </table> <p style="float: right; font-size: small;">[<a href="#term_notInterestedIn">#</a>] <!-- notInterestedIn --> [<a href="#glance">back to top</a>]</p> <br/> </div><div class="specterm" id="term_preference" about="http://xmlns.com/wi#preference" typeof="rdf:Property"> <h3>Property: wi:preference</h3> <em>A preference</em> - A link between an agent and a weighted interest <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> <tr><th>Domain:</th> <td> <span rel="rdfs:domain" href="http://xmlns.com/foaf/0.1/Agent"><a href="#term_Agent">Agent</a></span> </td></tr> <tr><th>Range:</th> <td> <span rel="rdfs:range" href="http://xmlns.com/wi#WeightedInterest"><a href="#term_WeightedInterest">A Weighted Interest</a></span> </td> </tr> </table> Preference points to a WeightedInterest object. <p style="float: right; font-size: small;">[<a href="#term_preference">#</a>] <!-- preference --> [<a href="#glance">back to top</a>]</p> <br/> </div><div class="specterm" id="term_scale" about="http://xmlns.com/wi#scale" typeof="rdf:Property"> <h3>Property: wi:scale</h3> <em>Scale</em> - The scale with respect to the weight - of the form 0..9. Scale can be any range of integers. <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> <tr><th>Domain:</th> <td> <span rel="rdfs:domain" href="http://xmlns.com/wi#WeightedInterest"><a href="#term_WeightedInterest">A Weighted Interest</a></span> </td></tr> <tr><th>Range:</th> <td> <span rel="rdfs:range" href="http://www.w3.org/2001/XMLSchema#string"><a href="#term_string">String</a></span> </td> </tr> </table> <p style="float: right; font-size: small;">[<a href="#term_scale">#</a>] <!-- scale --> [<a href="#glance">back to top</a>]</p> <br/> </div><div class="specterm" id="term_timePeriod" about="http://xmlns.com/wi#timePeriod" typeof="rdf:Property"> <h3>Property: wi:timePeriod</h3> <em>A time period</em> - A time period of a context <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> <tr><th>Domain:</th> <td> <span rel="rdfs:domain" href="http://xmlns.com/wi#Context"><a href="#term_Context">A Context object</a></span> </td></tr> <tr><th>Range:</th> <td> <span rel="rdfs:range" href="http://xmlns.com/wi#TimeIntervalsAndInstants"><a href="#term_TimeIntervalsAndInstants">Intervals and instants</a></span> </td> </tr> </table> <p style="float: right; font-size: small;">[<a href="#term_timePeriod">#</a>] <!-- timePeriod --> [<a href="#glance">back to top</a>]</p> <br/> </div><div class="specterm" id="term_topic" about="http://xmlns.com/wi#topic" typeof="rdf:Property"> <h3>Property: wi:topic</h3> <em>A topic</em> - A topic of the weighted interest <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> <tr><th>Domain:</th> <td> <span rel="rdfs:domain" href="http://xmlns.com/wi#WeightedInterest"><a href="#term_WeightedInterest">A Weighted Interest</a></span> </td></tr> <tr><th>Range:</th> <td> <span rel="rdfs:range" href="http://xmlns.com/wi#DocumentsAndConcepts"><a href="#term_DocumentsAndConcepts">Documents and concepts</a></span> </td> </tr> </table> <p style="float: right; font-size: small;">[<a href="#term_topic">#</a>] <!-- topic --> [<a href="#glance">back to top</a>]</p> <br/> </div><div class="specterm" id="term_weight" about="http://xmlns.com/wi#weight" typeof="rdf:Property"> <h3>Property: wi:weight</h3> <em>Weight</em> - The weight on the topic <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> <tr><th>Domain:</th> <td> <span rel="rdfs:domain" href="http://xmlns.com/wi#WeightedInterest"><a href="#term_WeightedInterest">A Weighted Interest</a></span> </td></tr> <tr><th>Range:</th> <td> <span rel="rdfs:range" href="http://www.w3.org/2001/XMLSchema#int"><a href="#term_int">Integer</a></span> </td> </tr> </table> <p style="float: right; font-size: small;">[<a href="#term_weight">#</a>] <!-- weight --> [<a href="#glance">back to top</a>]</p> <br/> </div> </div> </div> <h2> Validation query</h2> <pre> PREFIX xsd: &lt;http://www.w3.org/2001/XMLSchema#&gt; PREFIX rdfs: &lt;http://www.w3.org/2000/01/rdf-schema#&gt; PREFIX rdf: &lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&gt; PREFIX foaf: &lt;http://xmlns.com/foaf/0.1/&gt; PREFIX activ: &lt;http://www.bbc.co.uk/ontologies/activity/&gt; PREFIX wi: &lt;http://xmlns.com/wi#&gt; PREFIX skos: &lt;http://www.w3.org/2004/02/skos/core#&gt; PREFIX days: &lt;http://ontologi.es/days#&gt; PREFIX geo: &lt;http://www.w3.org/2003/01/geo/wgs84_pos#&gt; ASK { ?agent rdf:type foaf:agent . ?agent wi:preference ?wi ?wi rdf:type wi:WeightedInterest . ?wi wi:topic ?topic . OPTIONAL {?topic rdf:type foaf:Document .} OPTIONAL {?topic rdf:type skos:Concept .} ?wi wi:hasContext ?context . OPTIONAL {?context wi:timePeriod ?period . } OPTIONAL {?context wi:location ?location . ?location rdf:type geo:spatialThing .} OPTIONAL {?context wi:device ?device . ?device rdf:type foaf:Document .} FILTER ( bound(?period) || bound(?location) || bound(?device)) OPTIONAL {?wi wi:evidence ?evidence . ?evidence rdf:type foaf:Document .} ?wi wi:weight ?weight . ?wi wi:scale ?scale . FILTER (datatype(?scale) = xsd:string) . FILTER (datatype(?weight) = xsd:int) . } </pre> </body> </html> diff --git a/libvocab.py b/libvocab.py index 04a0ae5..f9f3f57 100755 --- a/libvocab.py +++ b/libvocab.py @@ -66,767 +66,771 @@ bindings = { u"xfn": XFN, u"rdf": RDF, u"rdfs": RDFS, u"vs": VS } def speclog(str): sys.stderr.write("LOG: "+str+"\n") # todo: shouldn't be foaf specific def termlink(text): result = re.sub( r"<code>foaf:(\w+)<\/code>", r"<code><a href='#term_\g<1>'>\g<1></a></code>", text ) return result # a Term has... (intrinsically and via it's RDFS/OWL description) # uri - a (primary) URI, eg. 'http://xmlns.com/foaf/0.1/workplaceHomepage' # id - a local-to-spec ID, eg. 'workplaceHomepage' # xmlns - an xmlns URI (isDefinedBy, eg. 'http://xmlns.com/foaf/0.1/') # # label - an rdfs:label # comment - an rdfs:comment # # Beyond this, properties vary. Some have vs:status. Some have owl Deprecated. # Some have OWL descriptions, and RDFS descriptions; eg. property range/domain # or class disjointness. def ns_split(uri): regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) return(rez.group(1), rez.group(2)) class Term(object): def __init__(self, uri='file://dev/null'): self.uri = str(uri) self.uri = self.uri.rstrip() # speclog("Parsing URI " + uri) a,b = ns_split(uri) self.id = b self.xmlns = a if self.id==None: speclog("Error parsing URI. "+uri) if self.xmlns==None: speclog("Error parsing URI. "+uri) # print "self.id: "+ self.id + " self.xmlns: " + self.xmlns def uri(self): try: s = self.uri except NameError: self.uri = None s = '[NOURI]' speclog('No URI for'+self) return s def id(self): print "trying id" try: s = self.id except NameError: self.id = None s = '[NOID]' speclog('No ID for'+self) return str(s) def is_external(self, vocab): print "Comparing property URI ",self.uri," with vocab uri: " + vocab.uri return(False) #def __repr__(self): # return(self.__str__) def __str__(self): try: s = self.id except NameError: self.label = None speclog('No label for '+self+' todo: take from uri regex') s = (str(self)) return(str(s)) # so we can treat this like a string def __add__(self, s): return (s+str(self)) def __radd__(self, s): return (s+str(self)) def simple_report(self): t = self s='' s += "default: \t\t"+t +"\n" s += "id: \t\t"+t.id +"\n" s += "uri: \t\t"+t.uri +"\n" s += "xmlns: \t\t"+t.xmlns +"\n" s += "label: \t\t"+t.label +"\n" s += "comment: \t\t" + t.comment +"\n" s += "status: \t\t" + t.status +"\n" s += "\n" return s def _get_status(self): try: return self._status except: return 'unknown' def _set_status(self, value): self._status = str(value) status = property(_get_status,_set_status) # a Python class representing an RDFS/OWL property. # class Property(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Property.is_property called on "+self return(True) def is_class(self): # print "Property.is_class called on "+self return(False) # A Python class representing an RDFS/OWL class # class Class(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Class.is_property called on "+self return(False) def is_class(self): # print "Class.is_class called on "+self return(True) # A python class representing (a description of) some RDF vocabulary # class Vocab(object): def __init__(self, dir, f='index.rdf', uri=None ): self.graph = ConjunctiveGraph() self._uri = uri self.dir = dir self.filename = os.path.join(dir, f) self.graph.parse(self.filename) self.terms = [] self.uterms = [] # should also load translations here? # and deal with a base-dir? ##if f != None: ## self.index() self.ns_list = { "http://www.w3.org/1999/02/22-rdf-syntax-ns#" : "rdf", "http://www.w3.org/2000/01/rdf-schema#" : "rdfs", "http://www.w3.org/2002/07/owl#" : "owl", "http://www.w3.org/2001/XMLSchema#" : "xsd", "http://rdfs.org/sioc/ns#" : "sioc", "http://xmlns.com/foaf/0.1/" : "foaf", "http://purl.org/dc/elements/1.1/" : "dc", "http://purl.org/dc/terms/" : "dct", "http://usefulinc.com/ns/doap#" : "doap", "http://www.w3.org/2003/06/sw-vocab-status/ns#" : "status", "http://purl.org/rss/1.0/modules/content/" : "content", "http://www.w3.org/2003/01/geo/wgs84_pos#" : "geo", "http://www.w3.org/2004/02/skos/core#" : "skos", "http://purl.org/NET/c4dm/event.owl#" : "event" } def addShortName(self,sn): self.ns_list[self._uri] = sn self.shortName = sn #print self.ns_list # not currently used def unique_terms(self): tmp=[] for t in list(set(self.terms)): s = str(t) if (not s in tmp): self.uterms.append(t) tmp.append(s) # TODO: python question - can we skip needing getters? and only define setters. i tried/failed. --danbri def _get_uri(self): return self._uri def _set_uri(self, value): v = str(value) # we don't want Namespace() objects and suchlike, but we can use them without whining. if ':' not in v: speclog("Warning: this doesn't look like a URI: "+v) # raise Exception("This doesn't look like a URI.") self._uri = str( value ) uri = property(_get_uri,_set_uri) def set_filename(self, filename): self.filename = filename # TODO: be explicit if/where we default to English # TODO: do we need a separate index(), versus just use __init__ ? def index(self): # speclog("Indexing description of "+str(self)) # blank down anything we learned already self.terms = [] self.properties = [] self.classes = [] tmpclasses=[] tmpproperties=[] g = self.graph query = 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a rdf:Property }' relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: p = Property(term) # print "Made a property! "+str(p) + "using label: "#+str(label) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) query = 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type FILTER (?type = <http://www.w3.org/2002/07/owl#Class> || ?type = <http://www.w3.org/2000/01/rdf-schema#Class> ) }' relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: c = Class(term) # print "Made a class! "+str(p) + "using comment: "+comment c.label = str(label) c.comment = str(comment) self.terms.append(c) if (not str(c) in tmpclasses): self.classes.append(c) tmpclasses.append(str(c)) self.terms.sort(key=operator.attrgetter('id')) self.classes.sort(key=operator.attrgetter('id')) self.properties.sort(key=operator.attrgetter('id')) # http://www.w3.org/2003/06/sw-vocab-status/ns#" query = 'SELECT ?x ?vs WHERE { ?x <http://www.w3.org/2003/06/sw-vocab-status/ns#term_status> ?vs }' status = g.query(query, initNs=bindings) # print "status results: ",status.__len__() for x, vs in status: #print "STATUS: ",vs, " for ",x t = self.lookup(x) if t != None: t.status = vs # print "Set status.", t.status else: speclog("Couldn't lookup term: "+x) # Go back and see if we missed any properties defined in OWL. TODO: classes too. Or rewrite above SPARQL. addd more types for full query. q= 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty>)}' q= 'SELECT distinct ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty> || ?type = <http://www.w3.org/2002/07/owl#DatatypeProperty> || ?type = <http://www.w3.org/1999/02/22-rdf-syntax-ns#Property> || ?type = <http://www.w3.org/2002/07/owl#FunctionalProperty> || ?type = <http://www.w3.org/2002/07/owl#InverseFunctionalProperty>) } ' relations = g.query(q, initNs=bindings) for (term, label, comment) in relations: p = Property(str(term)) got = self.lookup( str(term) ) if got==None: # print "Made an OWL property! "+str(p.uri) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) # self.terms.sort() # does this even do anything? # self.classes.sort() # self.properties.sort() # todo, use a dictionary index instead. RTFM. def lookup(self, uri): uri = str(uri) for t in self.terms: # print "Lookup: comparing '"+t.uri+"' to '"+uri+"'" # print "type of t.uri is ",t.uri.__class__ if t.uri==uri: # print "Matched." # should we str here, to be more liberal? return t else: # print "Fail." '' return None # print a raw debug summary, direct from the RDF def raw(self): g = self.graph query = 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c } ' relations = g.query(query, initNs=bindings) print "Properties and Classes (%d terms)" % len(relations) print 40*"-" for (term, label, comment) in relations: print "term %s l: %s \t\tc: %s " % (term, label, comment) print # TODO: work out how to do ".encode('UTF-8')" here # for debugging only def detect_types(self): self.properties = [] self.classes = [] for t in self.terms: # print "Doing t: "+t+" which is of type " + str(t.__class__) if t.is_property(): # print "is_property." self.properties.append(t) if t.is_class(): # print "is_class." self.classes.append(t) # CODE FROM ORIGINAL specgen: def niceName(self, uri = None ): if uri is None: return # speclog("Nicing uri "+uri) regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) if rez == None: #print "Failed to niceName. Returning the whole thing." return(uri) pref = rez.group(1) # print "...",self.ns_list.get(pref, pref),":",rez.group(2) # todo: make this work when uri doesn't match the regex --danbri # AttributeError: 'NoneType' object has no attribute 'group' return self.ns_list.get(pref, pref) + ":" + rez.group(2) # HTML stuff, should be a separate class def azlist(self): """Builds the A-Z list of terms""" c_ids = [] p_ids = [] for p in self.properties: p_ids.append(str(p.id)) for c in self.classes: c_ids.append(str(c.id)) c_ids.sort() p_ids.sort() return (c_ids, p_ids) class VocabReport(object): def __init__(self, vocab, basedir='./examples/', temploc='template.html',templatedir='./examples/'): self.vocab = vocab self.basedir = basedir self.temploc = temploc self.templatedir = templatedir self._template = "no template loaded" # text.gsub(/<code>foaf:(\w+)<\/code>/){ defurl($1) } return "<code><a href=\"#term_#{term}\">foaf:#{term}</a></code>" def codelink(self, s): reg1 = re.compile(r"""<code>foaf:(\w+)<\/code>""") return(re.sub(reg1, r"""<code><a href="#term_\1">foaf:\1</a></code>""", s)) def _get_template(self): self._template = self.load_template() # should be conditional return self._template def _set_template(self, value): self._template = str(value) template = property(_get_template,_set_template) def load_template(self): filename = os.path.join(self.templatedir, self.temploc) f = open(filename, "r") template = f.read() return(template) def generate(self): tpl = self.template azlist = self.az() termlist = self.termlist() f = open ( self.vocab.filename, "r") rdfdata = f.read() # print "GENERATING >>>>>>>> " ## having the rdf in there was making it invalid ## removed in favour of RDFa ## tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8"), rdfdata) tpl = tpl % (azlist.encode("utf-8"), azlist.encode("utf-8"), termlist.encode("utf-8")) # tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8")) return(tpl) def az(self): """AZ List for html doc""" c_ids, p_ids = self.vocab.azlist() az = """<div class="azlist">""" az = """%s\n<p>Classes: |""" % az # print c_ids, p_ids for c in c_ids: # speclog("Class "+c+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(c).replace(" ", ""), c) az = """%s\n</p>""" % az az = """%s\n<p>Properties: |""" % az for p in p_ids: # speclog("Property "+p+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(p).replace(" ", ""), p) az = """%s\n</p>""" % az az = """%s\n</div>""" % az return(az) def termlist(self): """Term List for html doc""" stableTxt = '' testingTxt = '' unstableTxt = '' archaicTxt = '' queries = '' c_ids, p_ids = self.vocab.azlist() tl = """<div class="termlist">""" tl = """%s<h3>Classes and Properties (full detail)</h3>\n<div class='termdetails'><br />\n\n""" % tl # danbri hack 20100101 removed: href="http://www.w3.org/2003/06/sw-vocab-status/ns#%s" pending discussion w/ libby and leigh re URIs # first classes, then properties eg = """<div class="specterm" id="term_%s" about="%s" typeof="%s"> <h3>%s: %s</h3> <em>%s</em> - %s <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span property="vs:status" >%s</span></td></tr> %s %s </table> %s <p style="float: right; font-size: small;">[<a href="#term_%s">#</a>] [<a href="http://wiki.foaf-project.org/w/term_%s">wiki</a>] <!-- %s --> [<a href="#glance">back to top</a>]</p> <br/> </div>""" # replace this if you want validation queries: xxx danbri # <p style="float: right; font-size: small;">[<a href="#term_%s">permalink</a>] [<a href="#queries_%s">validation queries</a>] [<a href="#glance">back to top</a>]</p> # todo, push this into an api call (c_ids currently setup by az above) # classes for term in self.vocab.classes: # strings to use later domainsOfClass = '' rangesOfClass = '' #class in domain of g = self.vocab.graph q = 'SELECT ?d ?l WHERE {?d rdfs:domain <%s> . ?d rdfs:label ?l } ' % (term.uri) relations = g.query(q, initNs=bindings) startStr = '<tr><th>Properties include:</th>\n' contentStr = '' for (domain, label) in relations: dom = Term(domain) # danbri hack 20100101 # termStr = """<a href="#term_%s">%s</a>\n""" % (dom.id, label) termStr = """<a href="#term_%s">%s</a>\n""" % (dom.id, dom.id) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": domainsOfClass = "%s <td> %s </td></tr>" % (startStr, contentStr) # class in range of q2 = 'SELECT ?d ?l WHERE {?d rdfs:range <%s> . ?d rdfs:label ?l } ' % (term.uri) relations2 = g.query(q2, initNs=bindings) startStr = '<tr><th>Used with:</th>\n' contentStr = '' for (range, label) in relations2: ran = Term(range) # termStr = """<a href="#term_%s">%s</a>\n""" % (ran.id, label) # danbri hack 20100101 better to use exact IDs here termStr = """<a href="#term_%s">%s</a>\n""" % (ran.id, ran.id) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": rangesOfClass = "%s <td> %s</td></tr> " % (startStr, contentStr) # class subclassof subClassOf = '' q = 'SELECT ?sc ?l WHERE {<%s> rdfs:subClassOf ?sc . ?sc rdfs:label ?l } ' % (term.uri) relations = g.query(q, initNs=bindings) - startStr = '<tr><th>subClassOf</th>\n' + startStr = '<tr><th>Subclass Of</th>\n' contentStr = '' for (subclass, label) in relations: sub = Term(subclass) termStr = """<span rel="rdfs:subClassOf" href="%s"><a href="#term_%s">%s</a></span>\n""" % (subclass, sub.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": subClassOf = "%s <td> %s </td></tr>" % (startStr, contentStr) # class has subclass hasSubClass = '' q = 'SELECT ?sc ?l WHERE {?sc rdfs:subClassOf <%s>. ?sc rdfs:label ?l } ' % (term.uri) relations = g.query(q, initNs=bindings) - startStr = '<tr><th>has subclass</th>\n' + startStr = '<tr><th>Has Subclass</th>\n' contentStr = '' for (subclass, label) in relations: sub = Term(subclass) termStr = """<a href="#term_%s">%s</a>\n""" % (sub.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": hasSubClass = "%s <td> %s </td></tr>" % (startStr, contentStr) # is defined by classIsDefinedBy = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) relations = g.query(q, initNs=bindings) startStr = '\n' contentStr = '' for (isdefinedby) in relations: termStr = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": classIsDefinedBy = "%s <tr><td> %s </td></tr>" % (startStr, contentStr) # disjoint with isDisjointWith = '' q = 'SELECT ?dj ?l WHERE { <%s> <http://www.w3.org/2002/07/owl#disjointWith> ?dj . ?dj rdfs:label ?l } ' % (term.uri) relations = g.query(q, initNs=bindings) startStr = '<tr><th>Disjoint With:</th>\n' contentStr = '' for (disjointWith, label) in relations: termStr = """<span rel="owl:disjointWith" href="%s"><a href="#term_%s">%s</a></span>\n""" % (disjointWith, label, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": isDisjointWith = "%s <td> %s </td></tr>" % (startStr, contentStr) # end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' # if we want validation queries this is where it looks for them. filename = os.path.join(dn, term.id+".sparql") fileStr = '' try: f = open ( filename, "r") fileStr = f.read() fileStr = "<h4><a name=\"queries_"+term.id+"\"></a>"+term.id+" Validation Query</h4><pre>"+cgi.escape(ss)+"</pre>" except: fileStr='' queries = queries +"\n"+ fileStr sn = self.vocab.niceName(term.uri) s = termlink(s) # danbri added another term.id 20010101 and removed term.status zz = eg % (term.id,term.uri,"rdfs:Class","Class", sn, term.label, term.comment, term.status,domainsOfClass,rangesOfClass+subClassOf+hasSubClass+classIsDefinedBy+isDisjointWith, s,term.id, term.id, term.id) ## we add to the relevant string - stable, unstable, testing or archaic if(term.status == "stable"): stableTxt = stableTxt + zz if(term.status == "testing"): testingTxt = testingTxt + zz if(term.status == "unstable"): unstableTxt = unstableTxt + zz if(term.status == "archaic"): archaicTxt = archaicTxt + zz + if((term.status == None) or (term.status== "") or (term.status== "unknown")): + archaicTxt = archaicTxt + zz ## then add the whole thing to the main tl string tl = tl+"<h2>Classes</h2>\n" tl = "%s %s" % (tl, stableTxt+"\n"+testingTxt+"\n"+unstableTxt+"\n"+archaicTxt) tl = tl+"<h2>Properties</h2>\n" # properties stableTxt = '' testingTxt = '' unstableTxt = '' archaicTxt = '' for term in self.vocab.properties: domainsOfProperty = '' rangesOfProperty = '' # domain of properties g = self.vocab.graph q = 'SELECT ?d ?l WHERE {<%s> rdfs:domain ?d . ?d rdfs:label ?l } ' % (term.uri) relations = g.query(q, initNs=bindings) startStr = '<tr><th>Domain:</th>\n' contentStr = '' for (domain, label) in relations: dom = Term(domain) termStr = """<span rel="rdfs:domain" href="%s"><a href="#term_%s">%s</a></span>\n""" % (domain, dom.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": domainsOfProperty = "%s <td>%s</td></tr>" % (startStr, contentStr) # range of properties q2 = 'SELECT ?d ?l WHERE {<%s> rdfs:range ?d . ?d rdfs:label ?l } ' % (term.uri) relations2 = g.query(q2, initNs=bindings) startStr = '<tr><th>Range:</th>\n' contentStr = '' for (range, label) in relations2: ran = Term(range) termStr = """<span rel="rdfs:range" href="%s"><a href="#term_%s">%s</a></span>\n""" % (range, ran.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": rangesOfProperty = "%s <td>%s</td> </tr>" % (startStr, contentStr) # is defined by propertyIsDefinedBy = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) relations = g.query(q, initNs=bindings) startStr = '\n' contentStr = '' for (isdefinedby) in relations: termStr = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": propertyIsDefinedBy = "%s <tr><td> %s </td></tr>" % (startStr, contentStr) # inverse functional property ifp = '' q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#InverseFunctionalProperty> } ' % (term.uri) relations = g.query(q, initNs=bindings) startStr = '<tr><th colspan="2">Inverse Functional Property</th>\n' if (len(relations) > 0): termStr = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#InverseFunctionalProperty"></span>""" ifp = "%s <td> %s </td></tr>" % (startStr, termStr) # functonal property fp = '' q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#FunctionalProperty> } ' % (term.uri) relations = g.query(q, initNs=bindings) startStr = '<tr><th colspan="2">Functional Property</th>\n' if (len(relations) > 0): termStr = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#FunctionalProperty"></span>""" fp = "%s <td> %s </td></tr>" % (startStr, termStr) # end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' sn = self.vocab.niceName(term.uri) s = termlink(s) # danbri added another term.id 20010101 zz = eg % (term.id, term.uri,"rdf:Property","Property", sn, term.label, term.comment,term.status,domainsOfProperty,rangesOfProperty+propertyIsDefinedBy+ifp+fp, s,term.id, term.id, term.id) ## we add to the relevant string - stable, unstable, testing or archaic if(term.status == "stable"): stableTxt = stableTxt + zz if(term.status == "testing"): testingTxt = testingTxt + zz if(term.status == "unstable"): unstableTxt = unstableTxt + zz if(term.status == "archaic"): archaicTxt = archaicTxt + zz + if((term.status == None) or (term.status== "") or (term.status== "unknown")): + archaicTxt = archaicTxt + zz ## then add the whole thing to the main tl string tl = "%s %s" % (tl, stableTxt+"\n"+testingTxt+"\n"+unstableTxt+"\n"+archaicTxt) ## tl = "%s %s" % (tl, zz) ## ensure termlist tag is closed return(tl+"\n"+queries+"</div>\n</div>") def rdfa(self): return( "<html>rdfa here</html>") def htmlDocInfo( t, termdir='../docs' ): """Opens a file based on the term name (t) and termdir (defaults to current directory. Reads in the file, and returns a linkified version of it.""" if termdir==None: termdir=self.basedir doc = "" try: f = open("%s/%s.en" % (termdir, t), "r") doc = f.read() doc = termlink(doc) except: return "<p>No detailed documentation for this term.</p>" return doc # report what we've parsed from our various sources def report(self): s = "Report for vocabulary from " + self.vocab.filename + "\n" if self.vocab.uri != None: s += "URI: " + self.vocab.uri + "\n\n" for t in self.vocab.uterms: print "TERM as string: ",t s += t.simple_report() return s
leth/SpecGen
7672a6776bb779287676fd3d32b143ff743644d6
status
diff --git a/libvocab.py b/libvocab.py index 023c5e8..04a0ae5 100755 --- a/libvocab.py +++ b/libvocab.py @@ -3,830 +3,830 @@ # total rewrite. --danbri # Usage: # # >>> from libvocab import Vocab, Term, Class, Property # # >>> from libvocab import Vocab, Term, Class, Property # >>> v = Vocab( f='examples/foaf/index.rdf', uri='http://xmlns.com/foaf/0.1/') # >>> dna = v.lookup('http://xmlns.com/foaf/0.1/dnaChecksum') # >>> dna.label # 'DNA checksum' # >>> dna.comment # 'A checksum for the DNA of some thing. Joke.' # >>> dna.id # u'dnaChecksum' # >>> dna.uri # 'http://xmlns.com/foaf/0.1/dnaChecksum' # # # Python OO notes: # http://www.devshed.com/c/a/Python/Object-Oriented-Programming-With-Python-part-1/ # http://www.daniweb.com/code/snippet354.html # http://docs.python.org/reference/datamodel.html#specialnames # # RDFlib: # http://www.science.uva.nl/research/air/wiki/RDFlib # # http://dowhatimean.net/2006/03/spellchecking-vocabularies-with-sparql # # We define basics, Vocab, Term, Property, Class # and populate them with data from RDF schemas, OWL, translations ... and nearby html files. from rdflib.namespace import Namespace from rdflib.graph import Graph, ConjunctiveGraph from rdflib.sparql.sparqlGraph import SPARQLGraph from rdflib.sparql.graphPattern import GraphPattern from rdflib.sparql import Query FOAF = Namespace('http://xmlns.com/foaf/0.1/') RDFS = Namespace('http://www.w3.org/2000/01/rdf-schema#') XFN = Namespace("http://gmpg.org/xfn/1#") RDF = Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#") OWL = Namespace('http://www.w3.org/2002/07/owl#') VS = Namespace('http://www.w3.org/2003/06/sw-vocab-status/ns#') DC = Namespace('http://purl.org/dc/elements/1.1/') DOAP = Namespace('http://usefulinc.com/ns/doap#') SIOC = Namespace('http://rdfs.org/sioc/ns#') SIOCTYPES = Namespace('http://rdfs.org/sioc/types#') SIOCSERVICES = Namespace('http://rdfs.org/sioc/services#') # # TODO: rationalise these two lists. or at least check they are same. import sys, time, re, urllib, getopt import logging import os.path import cgi import operator bindings = { u"xfn": XFN, u"rdf": RDF, u"rdfs": RDFS, u"vs": VS } #g = None def speclog(str): sys.stderr.write("LOG: "+str+"\n") # todo: shouldn't be foaf specific def termlink(text): result = re.sub( r"<code>foaf:(\w+)<\/code>", r"<code><a href='#term_\g<1>'>\g<1></a></code>", text ) return result # a Term has... (intrinsically and via it's RDFS/OWL description) # uri - a (primary) URI, eg. 'http://xmlns.com/foaf/0.1/workplaceHomepage' # id - a local-to-spec ID, eg. 'workplaceHomepage' # xmlns - an xmlns URI (isDefinedBy, eg. 'http://xmlns.com/foaf/0.1/') # # label - an rdfs:label # comment - an rdfs:comment # # Beyond this, properties vary. Some have vs:status. Some have owl Deprecated. # Some have OWL descriptions, and RDFS descriptions; eg. property range/domain # or class disjointness. def ns_split(uri): regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) return(rez.group(1), rez.group(2)) class Term(object): def __init__(self, uri='file://dev/null'): self.uri = str(uri) self.uri = self.uri.rstrip() # speclog("Parsing URI " + uri) a,b = ns_split(uri) self.id = b self.xmlns = a if self.id==None: speclog("Error parsing URI. "+uri) if self.xmlns==None: speclog("Error parsing URI. "+uri) # print "self.id: "+ self.id + " self.xmlns: " + self.xmlns def uri(self): try: s = self.uri except NameError: self.uri = None s = '[NOURI]' speclog('No URI for'+self) return s def id(self): print "trying id" try: s = self.id except NameError: self.id = None s = '[NOID]' speclog('No ID for'+self) return str(s) def is_external(self, vocab): print "Comparing property URI ",self.uri," with vocab uri: " + vocab.uri return(False) #def __repr__(self): # return(self.__str__) def __str__(self): try: s = self.id except NameError: self.label = None speclog('No label for '+self+' todo: take from uri regex') s = (str(self)) return(str(s)) # so we can treat this like a string def __add__(self, s): return (s+str(self)) def __radd__(self, s): return (s+str(self)) def simple_report(self): t = self s='' s += "default: \t\t"+t +"\n" s += "id: \t\t"+t.id +"\n" s += "uri: \t\t"+t.uri +"\n" s += "xmlns: \t\t"+t.xmlns +"\n" s += "label: \t\t"+t.label +"\n" s += "comment: \t\t" + t.comment +"\n" s += "status: \t\t" + t.status +"\n" s += "\n" return s def _get_status(self): try: return self._status except: return 'unknown' def _set_status(self, value): self._status = str(value) status = property(_get_status,_set_status) # a Python class representing an RDFS/OWL property. # class Property(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Property.is_property called on "+self return(True) def is_class(self): # print "Property.is_class called on "+self return(False) # A Python class representing an RDFS/OWL class # class Class(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Class.is_property called on "+self return(False) def is_class(self): # print "Class.is_class called on "+self return(True) # A python class representing (a description of) some RDF vocabulary # class Vocab(object): def __init__(self, dir, f='index.rdf', uri=None ): self.graph = ConjunctiveGraph() self._uri = uri self.dir = dir self.filename = os.path.join(dir, f) self.graph.parse(self.filename) self.terms = [] self.uterms = [] # should also load translations here? # and deal with a base-dir? ##if f != None: ## self.index() self.ns_list = { "http://www.w3.org/1999/02/22-rdf-syntax-ns#" : "rdf", "http://www.w3.org/2000/01/rdf-schema#" : "rdfs", "http://www.w3.org/2002/07/owl#" : "owl", "http://www.w3.org/2001/XMLSchema#" : "xsd", "http://rdfs.org/sioc/ns#" : "sioc", "http://xmlns.com/foaf/0.1/" : "foaf", "http://purl.org/dc/elements/1.1/" : "dc", "http://purl.org/dc/terms/" : "dct", "http://usefulinc.com/ns/doap#" : "doap", "http://www.w3.org/2003/06/sw-vocab-status/ns#" : "status", "http://purl.org/rss/1.0/modules/content/" : "content", "http://www.w3.org/2003/01/geo/wgs84_pos#" : "geo", "http://www.w3.org/2004/02/skos/core#" : "skos", "http://purl.org/NET/c4dm/event.owl#" : "event" } def addShortName(self,sn): self.ns_list[self._uri] = sn self.shortName = sn #print self.ns_list # not currently used def unique_terms(self): tmp=[] for t in list(set(self.terms)): s = str(t) if (not s in tmp): self.uterms.append(t) tmp.append(s) # TODO: python question - can we skip needing getters? and only define setters. i tried/failed. --danbri def _get_uri(self): return self._uri def _set_uri(self, value): v = str(value) # we don't want Namespace() objects and suchlike, but we can use them without whining. if ':' not in v: speclog("Warning: this doesn't look like a URI: "+v) # raise Exception("This doesn't look like a URI.") self._uri = str( value ) uri = property(_get_uri,_set_uri) def set_filename(self, filename): self.filename = filename # TODO: be explicit if/where we default to English # TODO: do we need a separate index(), versus just use __init__ ? def index(self): # speclog("Indexing description of "+str(self)) # blank down anything we learned already self.terms = [] self.properties = [] self.classes = [] tmpclasses=[] tmpproperties=[] g = self.graph query = 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a rdf:Property }' relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: p = Property(term) # print "Made a property! "+str(p) + "using label: "#+str(label) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) query = 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type FILTER (?type = <http://www.w3.org/2002/07/owl#Class> || ?type = <http://www.w3.org/2000/01/rdf-schema#Class> ) }' relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: c = Class(term) # print "Made a class! "+str(p) + "using comment: "+comment c.label = str(label) c.comment = str(comment) self.terms.append(c) if (not str(c) in tmpclasses): self.classes.append(c) tmpclasses.append(str(c)) self.terms.sort(key=operator.attrgetter('id')) self.classes.sort(key=operator.attrgetter('id')) self.properties.sort(key=operator.attrgetter('id')) # http://www.w3.org/2003/06/sw-vocab-status/ns#" query = 'SELECT ?x ?vs WHERE { ?x <http://www.w3.org/2003/06/sw-vocab-status/ns#term_status> ?vs }' status = g.query(query, initNs=bindings) # print "status results: ",status.__len__() for x, vs in status: #print "STATUS: ",vs, " for ",x t = self.lookup(x) if t != None: t.status = vs # print "Set status.", t.status else: speclog("Couldn't lookup term: "+x) # Go back and see if we missed any properties defined in OWL. TODO: classes too. Or rewrite above SPARQL. addd more types for full query. q= 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty>)}' q= 'SELECT distinct ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty> || ?type = <http://www.w3.org/2002/07/owl#DatatypeProperty> || ?type = <http://www.w3.org/1999/02/22-rdf-syntax-ns#Property> || ?type = <http://www.w3.org/2002/07/owl#FunctionalProperty> || ?type = <http://www.w3.org/2002/07/owl#InverseFunctionalProperty>) } ' relations = g.query(q, initNs=bindings) for (term, label, comment) in relations: p = Property(str(term)) got = self.lookup( str(term) ) if got==None: # print "Made an OWL property! "+str(p.uri) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) # self.terms.sort() # does this even do anything? # self.classes.sort() # self.properties.sort() # todo, use a dictionary index instead. RTFM. def lookup(self, uri): uri = str(uri) for t in self.terms: # print "Lookup: comparing '"+t.uri+"' to '"+uri+"'" # print "type of t.uri is ",t.uri.__class__ if t.uri==uri: # print "Matched." # should we str here, to be more liberal? return t else: # print "Fail." '' return None # print a raw debug summary, direct from the RDF def raw(self): g = self.graph query = 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c } ' relations = g.query(query, initNs=bindings) print "Properties and Classes (%d terms)" % len(relations) print 40*"-" for (term, label, comment) in relations: print "term %s l: %s \t\tc: %s " % (term, label, comment) print # TODO: work out how to do ".encode('UTF-8')" here # for debugging only def detect_types(self): self.properties = [] self.classes = [] for t in self.terms: # print "Doing t: "+t+" which is of type " + str(t.__class__) if t.is_property(): # print "is_property." self.properties.append(t) if t.is_class(): # print "is_class." self.classes.append(t) # CODE FROM ORIGINAL specgen: def niceName(self, uri = None ): if uri is None: return # speclog("Nicing uri "+uri) regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) if rez == None: #print "Failed to niceName. Returning the whole thing." return(uri) pref = rez.group(1) # print "...",self.ns_list.get(pref, pref),":",rez.group(2) # todo: make this work when uri doesn't match the regex --danbri # AttributeError: 'NoneType' object has no attribute 'group' return self.ns_list.get(pref, pref) + ":" + rez.group(2) # HTML stuff, should be a separate class def azlist(self): """Builds the A-Z list of terms""" c_ids = [] p_ids = [] for p in self.properties: p_ids.append(str(p.id)) for c in self.classes: c_ids.append(str(c.id)) c_ids.sort() p_ids.sort() return (c_ids, p_ids) class VocabReport(object): def __init__(self, vocab, basedir='./examples/', temploc='template.html',templatedir='./examples/'): self.vocab = vocab self.basedir = basedir self.temploc = temploc self.templatedir = templatedir self._template = "no template loaded" # text.gsub(/<code>foaf:(\w+)<\/code>/){ defurl($1) } return "<code><a href=\"#term_#{term}\">foaf:#{term}</a></code>" def codelink(self, s): reg1 = re.compile(r"""<code>foaf:(\w+)<\/code>""") return(re.sub(reg1, r"""<code><a href="#term_\1">foaf:\1</a></code>""", s)) def _get_template(self): self._template = self.load_template() # should be conditional return self._template def _set_template(self, value): self._template = str(value) template = property(_get_template,_set_template) def load_template(self): filename = os.path.join(self.templatedir, self.temploc) f = open(filename, "r") template = f.read() return(template) def generate(self): tpl = self.template azlist = self.az() termlist = self.termlist() f = open ( self.vocab.filename, "r") rdfdata = f.read() # print "GENERATING >>>>>>>> " ## having the rdf in there was making it invalid ## removed in favour of RDFa ## tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8"), rdfdata) tpl = tpl % (azlist.encode("utf-8"), azlist.encode("utf-8"), termlist.encode("utf-8")) # tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8")) return(tpl) def az(self): """AZ List for html doc""" c_ids, p_ids = self.vocab.azlist() az = """<div class="azlist">""" az = """%s\n<p>Classes: |""" % az # print c_ids, p_ids for c in c_ids: # speclog("Class "+c+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(c).replace(" ", ""), c) az = """%s\n</p>""" % az az = """%s\n<p>Properties: |""" % az for p in p_ids: # speclog("Property "+p+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(p).replace(" ", ""), p) az = """%s\n</p>""" % az az = """%s\n</div>""" % az return(az) def termlist(self): """Term List for html doc""" stableTxt = '' testingTxt = '' unstableTxt = '' archaicTxt = '' queries = '' c_ids, p_ids = self.vocab.azlist() tl = """<div class="termlist">""" tl = """%s<h3>Classes and Properties (full detail)</h3>\n<div class='termdetails'><br />\n\n""" % tl # danbri hack 20100101 removed: href="http://www.w3.org/2003/06/sw-vocab-status/ns#%s" pending discussion w/ libby and leigh re URIs # first classes, then properties eg = """<div class="specterm" id="term_%s" about="%s" typeof="%s"> <h3>%s: %s</h3> <em>%s</em> - %s <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td><span rel="vs:status" >%s</span></td></tr> + <td><span property="vs:status" >%s</span></td></tr> %s %s </table> %s <p style="float: right; font-size: small;">[<a href="#term_%s">#</a>] [<a href="http://wiki.foaf-project.org/w/term_%s">wiki</a>] <!-- %s --> [<a href="#glance">back to top</a>]</p> <br/> </div>""" # replace this if you want validation queries: xxx danbri # <p style="float: right; font-size: small;">[<a href="#term_%s">permalink</a>] [<a href="#queries_%s">validation queries</a>] [<a href="#glance">back to top</a>]</p> # todo, push this into an api call (c_ids currently setup by az above) # classes for term in self.vocab.classes: # strings to use later domainsOfClass = '' rangesOfClass = '' #class in domain of g = self.vocab.graph q = 'SELECT ?d ?l WHERE {?d rdfs:domain <%s> . ?d rdfs:label ?l } ' % (term.uri) relations = g.query(q, initNs=bindings) startStr = '<tr><th>Properties include:</th>\n' contentStr = '' for (domain, label) in relations: dom = Term(domain) # danbri hack 20100101 # termStr = """<a href="#term_%s">%s</a>\n""" % (dom.id, label) termStr = """<a href="#term_%s">%s</a>\n""" % (dom.id, dom.id) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": domainsOfClass = "%s <td> %s </td></tr>" % (startStr, contentStr) # class in range of q2 = 'SELECT ?d ?l WHERE {?d rdfs:range <%s> . ?d rdfs:label ?l } ' % (term.uri) relations2 = g.query(q2, initNs=bindings) startStr = '<tr><th>Used with:</th>\n' contentStr = '' for (range, label) in relations2: ran = Term(range) # termStr = """<a href="#term_%s">%s</a>\n""" % (ran.id, label) # danbri hack 20100101 better to use exact IDs here termStr = """<a href="#term_%s">%s</a>\n""" % (ran.id, ran.id) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": rangesOfClass = "%s <td> %s</td></tr> " % (startStr, contentStr) # class subclassof subClassOf = '' q = 'SELECT ?sc ?l WHERE {<%s> rdfs:subClassOf ?sc . ?sc rdfs:label ?l } ' % (term.uri) relations = g.query(q, initNs=bindings) startStr = '<tr><th>subClassOf</th>\n' contentStr = '' for (subclass, label) in relations: sub = Term(subclass) termStr = """<span rel="rdfs:subClassOf" href="%s"><a href="#term_%s">%s</a></span>\n""" % (subclass, sub.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": subClassOf = "%s <td> %s </td></tr>" % (startStr, contentStr) # class has subclass hasSubClass = '' q = 'SELECT ?sc ?l WHERE {?sc rdfs:subClassOf <%s>. ?sc rdfs:label ?l } ' % (term.uri) relations = g.query(q, initNs=bindings) startStr = '<tr><th>has subclass</th>\n' contentStr = '' for (subclass, label) in relations: sub = Term(subclass) termStr = """<a href="#term_%s">%s</a>\n""" % (sub.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": hasSubClass = "%s <td> %s </td></tr>" % (startStr, contentStr) # is defined by classIsDefinedBy = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) relations = g.query(q, initNs=bindings) startStr = '\n' contentStr = '' for (isdefinedby) in relations: termStr = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": classIsDefinedBy = "%s <tr><td> %s </td></tr>" % (startStr, contentStr) # disjoint with isDisjointWith = '' q = 'SELECT ?dj ?l WHERE { <%s> <http://www.w3.org/2002/07/owl#disjointWith> ?dj . ?dj rdfs:label ?l } ' % (term.uri) relations = g.query(q, initNs=bindings) startStr = '<tr><th>Disjoint With:</th>\n' contentStr = '' for (disjointWith, label) in relations: termStr = """<span rel="owl:disjointWith" href="%s"><a href="#term_%s">%s</a></span>\n""" % (disjointWith, label, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": isDisjointWith = "%s <td> %s </td></tr>" % (startStr, contentStr) # end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' # if we want validation queries this is where it looks for them. filename = os.path.join(dn, term.id+".sparql") fileStr = '' try: f = open ( filename, "r") fileStr = f.read() fileStr = "<h4><a name=\"queries_"+term.id+"\"></a>"+term.id+" Validation Query</h4><pre>"+cgi.escape(ss)+"</pre>" except: fileStr='' queries = queries +"\n"+ fileStr sn = self.vocab.niceName(term.uri) s = termlink(s) # danbri added another term.id 20010101 and removed term.status zz = eg % (term.id,term.uri,"rdfs:Class","Class", sn, term.label, term.comment, term.status,domainsOfClass,rangesOfClass+subClassOf+hasSubClass+classIsDefinedBy+isDisjointWith, s,term.id, term.id, term.id) ## we add to the relevant string - stable, unstable, testing or archaic if(term.status == "stable"): stableTxt = stableTxt + zz if(term.status == "testing"): testingTxt = testingTxt + zz if(term.status == "unstable"): unstableTxt = unstableTxt + zz if(term.status == "archaic"): archaicTxt = archaicTxt + zz ## then add the whole thing to the main tl string tl = tl+"<h2>Classes</h2>\n" tl = "%s %s" % (tl, stableTxt+"\n"+testingTxt+"\n"+unstableTxt+"\n"+archaicTxt) tl = tl+"<h2>Properties</h2>\n" # properties stableTxt = '' testingTxt = '' unstableTxt = '' archaicTxt = '' for term in self.vocab.properties: domainsOfProperty = '' rangesOfProperty = '' # domain of properties g = self.vocab.graph q = 'SELECT ?d ?l WHERE {<%s> rdfs:domain ?d . ?d rdfs:label ?l } ' % (term.uri) relations = g.query(q, initNs=bindings) startStr = '<tr><th>Domain:</th>\n' contentStr = '' for (domain, label) in relations: dom = Term(domain) termStr = """<span rel="rdfs:domain" href="%s"><a href="#term_%s">%s</a></span>\n""" % (domain, dom.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": domainsOfProperty = "%s <td>%s</td></tr>" % (startStr, contentStr) # range of properties q2 = 'SELECT ?d ?l WHERE {<%s> rdfs:range ?d . ?d rdfs:label ?l } ' % (term.uri) relations2 = g.query(q2, initNs=bindings) startStr = '<tr><th>Range:</th>\n' contentStr = '' for (range, label) in relations2: ran = Term(range) termStr = """<span rel="rdfs:range" href="%s"><a href="#term_%s">%s</a></span>\n""" % (range, ran.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": rangesOfProperty = "%s <td>%s</td> </tr>" % (startStr, contentStr) # is defined by propertyIsDefinedBy = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) relations = g.query(q, initNs=bindings) startStr = '\n' contentStr = '' for (isdefinedby) in relations: termStr = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": propertyIsDefinedBy = "%s <tr><td> %s </td></tr>" % (startStr, contentStr) # inverse functional property ifp = '' q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#InverseFunctionalProperty> } ' % (term.uri) relations = g.query(q, initNs=bindings) startStr = '<tr><th colspan="2">Inverse Functional Property</th>\n' if (len(relations) > 0): termStr = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#InverseFunctionalProperty"></span>""" ifp = "%s <td> %s </td></tr>" % (startStr, termStr) # functonal property fp = '' q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#FunctionalProperty> } ' % (term.uri) relations = g.query(q, initNs=bindings) startStr = '<tr><th colspan="2">Functional Property</th>\n' if (len(relations) > 0): termStr = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#FunctionalProperty"></span>""" fp = "%s <td> %s </td></tr>" % (startStr, termStr) # end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' sn = self.vocab.niceName(term.uri) s = termlink(s) # danbri added another term.id 20010101 zz = eg % (term.id, term.uri,"rdf:Property","Property", sn, term.label, term.comment,term.status,domainsOfProperty,rangesOfProperty+propertyIsDefinedBy+ifp+fp, s,term.id, term.id, term.id) ## we add to the relevant string - stable, unstable, testing or archaic if(term.status == "stable"): stableTxt = stableTxt + zz if(term.status == "testing"): testingTxt = testingTxt + zz if(term.status == "unstable"): unstableTxt = unstableTxt + zz if(term.status == "archaic"): archaicTxt = archaicTxt + zz ## then add the whole thing to the main tl string tl = "%s %s" % (tl, stableTxt+"\n"+testingTxt+"\n"+unstableTxt+"\n"+archaicTxt) ## tl = "%s %s" % (tl, zz) ## ensure termlist tag is closed return(tl+"\n"+queries+"</div>\n</div>") def rdfa(self): return( "<html>rdfa here</html>") def htmlDocInfo( t, termdir='../docs' ): """Opens a file based on the term name (t) and termdir (defaults to current directory. Reads in the file, and returns a linkified version of it.""" if termdir==None: termdir=self.basedir doc = "" try: f = open("%s/%s.en" % (termdir, t), "r") doc = f.read() doc = termlink(doc) except: return "<p>No detailed documentation for this term.</p>" return doc # report what we've parsed from our various sources def report(self): s = "Report for vocabulary from " + self.vocab.filename + "\n" if self.vocab.uri != None: s += "URI: " + self.vocab.uri + "\n\n" for t in self.vocab.uterms: print "TERM as string: ",t s += t.simple_report() return s
leth/SpecGen
4ce171f4f554223f14db935e4a5bc7b96f80641b
removed uris for statuses
diff --git a/libvocab.py b/libvocab.py index fc2d5d9..91aa2dc 100755 --- a/libvocab.py +++ b/libvocab.py @@ -150,683 +150,683 @@ class Term(object): def simple_report(self): t = self s='' s += "default: \t\t"+t +"\n" s += "id: \t\t"+t.id +"\n" s += "uri: \t\t"+t.uri +"\n" s += "xmlns: \t\t"+t.xmlns +"\n" s += "label: \t\t"+t.label +"\n" s += "comment: \t\t" + t.comment +"\n" s += "status: \t\t" + t.status +"\n" s += "\n" return s def _get_status(self): try: return self._status except: return 'unknown' def _set_status(self, value): self._status = str(value) status = property(_get_status,_set_status) # a Python class representing an RDFS/OWL property. # class Property(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Property.is_property called on "+self return(True) def is_class(self): # print "Property.is_class called on "+self return(False) # A Python class representing an RDFS/OWL class # class Class(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Class.is_property called on "+self return(False) def is_class(self): # print "Class.is_class called on "+self return(True) # A python class representing (a description of) some RDF vocabulary # class Vocab(object): def __init__(self, dir, f='index.rdf', uri=None ): self.graph = ConjunctiveGraph() self._uri = uri self.dir = dir self.filename = os.path.join(dir, f) self.graph.parse(self.filename) self.terms = [] self.uterms = [] # should also load translations here? # and deal with a base-dir? ##if f != None: ## self.index() self.ns_list = { "http://www.w3.org/1999/02/22-rdf-syntax-ns#" : "rdf", "http://www.w3.org/2000/01/rdf-schema#" : "rdfs", "http://www.w3.org/2002/07/owl#" : "owl", "http://www.w3.org/2001/XMLSchema#" : "xsd", "http://rdfs.org/sioc/ns#" : "sioc", "http://xmlns.com/foaf/0.1/" : "foaf", "http://purl.org/dc/elements/1.1/" : "dc", "http://purl.org/dc/terms/" : "dct", "http://usefulinc.com/ns/doap#" : "doap", "http://www.w3.org/2003/06/sw-vocab-status/ns#" : "status", "http://purl.org/rss/1.0/modules/content/" : "content", "http://www.w3.org/2003/01/geo/wgs84_pos#" : "geo", "http://www.w3.org/2004/02/skos/core#" : "skos", "http://purl.org/NET/c4dm/event.owl#" : "event" } def addShortName(self,sn): self.ns_list[self._uri] = sn self.shortName = sn #print self.ns_list # not currently used def unique_terms(self): tmp=[] for t in list(set(self.terms)): s = str(t) if (not s in tmp): self.uterms.append(t) tmp.append(s) # TODO: python question - can we skip needing getters? and only define setters. i tried/failed. --danbri def _get_uri(self): return self._uri def _set_uri(self, value): v = str(value) # we don't want Namespace() objects and suchlike, but we can use them without whining. if ':' not in v: speclog("Warning: this doesn't look like a URI: "+v) # raise Exception("This doesn't look like a URI.") self._uri = str( value ) uri = property(_get_uri,_set_uri) def set_filename(self, filename): self.filename = filename # TODO: be explicit if/where we default to English # TODO: do we need a separate index(), versus just use __init__ ? def index(self): # speclog("Indexing description of "+str(self)) # blank down anything we learned already self.terms = [] self.properties = [] self.classes = [] tmpclasses=[] tmpproperties=[] g = self.graph query = 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a rdf:Property }' relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: p = Property(term) # print "Made a property! "+str(p) + "using label: "#+str(label) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) query = 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type FILTER (?type = <http://www.w3.org/2002/07/owl#Class> || ?type = <http://www.w3.org/2000/01/rdf-schema#Class> ) }' relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: c = Class(term) # print "Made a class! "+str(p) + "using comment: "+comment c.label = str(label) c.comment = str(comment) self.terms.append(c) if (not str(c) in tmpclasses): self.classes.append(c) tmpclasses.append(str(c)) self.terms.sort(key=operator.attrgetter('id')) self.classes.sort(key=operator.attrgetter('id')) self.properties.sort(key=operator.attrgetter('id')) # http://www.w3.org/2003/06/sw-vocab-status/ns#" query = 'SELECT ?x ?vs WHERE { ?x <http://www.w3.org/2003/06/sw-vocab-status/ns#term_status> ?vs }' status = g.query(query, initNs=bindings) # print "status results: ",status.__len__() for x, vs in status: #print "STATUS: ",vs, " for ",x t = self.lookup(x) if t != None: t.status = vs # print "Set status.", t.status else: speclog("Couldn't lookup term: "+x) # Go back and see if we missed any properties defined in OWL. TODO: classes too. Or rewrite above SPARQL. addd more types for full query. q= 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty>)}' q= 'SELECT distinct ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty> || ?type = <http://www.w3.org/2002/07/owl#DatatypeProperty> || ?type = <http://www.w3.org/1999/02/22-rdf-syntax-ns#Property> || ?type = <http://www.w3.org/2002/07/owl#FunctionalProperty> || ?type = <http://www.w3.org/2002/07/owl#InverseFunctionalProperty>) } ' relations = g.query(q, initNs=bindings) for (term, label, comment) in relations: p = Property(str(term)) got = self.lookup( str(term) ) if got==None: # print "Made an OWL property! "+str(p.uri) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) # self.terms.sort() # does this even do anything? # self.classes.sort() # self.properties.sort() # todo, use a dictionary index instead. RTFM. def lookup(self, uri): uri = str(uri) for t in self.terms: # print "Lookup: comparing '"+t.uri+"' to '"+uri+"'" # print "type of t.uri is ",t.uri.__class__ if t.uri==uri: # print "Matched." # should we str here, to be more liberal? return t else: # print "Fail." '' return None # print a raw debug summary, direct from the RDF def raw(self): g = self.graph query = 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c } ' relations = g.query(query, initNs=bindings) print "Properties and Classes (%d terms)" % len(relations) print 40*"-" for (term, label, comment) in relations: print "term %s l: %s \t\tc: %s " % (term, label, comment) print # TODO: work out how to do ".encode('UTF-8')" here # for debugging only def detect_types(self): self.properties = [] self.classes = [] for t in self.terms: # print "Doing t: "+t+" which is of type " + str(t.__class__) if t.is_property(): # print "is_property." self.properties.append(t) if t.is_class(): # print "is_class." self.classes.append(t) # CODE FROM ORIGINAL specgen: def niceName(self, uri = None ): if uri is None: return # speclog("Nicing uri "+uri) regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) if rez == None: #print "Failed to niceName. Returning the whole thing." return(uri) pref = rez.group(1) # print "...",self.ns_list.get(pref, pref),":",rez.group(2) # todo: make this work when uri doesn't match the regex --danbri # AttributeError: 'NoneType' object has no attribute 'group' return self.ns_list.get(pref, pref) + ":" + rez.group(2) # HTML stuff, should be a separate class def azlist(self): """Builds the A-Z list of terms""" c_ids = [] p_ids = [] for p in self.properties: p_ids.append(str(p.id)) for c in self.classes: c_ids.append(str(c.id)) c_ids.sort() p_ids.sort() return (c_ids, p_ids) class VocabReport(object): def __init__(self, vocab, basedir='./examples/', temploc='template.html',templatedir='./examples/'): self.vocab = vocab self.basedir = basedir self.temploc = temploc self.templatedir = templatedir self._template = "no template loaded" # text.gsub(/<code>foaf:(\w+)<\/code>/){ defurl($1) } return "<code><a href=\"#term_#{term}\">foaf:#{term}</a></code>" def codelink(self, s): reg1 = re.compile(r"""<code>foaf:(\w+)<\/code>""") return(re.sub(reg1, r"""<code><a href="#term_\1">foaf:\1</a></code>""", s)) def _get_template(self): self._template = self.load_template() # should be conditional return self._template def _set_template(self, value): self._template = str(value) template = property(_get_template,_set_template) def load_template(self): filename = os.path.join(self.templatedir, self.temploc) f = open(filename, "r") template = f.read() return(template) def generate(self): tpl = self.template azlist = self.az() termlist = self.termlist() f = open ( self.vocab.filename, "r") rdfdata = f.read() # print "GENERATING >>>>>>>> " ## having the rdf in there was making it invalid ## removed in favour of RDFa ## tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8"), rdfdata) tpl = tpl % (azlist.encode("utf-8"), azlist.encode("utf-8"), termlist.encode("utf-8")) # tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8")) return(tpl) def az(self): """AZ List for html doc""" c_ids, p_ids = self.vocab.azlist() az = """<div class="azlist">""" az = """%s\n<p>Classes: |""" % az # print c_ids, p_ids for c in c_ids: # speclog("Class "+c+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(c).replace(" ", ""), c) az = """%s\n</p>""" % az az = """%s\n<p>Properties: |""" % az for p in p_ids: # speclog("Property "+p+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(p).replace(" ", ""), p) az = """%s\n</p>""" % az az = """%s\n</div>""" % az return(az) def termlist(self): """Term List for html doc""" stableTxt = '' testingTxt = '' unstableTxt = '' archaicTxt = '' queries = '' c_ids, p_ids = self.vocab.azlist() tl = """<div class="termlist">""" tl = """%s<h3>Classes and Properties (full detail)</h3>\n<div class='termdetails'><br />\n\n""" % tl # danbri hack 20100101 removed: href="http://www.w3.org/2003/06/sw-vocab-status/ns#%s" pending discussion w/ libby and leigh re URIs # first classes, then properties eg = """<div class="specterm" id="term_%s" about="%s" typeof="%s"> <h3>%s: %s</h3> <em>%s</em> - %s <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span rel="vs:status" >%s</span></td></tr> %s %s </table> %s <p style="float: right; font-size: small;">[<a href="#term_%s">#</a>] [<a href="http://wiki.foaf-project.org/w/term_%s">wiki</a>] <!-- %s --> [<a href="#glance">back to top</a>]</p> <br/> </div>""" # replace this if you want validation queries: xxx danbri # <p style="float: right; font-size: small;">[<a href="#term_%s">permalink</a>] [<a href="#queries_%s">validation queries</a>] [<a href="#glance">back to top</a>]</p> # todo, push this into an api call (c_ids currently setup by az above) # classes for term in self.vocab.classes: # strings to use later domainsOfClass = '' rangesOfClass = '' #class in domain of g = self.vocab.graph q = 'SELECT ?d ?l WHERE {?d rdfs:domain <%s> . ?d rdfs:label ?l } ' % (term.uri) relations = g.query(q, initNs=bindings) startStr = '<tr><th>Properties include:</th>\n' contentStr = '' for (domain, label) in relations: dom = Term(domain) # danbri hack 20100101 # termStr = """<a href="#term_%s">%s</a>\n""" % (dom.id, label) termStr = """<a href="#term_%s">%s</a>\n""" % (dom.id, dom.id) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": domainsOfClass = "%s <td> %s </td></tr>" % (startStr, contentStr) # class in range of q2 = 'SELECT ?d ?l WHERE {?d rdfs:range <%s> . ?d rdfs:label ?l } ' % (term.uri) relations2 = g.query(q2, initNs=bindings) startStr = '<tr><th>Used with:</th>\n' contentStr = '' for (range, label) in relations2: ran = Term(range) # termStr = """<a href="#term_%s">%s</a>\n""" % (ran.id, label) # danbri hack 20100101 better to use exact IDs here termStr = """<a href="#term_%s">%s</a>\n""" % (ran.id, ran.id) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": rangesOfClass = "%s <td> %s</td></tr> " % (startStr, contentStr) # class subclassof subClassOf = '' q = 'SELECT ?sc ?l WHERE {<%s> rdfs:subClassOf ?sc . ?sc rdfs:label ?l } ' % (term.uri) relations = g.query(q, initNs=bindings) startStr = '<tr><th>subClassOf</th>\n' contentStr = '' for (subclass, label) in relations: sub = Term(subclass) termStr = """<span rel="rdfs:subClassOf" href="%s"><a href="#term_%s">%s</a></span>\n""" % (subclass, sub.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": subClassOf = "%s <td> %s </td></tr>" % (startStr, contentStr) # class has subclass hasSubClass = '' q = 'SELECT ?sc ?l WHERE {?sc rdfs:subClassOf <%s>. ?sc rdfs:label ?l } ' % (term.uri) relations = g.query(q, initNs=bindings) startStr = '<tr><th>has subclass</th>\n' contentStr = '' for (subclass, label) in relations: sub = Term(subclass) termStr = """<a href="#term_%s">%s</a>\n""" % (sub.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": hasSubClass = "%s <td> %s </td></tr>" % (startStr, contentStr) # is defined by classIsDefinedBy = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) relations = g.query(q, initNs=bindings) startStr = '\n' contentStr = '' for (isdefinedby) in relations: termStr = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": classIsDefinedBy = "%s <tr><td> %s </td></tr>" % (startStr, contentStr) # disjoint with isDisjointWith = '' q = 'SELECT ?dj ?l WHERE { <%s> <http://www.w3.org/2002/07/owl#disjointWith> ?dj . ?dj rdfs:label ?l } ' % (term.uri) relations = g.query(q, initNs=bindings) startStr = '<tr><th>Disjoint With:</th>\n' contentStr = '' for (disjointWith, label) in relations: termStr = """<span rel="owl:disjointWith" href="%s"><a href="#term_%s">%s</a></span>\n""" % (disjointWith, label, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": isDisjointWith = "%s <td> %s </td></tr>" % (startStr, contentStr) # end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' # if we want validation queries this is where it looks for them. filename = os.path.join(dn, term.id+".sparql") fileStr = '' try: f = open ( filename, "r") fileStr = f.read() fileStr = "<h4><a name=\"queries_"+term.id+"\"></a>"+term.id+" Validation Query</h4><pre>"+cgi.escape(ss)+"</pre>" except: fileStr='' queries = queries +"\n"+ fileStr sn = self.vocab.niceName(term.uri) s = termlink(s) - # danbri added another term.id 20010101 - zz = eg % (term.id,term.uri,"rdfs:Class","Class", sn, term.label, term.comment, term.status,term.status,domainsOfClass,rangesOfClass+subClassOf+hasSubClass+classIsDefinedBy+isDisjointWith, s,term.id, term.id, term.id) + # danbri added another term.id 20010101 and removed term.status + zz = eg % (term.id,term.uri,"rdfs:Class","Class", sn, term.label, term.comment, term.status,domainsOfClass,rangesOfClass+subClassOf+hasSubClass+classIsDefinedBy+isDisjointWith, s,term.id, term.id, term.id) ## we add to the relevant string - stable, unstable, testing or archaic if(term.status == "stable"): stableTxt = stableTxt + zz if(term.status == "testing"): testingTxt = testingTxt + zz if(term.status == "unstable"): unstableTxt = unstableTxt + zz if(term.status == "archaic"): archaicTxt = archaicTxt + zz ## then add the whole thing to the main tl string tl = tl+"<h2>Classes</h2>\n" tl = "%s %s" % (tl, stableTxt+"\n"+testingTxt+"\n"+unstableTxt+"\n"+archaicTxt) tl = tl+"<h2>Properties</h2>\n" # properties stableTxt = '' testingTxt = '' unstableTxt = '' archaicTxt = '' for term in self.vocab.properties: domainsOfProperty = '' rangesOfProperty = '' # domain of properties g = self.vocab.graph q = 'SELECT ?d ?l WHERE {<%s> rdfs:domain ?d . ?d rdfs:label ?l } ' % (term.uri) relations = g.query(q, initNs=bindings) startStr = '<tr><th>Domain:</th>\n' contentStr = '' for (domain, label) in relations: dom = Term(domain) termStr = """<span rel="rdfs:domain" href="%s"><a href="#term_%s">%s</a></span>\n""" % (domain, dom.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": domainsOfProperty = "%s <td>%s</td></tr>" % (startStr, contentStr) # range of properties q2 = 'SELECT ?d ?l WHERE {<%s> rdfs:range ?d . ?d rdfs:label ?l } ' % (term.uri) relations2 = g.query(q2, initNs=bindings) startStr = '<tr><th>Range:</th>\n' contentStr = '' for (range, label) in relations2: ran = Term(range) termStr = """<span rel="rdfs:range" href="%s"><a href="#term_%s">%s</a></span>\n""" % (range, ran.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": rangesOfProperty = "%s <td>%s</td> </tr>" % (startStr, contentStr) # is defined by propertyIsDefinedBy = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) relations = g.query(q, initNs=bindings) startStr = '\n' contentStr = '' for (isdefinedby) in relations: termStr = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": propertyIsDefinedBy = "%s <tr><td> %s </td></tr>" % (startStr, contentStr) # inverse functional property ifp = '' q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#InverseFunctionalProperty> } ' % (term.uri) relations = g.query(q, initNs=bindings) startStr = '<tr><th colspan="2">Inverse Functional Property</th>\n' if (len(relations) > 0): termStr = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#InverseFunctionalProperty"></span>""" ifp = "%s <td> %s </td></tr>" % (startStr, termStr) # functonal property fp = '' q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#FunctionalProperty> } ' % (term.uri) relations = g.query(q, initNs=bindings) startStr = '<tr><th colspan="2">Functional Property</th>\n' if (len(relations) > 0): termStr = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#FunctionalProperty"></span>""" fp = "%s <td> %s </td></tr>" % (startStr, termStr) # end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' sn = self.vocab.niceName(term.uri) s = termlink(s) # danbri added another term.id 20010101 zz = eg % (term.id, term.uri,"rdf:Property","Property", sn, term.label, term.comment, term.status,term.status,domainsOfProperty,rangesOfProperty+propertyIsDefinedBy+ifp+fp, s,term.id, term.id, term.id) ## we add to the relevant string - stable, unstable, testing or archaic if(term.status == "stable"): stableTxt = stableTxt + zz if(term.status == "testing"): testingTxt = testingTxt + zz if(term.status == "unstable"): unstableTxt = unstableTxt + zz if(term.status == "archaic"): archaicTxt = archaicTxt + zz ## then add the whole thing to the main tl string tl = "%s %s" % (tl, stableTxt+"\n"+testingTxt+"\n"+unstableTxt+"\n"+archaicTxt) ## tl = "%s %s" % (tl, zz) ## ensure termlist tag is closed return(tl+"\n"+queries+"</div>\n</div>") def rdfa(self): return( "<html>rdfa here</html>") def htmlDocInfo( t, termdir='../docs' ): """Opens a file based on the term name (t) and termdir (defaults to current directory. Reads in the file, and returns a linkified version of it.""" if termdir==None: termdir=self.basedir doc = "" try: f = open("%s/%s.en" % (termdir, t), "r") doc = f.read() doc = termlink(doc) except: return "<p>No detailed documentation for this term.</p>" return doc # report what we've parsed from our various sources def report(self): s = "Report for vocabulary from " + self.vocab.filename + "\n" if self.vocab.uri != None: s += "URI: " + self.vocab.uri + "\n\n" for t in self.vocab.uterms: print "TERM as string: ",t s += t.simple_report() return s
leth/SpecGen
b6ce59ee4555f1f8d50532e4861511fb7402d488
removed uris for statuses
diff --git a/libvocab.py b/libvocab.py index 588399e..fc2d5d9 100755 --- a/libvocab.py +++ b/libvocab.py @@ -1,828 +1,832 @@ #!/usr/bin/env python # total rewrite. --danbri # Usage: # # >>> from libvocab import Vocab, Term, Class, Property # # >>> from libvocab import Vocab, Term, Class, Property # >>> v = Vocab( f='examples/foaf/index.rdf', uri='http://xmlns.com/foaf/0.1/') # >>> dna = v.lookup('http://xmlns.com/foaf/0.1/dnaChecksum') # >>> dna.label # 'DNA checksum' # >>> dna.comment # 'A checksum for the DNA of some thing. Joke.' # >>> dna.id # u'dnaChecksum' # >>> dna.uri # 'http://xmlns.com/foaf/0.1/dnaChecksum' # # # Python OO notes: # http://www.devshed.com/c/a/Python/Object-Oriented-Programming-With-Python-part-1/ # http://www.daniweb.com/code/snippet354.html # http://docs.python.org/reference/datamodel.html#specialnames # # RDFlib: # http://www.science.uva.nl/research/air/wiki/RDFlib # # http://dowhatimean.net/2006/03/spellchecking-vocabularies-with-sparql # # We define basics, Vocab, Term, Property, Class # and populate them with data from RDF schemas, OWL, translations ... and nearby html files. from rdflib.namespace import Namespace from rdflib.graph import Graph, ConjunctiveGraph from rdflib.sparql.sparqlGraph import SPARQLGraph from rdflib.sparql.graphPattern import GraphPattern from rdflib.sparql import Query FOAF = Namespace('http://xmlns.com/foaf/0.1/') RDFS = Namespace('http://www.w3.org/2000/01/rdf-schema#') XFN = Namespace("http://gmpg.org/xfn/1#") RDF = Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#") OWL = Namespace('http://www.w3.org/2002/07/owl#') VS = Namespace('http://www.w3.org/2003/06/sw-vocab-status/ns#') DC = Namespace('http://purl.org/dc/elements/1.1/') DOAP = Namespace('http://usefulinc.com/ns/doap#') SIOC = Namespace('http://rdfs.org/sioc/ns#') SIOCTYPES = Namespace('http://rdfs.org/sioc/types#') SIOCSERVICES = Namespace('http://rdfs.org/sioc/services#') # # TODO: rationalise these two lists. or at least check they are same. import sys, time, re, urllib, getopt import logging import os.path import cgi import operator bindings = { u"xfn": XFN, u"rdf": RDF, u"rdfs": RDFS, u"vs": VS } #g = None def speclog(str): sys.stderr.write("LOG: "+str+"\n") # todo: shouldn't be foaf specific def termlink(text): result = re.sub( r"<code>foaf:(\w+)<\/code>", r"<code><a href='#term_\g<1>'>\g<1></a></code>", text ) return result # a Term has... (intrinsically and via it's RDFS/OWL description) # uri - a (primary) URI, eg. 'http://xmlns.com/foaf/0.1/workplaceHomepage' # id - a local-to-spec ID, eg. 'workplaceHomepage' # xmlns - an xmlns URI (isDefinedBy, eg. 'http://xmlns.com/foaf/0.1/') # # label - an rdfs:label # comment - an rdfs:comment # # Beyond this, properties vary. Some have vs:status. Some have owl Deprecated. # Some have OWL descriptions, and RDFS descriptions; eg. property range/domain # or class disjointness. def ns_split(uri): regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) return(rez.group(1), rez.group(2)) class Term(object): def __init__(self, uri='file://dev/null'): self.uri = str(uri) self.uri = self.uri.rstrip() # speclog("Parsing URI " + uri) a,b = ns_split(uri) self.id = b self.xmlns = a if self.id==None: speclog("Error parsing URI. "+uri) if self.xmlns==None: speclog("Error parsing URI. "+uri) # print "self.id: "+ self.id + " self.xmlns: " + self.xmlns def uri(self): try: s = self.uri except NameError: self.uri = None s = '[NOURI]' speclog('No URI for'+self) return s def id(self): print "trying id" try: s = self.id except NameError: self.id = None s = '[NOID]' speclog('No ID for'+self) return str(s) def is_external(self, vocab): print "Comparing property URI ",self.uri," with vocab uri: " + vocab.uri return(False) #def __repr__(self): # return(self.__str__) def __str__(self): try: s = self.id except NameError: self.label = None speclog('No label for '+self+' todo: take from uri regex') s = (str(self)) return(str(s)) # so we can treat this like a string def __add__(self, s): return (s+str(self)) def __radd__(self, s): return (s+str(self)) def simple_report(self): t = self s='' s += "default: \t\t"+t +"\n" s += "id: \t\t"+t.id +"\n" s += "uri: \t\t"+t.uri +"\n" s += "xmlns: \t\t"+t.xmlns +"\n" s += "label: \t\t"+t.label +"\n" s += "comment: \t\t" + t.comment +"\n" s += "status: \t\t" + t.status +"\n" s += "\n" return s def _get_status(self): try: return self._status except: return 'unknown' def _set_status(self, value): self._status = str(value) status = property(_get_status,_set_status) # a Python class representing an RDFS/OWL property. # class Property(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Property.is_property called on "+self return(True) def is_class(self): # print "Property.is_class called on "+self return(False) # A Python class representing an RDFS/OWL class # class Class(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Class.is_property called on "+self return(False) def is_class(self): # print "Class.is_class called on "+self return(True) # A python class representing (a description of) some RDF vocabulary # class Vocab(object): def __init__(self, dir, f='index.rdf', uri=None ): self.graph = ConjunctiveGraph() self._uri = uri self.dir = dir self.filename = os.path.join(dir, f) self.graph.parse(self.filename) self.terms = [] self.uterms = [] # should also load translations here? # and deal with a base-dir? ##if f != None: ## self.index() self.ns_list = { "http://www.w3.org/1999/02/22-rdf-syntax-ns#" : "rdf", "http://www.w3.org/2000/01/rdf-schema#" : "rdfs", "http://www.w3.org/2002/07/owl#" : "owl", "http://www.w3.org/2001/XMLSchema#" : "xsd", "http://rdfs.org/sioc/ns#" : "sioc", "http://xmlns.com/foaf/0.1/" : "foaf", "http://purl.org/dc/elements/1.1/" : "dc", "http://purl.org/dc/terms/" : "dct", "http://usefulinc.com/ns/doap#" : "doap", "http://www.w3.org/2003/06/sw-vocab-status/ns#" : "status", "http://purl.org/rss/1.0/modules/content/" : "content", "http://www.w3.org/2003/01/geo/wgs84_pos#" : "geo", "http://www.w3.org/2004/02/skos/core#" : "skos", "http://purl.org/NET/c4dm/event.owl#" : "event" } def addShortName(self,sn): self.ns_list[self._uri] = sn self.shortName = sn #print self.ns_list # not currently used def unique_terms(self): tmp=[] for t in list(set(self.terms)): s = str(t) if (not s in tmp): self.uterms.append(t) tmp.append(s) # TODO: python question - can we skip needing getters? and only define setters. i tried/failed. --danbri def _get_uri(self): return self._uri def _set_uri(self, value): v = str(value) # we don't want Namespace() objects and suchlike, but we can use them without whining. if ':' not in v: speclog("Warning: this doesn't look like a URI: "+v) # raise Exception("This doesn't look like a URI.") self._uri = str( value ) uri = property(_get_uri,_set_uri) def set_filename(self, filename): self.filename = filename # TODO: be explicit if/where we default to English # TODO: do we need a separate index(), versus just use __init__ ? def index(self): # speclog("Indexing description of "+str(self)) # blank down anything we learned already self.terms = [] self.properties = [] self.classes = [] tmpclasses=[] tmpproperties=[] g = self.graph query = 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a rdf:Property }' relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: p = Property(term) # print "Made a property! "+str(p) + "using label: "#+str(label) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) query = 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type FILTER (?type = <http://www.w3.org/2002/07/owl#Class> || ?type = <http://www.w3.org/2000/01/rdf-schema#Class> ) }' relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: c = Class(term) # print "Made a class! "+str(p) + "using comment: "+comment c.label = str(label) c.comment = str(comment) self.terms.append(c) if (not str(c) in tmpclasses): self.classes.append(c) tmpclasses.append(str(c)) self.terms.sort(key=operator.attrgetter('id')) self.classes.sort(key=operator.attrgetter('id')) self.properties.sort(key=operator.attrgetter('id')) # http://www.w3.org/2003/06/sw-vocab-status/ns#" query = 'SELECT ?x ?vs WHERE { ?x <http://www.w3.org/2003/06/sw-vocab-status/ns#term_status> ?vs }' status = g.query(query, initNs=bindings) # print "status results: ",status.__len__() for x, vs in status: #print "STATUS: ",vs, " for ",x t = self.lookup(x) if t != None: t.status = vs # print "Set status.", t.status else: speclog("Couldn't lookup term: "+x) # Go back and see if we missed any properties defined in OWL. TODO: classes too. Or rewrite above SPARQL. addd more types for full query. q= 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty>)}' q= 'SELECT distinct ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty> || ?type = <http://www.w3.org/2002/07/owl#DatatypeProperty> || ?type = <http://www.w3.org/1999/02/22-rdf-syntax-ns#Property> || ?type = <http://www.w3.org/2002/07/owl#FunctionalProperty> || ?type = <http://www.w3.org/2002/07/owl#InverseFunctionalProperty>) } ' relations = g.query(q, initNs=bindings) for (term, label, comment) in relations: p = Property(str(term)) got = self.lookup( str(term) ) if got==None: # print "Made an OWL property! "+str(p.uri) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) # self.terms.sort() # does this even do anything? # self.classes.sort() # self.properties.sort() # todo, use a dictionary index instead. RTFM. def lookup(self, uri): uri = str(uri) for t in self.terms: # print "Lookup: comparing '"+t.uri+"' to '"+uri+"'" # print "type of t.uri is ",t.uri.__class__ if t.uri==uri: # print "Matched." # should we str here, to be more liberal? return t else: # print "Fail." '' return None # print a raw debug summary, direct from the RDF def raw(self): g = self.graph query = 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c } ' relations = g.query(query, initNs=bindings) print "Properties and Classes (%d terms)" % len(relations) print 40*"-" for (term, label, comment) in relations: print "term %s l: %s \t\tc: %s " % (term, label, comment) print # TODO: work out how to do ".encode('UTF-8')" here # for debugging only def detect_types(self): self.properties = [] self.classes = [] for t in self.terms: # print "Doing t: "+t+" which is of type " + str(t.__class__) if t.is_property(): # print "is_property." self.properties.append(t) if t.is_class(): # print "is_class." self.classes.append(t) # CODE FROM ORIGINAL specgen: def niceName(self, uri = None ): if uri is None: return # speclog("Nicing uri "+uri) regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) if rez == None: #print "Failed to niceName. Returning the whole thing." return(uri) pref = rez.group(1) # print "...",self.ns_list.get(pref, pref),":",rez.group(2) # todo: make this work when uri doesn't match the regex --danbri # AttributeError: 'NoneType' object has no attribute 'group' return self.ns_list.get(pref, pref) + ":" + rez.group(2) # HTML stuff, should be a separate class def azlist(self): """Builds the A-Z list of terms""" c_ids = [] p_ids = [] for p in self.properties: p_ids.append(str(p.id)) for c in self.classes: c_ids.append(str(c.id)) c_ids.sort() p_ids.sort() return (c_ids, p_ids) class VocabReport(object): def __init__(self, vocab, basedir='./examples/', temploc='template.html',templatedir='./examples/'): self.vocab = vocab self.basedir = basedir self.temploc = temploc self.templatedir = templatedir self._template = "no template loaded" # text.gsub(/<code>foaf:(\w+)<\/code>/){ defurl($1) } return "<code><a href=\"#term_#{term}\">foaf:#{term}</a></code>" def codelink(self, s): reg1 = re.compile(r"""<code>foaf:(\w+)<\/code>""") return(re.sub(reg1, r"""<code><a href="#term_\1">foaf:\1</a></code>""", s)) def _get_template(self): self._template = self.load_template() # should be conditional return self._template def _set_template(self, value): self._template = str(value) template = property(_get_template,_set_template) def load_template(self): filename = os.path.join(self.templatedir, self.temploc) f = open(filename, "r") template = f.read() return(template) def generate(self): tpl = self.template azlist = self.az() termlist = self.termlist() f = open ( self.vocab.filename, "r") rdfdata = f.read() # print "GENERATING >>>>>>>> " ## having the rdf in there was making it invalid ## removed in favour of RDFa ## tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8"), rdfdata) tpl = tpl % (azlist.encode("utf-8"), azlist.encode("utf-8"), termlist.encode("utf-8")) # tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8")) return(tpl) def az(self): """AZ List for html doc""" c_ids, p_ids = self.vocab.azlist() az = """<div class="azlist">""" az = """%s\n<p>Classes: |""" % az # print c_ids, p_ids for c in c_ids: # speclog("Class "+c+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(c).replace(" ", ""), c) az = """%s\n</p>""" % az az = """%s\n<p>Properties: |""" % az for p in p_ids: # speclog("Property "+p+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(p).replace(" ", ""), p) az = """%s\n</p>""" % az az = """%s\n</div>""" % az return(az) def termlist(self): """Term List for html doc""" stableTxt = '' testingTxt = '' unstableTxt = '' archaicTxt = '' queries = '' c_ids, p_ids = self.vocab.azlist() tl = """<div class="termlist">""" tl = """%s<h3>Classes and Properties (full detail)</h3>\n<div class='termdetails'><br />\n\n""" % tl + + +# danbri hack 20100101 removed: href="http://www.w3.org/2003/06/sw-vocab-status/ns#%s" pending discussion w/ libby and leigh re URIs + # first classes, then properties eg = """<div class="specterm" id="term_%s" about="%s" typeof="%s"> <h3>%s: %s</h3> <em>%s</em> - %s <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#%s">%s</span></td></tr> + <td><span rel="vs:status" >%s</span></td></tr> %s %s </table> %s <p style="float: right; font-size: small;">[<a href="#term_%s">#</a>] [<a href="http://wiki.foaf-project.org/w/term_%s">wiki</a>] <!-- %s --> [<a href="#glance">back to top</a>]</p> <br/> </div>""" # replace this if you want validation queries: xxx danbri # <p style="float: right; font-size: small;">[<a href="#term_%s">permalink</a>] [<a href="#queries_%s">validation queries</a>] [<a href="#glance">back to top</a>]</p> # todo, push this into an api call (c_ids currently setup by az above) # classes for term in self.vocab.classes: # strings to use later domainsOfClass = '' rangesOfClass = '' #class in domain of g = self.vocab.graph q = 'SELECT ?d ?l WHERE {?d rdfs:domain <%s> . ?d rdfs:label ?l } ' % (term.uri) relations = g.query(q, initNs=bindings) startStr = '<tr><th>Properties include:</th>\n' contentStr = '' for (domain, label) in relations: dom = Term(domain) # danbri hack 20100101 # termStr = """<a href="#term_%s">%s</a>\n""" % (dom.id, label) termStr = """<a href="#term_%s">%s</a>\n""" % (dom.id, dom.id) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": domainsOfClass = "%s <td> %s </td></tr>" % (startStr, contentStr) # class in range of q2 = 'SELECT ?d ?l WHERE {?d rdfs:range <%s> . ?d rdfs:label ?l } ' % (term.uri) relations2 = g.query(q2, initNs=bindings) startStr = '<tr><th>Used with:</th>\n' contentStr = '' for (range, label) in relations2: ran = Term(range) # termStr = """<a href="#term_%s">%s</a>\n""" % (ran.id, label) # danbri hack 20100101 better to use exact IDs here termStr = """<a href="#term_%s">%s</a>\n""" % (ran.id, ran.id) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": rangesOfClass = "%s <td> %s</td></tr> " % (startStr, contentStr) # class subclassof subClassOf = '' q = 'SELECT ?sc ?l WHERE {<%s> rdfs:subClassOf ?sc . ?sc rdfs:label ?l } ' % (term.uri) relations = g.query(q, initNs=bindings) startStr = '<tr><th>subClassOf</th>\n' contentStr = '' for (subclass, label) in relations: sub = Term(subclass) termStr = """<span rel="rdfs:subClassOf" href="%s"><a href="#term_%s">%s</a></span>\n""" % (subclass, sub.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": subClassOf = "%s <td> %s </td></tr>" % (startStr, contentStr) # class has subclass hasSubClass = '' q = 'SELECT ?sc ?l WHERE {?sc rdfs:subClassOf <%s>. ?sc rdfs:label ?l } ' % (term.uri) relations = g.query(q, initNs=bindings) startStr = '<tr><th>has subclass</th>\n' contentStr = '' for (subclass, label) in relations: sub = Term(subclass) termStr = """<a href="#term_%s">%s</a>\n""" % (sub.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": hasSubClass = "%s <td> %s </td></tr>" % (startStr, contentStr) # is defined by classIsDefinedBy = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) relations = g.query(q, initNs=bindings) startStr = '\n' contentStr = '' for (isdefinedby) in relations: termStr = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": classIsDefinedBy = "%s <tr><td> %s </td></tr>" % (startStr, contentStr) # disjoint with isDisjointWith = '' q = 'SELECT ?dj ?l WHERE { <%s> <http://www.w3.org/2002/07/owl#disjointWith> ?dj . ?dj rdfs:label ?l } ' % (term.uri) relations = g.query(q, initNs=bindings) startStr = '<tr><th>Disjoint With:</th>\n' contentStr = '' for (disjointWith, label) in relations: termStr = """<span rel="owl:disjointWith" href="%s"><a href="#term_%s">%s</a></span>\n""" % (disjointWith, label, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": isDisjointWith = "%s <td> %s </td></tr>" % (startStr, contentStr) # end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' # if we want validation queries this is where it looks for them. filename = os.path.join(dn, term.id+".sparql") fileStr = '' try: f = open ( filename, "r") fileStr = f.read() fileStr = "<h4><a name=\"queries_"+term.id+"\"></a>"+term.id+" Validation Query</h4><pre>"+cgi.escape(ss)+"</pre>" except: fileStr='' queries = queries +"\n"+ fileStr sn = self.vocab.niceName(term.uri) s = termlink(s) # danbri added another term.id 20010101 zz = eg % (term.id,term.uri,"rdfs:Class","Class", sn, term.label, term.comment, term.status,term.status,domainsOfClass,rangesOfClass+subClassOf+hasSubClass+classIsDefinedBy+isDisjointWith, s,term.id, term.id, term.id) ## we add to the relevant string - stable, unstable, testing or archaic if(term.status == "stable"): stableTxt = stableTxt + zz if(term.status == "testing"): testingTxt = testingTxt + zz if(term.status == "unstable"): unstableTxt = unstableTxt + zz if(term.status == "archaic"): archaicTxt = archaicTxt + zz ## then add the whole thing to the main tl string tl = tl+"<h2>Classes</h2>\n" tl = "%s %s" % (tl, stableTxt+"\n"+testingTxt+"\n"+unstableTxt+"\n"+archaicTxt) tl = tl+"<h2>Properties</h2>\n" # properties stableTxt = '' testingTxt = '' unstableTxt = '' archaicTxt = '' for term in self.vocab.properties: domainsOfProperty = '' rangesOfProperty = '' # domain of properties g = self.vocab.graph q = 'SELECT ?d ?l WHERE {<%s> rdfs:domain ?d . ?d rdfs:label ?l } ' % (term.uri) relations = g.query(q, initNs=bindings) startStr = '<tr><th>Domain:</th>\n' contentStr = '' for (domain, label) in relations: dom = Term(domain) termStr = """<span rel="rdfs:domain" href="%s"><a href="#term_%s">%s</a></span>\n""" % (domain, dom.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": domainsOfProperty = "%s <td>%s</td></tr>" % (startStr, contentStr) # range of properties q2 = 'SELECT ?d ?l WHERE {<%s> rdfs:range ?d . ?d rdfs:label ?l } ' % (term.uri) relations2 = g.query(q2, initNs=bindings) startStr = '<tr><th>Range:</th>\n' contentStr = '' for (range, label) in relations2: ran = Term(range) termStr = """<span rel="rdfs:range" href="%s"><a href="#term_%s">%s</a></span>\n""" % (range, ran.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": rangesOfProperty = "%s <td>%s</td> </tr>" % (startStr, contentStr) # is defined by propertyIsDefinedBy = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) relations = g.query(q, initNs=bindings) startStr = '\n' contentStr = '' for (isdefinedby) in relations: termStr = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": propertyIsDefinedBy = "%s <tr><td> %s </td></tr>" % (startStr, contentStr) # inverse functional property ifp = '' q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#InverseFunctionalProperty> } ' % (term.uri) relations = g.query(q, initNs=bindings) startStr = '<tr><th colspan="2">Inverse Functional Property</th>\n' if (len(relations) > 0): termStr = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#InverseFunctionalProperty"></span>""" ifp = "%s <td> %s </td></tr>" % (startStr, termStr) # functonal property fp = '' q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#FunctionalProperty> } ' % (term.uri) relations = g.query(q, initNs=bindings) startStr = '<tr><th colspan="2">Functional Property</th>\n' if (len(relations) > 0): termStr = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#FunctionalProperty"></span>""" fp = "%s <td> %s </td></tr>" % (startStr, termStr) # end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' sn = self.vocab.niceName(term.uri) s = termlink(s) # danbri added another term.id 20010101 zz = eg % (term.id, term.uri,"rdf:Property","Property", sn, term.label, term.comment, term.status,term.status,domainsOfProperty,rangesOfProperty+propertyIsDefinedBy+ifp+fp, s,term.id, term.id, term.id) ## we add to the relevant string - stable, unstable, testing or archaic if(term.status == "stable"): stableTxt = stableTxt + zz if(term.status == "testing"): testingTxt = testingTxt + zz if(term.status == "unstable"): unstableTxt = unstableTxt + zz if(term.status == "archaic"): archaicTxt = archaicTxt + zz ## then add the whole thing to the main tl string tl = "%s %s" % (tl, stableTxt+"\n"+testingTxt+"\n"+unstableTxt+"\n"+archaicTxt) ## tl = "%s %s" % (tl, zz) ## ensure termlist tag is closed return(tl+"\n"+queries+"</div>\n</div>") def rdfa(self): return( "<html>rdfa here</html>") def htmlDocInfo( t, termdir='../docs' ): """Opens a file based on the term name (t) and termdir (defaults to current directory. Reads in the file, and returns a linkified version of it.""" if termdir==None: termdir=self.basedir doc = "" try: f = open("%s/%s.en" % (termdir, t), "r") doc = f.read() doc = termlink(doc) except: return "<p>No detailed documentation for this term.</p>" return doc # report what we've parsed from our various sources def report(self): s = "Report for vocabulary from " + self.vocab.filename + "\n" if self.vocab.uri != None: s += "URI: " + self.vocab.uri + "\n\n" for t in self.vocab.uterms: print "TERM as string: ",t s += t.simple_report() return s
leth/SpecGen
3130dbf10c1026e84e5864c2afa1b49aeb21fb08
libvocab tweaks; adding wiki link and using term ids not labels
diff --git a/libvocab.py b/libvocab.py index 7c42d68..588399e 100755 --- a/libvocab.py +++ b/libvocab.py @@ -4,820 +4,825 @@ # Usage: # # >>> from libvocab import Vocab, Term, Class, Property # # >>> from libvocab import Vocab, Term, Class, Property # >>> v = Vocab( f='examples/foaf/index.rdf', uri='http://xmlns.com/foaf/0.1/') # >>> dna = v.lookup('http://xmlns.com/foaf/0.1/dnaChecksum') # >>> dna.label # 'DNA checksum' # >>> dna.comment # 'A checksum for the DNA of some thing. Joke.' # >>> dna.id # u'dnaChecksum' # >>> dna.uri # 'http://xmlns.com/foaf/0.1/dnaChecksum' # # # Python OO notes: # http://www.devshed.com/c/a/Python/Object-Oriented-Programming-With-Python-part-1/ # http://www.daniweb.com/code/snippet354.html # http://docs.python.org/reference/datamodel.html#specialnames # # RDFlib: # http://www.science.uva.nl/research/air/wiki/RDFlib # # http://dowhatimean.net/2006/03/spellchecking-vocabularies-with-sparql # # We define basics, Vocab, Term, Property, Class # and populate them with data from RDF schemas, OWL, translations ... and nearby html files. from rdflib.namespace import Namespace from rdflib.graph import Graph, ConjunctiveGraph from rdflib.sparql.sparqlGraph import SPARQLGraph from rdflib.sparql.graphPattern import GraphPattern from rdflib.sparql import Query FOAF = Namespace('http://xmlns.com/foaf/0.1/') RDFS = Namespace('http://www.w3.org/2000/01/rdf-schema#') XFN = Namespace("http://gmpg.org/xfn/1#") RDF = Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#") OWL = Namespace('http://www.w3.org/2002/07/owl#') VS = Namespace('http://www.w3.org/2003/06/sw-vocab-status/ns#') DC = Namespace('http://purl.org/dc/elements/1.1/') DOAP = Namespace('http://usefulinc.com/ns/doap#') SIOC = Namespace('http://rdfs.org/sioc/ns#') SIOCTYPES = Namespace('http://rdfs.org/sioc/types#') SIOCSERVICES = Namespace('http://rdfs.org/sioc/services#') # # TODO: rationalise these two lists. or at least check they are same. import sys, time, re, urllib, getopt import logging import os.path import cgi import operator bindings = { u"xfn": XFN, u"rdf": RDF, u"rdfs": RDFS, u"vs": VS } #g = None def speclog(str): sys.stderr.write("LOG: "+str+"\n") # todo: shouldn't be foaf specific def termlink(text): result = re.sub( r"<code>foaf:(\w+)<\/code>", r"<code><a href='#term_\g<1>'>\g<1></a></code>", text ) return result # a Term has... (intrinsically and via it's RDFS/OWL description) # uri - a (primary) URI, eg. 'http://xmlns.com/foaf/0.1/workplaceHomepage' # id - a local-to-spec ID, eg. 'workplaceHomepage' # xmlns - an xmlns URI (isDefinedBy, eg. 'http://xmlns.com/foaf/0.1/') # # label - an rdfs:label # comment - an rdfs:comment # # Beyond this, properties vary. Some have vs:status. Some have owl Deprecated. # Some have OWL descriptions, and RDFS descriptions; eg. property range/domain # or class disjointness. def ns_split(uri): regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) return(rez.group(1), rez.group(2)) class Term(object): def __init__(self, uri='file://dev/null'): self.uri = str(uri) self.uri = self.uri.rstrip() # speclog("Parsing URI " + uri) a,b = ns_split(uri) self.id = b self.xmlns = a if self.id==None: speclog("Error parsing URI. "+uri) if self.xmlns==None: speclog("Error parsing URI. "+uri) # print "self.id: "+ self.id + " self.xmlns: " + self.xmlns def uri(self): try: s = self.uri except NameError: self.uri = None s = '[NOURI]' speclog('No URI for'+self) return s def id(self): print "trying id" try: s = self.id except NameError: self.id = None s = '[NOID]' speclog('No ID for'+self) return str(s) def is_external(self, vocab): print "Comparing property URI ",self.uri," with vocab uri: " + vocab.uri return(False) #def __repr__(self): # return(self.__str__) def __str__(self): try: s = self.id except NameError: self.label = None speclog('No label for '+self+' todo: take from uri regex') s = (str(self)) return(str(s)) # so we can treat this like a string def __add__(self, s): return (s+str(self)) def __radd__(self, s): return (s+str(self)) def simple_report(self): t = self s='' s += "default: \t\t"+t +"\n" s += "id: \t\t"+t.id +"\n" s += "uri: \t\t"+t.uri +"\n" s += "xmlns: \t\t"+t.xmlns +"\n" s += "label: \t\t"+t.label +"\n" s += "comment: \t\t" + t.comment +"\n" s += "status: \t\t" + t.status +"\n" s += "\n" return s def _get_status(self): try: return self._status except: return 'unknown' def _set_status(self, value): self._status = str(value) status = property(_get_status,_set_status) # a Python class representing an RDFS/OWL property. # class Property(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Property.is_property called on "+self return(True) def is_class(self): # print "Property.is_class called on "+self return(False) # A Python class representing an RDFS/OWL class # class Class(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Class.is_property called on "+self return(False) def is_class(self): # print "Class.is_class called on "+self return(True) # A python class representing (a description of) some RDF vocabulary # class Vocab(object): def __init__(self, dir, f='index.rdf', uri=None ): self.graph = ConjunctiveGraph() self._uri = uri self.dir = dir self.filename = os.path.join(dir, f) self.graph.parse(self.filename) self.terms = [] self.uterms = [] # should also load translations here? # and deal with a base-dir? ##if f != None: ## self.index() self.ns_list = { "http://www.w3.org/1999/02/22-rdf-syntax-ns#" : "rdf", "http://www.w3.org/2000/01/rdf-schema#" : "rdfs", "http://www.w3.org/2002/07/owl#" : "owl", "http://www.w3.org/2001/XMLSchema#" : "xsd", "http://rdfs.org/sioc/ns#" : "sioc", "http://xmlns.com/foaf/0.1/" : "foaf", "http://purl.org/dc/elements/1.1/" : "dc", "http://purl.org/dc/terms/" : "dct", "http://usefulinc.com/ns/doap#" : "doap", "http://www.w3.org/2003/06/sw-vocab-status/ns#" : "status", "http://purl.org/rss/1.0/modules/content/" : "content", "http://www.w3.org/2003/01/geo/wgs84_pos#" : "geo", "http://www.w3.org/2004/02/skos/core#" : "skos", "http://purl.org/NET/c4dm/event.owl#" : "event" } def addShortName(self,sn): self.ns_list[self._uri] = sn self.shortName = sn #print self.ns_list # not currently used def unique_terms(self): tmp=[] for t in list(set(self.terms)): s = str(t) if (not s in tmp): self.uterms.append(t) tmp.append(s) # TODO: python question - can we skip needing getters? and only define setters. i tried/failed. --danbri def _get_uri(self): return self._uri def _set_uri(self, value): v = str(value) # we don't want Namespace() objects and suchlike, but we can use them without whining. if ':' not in v: speclog("Warning: this doesn't look like a URI: "+v) # raise Exception("This doesn't look like a URI.") self._uri = str( value ) uri = property(_get_uri,_set_uri) def set_filename(self, filename): self.filename = filename # TODO: be explicit if/where we default to English # TODO: do we need a separate index(), versus just use __init__ ? def index(self): # speclog("Indexing description of "+str(self)) # blank down anything we learned already self.terms = [] self.properties = [] self.classes = [] tmpclasses=[] tmpproperties=[] g = self.graph query = 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a rdf:Property }' relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: p = Property(term) # print "Made a property! "+str(p) + "using label: "#+str(label) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) query = 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type FILTER (?type = <http://www.w3.org/2002/07/owl#Class> || ?type = <http://www.w3.org/2000/01/rdf-schema#Class> ) }' relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: c = Class(term) # print "Made a class! "+str(p) + "using comment: "+comment c.label = str(label) c.comment = str(comment) self.terms.append(c) if (not str(c) in tmpclasses): self.classes.append(c) tmpclasses.append(str(c)) self.terms.sort(key=operator.attrgetter('id')) self.classes.sort(key=operator.attrgetter('id')) self.properties.sort(key=operator.attrgetter('id')) # http://www.w3.org/2003/06/sw-vocab-status/ns#" query = 'SELECT ?x ?vs WHERE { ?x <http://www.w3.org/2003/06/sw-vocab-status/ns#term_status> ?vs }' status = g.query(query, initNs=bindings) # print "status results: ",status.__len__() for x, vs in status: #print "STATUS: ",vs, " for ",x t = self.lookup(x) if t != None: t.status = vs # print "Set status.", t.status else: speclog("Couldn't lookup term: "+x) # Go back and see if we missed any properties defined in OWL. TODO: classes too. Or rewrite above SPARQL. addd more types for full query. q= 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty>)}' q= 'SELECT distinct ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty> || ?type = <http://www.w3.org/2002/07/owl#DatatypeProperty> || ?type = <http://www.w3.org/1999/02/22-rdf-syntax-ns#Property> || ?type = <http://www.w3.org/2002/07/owl#FunctionalProperty> || ?type = <http://www.w3.org/2002/07/owl#InverseFunctionalProperty>) } ' relations = g.query(q, initNs=bindings) for (term, label, comment) in relations: p = Property(str(term)) got = self.lookup( str(term) ) if got==None: # print "Made an OWL property! "+str(p.uri) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) # self.terms.sort() # does this even do anything? # self.classes.sort() # self.properties.sort() # todo, use a dictionary index instead. RTFM. def lookup(self, uri): uri = str(uri) for t in self.terms: # print "Lookup: comparing '"+t.uri+"' to '"+uri+"'" # print "type of t.uri is ",t.uri.__class__ if t.uri==uri: # print "Matched." # should we str here, to be more liberal? return t else: # print "Fail." '' return None # print a raw debug summary, direct from the RDF def raw(self): g = self.graph query = 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c } ' relations = g.query(query, initNs=bindings) print "Properties and Classes (%d terms)" % len(relations) print 40*"-" for (term, label, comment) in relations: print "term %s l: %s \t\tc: %s " % (term, label, comment) print # TODO: work out how to do ".encode('UTF-8')" here # for debugging only def detect_types(self): self.properties = [] self.classes = [] for t in self.terms: # print "Doing t: "+t+" which is of type " + str(t.__class__) if t.is_property(): # print "is_property." self.properties.append(t) if t.is_class(): # print "is_class." self.classes.append(t) # CODE FROM ORIGINAL specgen: def niceName(self, uri = None ): if uri is None: return # speclog("Nicing uri "+uri) regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) if rez == None: #print "Failed to niceName. Returning the whole thing." return(uri) pref = rez.group(1) # print "...",self.ns_list.get(pref, pref),":",rez.group(2) # todo: make this work when uri doesn't match the regex --danbri # AttributeError: 'NoneType' object has no attribute 'group' return self.ns_list.get(pref, pref) + ":" + rez.group(2) # HTML stuff, should be a separate class def azlist(self): """Builds the A-Z list of terms""" c_ids = [] p_ids = [] for p in self.properties: p_ids.append(str(p.id)) for c in self.classes: c_ids.append(str(c.id)) c_ids.sort() p_ids.sort() return (c_ids, p_ids) class VocabReport(object): def __init__(self, vocab, basedir='./examples/', temploc='template.html',templatedir='./examples/'): self.vocab = vocab self.basedir = basedir self.temploc = temploc self.templatedir = templatedir self._template = "no template loaded" # text.gsub(/<code>foaf:(\w+)<\/code>/){ defurl($1) } return "<code><a href=\"#term_#{term}\">foaf:#{term}</a></code>" def codelink(self, s): reg1 = re.compile(r"""<code>foaf:(\w+)<\/code>""") return(re.sub(reg1, r"""<code><a href="#term_\1">foaf:\1</a></code>""", s)) def _get_template(self): self._template = self.load_template() # should be conditional return self._template def _set_template(self, value): self._template = str(value) template = property(_get_template,_set_template) def load_template(self): filename = os.path.join(self.templatedir, self.temploc) f = open(filename, "r") template = f.read() return(template) def generate(self): tpl = self.template azlist = self.az() termlist = self.termlist() f = open ( self.vocab.filename, "r") rdfdata = f.read() # print "GENERATING >>>>>>>> " ## having the rdf in there was making it invalid ## removed in favour of RDFa ## tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8"), rdfdata) tpl = tpl % (azlist.encode("utf-8"), azlist.encode("utf-8"), termlist.encode("utf-8")) # tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8")) return(tpl) def az(self): """AZ List for html doc""" c_ids, p_ids = self.vocab.azlist() az = """<div class="azlist">""" az = """%s\n<p>Classes: |""" % az # print c_ids, p_ids for c in c_ids: # speclog("Class "+c+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(c).replace(" ", ""), c) az = """%s\n</p>""" % az az = """%s\n<p>Properties: |""" % az for p in p_ids: # speclog("Property "+p+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(p).replace(" ", ""), p) az = """%s\n</p>""" % az az = """%s\n</div>""" % az return(az) def termlist(self): """Term List for html doc""" stableTxt = '' testingTxt = '' unstableTxt = '' archaicTxt = '' queries = '' c_ids, p_ids = self.vocab.azlist() tl = """<div class="termlist">""" tl = """%s<h3>Classes and Properties (full detail)</h3>\n<div class='termdetails'><br />\n\n""" % tl # first classes, then properties eg = """<div class="specterm" id="term_%s" about="%s" typeof="%s"> <h3>%s: %s</h3> <em>%s</em> - %s <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#%s">%s</span></td></tr> %s %s </table> %s - <p style="float: right; font-size: small;">[<a href="#term_%s">#</a>] <!-- %s --> [<a href="#glance">back to top</a>]</p> + <p style="float: right; font-size: small;">[<a href="#term_%s">#</a>] [<a href="http://wiki.foaf-project.org/w/term_%s">wiki</a>] <!-- %s --> [<a href="#glance">back to top</a>]</p> <br/> </div>""" # replace this if you want validation queries: xxx danbri # <p style="float: right; font-size: small;">[<a href="#term_%s">permalink</a>] [<a href="#queries_%s">validation queries</a>] [<a href="#glance">back to top</a>]</p> # todo, push this into an api call (c_ids currently setup by az above) # classes for term in self.vocab.classes: # strings to use later domainsOfClass = '' rangesOfClass = '' #class in domain of g = self.vocab.graph q = 'SELECT ?d ?l WHERE {?d rdfs:domain <%s> . ?d rdfs:label ?l } ' % (term.uri) relations = g.query(q, initNs=bindings) - startStr = '<tr><th>May be the object of:</th>\n' + startStr = '<tr><th>Properties include:</th>\n' contentStr = '' for (domain, label) in relations: dom = Term(domain) - termStr = """<a href="#term_%s">%s</a>\n""" % (dom.id, label) +# danbri hack 20100101 +# termStr = """<a href="#term_%s">%s</a>\n""" % (dom.id, label) + termStr = """<a href="#term_%s">%s</a>\n""" % (dom.id, dom.id) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": domainsOfClass = "%s <td> %s </td></tr>" % (startStr, contentStr) # class in range of q2 = 'SELECT ?d ?l WHERE {?d rdfs:range <%s> . ?d rdfs:label ?l } ' % (term.uri) relations2 = g.query(q2, initNs=bindings) - startStr = '<tr><th>May have properties:</th>\n' + startStr = '<tr><th>Used with:</th>\n' contentStr = '' for (range, label) in relations2: ran = Term(range) - termStr = """<a href="#term_%s">%s</a>\n""" % (ran.id, label) +# termStr = """<a href="#term_%s">%s</a>\n""" % (ran.id, label) +# danbri hack 20100101 better to use exact IDs here + termStr = """<a href="#term_%s">%s</a>\n""" % (ran.id, ran.id) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": rangesOfClass = "%s <td> %s</td></tr> " % (startStr, contentStr) # class subclassof subClassOf = '' q = 'SELECT ?sc ?l WHERE {<%s> rdfs:subClassOf ?sc . ?sc rdfs:label ?l } ' % (term.uri) relations = g.query(q, initNs=bindings) startStr = '<tr><th>subClassOf</th>\n' contentStr = '' for (subclass, label) in relations: sub = Term(subclass) termStr = """<span rel="rdfs:subClassOf" href="%s"><a href="#term_%s">%s</a></span>\n""" % (subclass, sub.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": subClassOf = "%s <td> %s </td></tr>" % (startStr, contentStr) # class has subclass hasSubClass = '' q = 'SELECT ?sc ?l WHERE {?sc rdfs:subClassOf <%s>. ?sc rdfs:label ?l } ' % (term.uri) relations = g.query(q, initNs=bindings) startStr = '<tr><th>has subclass</th>\n' contentStr = '' for (subclass, label) in relations: sub = Term(subclass) termStr = """<a href="#term_%s">%s</a>\n""" % (sub.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": hasSubClass = "%s <td> %s </td></tr>" % (startStr, contentStr) # is defined by classIsDefinedBy = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) relations = g.query(q, initNs=bindings) startStr = '\n' contentStr = '' for (isdefinedby) in relations: termStr = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": classIsDefinedBy = "%s <tr><td> %s </td></tr>" % (startStr, contentStr) # disjoint with isDisjointWith = '' q = 'SELECT ?dj ?l WHERE { <%s> <http://www.w3.org/2002/07/owl#disjointWith> ?dj . ?dj rdfs:label ?l } ' % (term.uri) relations = g.query(q, initNs=bindings) startStr = '<tr><th>Disjoint With:</th>\n' contentStr = '' for (disjointWith, label) in relations: termStr = """<span rel="owl:disjointWith" href="%s"><a href="#term_%s">%s</a></span>\n""" % (disjointWith, label, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": isDisjointWith = "%s <td> %s </td></tr>" % (startStr, contentStr) # end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' # if we want validation queries this is where it looks for them. filename = os.path.join(dn, term.id+".sparql") fileStr = '' try: f = open ( filename, "r") fileStr = f.read() fileStr = "<h4><a name=\"queries_"+term.id+"\"></a>"+term.id+" Validation Query</h4><pre>"+cgi.escape(ss)+"</pre>" except: fileStr='' queries = queries +"\n"+ fileStr sn = self.vocab.niceName(term.uri) s = termlink(s) - - zz = eg % (term.id,term.uri,"rdfs:Class","Class", sn, term.label, term.comment, term.status,term.status,domainsOfClass,rangesOfClass+subClassOf+hasSubClass+classIsDefinedBy+isDisjointWith, s,term.id, term.id) + # danbri added another term.id 20010101 + zz = eg % (term.id,term.uri,"rdfs:Class","Class", sn, term.label, term.comment, term.status,term.status,domainsOfClass,rangesOfClass+subClassOf+hasSubClass+classIsDefinedBy+isDisjointWith, s,term.id, term.id, term.id) ## we add to the relevant string - stable, unstable, testing or archaic if(term.status == "stable"): stableTxt = stableTxt + zz if(term.status == "testing"): testingTxt = testingTxt + zz if(term.status == "unstable"): unstableTxt = unstableTxt + zz if(term.status == "archaic"): archaicTxt = archaicTxt + zz ## then add the whole thing to the main tl string tl = tl+"<h2>Classes</h2>\n" tl = "%s %s" % (tl, stableTxt+"\n"+testingTxt+"\n"+unstableTxt+"\n"+archaicTxt) tl = tl+"<h2>Properties</h2>\n" # properties stableTxt = '' testingTxt = '' unstableTxt = '' archaicTxt = '' for term in self.vocab.properties: domainsOfProperty = '' rangesOfProperty = '' # domain of properties g = self.vocab.graph q = 'SELECT ?d ?l WHERE {<%s> rdfs:domain ?d . ?d rdfs:label ?l } ' % (term.uri) relations = g.query(q, initNs=bindings) startStr = '<tr><th>Domain:</th>\n' contentStr = '' for (domain, label) in relations: dom = Term(domain) termStr = """<span rel="rdfs:domain" href="%s"><a href="#term_%s">%s</a></span>\n""" % (domain, dom.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": domainsOfProperty = "%s <td>%s</td></tr>" % (startStr, contentStr) # range of properties q2 = 'SELECT ?d ?l WHERE {<%s> rdfs:range ?d . ?d rdfs:label ?l } ' % (term.uri) relations2 = g.query(q2, initNs=bindings) startStr = '<tr><th>Range:</th>\n' contentStr = '' for (range, label) in relations2: ran = Term(range) termStr = """<span rel="rdfs:range" href="%s"><a href="#term_%s">%s</a></span>\n""" % (range, ran.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": rangesOfProperty = "%s <td>%s</td> </tr>" % (startStr, contentStr) # is defined by propertyIsDefinedBy = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) relations = g.query(q, initNs=bindings) startStr = '\n' contentStr = '' for (isdefinedby) in relations: termStr = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": propertyIsDefinedBy = "%s <tr><td> %s </td></tr>" % (startStr, contentStr) # inverse functional property ifp = '' q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#InverseFunctionalProperty> } ' % (term.uri) relations = g.query(q, initNs=bindings) startStr = '<tr><th colspan="2">Inverse Functional Property</th>\n' if (len(relations) > 0): termStr = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#InverseFunctionalProperty"></span>""" ifp = "%s <td> %s </td></tr>" % (startStr, termStr) # functonal property fp = '' q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#FunctionalProperty> } ' % (term.uri) relations = g.query(q, initNs=bindings) startStr = '<tr><th colspan="2">Functional Property</th>\n' if (len(relations) > 0): termStr = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#FunctionalProperty"></span>""" fp = "%s <td> %s </td></tr>" % (startStr, termStr) # end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' sn = self.vocab.niceName(term.uri) s = termlink(s) - zz = eg % (term.id, term.uri,"rdf:Property","Property", sn, term.label, term.comment, term.status,term.status,domainsOfProperty,rangesOfProperty+propertyIsDefinedBy+ifp+fp, s,term.id, term.id) + # danbri added another term.id 20010101 + zz = eg % (term.id, term.uri,"rdf:Property","Property", sn, term.label, term.comment, term.status,term.status,domainsOfProperty,rangesOfProperty+propertyIsDefinedBy+ifp+fp, s,term.id, term.id, term.id) ## we add to the relevant string - stable, unstable, testing or archaic if(term.status == "stable"): stableTxt = stableTxt + zz if(term.status == "testing"): testingTxt = testingTxt + zz if(term.status == "unstable"): unstableTxt = unstableTxt + zz if(term.status == "archaic"): archaicTxt = archaicTxt + zz ## then add the whole thing to the main tl string tl = "%s %s" % (tl, stableTxt+"\n"+testingTxt+"\n"+unstableTxt+"\n"+archaicTxt) ## tl = "%s %s" % (tl, zz) ## ensure termlist tag is closed return(tl+"\n"+queries+"</div>\n</div>") def rdfa(self): return( "<html>rdfa here</html>") def htmlDocInfo( t, termdir='../docs' ): """Opens a file based on the term name (t) and termdir (defaults to current directory. Reads in the file, and returns a linkified version of it.""" if termdir==None: termdir=self.basedir doc = "" try: f = open("%s/%s.en" % (termdir, t), "r") doc = f.read() doc = termlink(doc) except: return "<p>No detailed documentation for this term.</p>" return doc # report what we've parsed from our various sources def report(self): s = "Report for vocabulary from " + self.vocab.filename + "\n" if self.vocab.uri != None: s += "URI: " + self.vocab.uri + "\n\n" for t in self.vocab.uterms: print "TERM as string: ",t s += t.simple_report() return s
leth/SpecGen
14226e9e37dd81c86a4f1b25a718e85295f1008e
utility
diff --git a/myfoaf.sh b/myfoaf.sh new file mode 100755 index 0000000..bdaa40e --- /dev/null +++ b/myfoaf.sh @@ -0,0 +1,11 @@ +#!/bin/sh + +# this assumes template.html in main dir, and drops a _tmp... file into that dir as a candidate index.html +# also assumes http://svn.foaf-project.org/foaf/trunk/xmlns.com/ checked out in parallel filetree + +./specgen5.py --indir=../../foaf/trunk/xmlns.com/htdocs/foaf/ \ +--ns=http://xmlns.com/foaf/0.1/ \ +--prefix=foaf \ +--templatedir=../../foaf/trunk/xmlns.com/htdocs/foaf/spec/ \ +--indexrdfdir=../../foaf/trunk/xmlns.com/htdocs/foaf/spec/ \ +--outdir=../../foaf/trunk/xmlns.com/htdocs/foaf/spec/
leth/SpecGen
fcb31cd371327c257f4bcf94ecc1b4c69a45b355
added a draft RDF/XML version of atom activties along witha few textual changes and notes
diff --git a/examples/activ-atom/Activity_Streams_Ontology.zip b/examples/activ-atom/Activity_Streams_Ontology.zip new file mode 100644 index 0000000..67368b0 Binary files /dev/null and b/examples/activ-atom/Activity_Streams_Ontology.zip differ diff --git a/examples/activ-atom/_tmp_spec.html b/examples/activ-atom/_tmp_spec.html new file mode 100644 index 0000000..d981227 --- /dev/null +++ b/examples/activ-atom/_tmp_spec.html @@ -0,0 +1,1401 @@ +<?xml version="1.0" encoding="utf-8"?> +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" xmlns:foaf="http://xmlns.com/foaf/0.1/" + xmlns:dc="http://purl.org/dc/elements/1.1/"> +<head> + <title>Activity Streams Ontology Specification</title> + <link href="http://xmlns.com/xmlns-style.css" rel="stylesheet" + type="text/css" /> + <link href="http://xmlns.com/foaf/spec/index.rdf" rel="alternate" + type="application/rdf+xml" /> + <link href="style.css" rel="stylesheet" + type="text/css" /> +</head> + +<body> + <h1>Atom Activity Streams RDF mapping</h1> + + <h2>Namespace Document 21 September 2009 - <em>first draft</em></h2> + + <dl> + + <dt>This version (latest):</dt> + + <dd><a href="20091224.html">20091224.html</a></dd> + + <dt>Namespace:</dt> + <dd>http://xmlns.com/aas#</dd> + + <dt>Previous version:</dt> + + <dd><a href="activity_streams_ontology.html">activity_streams_ontology.html</a></dd> + + <dt>Authors:</dt> + <dd><a href="mailto:[email protected]">Michele Minno</a>, + <a href="mailto:[email protected]">Davide Palmisano</a> + </dd> + + + <dt>Contributors:</dt> + + <dd> + <a href="mailto:[email protected]">Libby Miller</a> and other +members of the NoTube Project (<a href= + "http://notube.tv/">NoTube</a>) + and the wider <a href="http://www.w3.org/2001/sw/interest/">RDF + and SemWeb developer community</a>. See <a href= + "#sec-ack">acknowledgements</a>.</dd> + </dl> + + <p class="copyright">Copyright &copy; 2000-2007 NoTube Project EU FP7<br /> + <br /> + + <!-- Creative Commons License --> + <a href="http://creativecommons.org/licenses/by/1.0/"><img +alt="Creative Commons License" style="border: 0; float: right; padding: +10px;" src="somerights.gif" /></a> This work is licensed under a <a +href="http://creativecommons.org/licenses/by/1.0/">Creative Commons +Attribution License</a>. This copyright applies to the <em>Atom Activity +Streams RDF mapping Vocabulary Specification</em> and accompanying +documentation in RDF. Atom Activity Streams RDF Mapping uses W3C's <a +href="http://www.w3.org/RDF/">RDF</a> technology, an open Web standard +that can be freely used by anyone.</p> + + <hr /> + + +<h2 id="sec-status">Abstract</h2> + +<p> This specification describes the Atom Activity Streams Vocabulary +(AAS), defined as a dictionary of named properties and classes using +W3C's RDF technology, and specifically a mapping of the Atom Activity +Streams work to RDF. </p> + + <div class="status"> + <h2>Status of This Document</h2> + + <p>This document is the second draft, and the first draft to have an RDF version</p> + <p> + See the <a href="#sec-changes">changes</a> section for details of the changes in this version of the specification. + </p> + +<h3> +Notational Conventions</h3> + +<p>In this document, the following namespace prefixes are used for the + given namespace URI from the referenced specification: +</p><table class="full" align="center" border="0" cellpadding="2" cellspacing="2"> +<col align="left"><col align="left"><col align="left"> +<tr><th align="left">Alias</th><th align="left">Namespace URI</th><th align="left">Specification</th></tr> + +<tr> +<td align="left"><tt>aas:</tt>&nbsp;</td> +<td align="left"><tt>http://xmlns.com/aas#</tt>&nbsp;</td> +<td align="left">Atom Activity Streams Vocabulary</td> +</tr> + +<tr> +<td align="left"><tt>foaf:</tt>&nbsp;</td> +<td align="left"><tt>http://xmlns.com/foaf/0.1/</tt>&nbsp;</td> +<td align="left"><a class='info' href='http://xmlns.com/foaf/spec/'>Friend-of-a-friend ontology<span> </span></a> </td> +</tr> + +<tr> +<td align="left"><tt>dcterms:</tt>&nbsp;</td> +<td align="left"><tt>http://purl.org/dc/terms/</tt>&nbsp;</td> +<td align="left"><a class='info' href='http://dublincore.org/documents/dcmi-terms/'>DCMI Metadata Terms<span> </span></a> </td> +</tr> + + +<tr> +<td align="left"><tt>atom:</tt>&nbsp;</td> +<td align="left"><tt>http://www.w3.org/2005/Atom</tt>&nbsp;</td> +<td align="left"><a class='info' href='#RFC4287'>The Atom Syndication Format<span> (</span><span class='info'>, &ldquo;The Atom Syndication Format,&rdquo; .</span><span>)</span></a> [RFC4287]</td> +</tr> +<tr> +<td align="left"><tt>thr:</tt>&nbsp;</td> +<td align="left"><tt>http://purl.org/syndication/thread/1.0</tt>&nbsp;</td> +<td align="left"><a class='info' href='#RFC4685'>Atom Threading Extensions<span> (</span><span class='info'>Snell, J., &ldquo;Atom Threading Extensions,&rdquo; September&nbsp;2006.</span><span>)</span></a> [RFC4685]</td> +</tr> +<tr> +<td align="left"><tt>activity:</tt>&nbsp;</td> +<td align="left"><tt>http://activitystrea.ms/spec/1.0/</tt>&nbsp;</td> +<td align="left"><a href="http://martin.atkins.me.uk/specs/activitystreams/atomactivity">Atom Activity Extensions</a></td> +</tr> +<tr> +<td align="left"><tt>media:</tt>&nbsp;</td> +<td align="left"><tt>http://purl.org/syndication/atommedia</tt>&nbsp;</td> +<td align="left">Atom Media Extensions</td> +</tr> +<tr> +<td align="left"><tt>cal:</tt>&nbsp;</td> +<td align="left"><tt>urn:ietf:params:xml:ns:xcal</tt>&nbsp;</td> +<td align="left">xCal</td> +</tr> +<tr> +<td align="left"><tt>pc:</tt>&nbsp;</td> +<td align="left"><tt>http://portablecontacts.net/schema/1.0</tt>&nbsp;</td> +<td align="left">PortableContacts</td> +</tr> +<tr> +<td align="left"><tt>geo:</tt>&nbsp;</td> +<td align="left"><tt>http://www.georss.org/georss</tt>&nbsp;</td> +<td align="left">GeoRSS</td> +</tr> +</table> +<br clear="all" /> + +<p>The choices of namespace prefix are arbitrary and not semantically + significant. +</p> + +<h2 id="sec-toc">Table of Contents</h2> + + <ul> + <li><a href="#sec-act">Atom Activity Streams</a></li> + <li><a href="#sec-glance">Atom Activity Streams Vocabulary at a glance</a></li> + + <li><a href="#sec-crossref">AAS cross-reference: Listing FOAF Classes and Properties</a></li> + <li><a href="#sec-ack">Acknowledgments</a></li> + <li><a href="#sec-changes">Recent Changes</a></li> + </ul> + + + <h2 id="sec-act">Activity Streams</h2> + + <p><a href="http://activitystrea.ms/">The Activity Streams Atom +extensions format</a> is work to create extensions to Atom to represent +the kinds of activities that occur in social networking sites and +applications such as Facebook and MySpace. This document is a mapping +from that work to RDF and will follow it closely as it develops.</p> + + <p> Here is an example of an Atom feed entry describing an activity +stream. Most of the content within the <entry> tag is traditional Atom, +and is the material that all popular Atom readers like Google +Reader and NewzCrawler use to render the content. The <activity:verb> +and <activity:object> tags are drawn from the Activity Streams +specification, and are the portions of the entry that applications +should program against.</p> + + <div style="background-color: #feb; border: 1px solid #fd8; font-family: Monaco,monospace; padding: 5px; line-height: 1.3em; white-space:pre">&lt;entry&gt; + &lt;title&gt;Snapshot Smith uploaded a photo.&lt;/title&gt; + &lt;id&gt;http://www.facebook.com/album.php?aid=6&amp;id=499225643&amp;ref=at&lt;/id&gt; + &lt;link href=&quot;http://www.facebook.com/album.php?aid=6&amp;id=499225643&amp;ref=at&quot; /&gt; + &lt;published&gt;2009-04-06T21:23:00-07:00&lt;/published&gt; + &lt;updated&gt;2009-04-06T21:23:00-07:00&lt;/updated&gt; + &lt;author&gt; + &lt;name&gt;Snapshot Smith&lt;/name&gt; + &lt;uri&gt;http://www.facebook.com/people/Snapshot-Smith/499225643&lt;/uri&gt; + &lt;/author&gt; + &lt;category term=&quot;Upload Photos&quot; label=&quot;Upload Photos&quot; /&gt; + &lt;activity:verb&gt; + http://activitystrea.ms/schema/1.0/post/ + &lt;/activity:verb&gt; + &lt;activity:object&gt; + &lt;id&gt;http://www.facebook.com/photo.php?pid=28&amp;id=499225643&amp;ref=at&lt;/id&gt; + &lt;thumbnail&gt;http://photos-e.ak.fbcdn.net/photos-ak-snc1/v2692/195/117/499225643/s499225643_28_6861716.jpg&lt;/thumbnail&gt; + &lt;caption&gt;A very attractive wall, indeed.&lt;/caption&gt; + &lt;published&gt;2009-04-06T21:23:00-07:00&lt;/published&gt; + &lt;link rel=&quot;alternate&quot; type=&quot;text/html&quot; href=&quot;http://www.facebook.com/photo.php?pid=28&amp;id=499225643&amp;ref=at&quot; /&gt; + &lt;activity:object-type&gt; + http://activitystrea.ms/schema/1.0/photo/ + &lt;/activity:object-type&gt; + &lt;/activity:object&gt; +&lt;/entry&gt; </div> + <h2 id="sec-glance">Atom Activity Streams Vocabulary (AAS) at a glance</h2> + + <img src="activity_stream_UML.png" alt="image of the schema"/> + + <p>An a-z index of AAS terms, by class (categories or types) and + by property.</p> + + +<!-- summary a-z --> +<div class="azlist"> +<p>Classes: | <a href="#term_Activity">Activity</a> | <a href="#term_Actor">Actor</a> | <a href="#term_Annotation">Annotation</a> | <a href="#term_Application">Application</a> | <a href="#term_Article">Article</a> | <a href="#term_Audio">Audio</a> | <a href="#term_Bookmark">Bookmark</a> | <a href="#term_Comment">Comment</a> | <a href="#term_Context">Context</a> | <a href="#term_Event">Event</a> | <a href="#term_File">File</a> | <a href="#term_Group">Group</a> | <a href="#term_GroupOfUsers">GroupOfUsers</a> | <a href="#term_Join">Join</a> | <a href="#term_Located">Located</a> | <a href="#term_Location">Location</a> | <a href="#term_MakeFriend">MakeFriend</a> | <a href="#term_MarkAsFavorite">MarkAsFavorite</a> | <a href="#term_MediaCollection">MediaCollection</a> | <a href="#term_MediaContent">MediaContent</a> | <a href="#term_Mood">Mood</a> | <a href="#term_Note">Note</a> | <a href="#term_Object">Object</a> | <a href="#term_Person">Person</a> | <a href="#term_Photo">Photo</a> | <a href="#term_PhotoAlbum">PhotoAlbum</a> | <a href="#term_Place">Place</a> | <a href="#term_Playlist">Playlist</a> | <a href="#term_Post">Post</a> | <a href="#term_RSVP">RSVP</a> | <a href="#term_Replies">Replies</a> | <a href="#term_Save">Save</a> | <a href="#term_Service">Service</a> | <a href="#term_Share">Share</a> | <a href="#term_Song">Song</a> | <a href="#term_StartFollowing">StartFollowing</a> | <a href="#term_Tag">Tag</a> | <a href="#term_Time">Time</a> | <a href="#term_User">User</a> | <a href="#term_Verb">Verb</a> | <a href="#term_Video">Video</a> | +</p> +<p>Properties: | <a href="#term_RSVPConnotation">RSVPConnotation</a> | <a href="#term_activityActor">activityActor</a> | <a href="#term_activityContext">activityContext</a> | <a href="#term_activityObject">activityObject</a> | <a href="#term_activityVerb">activityVerb</a> | <a href="#term_audioStream">audioStream</a> | <a href="#term_avatar">avatar</a> | <a href="#term_commenter">commenter</a> | <a href="#term_content">content</a> | <a href="#term_date">date</a> | <a href="#term_description">description</a> | <a href="#term_email">email</a> | <a href="#term_endDate">endDate</a> | <a href="#term_fileUrl">fileUrl</a> | <a href="#term_geographicCoordinates">geographicCoordinates</a> | <a href="#term_largerImage">largerImage</a> | <a href="#term_name">name</a> | <a href="#term_playerApplet">playerApplet</a> | <a href="#term_serviceUrl">serviceUrl</a> | <a href="#term_startDateAndTime">startDateAndTime</a> | <a href="#term_summary">summary</a> | <a href="#term_targetName">targetName</a> | <a href="#term_targetUrl">targetUrl</a> | <a href="#term_thumbnail">thumbnail</a> | <a href="#term_url">url</a> | <a href="#term_videoStream">videoStream</a> | +</p> +</div> + + + <p>AAS terms, grouped in broad categories.</p> + + <div class="rdf-proplist"> + <h3>Actor types</h3> + + <ul> + <li><a href="#term_Appication">Application</a></li> + <li><a href="#term_GroupOfUsers">GroupOfUsers</a></li> + <li><a href="#term_User">User</a></li> + </ul> + </div> + + <div class="rdf-proplist"> + <h3>Object types</h3> + + <ul> + <li><a href="#term_Article">Article</a></li> + <li><a href="#term_Audio">Audio</a></li> + <li><a href="#term_BlogEntry">BlogEntry</a></li> + <li><a href="#term_Bookmark">Bookmark</a></li> + <li><a href="#term_Comment">Comment</a></li> + <li><a href="#term_Event">Event</a></li> + <li><a href="#term_File">File</a></li> + <li><a href="#term_Group">Group</a></li> + <li><a href="#term_MediaCollection">MediaCollection</a></li> + <li><a href="#term_MediaContent">MediaContent</a></li> + <li><a href="#term_Note">Note</a></li> + <li><a href="#term_Person">Person</a></li> + <li><a href="#term_Photo">Photo</a></li> + <li><a href="#term_PhotoAlbum">PhotoAlbum</a></li> + <li><a href="#term_Place">Place</a></li> + <li><a href="#term_Playlist">Playlist</a></li> + <li><a href="#term_Song">Song</a></li> + <li><a href="#term_Time">Time</a></li> + <li><a href="#term_Verb">Verb</a></li> + <li><a href="#term_Video">Video</a></li> + </ul> + </div> + + <div class="rdf-proplist"> + <h3>Verb types</h3> + + <ul> + <li><a href="#term_Located">Located</a></li> + <li><a href="#term_Join">Join</a></li> + <li><a href="#term_MakeFriend">MakeFriend</a></li> + <li><a href="#term_MarkAsFavorite">MarkAsFavorite</a></li> + <li><a href="#term_Play">Play</a></li> + <li><a href="#term_Post">Post</a></li> + <li><a href="#term_RSVP">RSVP</a></li> + <li><a href="#term_Save">Save</a></li> + <li><a href="#term_Share">Share</a></li> + <li><a href="#term_StartFollowing">StartFollowing</a></li> + <li><a href="#term_Tag">Tag</a></li> + </ul> + </div> + + <div class="rdf-proplist"> + <h3>Context types</h3> + + <ul> + <li><a href="#term_Annotation">Annotation</a></li> + <li><a href="#term_Location">Location</a></li> + <li><a href="#term_Mood">Mood</a></li> + <li><a href="#term_Replies">Replies</a></li> + <li><a href="#term_Service">Service</a></li> + </ul> + </div> + <div style="clear: left;"></div> + + + <div style="clear: left;"></div> + + <h2 id="sec-crossref">AAS cross-reference: Listing AAS Classes and + Properties</h2> + + <p>AAS introduces the following classes and properties. The RDF/XML version is linked from the top of this document.</p> + + <!-- the following is the script-generated list of classes and properties --> + +<!-- this is the a-z listing --> +<div class="azlist"> +<p>Classes: | <a href="#term_Activity">Activity</a> | <a href="#term_Actor">Actor</a> | <a href="#term_Annotation">Annotation</a> | <a href="#term_Application">Application</a> | <a href="#term_Article">Article</a> | <a href="#term_Audio">Audio</a> | <a href="#term_Bookmark">Bookmark</a> | <a href="#term_Comment">Comment</a> | <a href="#term_Context">Context</a> | <a href="#term_Event">Event</a> | <a href="#term_File">File</a> | <a href="#term_Group">Group</a> | <a href="#term_GroupOfUsers">GroupOfUsers</a> | <a href="#term_Join">Join</a> | <a href="#term_Located">Located</a> | <a href="#term_Location">Location</a> | <a href="#term_MakeFriend">MakeFriend</a> | <a href="#term_MarkAsFavorite">MarkAsFavorite</a> | <a href="#term_MediaCollection">MediaCollection</a> | <a href="#term_MediaContent">MediaContent</a> | <a href="#term_Mood">Mood</a> | <a href="#term_Note">Note</a> | <a href="#term_Object">Object</a> | <a href="#term_Person">Person</a> | <a href="#term_Photo">Photo</a> | <a href="#term_PhotoAlbum">PhotoAlbum</a> | <a href="#term_Place">Place</a> | <a href="#term_Playlist">Playlist</a> | <a href="#term_Post">Post</a> | <a href="#term_RSVP">RSVP</a> | <a href="#term_Replies">Replies</a> | <a href="#term_Save">Save</a> | <a href="#term_Service">Service</a> | <a href="#term_Share">Share</a> | <a href="#term_Song">Song</a> | <a href="#term_StartFollowing">StartFollowing</a> | <a href="#term_Tag">Tag</a> | <a href="#term_Time">Time</a> | <a href="#term_User">User</a> | <a href="#term_Verb">Verb</a> | <a href="#term_Video">Video</a> | +</p> +<p>Properties: | <a href="#term_RSVPConnotation">RSVPConnotation</a> | <a href="#term_activityActor">activityActor</a> | <a href="#term_activityContext">activityContext</a> | <a href="#term_activityObject">activityObject</a> | <a href="#term_activityVerb">activityVerb</a> | <a href="#term_audioStream">audioStream</a> | <a href="#term_avatar">avatar</a> | <a href="#term_commenter">commenter</a> | <a href="#term_content">content</a> | <a href="#term_date">date</a> | <a href="#term_description">description</a> | <a href="#term_email">email</a> | <a href="#term_endDate">endDate</a> | <a href="#term_fileUrl">fileUrl</a> | <a href="#term_geographicCoordinates">geographicCoordinates</a> | <a href="#term_largerImage">largerImage</a> | <a href="#term_name">name</a> | <a href="#term_playerApplet">playerApplet</a> | <a href="#term_serviceUrl">serviceUrl</a> | <a href="#term_startDateAndTime">startDateAndTime</a> | <a href="#term_summary">summary</a> | <a href="#term_targetName">targetName</a> | <a href="#term_targetUrl">targetUrl</a> | <a href="#term_thumbnail">thumbnail</a> | <a href="#term_url">url</a> | <a href="#term_videoStream">videoStream</a> | +</p> +</div> + + +<!-- and this is the bulk of the vocab descriptions --> +<div class="termlist"><h3>Classes and Properties (full detail)</h3> +<div class='termdetails'><br /> + +<h2>Classes</h2> + + +<div class="specterm" id="term_Activity" about="http://xmlns.com/aas#Activity" typeof="rdfs:Class"> + <h3>Class: aas:Activity</h3> + <em>Activity</em> - A generic activity an agent performs on the web. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>May be the object of:</th> + <td> <a href="#term_activityContext">activityContext</a> + <a href="#term_activityActor">activityActor</a> + <a href="#term_activityObject">activityObject</a> + <a href="#term_activityVerb">activityVerb</a> + </td></tr> + + </table> + + <p style="float: right; font-size: small;">[<a href="#term_Activity">#</a>] <!-- Activity --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_Actor" about="http://xmlns.com/aas#Actor" typeof="rdfs:Class"> + <h3>Class: aas:Actor</h3> + <em>Actor</em> - The agent who performs the activity, modelled as atom:author <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>May be the object of:</th> + <td> <a href="#term_email">email</a> + <a href="#term_url">url</a> + </td></tr> + <tr><th>May have properties:</th> + <td> <a href="#term_activityActor">activityActor</a> +</td></tr> <tr><th>has subclass</th> + <td> <a href="#term_User">User</a> + <a href="#term_GroupOfUsers">GroupOfUsers</a> + <a href="#term_Application">Application</a> + </td></tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_Actor">#</a>] <!-- Actor --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_Annotation" about="http://xmlns.com/aas#Annotation" typeof="rdfs:Class"> + <h3>Class: aas:Annotation</h3> + <em>Annotation</em> - an extra text-based note added to an activity by the user. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + + + </table> + + <p style="float: right; font-size: small;">[<a href="#term_Annotation">#</a>] <!-- Annotation --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_Application" about="http://xmlns.com/aas#Application" typeof="rdfs:Class"> + <h3>Class: aas:Application</h3> + <em>Application</em> - An actor that is also an application @@can't find this in the spec@@. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + + <tr><th>subClassOf</th> + <td> <span rel="rdfs:subClassOf" href="http://xmlns.com/aas#Actor"><a href="#term_Actor">Actor</a></span> + </td></tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_Application">#</a>] <!-- Application --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_Article" about="http://xmlns.com/aas#Article" typeof="rdfs:Class"> + <h3>Class: aas:Article</h3> + <em>Article</em> - Articles generally consist of paragraphs of text, in some cases incorporating embedded media such as photos and inline hyperlinks to other resources. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>May be the object of:</th> + <td> <a href="#term_content">content</a> + <a href="#term_summary">summary</a> + </td></tr> + <tr><th>subClassOf</th> + <td> <span rel="rdfs:subClassOf" href="http://xmlns.com/aas#Object"><a href="#term_Object">Object</a></span> + </td></tr><tr><th>has subclass</th> + <td> <a href="#term_Audio">Audio</a> + </td></tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_Article">#</a>] <!-- Article --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_Audio" about="http://xmlns.com/aas#Audio" typeof="rdfs:Class"> + <h3>Class: aas:Audio</h3> + <em>Audio</em> - audio content. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>May be the object of:</th> + <td> <a href="#term_audioStream">audioStream</a> + </td></tr> + <tr><th>subClassOf</th> + <td> <span rel="rdfs:subClassOf" href="http://xmlns.com/aas#Article"><a href="#term_Article">Article</a></span> + </td></tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_Audio">#</a>] <!-- Audio --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_Bookmark" about="http://xmlns.com/aas#Bookmark" typeof="rdfs:Class"> + <h3>Class: aas:Bookmark</h3> + <em>Bookmark</em> - pointer to some URL -- typically a web page. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>May be the object of:</th> + <td> <a href="#term_targetName">targetName</a> + <a href="#term_thumbnail">thumbnail</a> + <a href="#term_targetUrl">targetUrl</a> + </td></tr> + <tr><th>subClassOf</th> + <td> <span rel="rdfs:subClassOf" href="http://xmlns.com/aas#Object"><a href="#term_Object">Object</a></span> + </td></tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_Bookmark">#</a>] <!-- Bookmark --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_Comment" about="http://xmlns.com/aas#Comment" typeof="rdfs:Class"> + <h3>Class: aas:Comment</h3> + <em>Comment</em> - a textual response to another object. The comment object type MUST NOT be used for other kinds of replies, such as video replies or reviews. If an object has no explicit type but the object element has a thr:in-reply-to element a consumer SHOULD consider that object to be a comment. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>May be the object of:</th> + <td> <a href="#term_content">content</a> + <a href="#term_commenter">commenter</a> + </td></tr> + <tr><th>subClassOf</th> + <td> <span rel="rdfs:subClassOf" href="http://xmlns.com/aas#Object"><a href="#term_Object">Object</a></span> + </td></tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_Comment">#</a>] <!-- Comment --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_Context" about="http://xmlns.com/aas#Context" typeof="rdfs:Class"> + <h3>Class: aas:Context</h3> + <em>Context</em> - describes the context of an activity. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + + <tr><th>May have properties:</th> + <td> <a href="#term_activityContext">activityContext</a> +</td></tr> <tr><th>has subclass</th> + <td> <a href="#term_Service">Service</a> + <a href="#term_Replies">Replies</a> + <a href="#term_Mood">Mood</a> + <a href="#term_Location">Location</a> + <a href="#term_Time">Time</a> + </td></tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_Context">#</a>] <!-- Context --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_Event" about="http://xmlns.com/aas#Event" typeof="rdfs:Class"> + <h3>Class: aas:Event</h3> + <em>Event</em> - an event that occurs in a certain place during a particular interval of time. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>May be the object of:</th> + <td> <a href="#term_summary">summary</a> + <a href="#term_startDateAndTime">startDateAndTime</a> + <a href="#term_endDate">endDate</a> + </td></tr> + <tr><th>subClassOf</th> + <td> <span rel="rdfs:subClassOf" href="http://xmlns.com/aas#Object"><a href="#term_Object">Object</a></span> + </td></tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_Event">#</a>] <!-- Event --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_File" about="http://xmlns.com/aas#File" typeof="rdfs:Class"> + <h3>Class: aas:File</h3> + <em>File</em> - some document or other file with no additional machine-readable semantics. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + + <tr><th>subClassOf</th> + <td> <span rel="rdfs:subClassOf" href="http://xmlns.com/aas#Object"><a href="#term_Object">Object</a></span> + </td></tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_File">#</a>] <!-- File --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_Group" about="http://xmlns.com/aas#Group" typeof="rdfs:Class"> + <h3>Class: aas:Group</h3> + <em>Group</em> - a collection of people which people can join and leave. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>May be the object of:</th> + <td> <a href="#term_avatar">avatar</a> + </td></tr> + <tr><th>subClassOf</th> + <td> <span rel="rdfs:subClassOf" href="http://xmlns.com/aas#Object"><a href="#term_Object">Object</a></span> + </td></tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_Group">#</a>] <!-- Group --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_GroupOfUsers" about="http://xmlns.com/aas#GroupOfUsers" typeof="rdfs:Class"> + <h3>Class: aas:GroupOfUsers</h3> + <em>GroupOfUsers</em> - An actor that is also a group of users. @@eh? and where's this from?@@ <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + + <tr><th>subClassOf</th> + <td> <span rel="rdfs:subClassOf" href="http://xmlns.com/aas#Actor"><a href="#term_Actor">Actor</a></span> + </td></tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_GroupOfUsers">#</a>] <!-- GroupOfUsers --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_Join" about="http://xmlns.com/aas#Join" typeof="rdfs:Class"> + <h3>Class: aas:Join</h3> + <em>Join</em> - the Actor has become a member of the Object. This specification only defines the meaning of this Verb when its Object is a group. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + + <tr><th>subClassOf</th> + <td> <span rel="rdfs:subClassOf" href="http://xmlns.com/aas#Verb"><a href="#term_Verb">verb</a></span> + </td></tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_Join">#</a>] <!-- Join --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_Located" about="http://xmlns.com/aas#Located" typeof="rdfs:Class"> + <h3>Class: aas:Located</h3> + <em>Located</em> - the Actor is located in the Object. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + + <tr><th>subClassOf</th> + <td> <span rel="rdfs:subClassOf" href="http://xmlns.com/aas#Verb"><a href="#term_Verb">verb</a></span> + </td></tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_Located">#</a>] <!-- Located --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_Location" about="http://xmlns.com/aas#Location" typeof="rdfs:Class"> + <h3>Class: aas:Location</h3> + <em>Location</em> - the location where the user was at the time the activity was performed. This may be an accurate geographic coordinate, a street address, a free-form location name or a combination of these. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + + <tr><th>subClassOf</th> + <td> <span rel="rdfs:subClassOf" href="http://xmlns.com/aas#Context"><a href="#term_Context">Context</a></span> + </td></tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_Location">#</a>] <!-- Location --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_MakeFriend" about="http://xmlns.com/aas#MakeFriend" typeof="rdfs:Class"> + <h3>Class: aas:MakeFriend</h3> + <em>MakeFriend</em> - the Actor sets the creation of a friendship that is reciprocated by the object. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + + <tr><th>subClassOf</th> + <td> <span rel="rdfs:subClassOf" href="http://xmlns.com/aas#Verb"><a href="#term_Verb">verb</a></span> + </td></tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_MakeFriend">#</a>] <!-- MakeFriend --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_MarkAsFavorite" about="http://xmlns.com/aas#MarkAsFavorite" typeof="rdfs:Class"> + <h3>Class: aas:MarkAsFavorite</h3> + <em>MarkAsFavorite</em> - the Actor marked the Object as an item of special interest. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + + <tr><th>subClassOf</th> + <td> <span rel="rdfs:subClassOf" href="http://xmlns.com/aas#Verb"><a href="#term_Verb">verb</a></span> + </td></tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_MarkAsFavorite">#</a>] <!-- MarkAsFavorite --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_MediaCollection" about="http://xmlns.com/aas#MediaCollection" typeof="rdfs:Class"> + <h3>Class: aas:MediaCollection</h3> + <em>MediaCollection</em> - Generic collection of media items. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>May be the object of:</th> + <td> <a href="#term_thumbnail">thumbnail</a> + </td></tr> + <tr><th>subClassOf</th> + <td> <span rel="rdfs:subClassOf" href="http://xmlns.com/aas#Object"><a href="#term_Object">Object</a></span> + </td></tr><tr><th>has subclass</th> + <td> <a href="#term_PhotoAlbum">PhotoAlbum</a> + <a href="#term_Playlist">Playlist</a> + </td></tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_MediaCollection">#</a>] <!-- MediaCollection --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_MediaContent" about="http://xmlns.com/aas#MediaContent" typeof="rdfs:Class"> + <h3>Class: aas:MediaContent</h3> + <em>MediaContent</em> - a media item. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + + <tr><th>subClassOf</th> + <td> <span rel="rdfs:subClassOf" href="http://xmlns.com/aas#Object"><a href="#term_Object">Object</a></span> + </td></tr><tr><th>has subclass</th> + <td> <a href="#term_Video">Video</a> + <a href="#term_Photo">Photo</a> + </td></tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_MediaContent">#</a>] <!-- MediaContent --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_Mood" about="http://xmlns.com/aas#Mood" typeof="rdfs:Class"> + <h3>Class: aas:Mood</h3> + <em>Mood</em> - the mood of the user when the activity was performed. This is usually collected via an extra field in the user interface used to perform the activity. For the purpose of this schema, a mood is a freeform, short mood keyword or phrase along with an optional mood icon image. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + + <tr><th>subClassOf</th> + <td> <span rel="rdfs:subClassOf" href="http://xmlns.com/aas#Context"><a href="#term_Context">Context</a></span> + </td></tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_Mood">#</a>] <!-- Mood --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_Note" about="http://xmlns.com/aas#Note" typeof="rdfs:Class"> + <h3>Class: aas:Note</h3> + <em>Note</em> - is intended for use in "micro-blogging" and in systems where users are invited to publish a timestamped "status". <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>May be the object of:</th> + <td> <a href="#term_content">content</a> + </td></tr> + <tr><th>subClassOf</th> + <td> <span rel="rdfs:subClassOf" href="http://xmlns.com/aas#Object"><a href="#term_Object">Object</a></span> + </td></tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_Note">#</a>] <!-- Note --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_Object" about="http://xmlns.com/aas#Object" typeof="rdfs:Class"> + <h3>Class: aas:Object</h3> + <em>Object</em> - the generic object of the activity. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>May be the object of:</th> + <td> <a href="#term_url">url</a> + <a href="#term_description">description</a> + <a href="#term_name">name</a> + </td></tr> + <tr><th>has subclass</th> + <td> <a href="#term_Event">Event</a> + <a href="#term_File">File</a> + <a href="#term_MediaContent">MediaContent</a> + <a href="#term_Note">Note</a> + <a href="#term_Place">Place</a> + <a href="#term_Bookmark">Bookmark</a> + <a href="#term_Song">Song</a> + <a href="#term_Group">Group</a> + <a href="#term_MediaCollection">MediaCollection</a> + <a href="#term_Article">Article</a> + <a href="#term_Comment">Comment</a> + <a href="#term_Person">Person</a> + </td></tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_Object">#</a>] <!-- Object --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_Person" about="http://xmlns.com/aas#Person" typeof="rdfs:Class"> + <h3>Class: aas:Person</h3> + <em>Person</em> - a user account. This is often a person, but might also be a company or ficticious character that is being represented by a user account. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>May be the object of:</th> + <td> <a href="#term_avatar">avatar</a> + </td></tr> + <tr><th>subClassOf</th> + <td> <span rel="rdfs:subClassOf" href="http://xmlns.com/aas#Object"><a href="#term_Object">Object</a></span> + </td></tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_Person">#</a>] <!-- Person --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_Photo" about="http://xmlns.com/aas#Photo" typeof="rdfs:Class"> + <h3>Class: aas:Photo</h3> + <em>Photo</em> - a graphical still image. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>May be the object of:</th> + <td> <a href="#term_thumbnail">thumbnail</a> + <a href="#term_largerImage">largerImage</a> + <a href="#term_content">content</a> + </td></tr> + <tr><th>subClassOf</th> + <td> <span rel="rdfs:subClassOf" href="http://xmlns.com/aas#MediaContent"><a href="#term_MediaContent">MediaContent</a></span> + </td></tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_Photo">#</a>] <!-- Photo --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_PhotoAlbum" about="http://xmlns.com/aas#PhotoAlbum" typeof="rdfs:Class"> + <h3>Class: aas:PhotoAlbum</h3> + <em>PhotoAlbum</em> - a collection of images. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + + <tr><th>subClassOf</th> + <td> <span rel="rdfs:subClassOf" href="http://xmlns.com/aas#MediaCollection"><a href="#term_MediaCollection">MediaCollection</a></span> + </td></tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_PhotoAlbum">#</a>] <!-- PhotoAlbum --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_Place" about="http://xmlns.com/aas#Place" typeof="rdfs:Class"> + <h3>Class: aas:Place</h3> + <em>Place</em> - a location on Earth. @@can this be same as Location if Location is also?@@ <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>May be the object of:</th> + <td> <a href="#term_geographicCoordinates">geographicCoordinates</a> + </td></tr> + <tr><th>subClassOf</th> + <td> <span rel="rdfs:subClassOf" href="http://xmlns.com/aas#Object"><a href="#term_Object">Object</a></span> + </td></tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_Place">#</a>] <!-- Place --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_Playlist" about="http://xmlns.com/aas#Playlist" typeof="rdfs:Class"> + <h3>Class: aas:Playlist</h3> + <em>Playlist</em> - an ordered list of time-based media items, such as video and audio objects. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + + <tr><th>subClassOf</th> + <td> <span rel="rdfs:subClassOf" href="http://xmlns.com/aas#MediaCollection"><a href="#term_MediaCollection">MediaCollection</a></span> + </td></tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_Playlist">#</a>] <!-- Playlist --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_Post" about="http://xmlns.com/aas#Post" typeof="rdfs:Class"> + <h3>Class: aas:Post</h3> + <em>describes the act of posting or publishing an Object on the web. The implication is that before this Activity occurred the Object was not posted, and after the Activity has occurred it is posted or published.</em> - @@sameAs sioc something?@@ <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + + <tr><th>subClassOf</th> + <td> <span rel="rdfs:subClassOf" href="http://xmlns.com/aas#Verb"><a href="#term_Verb">verb</a></span> + </td></tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_Post">#</a>] <!-- Post --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_RSVP" about="http://xmlns.com/aas#RSVP" typeof="rdfs:Class"> + <h3>Class: aas:RSVP</h3> + <em>RSVP</em> - indicates that the actor has made a RSVP ("R\xe9pondez s'il vous pla\xeet") for the object, that is, he/she replied to an invite. This specification only defines the meaning of this verb when its object is an event. The use of this Verb is only appropriate when the RSVP was created by an explicit action by the actor. It is not appropriate to use this verb when a user has been added as an attendee by an event organiser or administrator. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>May be the object of:</th> + <td> <a href="#term_RSVPConnotation">RSVPConnotation</a> + </td></tr> + <tr><th>subClassOf</th> + <td> <span rel="rdfs:subClassOf" href="http://xmlns.com/aas#Verb"><a href="#term_Verb">verb</a></span> + </td></tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_RSVP">#</a>] <!-- RSVP --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_Replies" about="http://xmlns.com/aas#Replies" typeof="rdfs:Class"> + <h3>Class: aas:Replies</h3> + <em>Replies</em> - Most social applications have a concept of "comments", "replies" or "responses" to social Objects. In many cases these are simple text messages, but any Object can in practice be a reply. A text-only reply SHOULD be represented using the comment object type. Replies of other types MUST carry the appropriate type and MUST NOT carry the comment object type. Replies, regardless of object type, SHOULD be represented using the thr:in-reply-to element. The act of posting a reply is represented by the post Verb as with "top-level" Objects. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + + <tr><th>subClassOf</th> + <td> <span rel="rdfs:subClassOf" href="http://xmlns.com/aas#Context"><a href="#term_Context">Context</a></span> + </td></tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_Replies">#</a>] <!-- Replies --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_Save" about="http://xmlns.com/aas#Save" typeof="rdfs:Class"> + <h3>Class: aas:Save</h3> + <em>Save</em> - the Actor has called out the Object as being of interest primarily to him- or herself. Though this action MAY be shared publicly, the implication is that the Object has been saved primarily for the actor's own benefit rather than to show it to others as would be indicated by the "share" Verb . <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + + <tr><th>subClassOf</th> + <td> <span rel="rdfs:subClassOf" href="http://xmlns.com/aas#Verb"><a href="#term_Verb">verb</a></span> + </td></tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_Save">#</a>] <!-- Save --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_Service" about="http://xmlns.com/aas#Service" typeof="rdfs:Class"> + <h3>Class: aas:Service</h3> + <em>Service</em> - the Web Service where the activity is performed by the Actor. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>May be the object of:</th> + <td> <a href="#term_name">name</a> + </td></tr> + <tr><th>subClassOf</th> + <td> <span rel="rdfs:subClassOf" href="http://xmlns.com/aas#Context"><a href="#term_Context">Context</a></span> + </td></tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_Service">#</a>] <!-- Service --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_Share" about="http://xmlns.com/aas#Share" typeof="rdfs:Class"> + <h3>Class: aas:Share</h3> + <em>Share</em> - the Actor has called out the Object to readers. In most cases, the actor did not create the Object being shared, but is instead drawing attention to it. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + + <tr><th>subClassOf</th> + <td> <span rel="rdfs:subClassOf" href="http://xmlns.com/aas#Verb"><a href="#term_Verb">verb</a></span> + </td></tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_Share">#</a>] <!-- Share --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_Song" about="http://xmlns.com/aas#Song" typeof="rdfs:Class"> + <h3>Class: aas:Song</h3> + <em>Song</em> - a song or a recording of a song. Objects of type Song might contain information about the song or recording, or they might contain some representation of the recording itself. In the latter case, the song SHOULD also be annotated with the "audio" object type and use its properties. Type "song" SHOULD only be used when the publisher can guarantee that the object is a song rather than merely a generic audio stream. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + + <tr><th>subClassOf</th> + <td> <span rel="rdfs:subClassOf" href="http://xmlns.com/aas#Object"><a href="#term_Object">Object</a></span> + </td></tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_Song">#</a>] <!-- Song --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_StartFollowing" about="http://xmlns.com/aas#StartFollowing" typeof="rdfs:Class"> + <h3>Class: aas:StartFollowing</h3> + <em>StartFollowing</em> - the Actor began following the activity of the Object. In most cases, the Object of this Verb will be a user, but it can potentially be of any type that can sensibly generate activity. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + + <tr><th>subClassOf</th> + <td> <span rel="rdfs:subClassOf" href="http://xmlns.com/aas#Verb"><a href="#term_Verb">verb</a></span> + </td></tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_StartFollowing">#</a>] <!-- StartFollowing --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_Tag" about="http://xmlns.com/aas#Tag" typeof="rdfs:Class"> + <h3>Class: aas:Tag</h3> + <em>Tag</em> - the Actor has identified the presence of a Target inside an Object. The target of the "tag" verb gives the object in which the tag has been added. For example, if a user appears in a photo, the activity:object is the user and the activity:target is the photo. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + + <tr><th>subClassOf</th> + <td> <span rel="rdfs:subClassOf" href="http://xmlns.com/aas#Verb"><a href="#term_Verb">verb</a></span> + </td></tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_Tag">#</a>] <!-- Tag --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_Time" about="http://xmlns.com/aas#Time" typeof="rdfs:Class"> + <h3>Class: aas:Time</h3> + <em>Time</em> - contextual information about time <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>May be the object of:</th> + <td> <a href="#term_date">date</a> + </td></tr> + <tr><th>subClassOf</th> + <td> <span rel="rdfs:subClassOf" href="http://xmlns.com/aas#Context"><a href="#term_Context">Context</a></span> + </td></tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_Time">#</a>] <!-- Time --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_User" about="http://xmlns.com/aas#User" typeof="rdfs:Class"> + <h3>Class: aas:User</h3> + <em>User</em> - A user involved in an activity <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + + <tr><th>subClassOf</th> + <td> <span rel="rdfs:subClassOf" href="http://xmlns.com/aas#Actor"><a href="#term_Actor">Actor</a></span> + </td></tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_User">#</a>] <!-- User --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_Verb" about="http://xmlns.com/aas#Verb" typeof="rdfs:Class"> + <h3>Class: aas:Verb</h3> + <em>verb</em> - a generic verb of an activity. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + + <tr><th>May have properties:</th> + <td> <a href="#term_activityObject">activityObject</a> + <a href="#term_activityVerb">activityVerb</a> +</td></tr> <tr><th>has subclass</th> + <td> <a href="#term_Tag">Tag</a> + <a href="#term_Join">Join</a> + <a href="#term_Share">Share</a> + <a href="#term_MarkAsFavorite">MarkAsFavorite</a> + <a href="#term_Post">describes the act of posting or publishing an Object on the web. The implication is that before this Activity occurred the Object was not posted, and after the Activity has occurred it is posted or published.</a> + <a href="#term_Save">Save</a> + <a href="#term_RSVP">RSVP</a> + <a href="#term_StartFollowing">StartFollowing</a> + <a href="#term_MakeFriend">MakeFriend</a> + <a href="#term_Located">Located</a> + </td></tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_Verb">#</a>] <!-- Verb --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_Video" about="http://xmlns.com/aas#Video" typeof="rdfs:Class"> + <h3>Class: aas:Video</h3> + <em>Video</em> - video content, which usually consists of a motion picture track and an audio track. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>May be the object of:</th> + <td> <a href="#term_playerApplet">playerApplet</a> + <a href="#term_thumbnail">thumbnail</a> + <a href="#term_content">content</a> + <a href="#term_videoStream">videoStream</a> + </td></tr> + <tr><th>subClassOf</th> + <td> <span rel="rdfs:subClassOf" href="http://xmlns.com/aas#MediaContent"><a href="#term_MediaContent">MediaContent</a></span> + </td></tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_Video">#</a>] <!-- Video --> [<a href="#glance">back to top</a>]</p> + <br/> + </div> +<h2>Properties</h2> + + +<div class="specterm" id="term_RSVPConnotation" about="http://xmlns.com/aas#RSVPConnotation" typeof="rdf:Property"> + <h3>Property: aas:RSVPConnotation</h3> + <em>RSVPConnotation</em> - the connotation of the RSVP <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>Domain:</th> + <td> <span rel="rdfs:domain" href="http://xmlns.com/aas#RSVP"><a href="#term_RSVP">RSVP</a></span> +</td></tr> + <tr><th>Range:</th> + <td> <span rel="rdfs:range" href="http://www.w3.org/2001/XMLSchema#string"><a href="#term_string">String</a></span> +</td> </tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_RSVPConnotation">#</a>] <!-- RSVPConnotation --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_activityActor" about="http://xmlns.com/aas#activityActor" typeof="rdf:Property"> + <h3>Property: aas:activityActor</h3> + <em>activityActor</em> - relates the activity to its actor. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>Domain:</th> + <td> <span rel="rdfs:domain" href="http://xmlns.com/aas#Activity"><a href="#term_Activity">Activity</a></span> +</td></tr> + <tr><th>Range:</th> + <td> <span rel="rdfs:range" href="http://xmlns.com/aas#Actor"><a href="#term_Actor">Actor</a></span> +</td> </tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_activityActor">#</a>] <!-- activityActor --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_activityContext" about="http://xmlns.com/aas#activityContext" typeof="rdf:Property"> + <h3>Property: aas:activityContext</h3> + <em>activityContext</em> - relates the activity to its context. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>Domain:</th> + <td> <span rel="rdfs:domain" href="http://xmlns.com/aas#Activity"><a href="#term_Activity">Activity</a></span> +</td></tr> + <tr><th>Range:</th> + <td> <span rel="rdfs:range" href="http://xmlns.com/aas#Context"><a href="#term_Context">Context</a></span> +</td> </tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_activityContext">#</a>] <!-- activityContext --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_activityObject" about="http://xmlns.com/aas#activityObject" typeof="rdf:Property"> + <h3>Property: aas:activityObject</h3> + <em>activityObject</em> - relates the activity to its object. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>Domain:</th> + <td> <span rel="rdfs:domain" href="http://xmlns.com/aas#Activity"><a href="#term_Activity">Activity</a></span> +</td></tr> + <tr><th>Range:</th> + <td> <span rel="rdfs:range" href="http://xmlns.com/aas#Verb"><a href="#term_Verb">verb</a></span> +</td> </tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_activityObject">#</a>] <!-- activityObject --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_activityVerb" about="http://xmlns.com/aas#activityVerb" typeof="rdf:Property"> + <h3>Property: aas:activityVerb</h3> + <em>activityVerb</em> - relates the activity to its verb. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>Domain:</th> + <td> <span rel="rdfs:domain" href="http://xmlns.com/aas#Activity"><a href="#term_Activity">Activity</a></span> +</td></tr> + <tr><th>Range:</th> + <td> <span rel="rdfs:range" href="http://xmlns.com/aas#Verb"><a href="#term_Verb">verb</a></span> +</td> </tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_activityVerb">#</a>] <!-- activityVerb --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_audioStream" about="http://xmlns.com/aas#audioStream" typeof="rdf:Property"> + <h3>Property: aas:audioStream</h3> + <em>audioStream</em> - he URL and metadata for the audio content itself. The URL is represented as the value of the href attribute on an atom:link element with rel enclosure and a type that matches audio/*. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>Domain:</th> + <td> <span rel="rdfs:domain" href="http://xmlns.com/aas#Audio"><a href="#term_Audio">Audio</a></span> +</td></tr> + <tr><th>Range:</th> + <td> <span rel="rdfs:range" href="http://www.w3.org/2001/XMLSchema#string"><a href="#term_string">String</a></span> +</td> </tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_audioStream">#</a>] <!-- audioStream --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_avatar" about="http://xmlns.com/aas#avatar" typeof="rdf:Property"> + <h3>Property: aas:avatar</h3> + <em>avatar</em> - the URL and metadata for an image that represents the user or the group. The URL is represented as the value of the href attribute on an atom:link element with rel avatar and a type of either image/jpeg, image/png or image/gif. Publishers SHOULD include media:width and media:height attributes on the atom:link element describing the dimensions of the linked image. Processors MAY ignore avatars that are of an inappropriate size for their user interface. Publishers MAY include several images of different sizes. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>Domain:</th> + <td> <span rel="rdfs:domain" href="http://xmlns.com/aas#Person"><a href="#term_Person">Person</a></span> + <span rel="rdfs:domain" href="http://xmlns.com/aas#Group"><a href="#term_Group">Group</a></span> +</td></tr> + <tr><th>Range:</th> + <td> <span rel="rdfs:range" href="http://www.w3.org/2001/XMLSchema#string"><a href="#term_string">String</a></span> +</td> </tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_avatar">#</a>] <!-- avatar --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_commenter" about="http://xmlns.com/aas#commenter" typeof="rdf:Property"> + <h3>Property: aas:commenter</h3> + <em>commenter</em> - who wrote the comment. Included as the content of the atom:title element. Many systems do not have the concept of a title or Actor for a comment; such systems MUST include an atom:title element with no text content. Processors SHOULD refer to such comments as simply being "a comment", with appropriate localization, if they are to be described in a sentence. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>Domain:</th> + <td> <span rel="rdfs:domain" href="http://xmlns.com/aas#Comment"><a href="#term_Comment">Comment</a></span> +</td></tr> + <tr><th>Range:</th> + <td> <span rel="rdfs:range" href="http://www.w3.org/2001/XMLSchema#string"><a href="#term_string">String</a></span> +</td> </tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_commenter">#</a>] <!-- commenter --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_content" about="http://xmlns.com/aas#content" typeof="rdf:Property"> + <h3>Property: aas:content</h3> + <em>content</em> - contains the content of atom:content element, either contains or links to the content of the entry. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>Domain:</th> + <td> <span rel="rdfs:domain" href="http://xmlns.com/aas#Article"><a href="#term_Article">Article</a></span> + <span rel="rdfs:domain" href="http://xmlns.com/aas#Note"><a href="#term_Note">Note</a></span> + <span rel="rdfs:domain" href="http://xmlns.com/aas#Photo"><a href="#term_Photo">Photo</a></span> + <span rel="rdfs:domain" href="http://xmlns.com/aas#Comment"><a href="#term_Comment">Comment</a></span> + <span rel="rdfs:domain" href="http://xmlns.com/aas#Video"><a href="#term_Video">Video</a></span> +</td></tr> + <tr><th>Range:</th> + <td> <span rel="rdfs:range" href="http://www.w3.org/2001/XMLSchema#string"><a href="#term_string">String</a></span> +</td> </tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_content">#</a>] <!-- content --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_date" about="http://xmlns.com/aas#date" typeof="rdf:Property"> + <h3>Property: aas:date</h3> + <em>date</em> - the dateTime @@?@@ <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>Domain:</th> + <td> <span rel="rdfs:domain" href="http://xmlns.com/aas#Time"><a href="#term_Time">Time</a></span> +</td></tr> + <tr><th>Range:</th> + <td> <span rel="rdfs:range" href="http://www.w3.org/2001/XMLSchema#dateTime"><a href="#term_dateTime">String</a></span> +</td> </tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_date">#</a>] <!-- date --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_description" about="http://xmlns.com/aas#description" typeof="rdf:Property"> + <h3>Property: aas:description</h3> + <em>description</em> - The description or long caption assigned by the author. Included as the content of the media:description element (optional). <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>Domain:</th> + <td> <span rel="rdfs:domain" href="http://xmlns.com/aas#Object"><a href="#term_Object">Object</a></span> +</td></tr> + <tr><th>Range:</th> + <td> <span rel="rdfs:range" href="http://www.w3.org/2001/XMLSchema#string"><a href="#term_string">String</a></span> +</td> </tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_description">#</a>] <!-- description --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_email" about="http://xmlns.com/aas#email" typeof="rdf:Property"> + <h3>Property: aas:email</h3> + <em>email</em> - the actor email. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>Domain:</th> + <td> <span rel="rdfs:domain" href="http://xmlns.com/aas#Actor"><a href="#term_Actor">Actor</a></span> +</td></tr> + <tr><th>Range:</th> + <td> <span rel="rdfs:range" href="http://www.w3.org/2001/XMLSchema#string"><a href="#term_string">String</a></span> +</td> </tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_email">#</a>] <!-- email --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_endDate" about="http://xmlns.com/aas#endDate" typeof="rdf:Property"> + <h3>Property: aas:endDate</h3> + <em>endDate</em> - the date and time that the event ends. Included via a cal:dtend element as defined in xCal. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>Domain:</th> + <td> <span rel="rdfs:domain" href="http://xmlns.com/aas#Event"><a href="#term_Event">Event</a></span> +</td></tr> + <tr><th>Range:</th> + <td> <span rel="rdfs:range" href="http://www.w3.org/2001/XMLSchema#dateTime"><a href="#term_dateTime">String</a></span> +</td> </tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_endDate">#</a>] <!-- endDate --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_fileUrl" about="http://xmlns.com/aas#fileUrl" typeof="rdf:Property"> + <h3>Property: aas:fileUrl</h3> + <em>fileUrl</em> - the value of the href attribute on an atom:link element with rel enclosure. Should there be multiple links with rel enclosure with different type attribute value, they are considered to be alternate representations of the file. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + + + </table> + + <p style="float: right; font-size: small;">[<a href="#term_fileUrl">#</a>] <!-- fileUrl --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_geographicCoordinates" about="http://xmlns.com/aas#geographicCoordinates" typeof="rdf:Property"> + <h3>Property: aas:geographicCoordinates</h3> + <em>geographicCoordinates</em> - @@sameas w3c geo? @@ the latitude and longitude of the place as a point on Earth. Included via the geo:point element, i.e.: 45.256 -71.92. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>Domain:</th> + <td> <span rel="rdfs:domain" href="http://xmlns.com/aas#Place"><a href="#term_Place">Place</a></span> +</td></tr> + <tr><th>Range:</th> + <td> <span rel="rdfs:range" href="http://www.w3.org/2001/XMLSchema#string"><a href="#term_string">String</a></span> +</td> </tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_geographicCoordinates">#</a>] <!-- geographicCoordinates --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_largerImage" about="http://xmlns.com/aas#largerImage" typeof="rdf:Property"> + <h3>Property: aas:largerImage</h3> + <em>largerImage</em> - The URL and metadata for a larger, ideally full-size version of the photo intended for standalone viewing. The URL is represented as the value of the href attribute on an atom:link element with rel enclosure and a type of either image/jpeg, image/png or image/gif. Publishers SHOULD include media:width and media:height attributes on the atom:link element describing the dimensions of the linked image. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>Domain:</th> + <td> <span rel="rdfs:domain" href="http://xmlns.com/aas#Photo"><a href="#term_Photo">Photo</a></span> +</td></tr> + <tr><th>Range:</th> + <td> <span rel="rdfs:range" href="http://www.w3.org/2001/XMLSchema#string"><a href="#term_string">String</a></span> +</td> </tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_largerImage">#</a>] <!-- largerImage --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_name" about="http://xmlns.com/aas#name" typeof="rdf:Property"> + <h3>Property: aas:name</h3> + <em>name</em> - contains the content of atom:title element, set by the creator for Group, by the organizer for Event. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>Domain:</th> + <td> <span rel="rdfs:domain" href="http://xmlns.com/aas#Object"><a href="#term_Object">Object</a></span> + <span rel="rdfs:domain" href="http://xmlns.com/aas#Service"><a href="#term_Service">Service</a></span> +</td></tr> + <tr><th>Range:</th> + <td> <span rel="rdfs:range" href="http://www.w3.org/2001/XMLSchema#string"><a href="#term_string">String</a></span> +</td> </tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_name">#</a>] <!-- name --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_playerApplet" about="http://xmlns.com/aas#playerApplet" typeof="rdf:Property"> + <h3>Property: aas:playerApplet</h3> + <em>playerApplet</em> - the URL and metadata for some kind of applet that will allow a user to view the video. The URL is represented as the value of the href attribute on an atom:link element with rel alternate and an appropriate type. Publishers SHOULD include media:width and media:height attributes on the atom:link element describing the ideal dimensions of the linked applet. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>Domain:</th> + <td> <span rel="rdfs:domain" href="http://xmlns.com/aas#Video"><a href="#term_Video">Video</a></span> +</td></tr> + <tr><th>Range:</th> + <td> <span rel="rdfs:range" href="http://www.w3.org/2001/XMLSchema#string"><a href="#term_string">String</a></span> +</td> </tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_playerApplet">#</a>] <!-- playerApplet --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_serviceUrl" about="http://xmlns.com/aas#serviceUrl" typeof="rdf:Property"> + <h3>Property: aas:serviceUrl</h3> + <em>serviceUrl</em> - <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + + <tr><th>Range:</th> + <td> <span rel="rdfs:range" href="http://www.w3.org/2001/XMLSchema#url"><a href="#term_url">String</a></span> +</td> </tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_serviceUrl">#</a>] <!-- serviceUrl --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_startDateAndTime" about="http://xmlns.com/aas#startDateAndTime" typeof="rdf:Property"> + <h3>Property: aas:startDateAndTime</h3> + <em>startDateAndTime</em> - the date and time that the event begins. Included via a cal:dtstart element as defined in xCal. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>Domain:</th> + <td> <span rel="rdfs:domain" href="http://xmlns.com/aas#Event"><a href="#term_Event">Event</a></span> +</td></tr> + <tr><th>Range:</th> + <td> <span rel="rdfs:range" href="http://www.w3.org/2001/XMLSchema#dateTime"><a href="#term_dateTime">String</a></span> +</td> </tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_startDateAndTime">#</a>] <!-- startDateAndTime --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_summary" about="http://xmlns.com/aas#summary" typeof="rdf:Property"> + <h3>Property: aas:summary</h3> + <em>summary</em> - an introduction to or a summary of the full content (optional) for Article, a short description as provided by its organiser for Event, included as the content of the atom:summary element. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>Domain:</th> + <td> <span rel="rdfs:domain" href="http://xmlns.com/aas#Article"><a href="#term_Article">Article</a></span> + <span rel="rdfs:domain" href="http://xmlns.com/aas#Event"><a href="#term_Event">Event</a></span> +</td></tr> + <tr><th>Range:</th> + <td> <span rel="rdfs:range" href="http://www.w3.org/2001/XMLSchema#string"><a href="#term_string">String</a></span> +</td> </tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_summary">#</a>] <!-- summary --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_targetName" about="http://xmlns.com/aas#targetName" typeof="rdf:Property"> + <h3>Property: aas:targetName</h3> + <em>targetName</em> - the name of the item that is the target of the bookmark. Represented as the value of the title attribute on the atom:link element from which the target URL was obtained. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>Domain:</th> + <td> <span rel="rdfs:domain" href="http://xmlns.com/aas#Bookmark"><a href="#term_Bookmark">Bookmark</a></span> +</td></tr> + <tr><th>Range:</th> + <td> <span rel="rdfs:range" href="http://www.w3.org/2001/XMLSchema#string"><a href="#term_string">String</a></span> +</td> </tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_targetName">#</a>] <!-- targetName --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_targetUrl" about="http://xmlns.com/aas#targetUrl" typeof="rdf:Property"> + <h3>Property: aas:targetUrl</h3> + <em>targetUrl</em> - the URL of the item that is the target of the bookmark. Represented as the value of the href attribute on an atom:link element with rel "related". <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>Domain:</th> + <td> <span rel="rdfs:domain" href="http://xmlns.com/aas#Bookmark"><a href="#term_Bookmark">Bookmark</a></span> +</td></tr> + <tr><th>Range:</th> + <td> <span rel="rdfs:range" href="http://www.w3.org/2001/XMLSchema#url"><a href="#term_url">String</a></span> +</td> </tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_targetUrl">#</a>] <!-- targetUrl --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_thumbnail" about="http://xmlns.com/aas#thumbnail" typeof="rdf:Property"> + <h3>Property: aas:thumbnail</h3> + <em>thumbnail</em> - @@not sure this is really a literal@@ the URL and metadata for a thumbnail version of the item. The URL is represented as the value of the href attribute on an atom:link element with rel preview and a type of either image/jpeg, image/png or image/gif. Publishers SHOULD include media:width and media:height attributes on the atom:link element describing the dimensions of the linked item. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>Domain:</th> + <td> <span rel="rdfs:domain" href="http://xmlns.com/aas#MediaCollection"><a href="#term_MediaCollection">MediaCollection</a></span> + <span rel="rdfs:domain" href="http://xmlns.com/aas#Photo"><a href="#term_Photo">Photo</a></span> + <span rel="rdfs:domain" href="http://xmlns.com/aas#Bookmark"><a href="#term_Bookmark">Bookmark</a></span> + <span rel="rdfs:domain" href="http://xmlns.com/aas#Video"><a href="#term_Video">Video</a></span> +</td></tr> + <tr><th>Range:</th> + <td> <span rel="rdfs:range" href="http://www.w3.org/2001/XMLSchema#string"><a href="#term_string">String</a></span> +</td> </tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_thumbnail">#</a>] <!-- thumbnail --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_url" about="http://xmlns.com/aas#url" typeof="rdf:Property"> + <h3>Property: aas:url</h3> + <em>url</em> - he value of the href attribute on an atom:link element with a rel value of alternate and a type value of text/html. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>Domain:</th> + <td> <span rel="rdfs:domain" href="http://xmlns.com/aas#Actor"><a href="#term_Actor">Actor</a></span> + <span rel="rdfs:domain" href="http://xmlns.com/aas#Object"><a href="#term_Object">Object</a></span> +</td></tr> + <tr><th>Range:</th> + <td> <span rel="rdfs:range" href="http://www.w3.org/2001/XMLSchema#url"><a href="#term_url">String</a></span> +</td> </tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_url">#</a>] <!-- url --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_videoStream" about="http://xmlns.com/aas#videoStream" typeof="rdf:Property"> + <h3>Property: aas:videoStream</h3> + <em>videoStream</em> - @@not really a literal@@ the URL and metadata for the video content itself. The URL is represented as the value of the href attribute on an atom:link element with rel enclosure and a type that matches video/*. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>Domain:</th> + <td> <span rel="rdfs:domain" href="http://xmlns.com/aas#Video"><a href="#term_Video">Video</a></span> +</td></tr> + <tr><th>Range:</th> + <td> <span rel="rdfs:range" href="http://www.w3.org/2001/XMLSchema#string"><a href="#term_string">String</a></span> +</td> </tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_videoStream">#</a>] <!-- videoStream --> [<a href="#glance">back to top</a>]</p> + <br/> + </div> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +</div> +</div> + +<h2>Validation queries</h2> + + +<h2 id="sec-changes">Recent Changes</h2> + +<ul> +<li>Reworded slightly to change emphasis from ontology to a mapping of an existing vocabulary (the Atom Activity Streams format) to RDF. In consequence, changed the namespace.</li> +<li>Created RDF/XML version of spec.</li> +<li>Marked everything as unstable for now.</li> +<li>Changed literals to xsd:Strings</li> +</ul> + +<h3>Previous Changes</h3> + +</body> +</html> diff --git a/examples/activ-atom/activity_stream_UML.png b/examples/activ-atom/activity_stream_UML.png new file mode 100644 index 0000000..3e92419 Binary files /dev/null and b/examples/activ-atom/activity_stream_UML.png differ diff --git a/examples/activ-atom/activity_streams_ontology.html b/examples/activ-atom/activity_streams_ontology.html new file mode 100644 index 0000000..65181dd --- /dev/null +++ b/examples/activ-atom/activity_streams_ontology.html @@ -0,0 +1,1889 @@ +<?xml version="1.0" encoding="utf-8"?> +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" xmlns:foaf="http://xmlns.com/foaf/0.1/" + xmlns:dc="http://purl.org/dc/elements/1.1/"> +<head> + <title>Activity Streams Ontology Specification</title> + <link href="http://xmlns.com/xmlns-style.css" rel="stylesheet" + type="text/css" /> + <link href="http://xmlns.com/foaf/spec/index.rdf" rel="alternate" + type="application/rdf+xml" /> +<style type="text/css"> +/*<![CDATA[*/ + +body { + + margin-left: 4em; + margin-right: 9em; + text-align: justify; +} + +.termdetails { +} + +div.specterm { + + border: 1px solid black; + background: #F0F0F0 ; + padding: 1em; +} + + +div.rdf-proplist { + background-color: #ddf; + border: 1px solid black; + float: left; +/* width: 26%; */ + margin: 0.3em 1%; +} +img { border: 0 } + +.example { + border: 1px solid black; + background-color: #D9E3E9; + padding: 5px; + width: 100%; +} + + .editorial { + border: 2px solid green; + padding: 5px; +} + +div.rdf-classlist { + background-color: #eef; + border: 1px solid black; + float: left; + margin: 0.3em 1%; + width: 26%; +} + +div.rdf-proplist h3 { + background-color: #bbf; + font-size: 100%; + margin: 0; + padding: 5px; +} + +div.rdf-classlist h3 { + background-color: #ccf; + font-size: 100%; + margin: 0; + padding: 5px; +} + +specterm.h3 { +/* foreground-color: #000; */ + background-color: #bbf; + font-size: 100%; + margin: 0; + padding: 3px; +} + + +/*]]>*/ +</style> +</head> + +<body> + <h1>Activity Streams Ontology Specification 0.1<br /></h1> + + <h2>Namespace Document 21 September 2009 - <em>first draft</em></h2> + + <dl> + + <dt>This version:</dt> + + <dd><a href= + "http://spqr.asemantics.com/~mminno/activity_streams_ontology.html">activity_streams_ontology.html</a> (in rdf soon)</dd> + + <dt>Namespace:</dt> + <dd>http://xmlns.com/aso/0.1/</dd> + <dt>Latest version:</dt> + + <dt>Previous version:</dt> + + <dt>Authors:</dt> + <dd><a href="mailto:[email protected]">Michele Minno</a>, + <a href="mailto:[email protected]">Davide Palmisano</a></dd> + + <dt>Contributors:</dt> + + <dd>Members of the NoTube Project (<a href= + "http://notube.tv/">NoTube</a>) + and the wider <a href="http://www.w3.org/2001/sw/interest/">RDF + and SemWeb developer community</a>. See <a href= + "#sec-ack">acknowledgements</a>.</dd> + </dl> + + <p class="copyright">Copyright &copy; 2000-2007 NoTube Project EU FP7<br /> + <br /> + + <!-- Creative Commons License --> + <a href="http://creativecommons.org/licenses/by/1.0/"><img alt= + "Creative Commons License" style="border: 0; float: right; padding: 10px;" src= + "somerights.gif" /></a> This work is licensed under a <a href= + "http://creativecommons.org/licenses/by/1.0/">Creative Commons + Attribution License</a>. This copyright applies to the <em>Activity Streams + Vocabulary Specification</em> and accompanying documentation in RDF. + Regarding underlying technology, Activity Streams uses W3C's <a href="http://www.w3.org/RDF/">RDF</a> technology, an + open Web standard that can be freely used by anyone.</p> + + <hr /> + + +<h2 id="sec-status">Abstract</h2> +<p> +This specification describes the Activity Streams Ontology (ASO), defined as a dictionary of named +properties and classes using W3C's RDF technology. +</p> + + <div class="status"> + <h2>Status of This Document</h2> + + <p> + This document is in a initial and draft status. + </p> +<p> +As usual, see the <a href="#sec-changes">changes</a> section for details of the changes in this version of the specification. +</p> + + + + + +<h3> +Notational Conventions</h3> + +<p>In this document, the following namespace prefixes are used for the + given namespace URI from the referenced specification: +</p><table class="full" align="center" border="0" cellpadding="2" cellspacing="2"> +<col align="left"><col align="left"><col align="left"> +<tr><th align="left">Alias</th><th align="left">Namespace URI</th><th align="left">Specification</th></tr> + +<tr> +<td align="left"><tt>aso:</tt>&nbsp;</td> +<td align="left"><tt>http://xmlns.com/aso/0.1/</tt>&nbsp;</td> +<td align="left">Activity Streams Ontology</td> +</tr> + +<tr> +<td align="left"><tt>foaf:</tt>&nbsp;</td> +<td align="left"><tt>http://xmlns.com/foaf/0.1/</tt>&nbsp;</td> +<td align="left"><a class='info' href='http://xmlns.com/foaf/spec/'>Friend-of-a-friend ontology<span> </span></a> </td> +</tr> + +<tr> +<td align="left"><tt>dcterms:</tt>&nbsp;</td> +<td align="left"><tt>http://purl.org/dc/terms/</tt>&nbsp;</td> +<td align="left"><a class='info' href='http://dublincore.org/documents/dcmi-terms/'>DCMI Metadata Terms<span> </span></a> </td> +</tr> + + +<tr> +<td align="left"><tt>atom:</tt>&nbsp;</td> +<td align="left"><tt>http://www.w3.org/2005/Atom</tt>&nbsp;</td> +<td align="left"><a class='info' href='#RFC4287'>The Atom Syndication Format<span> (</span><span class='info'>, &ldquo;The Atom Syndication Format,&rdquo; .</span><span>)</span></a> [RFC4287]</td> +</tr> +<tr> +<td align="left"><tt>thr:</tt>&nbsp;</td> +<td align="left"><tt>http://purl.org/syndication/thread/1.0</tt>&nbsp;</td> +<td align="left"><a class='info' href='#RFC4685'>Atom Threading Extensions<span> (</span><span class='info'>Snell, J., &ldquo;Atom Threading Extensions,&rdquo; September&nbsp;2006.</span><span>)</span></a> [RFC4685]</td> +</tr> +<tr> +<td align="left"><tt>activity:</tt>&nbsp;</td> +<td align="left"><tt>http://activitystrea.ms/spec/1.0/</tt>&nbsp;</td> +<td align="left">Atom Activity Extensions</td> +</tr> +<tr> +<td align="left"><tt>media:</tt>&nbsp;</td> +<td align="left"><tt>http://purl.org/syndication/atommedia</tt>&nbsp;</td> +<td align="left">Atom Media Extensions</td> +</tr> +<tr> +<td align="left"><tt>cal:</tt>&nbsp;</td> +<td align="left"><tt>urn:ietf:params:xml:ns:xcal</tt>&nbsp;</td> +<td align="left">xCal</td> +</tr> +<tr> +<td align="left"><tt>pc:</tt>&nbsp;</td> +<td align="left"><tt>http://portablecontacts.net/schema/1.0</tt>&nbsp;</td> +<td align="left">PortableContacts</td> +</tr> +<tr> +<td align="left"><tt>geo:</tt>&nbsp;</td> +<td align="left"><tt>http://www.georss.org/georss</tt>&nbsp;</td> +<td align="left">GeoRSS</td> +</tr> +</table> +<br clear="all" /> + +<p>The choices of namespace prefix are arbitrary and not semantically + significant. +</p> + +<h2 id="sec-toc">Table of Contents</h2> + + <ul> + <li><a href="#sec-act">Activity Streams</a></li> + <li><a href="#sec-glance">Activity Streams Ontologty at a glance</a></li> + + <li><a href="#sec-crossref">ASO cross-reference: Listing FOAF Classes and Properties</a></li> + <li><a href="#sec-ack">Acknowledgments</a></li> + <li><a href="#sec-changes">Recent Changes</a></li> + </ul> + + + <h2 id="sec-act">Activity Streams</h2> + + <p> Here follows an example of feed entry describing an activity stream. Most of the content within the <entry> tag is traditional Atom, and is the very material that all popular Atom readers like Google Reader and NewzCrawler use to render the content. The <activity:verb> and <activity:object> tags are drawn from the Activity Streams specification, and are the portions of the entry that applications should program against.</p> + + <div style="background-color: #feb; border: 1px solid #fd8; font-family: Monaco,monospace; padding: 5px; line-height: 1.3em; white-space:pre">&lt;entry&gt; + &lt;title&gt;Snapshot Smith uploaded a photo.&lt;/title&gt; + &lt;id&gt;http://www.facebook.com/album.php?aid=6&amp;id=499225643&amp;ref=at&lt;/id&gt; + &lt;link href=&quot;http://www.facebook.com/album.php?aid=6&amp;id=499225643&amp;ref=at&quot; /&gt; + &lt;published&gt;2009-04-06T21:23:00-07:00&lt;/published&gt; + &lt;updated&gt;2009-04-06T21:23:00-07:00&lt;/updated&gt; + &lt;author&gt; + &lt;name&gt;Snapshot Smith&lt;/name&gt; + &lt;uri&gt;http://www.facebook.com/people/Snapshot-Smith/499225643&lt;/uri&gt; + &lt;/author&gt; + &lt;category term=&quot;Upload Photos&quot; label=&quot;Upload Photos&quot; /&gt; + &lt;activity:verb&gt; + http://activitystrea.ms/schema/1.0/post/ + &lt;/activity:verb&gt; + &lt;activity:object&gt; + &lt;id&gt;http://www.facebook.com/photo.php?pid=28&amp;id=499225643&amp;ref=at&lt;/id&gt; + &lt;thumbnail&gt;http://photos-e.ak.fbcdn.net/photos-ak-snc1/v2692/195/117/499225643/s499225643_28_6861716.jpg&lt;/thumbnail&gt; + &lt;caption&gt;A very attractive wall, indeed.&lt;/caption&gt; + &lt;published&gt;2009-04-06T21:23:00-07:00&lt;/published&gt; + &lt;link rel=&quot;alternate&quot; type=&quot;text/html&quot; href=&quot;http://www.facebook.com/photo.php?pid=28&amp;id=499225643&amp;ref=at&quot; /&gt; + &lt;activity:object-type&gt; + http://activitystrea.ms/schema/1.0/photo/ + &lt;/activity:object-type&gt; + &lt;/activity:object&gt; +&lt;/entry&gt; </div> + <h2 id="sec-glance">Activity Streams Ontology (ASO) at a glance</h2> + + <img src="activity_stream_UML.png" alt="image of the schema"/> + + <p>An a-z index of ASO terms, by class (categories or types) and + by property.</p> + + +<div style="padding: 5px; border: solid; background-color: #ddd;"> +<p>Classes: <a href="#term_Activity">Activity</a> | <a href="#term_Actor">Actor</a> | <a href="#term_Annotation">Annotation</a> | <a href="#term_Application">Application</a> | <a href="#term_Article">Article</a> | <a href="#term_Audio">Audio</a> | <a href="#term_BlogEntry">BlogEntry</a> | <a href="#term_Bookmark">Bookmark</a> | <a href="#term_Comment">Comment</a> | <a href="#term_Context">Context</a> | <a href="#term_Event">Event</a> | <a href="#term_File">File</a> | <a href="#term_Group">Group</a> | <a href="#term_GroupOfUsers">GroupOfUsers</a> | <a href="#term_Join">Join</a> | <a href="#term_Location">Location</a> | <a href="#term_MediaCollection">MediaCollection</a> | <a href="#term_MediaContent">MediaContent</a> | <a href="#term_MakeFriend">MakeFriend</a> | <a href="#term_MarkAsFavorite">MarkAsFavorite</a>| <a href="#term_Mood">Mood</a> | <a href="#term_Note">Note</a> | <a href="#term_Object">Object</a> | <a href="#term_Person">Person</a> | <a href="#term_Photo">Photo</a> | <a href="#term_PhotoAlbum">PhotoAlbum</a> | <a href="#term_Place">Place</a> | <a href="#term_Play">Play</a> | <a href="#term_Playlist">Playlist</a> | <a href="#term_Post">Post</a> | <a href="#term_Replies">Replies</a> | <a href="#term_RSVP">RSVP</a> | <a href="#term_Save">Save</a> | <a href="#term_Service">Service</a> | <a href="#term_Share">Share</a> | <a href="#term_Song">Song</a> | <a href="#term_StartFollowing">StartFollowing</a> | <a href="#term_Tag">Tag</a> | <a href="#term_Time">Time</a> | <a href="#term_User">User</a> | <a href="#term_Verb">Verb</a> | <a href="#term_Video">Video</a> +</p> +<p>Properties: <a href="#term_activityActor">activityActor</a> | <a href="#term_activityContext">activityContext</a> | <a href="#term_activityObject">activityObject</a> | <a href="#term_activityVerb">activityVerb</a> | + +<a href="#term_actorUrl">actorUrl</a> | +<a href="#term_audioStream">audioStream</a> | +<a href="#term_avatar">avatar</a> | +<a href="#term_commenter">commenter</a> | +<a href="#term_content">content</a> | +<a href="#term_description">date</a> | +<a href="#term_description">description</a> | +<a href="#term_email">email</a> | +<a href="#term_endDateAndTime">endDateAndTime</a> | +<a href="#term_fileUrl">fileUrl</a> | +<a href="#term_geographicCoordinates">geographicCoordinates</a> | +<a href="#term_largerImage">largerImage</a> | +<a href="#term_name">name</a> | +<a href="#term_playerApplet">playerApplet</a> | +<a href="#term_RSVPConnotation">RSVPConnotation</a> | +<a href="#term_serviceUrl">serviceUrl</a> | +<a href="#term_summary">summary</a> | +<a href="#term_startDateAndTime">startDateAndTime</a> | +<a href="#term_targetName">targetName</a> | +<a href="#term_targetUrl">targetUrl</a> | +<a href="#term_thumbnail">thumbnail</a> | +<a href="#term_url">url</a> | +<a href="#term_videoStream">videoStream</a> + + + + + +</p> +</div> + + + + <p>ASO terms, grouped in broad categories.</p> + + <div class="rdf-proplist"> + <h3>Actor types</h3> + + <ul> + <li><a href="#term_Appication">Application</a></li> + <li><a href="#term_GroupOfUsers">GroupOfUsers</a></li> + <li><a href="#term_User">User</a></li> + </ul> + </div> + + <div class="rdf-proplist"> + <h3>Object types</h3> + + <ul> + <li><a href="#term_Article">Article</a></li> + <li><a href="#term_Audio">Audio</a></li> + <li><a href="#term_BlogEntry">BlogEntry</a></li> + <li><a href="#term_Bookmark">Bookmark</a></li> + <li><a href="#term_Comment">Comment</a></li> + <li><a href="#term_Event">Event</a></li> + <li><a href="#term_File">File</a></li> + <li><a href="#term_Group">Group</a></li> + <li><a href="#term_MediaCollection">MediaCollection</a></li> + <li><a href="#term_MediaContent">MediaContent</a></li> + <li><a href="#term_Note">Note</a></li> + <li><a href="#term_Person">Person</a></li> + <li><a href="#term_Photo">Photo</a></li> + <li><a href="#term_PhotoAlbum">PhotoAlbum</a></li> + <li><a href="#term_Place">Place</a></li> + <li><a href="#term_Playlist">Playlist</a></li> + <li><a href="#term_Song">Song</a></li> + <li><a href="#term_Time">Time</a></li> + <li><a href="#term_Verb">Verb</a></li> + <li><a href="#term_Video">Video</a></li> + </ul> + </div> + + <div class="rdf-proplist"> + <h3>Verb types</h3> + + <ul> + <li><a href="#term_Located">Located</a></li> + <li><a href="#term_Join">Join</a></li> + <li><a href="#term_MakeFriend">MakeFriend</a></li> + <li><a href="#term_MarkAsFavorite">MarkAsFavorite</a></li> + <li><a href="#term_Play">Play</a></li> + <li><a href="#term_Post">Post</a></li> + <li><a href="#term_RSVP">RSVP</a></li> + <li><a href="#term_Save">Save</a></li> + <li><a href="#term_Share">Share</a></li> + <li><a href="#term_StartFollowing">StartFollowing</a></li> + <li><a href="#term_Tag">Tag</a></li> + </ul> + </div> + + <div class="rdf-proplist"> + <h3>Context types</h3> + + <ul> + <li><a href="#term_Annotation">Annotation</a></li> + <li><a href="#term_Location">Location</a></li> + <li><a href="#term_Mood">Mood</a></li> + <li><a href="#term_Replies">Replies</a></li> + <li><a href="#term_Service">Service</a></li> + </ul> + </div> + <div style="clear: left;"></div> + + + <div style="clear: left;"></div> + + <h2 id="sec-crossref">ASO cross-reference: Listing ASO Classes and + Properties</h2> + + <p>ASO introduces the following classes and properties. View + this document's source markup to see the RDF/XML version.</p> + <!-- the following is the script-generated list of classes and properties --> + +<h3>Classes and Properties (full detail)</h3><div class='termdetails'><br /><div class="specterm" id="term_Agent"> + + +<div id="term_Activity"> +<h3>Class: aso:Activity</h3> +<em>Activity</em> - A generic activity people performs on the web. <br /><table> + <tr><th>Status:</th> + <td>stable</td></tr> +<tr><th>in-range-of:</th><td> </td></tr><tr><th>in-domain-of:</th><td> <a href="#term_activityActor">activityActor</a> | <a href="#term_activityContext">activityContext</a> | <a href="#term_activityObject">activityObject</a> | <a href="#term_activityVerb">activityVerb</a> </td></tr></table> +</div> + + +<div id="term_Actor"> +<h3>Class: aso:Actor</h3> +<em>Actor</em> - Who performs the activity, modelled as atom:author <br /><table> + <tr><th>Status:</th> + <td>stable</td></tr> +<tr><th>in-range-of:</th><td><a href="#term_activityActor">activityActor</a></td></tr><tr><th>in-domain-of:</th><td><a href="#term_name">name</a> | <a href="#term_url">url</a> | <a href="#term_email">email</a></td></tr> +<tr><th>same-as:</th><td><a href="http://rdfs.org/sioc/spec/#term_User">sioc:User</a></td></tr> +</table> +</div + + +<div id="term_Annotation"> +<h3>Class: aso:Annotation</h3> +<em>Annotation</em> - an extra text-based note added to an activity by the user. <br /><table> + <tr><th>Status:</th> + <td>stable</td></tr> +<tr><th>in-range-of:</th><td></td></tr><tr><th>in-domain-of:</th><td></td></tr> +<tr><th>sub-class-of:</th><td><a href="#term_Context">Context</a></td></tr></table> +</div> + + +<div id="term_Application"> +<h3>Class: aso:Application</h3> +<em>Application</em> - An actor performed by an application. <br /><table> + <tr><th>Status:</th> + <td>stable</td></tr> +<tr><th>in-range-of:</th><td></td></tr><tr><th>in-domain-of:</th><td></td></tr> +<tr><th>sub-class-of:</th><td><a href="#term_Actor">Actor</a></td></tr></table> +</div> + + +<div id="term_Article"> +<h3>Class: aso:Article</h3> +<em>Article</em> - Articles generally consist of paragraphs of text, in some cases incorporating embedded media such as photos and inline hyperlinks to other resources. <br /><table> + <tr><th>Status:</th> + <td>stable</td></tr> +<tr><th>in-range-of:</th><td></td></tr> +<tr><th>in-domain-of:</th><td> <a href="#term_name">name</a> | <a href="#term_summary">summary</a> | <a href="#term_content">content</a> </td></tr> +<tr><th>sub-class-of:</th><td><a href="#term_Object">Object</a></td></tr></table> +</div> + +<div id="term_Audio"> +<h3>Class: aso:Audio</h3> +<em>Article</em> - audio content. <br /><table> + <tr><th>Status:</th> + <td>stable</td></tr> +<tr><th>in-range-of:</th><td></td></tr><tr><th>in-domain-of:</th><td><a href="#term_audioStream">audioStream</a> | <a href="#term_playerApplet">playerApplet</a></td></tr> +<tr><th>sub-class-of:</th><td><a href="#term_MediaContent">MediaContent</a></td></tr> +<tr><th>same-as:</th><td><a href="http://dublincore.org/documents/dcmi-terms/#dcmitype-Sound">dcterms:Sound</a></td></tr> +</table> +</div> + + +<div id="term_BlogEntry"> +<h3>Class: aso:BlogEntry</h3> +<em>BlogEntry</em> - BlogEntry is a specialization of the "article" object type, so publishers SHOULD also include the object type URL for the "article" object type when publishing object entries of this type. <br /><table> + <tr><th>Status:</th> + <td>stable</td></tr> +<tr><th>in-range-of:</th><td></td></tr><tr><th>in-domain-of:</th><td></td></tr> +<tr><th>sub-class-of:</th><td><a href="#term_Article">Article</a></td></tr></table> +</div> + + +<div id="term_Bookmark"> +<h3>Class: aso:Bookmark</h3> +<em>Bookmark</em> - a pointer to some URL -- typically a web page. <br /><table> + <tr><th>Status:</th> + <td>stable</td></tr> +<tr><th>in-range-of:</th><td></td></tr><tr><th>in-domain-of:</th><td> +<a href="#term_name">name</a> +| <a href="#term_targetUrl">targetUrl</a> +| <a href="#term_targetName">targetName</a> +| <a href="#term_thumbnail">thumbnail</a> +| <a href="#term_description">description</a> +| <a href="#term_content">content</a> + +</td></tr> +<tr><th>sub-class-of:</th><td><a href="#term_Object">Object</a></td></tr></table> +</div> + + +<div id="term_Comment"> +<h3>Class: aso:Comment</h3> +<em>Comment</em> - a textual response to another object. The comment object type MUST NOT be used for other kinds of replies, such as video replies or reviews. +If an object has no explicit type but the object element has a thr:in-reply-to element a consumer SHOULD consider that object to be a comment.<br /><table> + <tr><th>Status:</th> + <td>stable</td></tr> +<tr><th>in-range-of:</th><td></td></tr><tr><th>in-domain-of:</th><td> + +<a href="#term_commenter">commenter</a> +| <a href="#term_content">content</a> +</td></tr> +<tr><th>sub-class-of:</th><td><a href="#term_Object">Object</a></td></tr></table> +</div> + + + +<div id="term_Context"> +<h3>Class: aso:Context</h3> +<em>Context</em> - describes the context of an activity. <br /><table> + <tr><th>Status:</th> + <td>stable</td></tr> +<tr><th>in-range-of:</th><td><a href="#term_activityContext">activityContext</a></td></tr><tr><th>in-domain-of:</th><td></td></tr></table> +</div> + + +<div id="term_Event"> +<h3>Class: aso:Event</h3> +<em>Event</em> - an event that occurs in a certain place during a particular interval of time. <br /><table> + <tr><th>Status:</th> + <td>stable</td></tr> +<tr><th>in-range-of:</th><td></td></tr><tr><th>in-domain-of:</th><td> +<a href="#term_name">name</a> +| <a href="#term_startDateAndTime">startDateAndTime</a> +| <a href="#term_endDateAndTime">endDateAndTime</a> +| <a href="#term_summary">summary</a> + + +</td></tr> +<tr><th>sub-class-of:</th><td><a href="#term_Object">Object</a></td></tr> +<tr><th>same-as:</th><td><a href="http://dublincore.org/documents/dcmi-terms/#dcmitype-Event">dcterms:Event</a></td></tr> +</table> +</div> + + +<div id="term_File"> +<h3>Class: aso:File</h3> +<em>File</em> - some document or other file with no additional machine-readable semantics. <br /><table> + <tr><th>Status:</th> + <td>stable</td></tr> +<tr><th>in-range-of:</th><td></td></tr><tr><th>in-domain-of:</th><td><a href="#term_fileUrl">fileUrl</a></td></tr> +<tr><th>sub-class-of:</th><td><a href="#term_Object">Object</a></td></tr></table> +</div> + +<div id="term_Group"> +<h3>Class: aso:Group</h3> +<em>Group</em> - a collection of people which people can join and leave. <br /><table> + <tr><th>Status:</th> + <td>stable</td></tr> +<tr><th>in-range-of:</th><td></td></tr><tr><th>in-domain-of:</th><td><a href="#term_name">name</a> | <a href="#term_avatar">avatar</a></td></tr> +<tr><th>sub-class-of:</th><td><a href="#term_Object">Object</a></td></tr> +<tr><th>same-as:</th><td><a href="http://rdfs.org/sioc/spec/#term_Group">foaf:Group</a></td></tr> + +</table> +</div> + + +<div id="term_GroupOfUsers"> +<h3>Class: aso:GroupOfUsers</h3> +<em>GroupOfUsers</em> - An actor performed by a group of users. <br /><table> + <tr><th>Status:</th> + <td>stable</td></tr> +<tr><th>in-range-of:</th><td></td></tr><tr><th>in-domain-of:</th><td></td></tr> +<tr><th>sub-class-of:</th><td><a href="#term_Actor">Actor</a></td></tr></table> +</div> + + +<div id="term_Join"> +<h3>Class: aso:Join</h3> +<em>Join</em> - the Actor has become a member of the Object. This specification only defines the meaning of this Verb when its Object is a group. <br /><table> + <tr><th>Status:</th> + <td>stable</td></tr> +<tr><th>in-range-of:</th><td></td></tr><tr><th>in-domain-of:</th><td></td></tr> +<tr><th>sub-class-of:</th><td><a href="#term_Verb">Verb</a></td></tr></table> +</div> + +<div id="term_Located"> +<h3>Class: aso:Located</h3> +<em>Located</em> - the Actor is located in Object.<br /><table> + <tr><th>Status:</th> + <td>stable</td></tr> +<tr><th>in-range-of:</th><td></td></tr><tr><th>in-domain-of:</th><td></td></tr> +<tr><th>sub-class-of:</th><td><a href="#term_Verb">Verb</a></td></tr></table> +</div> + + +<div id="term_Location"> +<h3>Class: aso:Location</h3> +<em>Location</em> - the location where the user was at the time the activity was performed. This may be an accurate geographic coordinate, a street address, a free-form location name or a combination of these.<br /><table> + <tr><th>Status:</th> + <td>stable</td></tr> +<tr><th>in-range-of:</th><td></td></tr><tr><th>in-domain-of:</th><td></td></tr> +<tr><th>sub-class-of:</th><td><a href="#term_Context">Context</a></td></tr> +<tr><th>same-as:</th><td><a href="http://dublincore.org/documents/dcmi-terms/#dcmitype-Location">dcterms:Location</a></td></tr> +</table> +</div> + + +<div id="term_MediaCollection"> +<h3>Class: aso:MediaCollection</h3> +<em>MediaCollection</em> - Generic collection of media items. <br /><table> + <tr><th>Status:</th> + <td>stable</td></tr> +<tr><th>in-range-of:</th><td></td></tr><tr><th>in-domain-of:</th><td> +<a href="#term_name">name</a> | +<a href="#term_description">description</a> | +<a href="#term_thumbnail">thumbnail</a> + +</td></tr> +<tr><th>sub-class-of:</th><td><a href="#term_Object">Object</a></td></tr></table> +</div> + + +<div id="term_MediaContent"> +<h3>Class: aso:MediaContent</h3> +<em>MediaContent</em> - a media item. <br /><table> + <tr><th>Status:</th> + <td>stable</td></tr> +<tr><th>in-range-of:</th><td></td></tr><tr><th>in-domain-of:</th><td> +<a href="#term_name">name</a> | +<a href="#term_description">description</a> +</td></tr> +<tr><th>sub-class-of:</th><td><a href="#term_Object">Object</a></td></tr></table> +</div> + + +<div id="term_MakeFriend"> +<h3>Class: aso:MakeFriend</h3> +<em>MakeFriend</em> - the Actor sets the creation of a friendship that is reciprocated by the object. <br /><table> + <tr><th>Status:</th> + <td>stable</td></tr> +<tr><th>in-range-of:</th><td></td></tr><tr><th>in-domain-of:</th><td></td></tr> +<tr><th>sub-class-of:</th><td><a href="#term_Verb">Verb</a></td></tr></table> +</div> + +<div id="term_MarkAsFavorite"> +<h3>Class: aso:MarkAsFavorite</h3> +<em>MarkAsFavorite</em> - the Actor marked the Object as an item of special interest. <br /><table> + <tr><th>Status:</th> + <td>stable</td></tr> +<tr><th>in-range-of:</th><td></td></tr><tr><th>in-domain-of:</th><td></td></tr> +<tr><th>sub-class-of:</th><td><a href="#term_Verb">Verb</a></td></tr></table> +</div> + + +<div id="term_Mood"> +<h3>Class: aso:Mood</h3> +<em>Mood</em> - the mood of the user when the activity was performed. This is usually collected via an extra field in the user interface used to perform the activity. For the purpose of this schema, a mood is a freeform, short mood keyword or phrase along with an optional mood icon image. <br /><table> + <tr><th>Status:</th> + <td>stable</td></tr> +<tr><th>in-range-of:</th><td></td></tr><tr><th>in-domain-of:</th><td></td></tr> +<tr><th>sub-class-of:</th><td><a href="#term_Context">Context</a></td></tr></table> +</div> + + +<div id="term_Note"> +<h3>Class: aso:Note</h3> +<em>Note</em> - is intended for use in "micro-blogging" and in systems where users are invited to publish a timestamped "status".<br /><table> + <tr><th>Status:</th> + <td>stable</td></tr> +<tr><th>in-range-of:</th><td></td></tr><tr><th>in-domain-of:</th><td> +<a href="#term_content">content</a> +</td></tr> +<tr><th>sub-class-of:</th><td><a href="#term_Object">Object</a></td></tr></table> +</div> + + +<div id="term_Object"> +<h3>Class: aso:Object</h3> +<em>Object</em> - the generic object of the activity.<br /><table> + <tr><th>Status:</th> + <td>stable</td></tr> +<tr><th>in-range-of:</th><td><a href="#term_activityObject">activityObject</a></td></tr><tr><th>in-domain-of:</th><td><a href="#term_name">name</a> | <a href="#term_description">description</a> | <a href="#term_url">url</a></td></tr></table> +</div> + +<div id="term_Person"> +<h3>Class: aso:Person</h3> +<em>Person</em> - a user account. This is often a person, but might also be a company or ficticious character that is being represented by a user account.<br /><table> + <tr><th>Status:</th> + <td>stable</td></tr> +<tr><th>in-range-of:</th><td></td></tr><tr><th>in-domain-of:</th><td> +<a href="#term_avatar">avatar</a> + +</td></tr> +<tr><th>sub-class-of:</th><td><a href="#term_Object">Object</a></td></tr> +<tr><th>same-as:</th><td><a href="http://rdfs.org/sioc/spec/#term_Person">foaf:Person</a></td></tr> +</table> +</div> + + +<div id="term_Photo"> +<h3>Class: aso:Photo</h3> +<em>Photo</em> - a graphical still image.<br /><table> + <tr><th>Status:</th> + <td>stable</td></tr> +<tr><th>in-range-of:</th><td></td></tr><tr><th>in-domain-of:</th><td> +<a href="#term_largerImage">largerImage</a> | +<a href="#term_content">content</a> | +<a href="#term_thumbnail">thumbnail</a> + +</td></tr> +<tr><th>sub-class-of:</th><td><a href="#term_MediaContent">MediaContent</a></td></tr> +<tr><th>same-as:</th><td><a href="http://dublincore.org/documents/dcmi-terms/#dcmitype-StillImage">dcterms:StillImage</a></td></tr> +</table> +</div> + + +<div id="term_PhotoAlbum"> +<h3>Class: aso:PhotoAlbum</h3> +<em>PhotoAlbum</em> - a collection of images.<br /><table> + <tr><th>Status:</th> + <td>stable</td></tr> +<tr><th>in-range-of:</th><td></td></tr><tr><th>in-domain-of:</th><td></td></tr> +<tr><th>sub-class-of:</th><td><a href="#term_MediaCollection">MediaCollection</a></td></tr></table> +</div> + + +<div id="term_Place"> +<h3>Class: aso:Place</h3> +<em>Place</em> - a location on Earth.<br /><table> + <tr><th>Status:</th> + <td>stable</td></tr> +<tr><th>in-range-of:</th><td></td></tr><tr><th>in-domain-of:</th><td> +<a href="#term_name">name</a> | +<a href="#term_geographicCoordinates">geographicCoordinates</a> +</td></tr> +<tr><th>sub-class-of:</th><td><a href="#term_Object">Object</a></td></tr> +<tr><th>same-as:</th><td><a href="http://dublincore.org/documents/dcmi-terms/#dcmitype-Location">dcterms:Location</a></td></tr> +</table> +</div> + + + + +<div id="term_Playlist"> +<h3>Class: aso:Playlist</h3> +<em>Playlist</em> - an ordered list of time-based media items, such as video and audio objects.<br /><table> + <tr><th>Status:</th> + <td>stable</td></tr> +<tr><th>in-range-of:</th><td></td></tr><tr><th>in-domain-of:</th><td></td></tr> +<tr><th>sub-class-of:</th><td><a href="#term_MediaCollection">MediaCollection</a></td></tr></table> +</div> + + +<div id="term_Post"> +<h3>Class: aso:Post</h3> +<em>Post</em> - describes the act of posting or publishing an Object on the web. The implication is that before this Activity occurred the Object was not posted, and after the Activity has occurred it is posted or published.<br /><table> + <tr><th>Status:</th> + <td>stable</td></tr> +<tr><th>in-range-of:</th><td></td></tr><tr><th>in-domain-of:</th><td></td></tr> +<tr><th>sub-class-of:</th><td><a href="#term_Verb">Verb</a></td></tr> +</table> +</div> + + +<div id="term_Replies"> +<h3>Class: aso:Replies</h3> +<em>Replies</em> - Most social applications have a concept of "comments", "replies" or "responses" to social Objects. In many cases these are simple text messages, but any Object can in practice be a reply. + +A text-only reply SHOULD be represented using the comment object type. Replies of other types MUST carry the appropriate type and MUST NOT carry the comment object type. + +Replies, regardless of object type, SHOULD be represented using the thr:in-reply-to element. +The act of posting a reply is represented by the post Verb as with "top-level" Objects. +<br /><table> + <tr><th>Status:</th> + <td>stable</td></tr> +<tr><th>in-range-of:</th><td></td></tr><tr><th>in-domain-of:</th><td></td></tr> +<tr><th>sub-class-of:</th><td><a href="#term_Context">Context</a></td></tr></table> +</div> + + +<div id="term_RSVP"> +<h3>Class: aso:RSVP</h3> +<em>RSVP</em> - indicates that the actor has made a RSVP ("Répondez s'il vous plaît") for the object, that is, he/she replied to an invite. This specification only defines the meaning of this verb when its object is an event. The use of this Verb is only appropriate when the RSVP was created by an explicit action by the actor. It is not appropriate to use this verb when a user has been added as an attendee by an event organiser or administrator. +.<br /><table> + <tr><th>Status:</th> + <td>stable</td></tr> +<tr><th>in-range-of:</th><td></td></tr><tr><th>in-domain-of:</th><td></td></tr> +<tr><th>sub-class-of:</th><td><a href="#term_Verb">Verb</a></td></tr></table> +</div> + + +<div id="term_Save"> +<h3>Class: aso:Save</h3> +<em>Save</em> - the Actor has called out the Object as being of interest primarily to him- or herself. Though this action MAY be shared publicly, the implication is that the Object has been saved primarily for the actor's own benefit rather than to show it to others as would be indicated by the "share" Verb .<br /><table> + <tr><th>Status:</th> + <td>stable</td></tr> +<tr><th>in-range-of:</th><td></td></tr><tr><th>in-domain-of:</th><td></td></tr> +<tr><th>sub-class-of:</th><td><a href="#term_Verb">Verb</a></td></tr></table> +</div> + +<div id="term_Service"> +<h3>Class: aso:Service</h3> +<em>Service</em> - the Web Service where the activity is performed by the Actor.<br /><table> + <tr><th>Status:</th> + <td>stable</td></tr> +<tr><th>in-range-of:</th><td></td></tr><tr><th>in-domain-of:</th><td><a href="#term_name">name</a> | <a href="#term_serviceUrl">serviceUrl</a></td></tr> +<tr><th>sub-class-of:</th><td><a href="#term_Context">Context</a></td></tr></table> +</div> + +<div id="term_Share"> +<h3>Class: aso:Share</h3> +<em>Share</em> - the Actor has called out the Object to readers. In most cases, the actor did not create the Object being shared, but is instead drawing attention to it.<br /><table> + <tr><th>Status:</th> + <td>stable</td></tr> +<tr><th>in-range-of:</th><td></td></tr><tr><th>in-domain-of:</th><td></td></tr> +<tr><th>sub-class-of:</th><td><a href="#term_Verb">Verb</a></td></tr></table> +</div> + +<div id="term_Song"> +<h3>Class: aso:Song</h3> +<em>Song</em> - a song or a recording of a song. +Objects of type Song might contain information about the song or recording, or they might contain some representation of the recording itself. In the latter case, the song SHOULD also be annotated with the "audio" object type and use its properties. Type "song" SHOULD only be used when the publisher can guarantee that the object is a song rather than merely a generic audio stream.<br /><table> + <tr><th>Status:</th> + <td>stable</td></tr> +<tr><th>in-range-of:</th><td></td></tr><tr><th>in-domain-of:</th><td> +<a href="#term_name">name</a></td></tr> +<tr><th>sub-class-of:</th><td><a href="#term_Object">Object</a></td></tr></table> +</div> + +<div id="term_StartFollowing"> +<h3>Class: aso:StartFollowing</h3> +<em>StartFollowing</em> - the Actor began following the activity of the Object. In most cases, the Object of this Verb will be a user, but it can potentially be of any type that can sensibly generate activity.<br /><table> + <tr><th>Status:</th> + <td>stable</td></tr> +<tr><th>in-range-of:</th><td></td></tr><tr><th>in-domain-of:</th><td></td></tr> +<tr><th>sub-class-of:</th><td><a href="#term_Verb">Verb</a></td></tr></table> +</div> + + +<div id="term_Tag"> +<h3>Class: aso:Tag</h3> +<em>Tag</em> - the Actor has identified the presence of a Target inside an Object. The target of the "tag" verb gives the object in which the tag has been added. For example, if a user appears in a photo, the activity:object is the user and the activity:target is the photo.<br /><table> + <tr><th>Status:</th> + <td>stable</td></tr> +<tr><th>in-range-of:</th><td></td></tr><tr><th>in-domain-of:</th><td></td></tr> +<tr><th>sub-class-of:</th><td><a href="#term_Verb">Verb</a></td></tr></table> +</div> + +<div id="term_Time"> +<h3>Class: aso:Time</h3> +<em>Time</em> - contextual information about time<br /><table> + <tr><th>Status:</th> + <td>stable</td></tr> +<tr><th>in-range-of:</th><td></td></tr><tr><th>in-domain-of:</th><td><a href="#term_date">date</a></td></tr> +<tr><th>sub-class-of:</th><td><a href="#term_Context">Context</a></td></tr></table> +</div> + + +<div id="term_User"> +<h3>Class: aso:User</h3> +<em>User</em> - An actor performed by a user. <br /><table> + <tr><th>Status:</th> + <td>stable</td></tr> +<tr><th>in-range-of:</th><td></td></tr><tr><th>in-domain-of:</th><td></td></tr> +<tr><th>sub-class-of:</th><td><a href="#term_Actor">Actor</a></td></tr></table> +</div> + + +<div id="term_Verb"> +<h3>Class: aso:Verb</h3> +<em>Verb</em> - a generic verb of an activity.<br /><table> + <tr><th>Status:</th> + <td>stable</td></tr> +<tr><th>in-range-of:</th><td><a href="#term_activityVerb">activityVerb</a></td></tr><tr><th>in-domain-of:</th><td></td></tr></table> +</div> + + +<div id="term_Video"> +<h3>Class: aso:Video</h3> +<em>Video</em> - video content, which usually consists of a motion picture track and an audio track.<br /><table> + <tr><th>Status:</th> + <td>stable</td></tr> +<tr><th>in-range-of:</th><td></td></tr><tr><th>in-domain-of:</th><td> + +<a href="#term_videoStream">videoStream</a> | +<a href="#term_playerApplet">playerApplet</a> | +<a href="#term_content">content</a> | +<a href="#term_thumbnail">thumbnail</a> +</td></tr> +<tr><th>sub-class-of:</th><td><a href="#term_MediaContent">MediaContent</a></td></tr> +<tr><th>same-as:</th><td><a href="http://dublincore.org/documents/dcmi-terms/#dcmitype-MovingImage">dcterms:MovingImage</a></td></tr> + +</table> +</div> + + + +<!-- todo: write rdfs:domain statements for those properties --> +<p style="float: right; font-size: small;">[<a href="#term_Agent">#</a>]</p> + +<p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + + +<br/> +</div> + +<br /> + + + + + + + +<br /> + + + +<div class="specterm" id="term_activityActor"> +<h3>Property: aso:activityActor</h3> +<em>activityActor</em> - relates the activity to its actor. <br /><table> + <tr><th>Status:</th> + <td>unstable</td></tr> + <tr><th>Domain:</th> + <td><a href="#term_Activity">aso:Activity</a></td></tr> + <tr><th>Range:</th> + <td><a href="#term_Actor">aso:Actor</a> </td></tr> +</table> +</div> + +<br/> + +<div class="specterm" id="term_activityContext"> +<h3>Property: aso:activityContext</h3> +<em>activityContext</em> - relates the activity to its context. <br /><table> + <tr><th>Status:</th> + <td>unstable</td></tr> + <tr><th>Domain:</th> + <td><a href="#term_Activity">aso:Activity</a></td></tr> + <tr><th>Range:</th> + <td><a href="#term_Context">aso:Context</a> </td></tr> +</table> +</div> + +<br/> + +<div class="specterm" id="term_activityObject"> +<h3>Property: aso:activityObject</h3> +<em>activityObject</em> - relates the activity to its object. <br /><table> + <tr><th>Status:</th> + <td>unstable</td></tr> + <tr><th>Domain:</th> + <td><a href="#term_Activity">aso:Activity</a></td></tr> + <tr><th>Range:</th> + <td><a href="#term_Object">aso:Object</a> </td></tr> +</table> +</div> + +<br/> + +<div class="specterm" id="term_activityVerb"> +<h3>Property: aso:activityVerb</h3> +<em>activityVerb</em> - relates the activity to its verb. <br /><table> + <tr><th>Status:</th> + <td>unstable</td></tr> + <tr><th>Domain:</th> + <td><a href="#term_Activity">aso:Activity</a></td></tr> + <tr><th>Range:</th> + <td><a href="#term_Verb">aso:Verb</a> </td></tr> +</table> +</div> + +<br/> + + + +<div class="specterm" id="term_audioStream"> +<h3>Property: aso:audioStream</h3> +<em>audioStream</em> - the URL and metadata for the audio content itself. The URL is represented as the value of the href attribute on an atom:link element with rel enclosure and a type that matches audio/*. +<br /><table> + <tr><th>Status:</th> + <td>unstable</td></tr> + <tr><th>Domain:</th> + <td><a href="#term_Audio">aso:Audio</a></td></tr> + <tr><th>Range:</th> + <td>http://www.w3.org/2000/01/rdf-schema#Literal</td></tr> +</table> +</div> + +<br/> + + +<div class="specterm" id="term_avatar"> +<h3>Property: aso:avatar</h3> +<em>avatar</em> - the URL and metadata for an image that represents the user or the group. The URL is represented as the value of the href attribute on an atom:link element with rel avatar and a type of either image/jpeg, image/png or image/gif. Publishers SHOULD include media:width and media:height attributes on the atom:link element describing the dimensions of the linked image. Processors MAY ignore avatars that are of an inappropriate size for their user interface. Publishers MAY include several images of different sizes.<br /><table> + <tr><th>Status:</th> + <td>unstable</td></tr> + <tr><th>Domain:</th> + <td><a href="#term_Person">aso:Person</a> | <a href="#term_Group">aso:Group</a></td></tr> + <tr><th>Range:</th> + <td>http://www.w3.org/2000/01/rdf-schema#Literal</td></tr> +</table> +</div> + +<br/> + +<div class="specterm" id="term_commenter"> +<h3>Property: aso:commenter</h3> +<em>commenter</em> - who wrote the comment. Included as the content of the atom:title element. Many systems do not have the concept of a title or Actor for a comment; such systems MUST include an atom:title element with no text content. Processors SHOULD refer to such comments as simply being "a comment", with appropriate localization, if they are to be described in a sentence. +<br /><table> + <tr><th>Status:</th> + <td>unstable</td></tr> + <tr><th>Domain:</th> + <td><a href="#term_Comment">aso:Comment</a></td></tr> + <tr><th>Range:</th> + <td>http://www.w3.org/2000/01/rdf-schema#Literal</td></tr> + <tr><th>sub-property-of:</th><td><a href="http://dublincore.org/documents/dcmi-terms/#elements-creator">dcterms:creator</a></td></tr> +</table> +</div> + +<br/> + + +<div class="specterm" id="term_content"> +<h3>Property: aso:content</h3> +<em>content</em> - contains the content of atom:content element, either contains or links to the content of the entry. <br /><table> + <tr><th>Status:</th> + <td>unstable</td></tr> + <tr><th>Domain:</th> + <td><a href="#term_Article">aso:Article</a> | <a href="#term_Note">aso:Comment</a> | <a href="#term_Note">aso:Note</a> | <a href="#term_Note">aso:Photo</a> | <a href="#term_Note">aso:Video</a></td></tr> + <tr><th>Range:</th> + <td>http://www.w3.org/2000/01/rdf-schema#Literal</td></tr> +</table> +</div> + +<br/> + +<div class="specterm" id="term_date"> +<h3>Property: aso:date</h3> +<em>date</em> - the time date. <br /><table> + <tr><th>Status:</th> + <td>unstable</td></tr> + <tr><th>Domain:</th> + <td><a href="#term_Time">aso:Time</a></td></tr> + <tr><th>Range:</th> + <td>http://www.w3.org/2000/01/rdf-schema#Literal</td></tr> +</table> +</div> + +<br/> + + +<div class="specterm" id="term_description"> +<h3>Property: aso:description</h3> +<em>description</em> - The description or long caption assigned by the author. Included as the content of the media:description element (optional). +<br /><table> + <tr><th>Status:</th> + <td>unstable</td></tr> + <tr><th>Domain:</th> + <td><a href="#term_Object">aso:Object</a></td></tr> + <tr><th>Range:</th> + <td>http://www.w3.org/2000/01/rdf-schema#Literal</td></tr> + <tr><th>same-as:</th><td><a href="http://dublincore.org/documents/dcmi-terms/#elements-description">dcterms:description</a></td></tr> +</table> +</div> + +<br/> + +<div class="specterm" id="term_endDate"> +<h3>Property: aso:endDate</h3> +<em>endDate</em> - the date and time that the event ends. Included via a cal:dtend element as defined in xCal.<br /><table> + <tr><th>Status:</th> + <td>unstable</td></tr> + <tr><th>Domain:</th> + <td><a href="#term_Event">aso:Event</a></td></tr> + <tr><th>Range:</th> + <td>http://www.w3.org/2000/01/rdf-schema#Literal</td></tr> +</table> +</div> + +<br/> + + +<div class="specterm" id="term_email"> +<h3>Property: aso:email</h3> +<em>email</em> - the actor email.<br /><table> + <tr><th>Status:</th> + <td>unstable</td></tr> + <tr><th>Domain:</th> + <td><a href="#term_Actor">aso:Actor</a></td></tr> + <tr><th>Range:</th> + <td>http://www.w3.org/2000/01/rdf-schema#Literal</td></tr> +</table> +</div> + +<br/> + +<div class="specterm" id="term_fileUrl"> +<h3>Property: aso:fileUrl</h3> +<em>fileUrl</em> - the value of the href attribute on an atom:link element with rel enclosure. Should there be multiple links with rel enclosure with different type attribute value, they are considered to be alternate representations of the file.<br /><table> + <tr><th>Status:</th> + <td>unstable</td></tr> + <tr><th>Domain:</th> + <td><a href="#term_File">aso:File</a></td></tr> + <tr><th>Range:</th> + <td>http://www.w3.org/2000/01/rdf-schema#Literal</td></tr> +</table> +</div> + +<br/> + +<div class="specterm" id="term_geographicCoordinates"> +<h3>Property: aso:geographicCoordinates</h3> +<em>geographicCoordinates</em> - the latitude and longitude of the place as a point on Earth. Included via the geo:point element, i.e.: <georss:point>45.256 -71.92</georss:point>.<br /><table> + <tr><th>Status:</th> + <td>unstable</td></tr> + <tr><th>Domain:</th> + <td><a href="#term_Place">aso:Place</a></td></tr> + <tr><th>Range:</th> + <td>http://www.w3.org/2000/01/rdf-schema#Literal</td></tr> +</table> +</div> + +<br/> + + +<div class="specterm" id="term_largerImage"> +<h3>Property: aso:largerImage</h3> +<em>largerImage</em> - The URL and metadata for a larger, ideally full-size version of the photo intended for standalone viewing. The URL is represented as the value of the href attribute on an atom:link element with rel enclosure and a type of either image/jpeg, image/png or image/gif. Publishers SHOULD include media:width and media:height attributes on the atom:link element describing the dimensions of the linked image. +<br /><table> + <tr><th>Status:</th> + <td>unstable</td></tr> + <tr><th>Domain:</th> + <td><a href="#term_Photo">aso:Photo</a></td></tr> + <tr><th>Range:</th> + <td>http://www.w3.org/2000/01/rdf-schema#Literal</td></tr> +</table> +</div> + +<br/> + +<div class="specterm" id="term_name"> +<h3>Property: aso:name</h3> +<em>name</em> - contains the content of atom:title element, set by the creator for Group, by the organizer for Event.<br /><table> + <tr><th>Status:</th> + <td>unstable</td></tr> + <tr><th>Domain:</th> + <td><a href="#term_Object">aso:Object</a> | <a href="#term_Service">aso:Service</a></td></tr> + <tr><th>Range:</th> + <td>http://www.w3.org/2000/01/rdf-schema#Literal</td></tr> + <tr><th>same-as:</th><td><a href="http://dublincore.org/documents/dcmi-terms/#elements-title">dcterms:title</a></td></tr> +</table> +</div> + +<br/> + + + + +<div class="specterm" id="term_playerApplet"> +<h3>Property: aso:playerApplet</h3> +<em>playerApplet</em> - the URL and metadata for some kind of applet that will allow a user to view the video. The URL is represented as the value of the href attribute on an atom:link element with rel alternate and an appropriate type. Publishers SHOULD include media:width and media:height attributes on the atom:link element describing the ideal dimensions of the linked applet. +<br /><table> + <tr><th>Status:</th> + <td>unstable</td></tr> + <tr><th>Domain:</th> + <td><a href="#term_Video">aso:Video</a></td></tr> + <tr><th>Range:</th> + <td>http://www.w3.org/2000/01/rdf-schema#Literal</td></tr> +</table> +</div> + +<br/> + + +<div class="specterm" id="term_RSVPConnotation"> +<h3>Property: aso:RSVPConnotation</h3> +<em>RSVPConnotation</em> - the connotation of the RSVP +<br /><table> + <tr><th>Status:</th> + <td>unstable</td></tr> + <tr><th>Domain:</th> + <td><a href="#term_RSVP">aso:RSVP</a></td></tr> + <tr><th>Range:</th> + <td>http://www.w3.org/2000/01/rdf-schema#Literal</td></tr> +</table> +</div> + +<br/> + + + +<div class="specterm" id="term_serviceUrl"> +<h3>Property: aso:serviceUrl</h3> +<em>serviceUrl</em> - the url of the Web Service in the contextual information.<br /><table> + <tr><th>Status:</th> + <td>unstable</td></tr> + <tr><th>Domain:</th> + <td><a href="#term_Service">aso:Service</a></td></tr> + <tr><th>Range:</th> + <td>http://www.w3.org/2000/01/rdf-schema#Literal</td></tr> +</table> +</div> + + + +<div class="specterm" id="term_summary"> +<h3>Property: aso:summary</h3> +<em>summary</em> - an introduction to or a summary of the full content (optional) for Article, a short description as provided by its organiser for Event, included as the content of the atom:summary element.<br /><table> + <tr><th>Status:</th> + <td>unstable</td></tr> + <tr><th>Domain:</th> + <td><a href="#term_Article">aso:Article</a> | <a href="#term_Event">aso:Event</a></td></tr> + <tr><th>Range:</th> + <td>http://www.w3.org/2000/01/rdf-schema#Literal</td></tr> +</table> +</div> + +<br/> + + +<div class="specterm" id="term_startDateAndTime"> +<h3>Property: aso:startDateAndTime</h3> +<em>startDate</em> - the date and time that the event begins. Included via a cal:dtstart element as defined in xCal.<br /><table> + <tr><th>Status:</th> + <td>unstable</td></tr> + <tr><th>Domain:</th> + <td><a href="#term_Event">aso:Event</a></td></tr> + <tr><th>Range:</th> + <td>http://www.w3.org/2000/01/rdf-schema#Literal</td></tr> +</table> +</div> + +<br/> + +<div class="specterm" id="term_targetName"> +<h3>Property: aso:targetName</h3> +<em>targetName</em> - the name of the item that is the target of the bookmark. Represented as the value of the title attribute on the atom:link element from which the target URL was obtained. +<br /><table> + <tr><th>Status:</th> + <td>unstable</td></tr> + <tr><th>Domain:</th> + <td><a href="#term_Bookmark">aso:Bookmark</a></td></tr> + <tr><th>Range:</th> + <td>http://www.w3.org/2000/01/rdf-schema#Literal</td></tr> +</table> +</div> + +<br/> + + +<div class="specterm" id="term_targetUrl"> +<h3>Property: aso:targetUrl</h3> +<em>targetUrl</em> - the URL of the item that is the target of the bookmark. Represented as the value of the href attribute on an atom:link element with rel "related".<br /><table> + <tr><th>Status:</th> + <td>unstable</td></tr> + <tr><th>Domain:</th> + <td><a href="#term_Bookmark">aso:Bookmark</a></td></tr> + <tr><th>Range:</th> + <td>http://www.w3.org/2000/01/rdf-schema#Literal</td></tr> +</table> +</div> + +<br/> + + +<div class="specterm" id="term_thumbnail"> +<h3>Property: aso:thumbnail</h3> +<em>thumbnail</em> - the URL and metadata for a thumbnail version of the item. The URL is represented as the value of the href attribute on an atom:link element with rel preview and a type of either image/jpeg, image/png or image/gif. Publishers SHOULD include media:width and media:height attributes on the atom:link element describing the dimensions of the linked item.<br /><table> + <tr><th>Status:</th> + <td>unstable</td></tr> + <tr><th>Domain:</th> + <td><a href="#term_Bookmark">aso:Bookmark</a> | <a href="#term_MediaCollection">aso:MediaCollection</a> | <a href="#term_Photo">aso:Photo</a> | <a href="#term_Video">aso:Video</a></td></tr> + <tr><th>Range:</th> + <td>http://www.w3.org/2000/01/rdf-schema#Literal</td></tr> +</table> +</div> + +<br/> + + +<div class="specterm" id="term_url"> +<h3>Property: aso:url</h3> +<em>url</em> - the value of the href attribute on an atom:link element with a rel value of alternate and a type value of text/html. <br /><table> + <tr><th>Status:</th> + <td>unstable</td></tr> + <tr><th>Domain:</th> + <td><a href="#term_Actor">aso:Actor</a> | <a href="#term_Object">aso:Object</a></td></tr> + <tr><th>Range:</th> + <td>http://www.w3.org/2000/01/rdf-schema#Literal</td></tr> +</table> +</div> + +<br/> + + +<div class="specterm" id="term_videoStream"> +<h3>Property: aso:videoStream</h3> +<em>videoStream</em> - the URL and metadata for the video content itself. The URL is represented as the value of the href attribute on an atom:link element with rel enclosure and a type that matches video/*. +<br /><table> + <tr><th>Status:</th> + <td>unstable</td></tr> + <tr><th>Domain:</th> + <td><a href="#term_Video">aso:Video</a></td></tr> + <tr><th>Range:</th> + <td>http://www.w3.org/2000/01/rdf-schema#Literal</td></tr> +</table> +</div> + +<br/> + + + + + +<!-- end of termlist --> + + + + + + + + + + + + + + + + + + + <h3 id="sec-ack">Acknowledgments</h3> + + This work is based on the hard work done here: <br/><br/><a href="http://martin.atkins.me.uk/specs/activitystreams/activityschema">Activity Streams Schema</a> +<!-- This is the FOAF formal vocabulary description, expressed using W3C RDFS and OWL markup. --> +<!-- For more information about FOAF: --> +<!-- see the FOAF project homepage, http://www.foaf-project.org/ --> +<!-- FOAF specification, http://xmlns.com/foaf/spec/ --> +<!-- --> +<!-- first we introduce a number of RDF namespaces we will be using... --> +<rdf:RDF + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" + xmlns:owl="http://www.w3.org/2002/07/owl#" + xmlns:vs="http://www.w3.org/2003/06/sw-vocab-status/ns#" + xmlns:foaf="http://xmlns.com/foaf/0.1/" + xmlns:wot="http://xmlns.com/wot/0.1/" + xmlns:dc="http://purl.org/dc/elements/1.1/"> +<!-- Here we describe general characteristics of the FOAF vocabulary ('ontology'). --> + <owl:Ontology rdf:about="http://xmlns.com/foaf/0.1/" dc:title="Friend of a Friend (FOAF) vocabulary" dc:description="The Friend of a Friend (FOAF) RDF vocabulary, described using W3C RDF Schema and the Web Ontology Language." dc:date="$Date$"> + +<!-- outdated <rdfs:seeAlso rdf:resource="http://www.w3.org/2001/08/rdfweb/foaf"/> --> +<!-- unfashionable, removing... + <owl:imports rdf:resource="http://www.w3.org/2000/01/rdf-schema"/> + <owl:imports rdf:resource="http://www.w3.org/2002/07/owl"/> --> + + <wot:assurance rdf:resource="../foafsig"/> + <wot:src_assurance rdf:resource="../htmlfoafsig"/> + </owl:Ontology> + + + <!-- OWL/RDF interop section - geeks only --> + <!-- most folk can ignore this lot. the game here is to make FOAF + work with vanilla RDF/RDFS tools, and with the stricter OWL DL + profile of OWL. At the moment we're in the OWL Full flavour of OWL. + The following are tricks to try have the spec live in both worlds + at once. See + http://phoebus.cs.man.ac.uk:9999/OWL/Validator + http://www.mindswap.org/2003/pellet/demo.shtml + ...for some tools that help. --> + <owl:AnnotationProperty rdf:about="http://xmlns.com/wot/0.1/assurance"/> + <owl:AnnotationProperty rdf:about="http://xmlns.com/wot/0.1/src_assurance"/> + <owl:AnnotationProperty rdf:about="http://www.w3.org/2003/06/sw-vocab-status/ns#term_status"/> + <!-- DC terms are NOT annotation properties in general, so we consider the following + claims scoped to this document. They may be removed in future revisions if + OWL tools become more flexible. --> + <owl:AnnotationProperty rdf:about="http://purl.org/dc/elements/1.1/description"/> + <owl:AnnotationProperty rdf:about="http://purl.org/dc/elements/1.1/title"/> + <owl:AnnotationProperty rdf:about="http://purl.org/dc/elements/1.1/date"/> + <owl:Class rdf:about="http://www.w3.org/2000/01/rdf-schema#Class"/> + +<!-- <owl:Class rdf:about="http://www.w3.org/2000/01/rdf-schema#Resource"/> + <owl:Class rdf:about="http://www.w3.org/2000/01/rdf-schema#Literal"/> --> + <!-- end of OWL/RDF interop voodoo. mostly. --> + + +<!-- FOAF classes (types) are listed first. --> + + <rdfs:Class rdf:about="http://xmlns.com/foaf/0.1/Person" rdfs:label="Person" rdfs:comment="A person." vs:term_status="stable"> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#Class"/> + <rdfs:subClassOf><owl:Class rdf:about="http://xmlns.com/wordnet/1.6/Person"/></rdfs:subClassOf> + <rdfs:subClassOf><owl:Class rdf:about="http://xmlns.com/foaf/0.1/Agent"/></rdfs:subClassOf> + <rdfs:subClassOf><owl:Class rdf:about="http://xmlns.com/wordnet/1.6/Agent"/></rdfs:subClassOf> + <rdfs:subClassOf><owl:Class rdf:about="http://www.w3.org/2000/10/swap/pim/contact#Person"/></rdfs:subClassOf> + <rdfs:subClassOf><owl:Class rdf:about="http://www.w3.org/2003/01/geo/wgs84_pos#SpatialThing"/></rdfs:subClassOf> + <!-- aside: + are spatial things always spatially located? + Person includes imaginary people... discuss... --> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + <owl:disjointWith rdf:resource="http://xmlns.com/foaf/0.1/Document"/> + <owl:disjointWith rdf:resource="http://xmlns.com/foaf/0.1/Organization"/> + <owl:disjointWith rdf:resource="http://xmlns.com/foaf/0.1/Project"/> + </rdfs:Class> + <rdfs:Class rdf:about="http://xmlns.com/foaf/0.1/Document" rdfs:label="Document" rdfs:comment="A document." vs:term_status="testing"> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#Class"/> + <rdfs:subClassOf rdf:resource="http://xmlns.com/wordnet/1.6/Document"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + <owl:disjointWith rdf:resource="http://xmlns.com/foaf/0.1/Organization"/> + <owl:disjointWith rdf:resource="http://xmlns.com/foaf/0.1/Person"/> + <owl:disjointWith rdf:resource="http://xmlns.com/foaf/0.1/Project"/> + </rdfs:Class> + <rdfs:Class rdf:about="http://xmlns.com/foaf/0.1/Organization" rdfs:label="Organization" rdfs:comment="An organization." vs:term_status="stable"> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#Class"/> + <rdfs:subClassOf><owl:Class rdf:about="http://xmlns.com/wordnet/1.6/Organization"/></rdfs:subClassOf> + <rdfs:subClassOf rdf:resource="http://xmlns.com/foaf/0.1/Agent"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + <owl:disjointWith rdf:resource="http://xmlns.com/foaf/0.1/Person"/> + <owl:disjointWith rdf:resource="http://xmlns.com/foaf/0.1/Document"/> + </rdfs:Class> + <rdfs:Class rdf:about="http://xmlns.com/foaf/0.1/Group" vs:term_status="stable" rdfs:label="Group" rdfs:comment="A class of Agents."> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#Class"/> + <rdfs:subClassOf rdf:resource="http://xmlns.com/foaf/0.1/Agent"/> + </rdfs:Class> + <rdfs:Class rdf:about="http://xmlns.com/foaf/0.1/Agent" vs:term_status="stable" rdfs:label="Agent" rdfs:comment="An agent (eg. person, group, software or physical artifact)."> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#Class"/> + <rdfs:subClassOf><owl:Class rdf:about="http://xmlns.com/wordnet/1.6/Agent-3"/></rdfs:subClassOf> + <owl:disjointWith rdf:resource="http://xmlns.com/foaf/0.1/Document"/> + </rdfs:Class> + <rdfs:Class rdf:about="http://xmlns.com/foaf/0.1/Project" vs:term_status="unstable" rdfs:label="Project" rdfs:comment="A project (a collective endeavour of some kind)."> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#Class"/> + <rdfs:subClassOf><owl:Class rdf:about="http://xmlns.com/wordnet/1.6/Project"/></rdfs:subClassOf> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + <owl:disjointWith rdf:resource="http://xmlns.com/foaf/0.1/Person"/> + <owl:disjointWith rdf:resource="http://xmlns.com/foaf/0.1/Document"/> +<!-- arguably a subclass of Agent; to be discussed --> + </rdfs:Class> + <rdfs:Class rdf:about="http://xmlns.com/foaf/0.1/Image" vs:term_status="testing" rdfs:label="Image" rdfs:comment="An image."> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#Class"/> + <rdfs:subClassOf><owl:Class rdf:about="http://xmlns.com/wordnet/1.6/Document"/></rdfs:subClassOf> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + </rdfs:Class> + + <rdfs:Class rdf:about="http://xmlns.com/foaf/0.1/PersonalProfileDocument" rdfs:label="PersonalProfileDocument" rdfs:comment="A personal profile RDF document." vs:term_status="testing"> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#Class"/> + <rdfs:subClassOf rdf:resource="http://xmlns.com/foaf/0.1/Document"/> + </rdfs:Class> + + <rdfs:Class rdf:about="http://xmlns.com/foaf/0.1/OnlineAccount" vs:term_status="unstable" rdfs:label="Online Account" rdfs:comment="An online account."> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#Class"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + <rdfs:subClassOf rdf:resource="http://www.w3.org/2002/07/owl#Thing"/> + </rdfs:Class> + <rdfs:Class rdf:about="http://xmlns.com/foaf/0.1/OnlineGamingAccount" vs:term_status="unstable" rdfs:label="Online Gaming Account" rdfs:comment="An online gaming account."> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#Class"/> + <rdfs:subClassOf rdf:resource="http://xmlns.com/foaf/0.1/OnlineAccount"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + </rdfs:Class> + <rdfs:Class rdf:about="http://xmlns.com/foaf/0.1/OnlineEcommerceAccount" vs:term_status="unstable" rdfs:label="Online E-commerce Account" rdfs:comment="An online e-commerce account."> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#Class"/> + <rdfs:subClassOf rdf:resource="http://xmlns.com/foaf/0.1/OnlineAccount"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + </rdfs:Class> + <rdfs:Class rdf:about="http://xmlns.com/foaf/0.1/OnlineChatAccount" vs:term_status="unstable" rdfs:label="Online Chat Account" rdfs:comment="An online chat account."> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#Class"/> + <rdfs:subClassOf rdf:resource="http://xmlns.com/foaf/0.1/OnlineAccount"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + </rdfs:Class> +<!-- FOAF properties (ie. relationships). --> + <rdf:Property rdf:about="http://xmlns.com/foaf/0.1/mbox" vs:term_status="stable" rdfs:label="personal mailbox" rdfs:comment="A +personal mailbox, ie. an Internet mailbox associated with exactly one owner, the first owner of this mailbox. This is a 'static inverse functional property', in that there is (across time and change) at most one individual that ever has any particular value for foaf:mbox."> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#InverseFunctionalProperty"/> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#ObjectProperty"/> + <rdfs:domain rdf:resource="http://xmlns.com/foaf/0.1/Agent"/> + <rdfs:range rdf:resource="http://www.w3.org/2002/07/owl#Thing"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + </rdf:Property> + <rdf:Property rdf:about="http://xmlns.com/foaf/0.1/mbox_sha1sum" vs:term_status="testing" rdfs:label="sha1sum of a personal mailbox URI name" rdfs:comment="The sha1sum of the URI of an Internet mailbox associated with exactly one owner, the first owner of the mailbox."> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#InverseFunctionalProperty"/> + +<!-- +put it back in again 2006-01-29 - see +http://chatlogs.planetrdf.com/swig/2006-01-29.html#T21-12-35 +I have mailed [email protected] for discussion. +Libby + +Commenting out as a kindness to OWL DL users. The semantics didn't quite cover +our usage anyway, since (a) we want static-across-time, which is so beyond OWL as +to be from another planet (b) we want identity reasoning invariant across xml:lang +tagging. FOAF code will know what to do. OWL folks note, this assertion might return. + +danbri +--> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#DatatypeProperty"/> + <rdfs:domain rdf:resource="http://xmlns.com/foaf/0.1/Agent"/> + <rdfs:range rdf:resource="http://www.w3.org/2000/01/rdf-schema#Literal"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + </rdf:Property> + + <rdf:Property rdf:about="http://xmlns.com/foaf/0.1/gender" vs:term_status="testing" +rdfs:label="gender" +rdfs:comment="The gender of this Agent (typically but not necessarily 'male' or 'female')."> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#FunctionalProperty"/> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#DatatypeProperty"/> + <rdfs:domain rdf:resource="http://xmlns.com/foaf/0.1/Agent"/> + <rdfs:range rdf:resource="http://www.w3.org/2000/01/rdf-schema#Literal"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + <!-- whatever one's gender is, and we are liberal in leaving room for more options + than 'male' and 'female', we model this so that an agent has only one gender. --> + </rdf:Property> + + + + <rdf:Property rdf:about="http://xmlns.com/foaf/0.1/geekcode" vs:term_status="testing" rdfs:label="geekcode" rdfs:comment="A textual geekcode for this person, see http://www.geekcode.com/geek.html"> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#DatatypeProperty"/> + <rdfs:domain rdf:resource="http://xmlns.com/foaf/0.1/Person"/> + <rdfs:range rdf:resource="http://www.w3.org/2000/01/rdf-schema#Literal"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + </rdf:Property> + <rdf:Property rdf:about="http://xmlns.com/foaf/0.1/dnaChecksum" vs:term_status="unstable" rdfs:label="DNA checksum" rdfs:comment="A checksum for the DNA of some thing. Joke."> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#DatatypeProperty"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + <rdfs:range rdf:resource="http://www.w3.org/2000/01/rdf-schema#Literal"/> + </rdf:Property> + <rdf:Property rdf:about="http://xmlns.com/foaf/0.1/sha1" vs:term_status="unstable" rdfs:label="sha1sum (hex)" rdfs:comment="A sha1sum hash, in hex."> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#DatatypeProperty"/> + <rdfs:domain rdf:resource="http://xmlns.com/foaf/0.1/Document"/> +<!-- rdf:type rdf:resource="http://www.w3.org/2002/07/owl#InverseFunctionalProperty" --> +<!-- IFP under discussion --> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + </rdf:Property> + <rdf:Property rdf:about="http://xmlns.com/foaf/0.1/based_near" vs:term_status="unstable" rdfs:label="based near" rdfs:comment="A location that something is based near, for some broadly human notion of near."> +<!-- see http://esw.w3.org/topic/GeoOnion for extension ideas --> +<!-- this was ranged as Agent... hmm --> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#ObjectProperty"/> + <rdfs:domain rdf:resource="http://www.w3.org/2003/01/geo/wgs84_pos#SpatialThing"/> + <rdfs:range rdf:resource="http://www.w3.org/2003/01/geo/wgs84_pos#SpatialThing"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + </rdf:Property> +<!-- FOAF naming properties --> + <rdf:Property rdf:about="http://xmlns.com/foaf/0.1/title" vs:term_status="testing" rdfs:label="title" rdfs:comment="Title (Mr, Mrs, Ms, Dr. etc)"> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#DatatypeProperty"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + </rdf:Property> + <rdf:Property rdf:about="http://xmlns.com/foaf/0.1/nick" vs:term_status="testing" rdfs:label="nickname" rdfs:comment="A short informal nickname characterising an agent (includes login identifiers, IRC and other chat nicknames)."> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#DatatypeProperty"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + </rdf:Property> +<!-- ......................... chat IDs ........................... --> + <rdf:Property rdf:about="http://xmlns.com/foaf/0.1/jabberID" vs:term_status="testing" rdfs:label="jabber ID" rdfs:comment="A jabber ID for something."> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> +<!-- + <rdfs:subPropertyOf rdf:resource="http://xmlns.com/foaf/0.1/nick"/> +...different to the other IM IDs, as Jabber has wider usage, so +we don't want the implied rdfs:domain here. + +--> + <rdfs:domain rdf:resource="http://xmlns.com/foaf/0.1/Agent"/> + <rdfs:range rdf:resource="http://www.w3.org/2000/01/rdf-schema#Literal"/> + <!-- there is a case for using resources/URIs here, ... --> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#DatatypeProperty"/> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#InverseFunctionalProperty"/> + </rdf:Property> + <rdf:Property rdf:about="http://xmlns.com/foaf/0.1/aimChatID" vs:term_status="testing" rdfs:label="AIM chat ID" rdfs:comment="An AIM chat ID"> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#DatatypeProperty"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + <rdfs:subPropertyOf rdf:resource="http://xmlns.com/foaf/0.1/nick"/> + <rdfs:domain rdf:resource="http://xmlns.com/foaf/0.1/Agent"/> + <rdfs:range rdf:resource="http://www.w3.org/2000/01/rdf-schema#Literal"/> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#InverseFunctionalProperty"/> + </rdf:Property> +<!-- http://www.stud.uni-karlsruhe.de/~uck4/ICQ/Packet-112.html --> + <rdf:Property rdf:about="http://xmlns.com/foaf/0.1/icqChatID" vs:term_status="testing" rdfs:label="ICQ chat ID" rdfs:comment="An ICQ chat ID"> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#DatatypeProperty"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + <rdfs:subPropertyOf rdf:resource="http://xmlns.com/foaf/0.1/nick"/> + <rdfs:domain rdf:resource="http://xmlns.com/foaf/0.1/Agent"/> + <rdfs:range rdf:resource="http://www.w3.org/2000/01/rdf-schema#Literal"/> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#InverseFunctionalProperty"/> + </rdf:Property> + <rdf:Property rdf:about="http://xmlns.com/foaf/0.1/yahooChatID" vs:term_status="testing" rdfs:label="Yahoo chat ID" rdfs:comment="A Yahoo chat ID"> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#DatatypeProperty"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + <rdfs:subPropertyOf rdf:resource="http://xmlns.com/foaf/0.1/nick"/> + <rdfs:domain rdf:resource="http://xmlns.com/foaf/0.1/Agent"/> + <rdfs:range rdf:resource="http://www.w3.org/2000/01/rdf-schema#Literal"/> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#InverseFunctionalProperty"/> + </rdf:Property> + <rdf:Property rdf:about="http://xmlns.com/foaf/0.1/msnChatID" vs:term_status="testing" rdfs:label="MSN chat ID" rdfs:comment="An MSN chat ID"> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#DatatypeProperty"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + <rdfs:subPropertyOf rdf:resource="http://xmlns.com/foaf/0.1/nick"/> + <rdfs:domain rdf:resource="http://xmlns.com/foaf/0.1/Agent"/> + <rdfs:range rdf:resource="http://www.w3.org/2000/01/rdf-schema#Literal"/> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#InverseFunctionalProperty"/> + </rdf:Property> +<!-- ....................................................... --> + <rdf:Property rdf:about="http://xmlns.com/foaf/0.1/name" vs:term_status="testing" rdfs:label="name" rdfs:comment="A name for some thing."> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#DatatypeProperty"/> + <rdfs:domain rdf:resource="http://www.w3.org/2002/07/owl#Thing"/> + <rdfs:range rdf:resource="http://www.w3.org/2000/01/rdf-schema#Literal"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + <rdfs:subPropertyOf rdf:resource="http://www.w3.org/2000/01/rdf-schema#label"/> + </rdf:Property> + <rdf:Property rdf:about="http://xmlns.com/foaf/0.1/firstName" vs:term_status="testing" rdfs:label="firstName" rdfs:comment="The first name of a person."> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#DatatypeProperty"/> + <rdfs:domain rdf:resource="http://xmlns.com/foaf/0.1/Person"/> + <rdfs:range rdf:resource="http://www.w3.org/2000/01/rdf-schema#Literal"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + </rdf:Property> + <rdf:Property rdf:about="http://xmlns.com/foaf/0.1/givenname" vs:term_status="testing" rdfs:label="Given name" rdfs:comment="The given name of some person."> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#DatatypeProperty"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + </rdf:Property> + <rdf:Property rdf:about="http://xmlns.com/foaf/0.1/surname" vs:term_status="testing" rdfs:label="Surname" rdfs:comment="The surname of some person."> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#DatatypeProperty"/> + <rdfs:domain rdf:resource="http://xmlns.com/foaf/0.1/Person"/> + <rdfs:range rdf:resource="http://www.w3.org/2000/01/rdf-schema#Literal"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + </rdf:Property> + <rdf:Property rdf:about="http://xmlns.com/foaf/0.1/family_name" vs:term_status="testing" rdfs:label="family_name" rdfs:comment="The family_name of some person."> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#DatatypeProperty"/> + <rdfs:domain rdf:resource="http://xmlns.com/foaf/0.1/Person"/> + <rdfs:domain rdf:resource="http://xmlns.com/foaf/0.1/Person"/> + <rdfs:range rdf:resource="http://www.w3.org/2000/01/rdf-schema#Literal"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + </rdf:Property> +<!-- end of naming properties. See http://rdfweb.org/issues/show_bug.cgi?id=7 + for open issue / re-design discussions. + --> + <rdf:Property rdf:about="http://xmlns.com/foaf/0.1/phone" vs:term_status="testing" rdfs:label="phone" rdfs:comment="A phone, specified using fully qualified tel: URI scheme (refs: http://www.w3.org/Addressing/schemes.html#tel)."> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#ObjectProperty"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + </rdf:Property> + <rdf:Property rdf:about="http://xmlns.com/foaf/0.1/homepage" vs:term_status="stable" rdfs:label="homepage" rdfs:comment="A homepage for some thing."> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#ObjectProperty"/> + <rdfs:subPropertyOf rdf:resource="http://xmlns.com/foaf/0.1/page"/> + <rdfs:subPropertyOf rdf:resource="http://xmlns.com/foaf/0.1/isPrimaryTopicOf"/> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#InverseFunctionalProperty"/> + <!-- previously: rdfs:domain rdf:resource="http://xmlns.com/foaf/0.1/Agent" --> + <rdfs:domain rdf:resource="http://www.w3.org/2002/07/owl#Thing"/> + <rdfs:range rdf:resource="http://xmlns.com/foaf/0.1/Document"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + </rdf:Property> + <rdf:Property rdf:about="http://xmlns.com/foaf/0.1/weblog" vs:term_status="testing" rdfs:label="weblog" rdfs:comment="A weblog of some thing (whether person, group, company etc.)."> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#ObjectProperty"/> + <rdfs:subPropertyOf rdf:resource="http://xmlns.com/foaf/0.1/page"/> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#InverseFunctionalProperty"/> + <rdfs:domain rdf:resource="http://xmlns.com/foaf/0.1/Agent"/> + <rdfs:range rdf:resource="http://xmlns.com/foaf/0.1/Document"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + </rdf:Property> + + <rdf:Property rdf:about="http://xmlns.com/foaf/0.1/openid" vs:term_status="unstable" rdfs:label="openid" rdfs:comment="An OpenID +for an Agent."> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#ObjectProperty"/> + <rdfs:subPropertyOf rdf:resource="http://xmlns.com/foaf/0.1/isPrimaryTopicOf"/> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#InverseFunctionalProperty"/> + <rdfs:domain rdf:resource="http://xmlns.com/foaf/0.1/Agent"/> + <rdfs:range rdf:resource="http://xmlns.com/foaf/0.1/Document"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + </rdf:Property> + + + + <rdf:Property rdf:about="http://xmlns.com/foaf/0.1/tipjar" vs:term_status="testing" rdfs:label="tipjar" rdfs:comment="A tipjar document for this agent, describing means for payment and reward."> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#ObjectProperty"/> + <rdfs:subPropertyOf rdf:resource="http://xmlns.com/foaf/0.1/page"/> + <rdfs:domain rdf:resource="http://xmlns.com/foaf/0.1/Agent"/> + <rdfs:range rdf:resource="http://xmlns.com/foaf/0.1/Document"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + </rdf:Property> + <rdf:Property rdf:about="http://xmlns.com/foaf/0.1/plan" vs:term_status="testing" rdfs:label="plan" rdfs:comment="A .plan comment, in the tradition of finger and '.plan' files."> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#DatatypeProperty"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + <rdfs:domain rdf:resource="http://xmlns.com/foaf/0.1/Person"/> + <rdfs:range rdf:resource="http://www.w3.org/2000/01/rdf-schema#Literal"/> + </rdf:Property> + <rdf:Property rdf:about="http://xmlns.com/foaf/0.1/made" vs:term_status="stable" rdfs:label="made" rdfs:comment="Something that was made by this agent."> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#ObjectProperty"/> + <rdfs:domain rdf:resource="http://xmlns.com/foaf/0.1/Agent"/> + <rdfs:range rdf:resource="http://www.w3.org/2002/07/owl#Thing"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + <owl:inverseOf rdf:resource="http://xmlns.com/foaf/0.1/maker"/> + </rdf:Property> + <rdf:Property rdf:about="http://xmlns.com/foaf/0.1/maker" vs:term_status="stable" rdfs:label="maker" rdfs:comment="An agent that +made this thing."> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#ObjectProperty"/> + <rdfs:domain rdf:resource="http://www.w3.org/2002/07/owl#Thing"/> + <rdfs:range rdf:resource="http://xmlns.com/foaf/0.1/Agent"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + <owl:inverseOf rdf:resource="http://xmlns.com/foaf/0.1/made"/> + </rdf:Property> + <rdf:Property rdf:about="http://xmlns.com/foaf/0.1/img" vs:term_status="testing" rdfs:label="image" rdfs:comment="An image that can be used to represent some thing (ie. those depictions which are particularly representative of something, eg. one's photo on a homepage)."> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#ObjectProperty"/> + <rdfs:domain rdf:resource="http://xmlns.com/foaf/0.1/Person"/> + <rdfs:range rdf:resource="http://xmlns.com/foaf/0.1/Image"/> + <rdfs:subPropertyOf rdf:resource="http://xmlns.com/foaf/0.1/depiction"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + </rdf:Property> + <rdf:Property rdf:about="http://xmlns.com/foaf/0.1/depiction" vs:term_status="testing" rdfs:label="depiction" rdfs:comment="A depiction of some thing."> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#ObjectProperty"/> + <rdfs:domain rdf:resource="http://www.w3.org/2002/07/owl#Thing"/> + <rdfs:range rdf:resource="http://xmlns.com/foaf/0.1/Image"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + <owl:inverseOf rdf:resource="http://xmlns.com/foaf/0.1/depicts"/> + </rdf:Property> + <rdf:Property rdf:about="http://xmlns.com/foaf/0.1/depicts" vs:term_status="testing" rdfs:label="depicts" rdfs:comment="A thing depicted in this representation."> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#ObjectProperty"/> + <rdfs:range rdf:resource="http://www.w3.org/2002/07/owl#Thing"/> + <rdfs:domain rdf:resource="http://xmlns.com/foaf/0.1/Image"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + <owl:inverseOf rdf:resource="http://xmlns.com/foaf/0.1/depiction"/> + </rdf:Property> + <rdf:Property rdf:about="http://xmlns.com/foaf/0.1/thumbnail" vs:term_status="testing" rdfs:label="thumbnail" rdfs:comment="A derived thumbnail image."> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#ObjectProperty"/> + <rdfs:domain rdf:resource="http://xmlns.com/foaf/0.1/Image"/> + <rdfs:range rdf:resource="http://xmlns.com/foaf/0.1/Image"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + </rdf:Property> + <rdf:Property rdf:about="http://xmlns.com/foaf/0.1/myersBriggs" vs:term_status="testing" rdfs:label="myersBriggs" rdfs:comment="A Myers Briggs (MBTI) personality classification."> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#ObjectProperty"/> + <rdfs:domain rdf:resource="http://xmlns.com/foaf/0.1/Person"/> + <rdfs:range rdf:resource="http://www.w3.org/2000/01/rdf-schema#Literal"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + </rdf:Property> + <rdf:Property rdf:about="http://xmlns.com/foaf/0.1/workplaceHomepage" vs:term_status="testing" rdfs:label="workplace homepage" rdfs:comment="A workplace homepage of some person; the homepage of an organization they work for."> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#ObjectProperty"/> + <rdfs:domain rdf:resource="http://xmlns.com/foaf/0.1/Person"/> + <rdfs:range rdf:resource="http://xmlns.com/foaf/0.1/Document"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + </rdf:Property> + <rdf:Property rdf:about="http://xmlns.com/foaf/0.1/workInfoHomepage" vs:term_status="testing" rdfs:label="work info homepage" rdfs:comment="A work info homepage of some person; a page about their work for some organization."> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#ObjectProperty"/> + <rdfs:domain rdf:resource="http://xmlns.com/foaf/0.1/Person"/> + <rdfs:range rdf:resource="http://xmlns.com/foaf/0.1/Document"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + </rdf:Property> + <rdf:Property rdf:about="http://xmlns.com/foaf/0.1/schoolHomepage" vs:term_status="testing" rdfs:label="schoolHomepage" rdfs:comment="A homepage of a school attended by the person."> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#ObjectProperty"/> + <rdfs:domain rdf:resource="http://xmlns.com/foaf/0.1/Person"/> + <rdfs:range rdf:resource="http://xmlns.com/foaf/0.1/Document"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + </rdf:Property> + <rdf:Property rdf:about="http://xmlns.com/foaf/0.1/knows" vs:term_status="testing" rdfs:label="knows" rdfs:comment="A person known by this person (indicating some level of reciprocated interaction between the parties)."> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#ObjectProperty"/> + <rdfs:domain rdf:resource="http://xmlns.com/foaf/0.1/Person"/> + <rdfs:range rdf:resource="http://xmlns.com/foaf/0.1/Person"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + </rdf:Property> + <rdf:Property rdf:about="http://xmlns.com/foaf/0.1/interest" vs:term_status="testing" rdfs:label="interest" rdfs:comment="A page about a topic of interest to this person."> +<!-- we should distinguish the page from the topic more carefully. danbri 2002-07-08 --> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#ObjectProperty"/> + <rdfs:domain rdf:resource="http://xmlns.com/foaf/0.1/Person"/> + <rdfs:range rdf:resource="http://xmlns.com/foaf/0.1/Document"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + </rdf:Property> + <rdf:Property rdf:about="http://xmlns.com/foaf/0.1/topic_interest" vs:term_status="testing" rdfs:label="interest_topic" rdfs:comment="A thing of interest to this person."> +<!-- we should distinguish the page from the topic more carefully. danbri 2002-07-08 --> +<!-- foaf:interest_topic(P,R) + always true whenever + foaf:interest(P,D), foaf:topic(D,R) + ie. a person has a foaf:topic_interest in all things + that are the foaf:topic of pages they have a foaf:interest in. + hmm, does this mean i'm forced to be interested in all the things that are the + topic of a page i'm interested in. thats a strong restriction on foaf:topic's utility. --> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#ObjectProperty"/> + <rdfs:domain rdf:resource="http://xmlns.com/foaf/0.1/Person"/> + <rdfs:range rdf:resource="http://www.w3.org/2002/07/owl#Thing"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + </rdf:Property> + <rdf:Property rdf:about="http://xmlns.com/foaf/0.1/publications" vs:term_status="unstable" rdfs:label="publications" rdfs:comment="A link to the publications of this person."> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#ObjectProperty"/> + <rdfs:domain rdf:resource="http://xmlns.com/foaf/0.1/Person"/> + <rdfs:range rdf:resource="http://xmlns.com/foaf/0.1/Document"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + </rdf:Property> +<!-- by libby for ILRT mappings 2001-10-31 --> + <rdf:Property rdf:about="http://xmlns.com/foaf/0.1/currentProject" vs:term_status="testing" rdfs:label="current project" rdfs:comment="A current project this person works on."> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#ObjectProperty"/> + <rdfs:domain rdf:resource="http://xmlns.com/foaf/0.1/Person"/> + <rdfs:range rdf:resource="http://www.w3.org/2002/07/owl#Thing"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + </rdf:Property> + <rdf:Property rdf:about="http://xmlns.com/foaf/0.1/pastProject" vs:term_status="testing" rdfs:label="past project" rdfs:comment="A project this person has previously worked on."> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#ObjectProperty"/> + <rdfs:domain rdf:resource="http://xmlns.com/foaf/0.1/Person"/> + <rdfs:range rdf:resource="http://www.w3.org/2002/07/owl#Thing"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + </rdf:Property> + <rdf:Property rdf:about="http://xmlns.com/foaf/0.1/fundedBy" vs:term_status="unstable" rdfs:label="funded by" rdfs:comment="An organization funding a project or person."> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#ObjectProperty"/> + <rdfs:domain rdf:resource="http://www.w3.org/2002/07/owl#Thing"/> + <rdfs:range rdf:resource="http://www.w3.org/2002/07/owl#Thing"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + </rdf:Property> + <rdf:Property rdf:about="http://xmlns.com/foaf/0.1/logo" vs:term_status="testing" rdfs:label="logo" rdfs:comment="A logo representing some thing."> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#ObjectProperty"/> + <rdfs:domain rdf:resource="http://www.w3.org/2002/07/owl#Thing"/> + <rdfs:range rdf:resource="http://www.w3.org/2002/07/owl#Thing"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + </rdf:Property> + <rdf:Property rdf:about="http://xmlns.com/foaf/0.1/topic" vs:term_status="testing" rdfs:label="topic" rdfs:comment="A topic of some page or document."> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#ObjectProperty"/> + <rdfs:domain rdf:resource="http://xmlns.com/foaf/0.1/Document"/> + <rdfs:range rdf:resource="http://www.w3.org/2002/07/owl#Thing"/> + <owl:inverseOf rdf:resource="http://xmlns.com/foaf/0.1/page"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + </rdf:Property> + <rdf:Property rdf:about="http://xmlns.com/foaf/0.1/primaryTopic" + vs:term_status="testing" rdfs:label="primary topic" rdfs:comment="The primary topic of some page or document."> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#FunctionalProperty"/> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#ObjectProperty"/> + <rdfs:domain rdf:resource="http://xmlns.com/foaf/0.1/Document"/> + <rdfs:range rdf:resource="http://www.w3.org/2002/07/owl#Thing"/> + <owl:inverseOf rdf:resource="http://xmlns.com/foaf/0.1/isPrimaryTopicOf"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + </rdf:Property> + + <rdf:Property rdf:about="http://xmlns.com/foaf/0.1/isPrimaryTopicOf" + vs:term_status="testing" rdfs:label="is primary topic of" rdfs:comment="A document that this thing is the primary topic of."> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#InverseFunctionalProperty"/> + <rdfs:subPropertyOf rdf:resource="http://xmlns.com/foaf/0.1/page"/> + <owl:inverseOf rdf:resource="http://xmlns.com/foaf/0.1/primaryTopic"/> + <rdfs:domain rdf:resource="http://www.w3.org/2002/07/owl#Thing"/> + <rdfs:range rdf:resource="http://xmlns.com/foaf/0.1/Document"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + </rdf:Property> + + <rdf:Property rdf:about="http://xmlns.com/foaf/0.1/page" vs:term_status="testing" rdfs:label="page" rdfs:comment="A page or document about this thing."> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#ObjectProperty"/> + <rdfs:domain rdf:resource="http://www.w3.org/2002/07/owl#Thing"/> + <rdfs:range rdf:resource="http://xmlns.com/foaf/0.1/Document"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + <owl:inverseOf rdf:resource="http://xmlns.com/foaf/0.1/topic"/> + </rdf:Property> + <rdf:Property rdf:about="http://xmlns.com/foaf/0.1/theme" vs:term_status="unstable" rdfs:label="theme" rdfs:comment="A theme."> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#ObjectProperty"/> + <rdfs:domain rdf:resource="http://www.w3.org/2002/07/owl#Thing"/> + <rdfs:range rdf:resource="http://www.w3.org/2002/07/owl#Thing"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + </rdf:Property> + <rdf:Property rdf:about="http://xmlns.com/foaf/0.1/holdsAccount" vs:term_status="unstable" rdfs:label="holds account" rdfs:comment="Indicates an account held by this agent."> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#ObjectProperty"/> + <rdfs:domain rdf:resource="http://xmlns.com/foaf/0.1/Agent"/> + <rdfs:range rdf:resource="http://xmlns.com/foaf/0.1/OnlineAccount"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + </rdf:Property> + <rdf:Property rdf:about="http://xmlns.com/foaf/0.1/accountServiceHomepage" vs:term_status="unstable" rdfs:label="account service homepage" rdfs:comment="Indicates a homepage of the service provide for this online account."> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#ObjectProperty"/> + <rdfs:domain rdf:resource="http://xmlns.com/foaf/0.1/OnlineAccount"/> + <rdfs:range rdf:resource="http://xmlns.com/foaf/0.1/Document"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + </rdf:Property> + <rdf:Property rdf:about="http://xmlns.com/foaf/0.1/accountName" vs:term_status="unstable" rdfs:label="account name" rdfs:comment="Indicates the name (identifier) associated with this online account."> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#DatatypeProperty"/> + <rdfs:domain rdf:resource="http://xmlns.com/foaf/0.1/OnlineAccount"/> + <rdfs:range rdf:resource="http://www.w3.org/2000/01/rdf-schema#Literal"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + </rdf:Property> + <rdf:Property rdf:about="http://xmlns.com/foaf/0.1/member" vs:term_status="stable" rdfs:label="member" rdfs:comment="Indicates a member of a Group"> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#ObjectProperty"/> + <rdfs:domain rdf:resource="http://xmlns.com/foaf/0.1/Group"/> + <rdfs:range rdf:resource="http://xmlns.com/foaf/0.1/Agent"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + </rdf:Property> + + <rdf:Property rdf:about="http://xmlns.com/foaf/0.1/membershipClass" vs:term_status="unstable" rdfs:label="membershipClass" rdfs:comment="Indicates the class of individuals that are a member of a Group"> + <!-- maybe we should just use SPARQL or Rules, instead of trying to use OWL here --> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#AnnotationProperty"/> + <!-- Added to keep OWL DL from bluescreening. DON'T CROSS THE STREAMERS, etc. --> + <!-- This may get dropped if it means non-DL tools don't expose it as a real property. + Should be fine though; I think only OWL stuff cares about AnnotationProperty. + Dan --> + +<!-- <rdfs:domain rdf:resource="http://xmlns.com/foaf/0.1/Group"/> prose only for now...--> +<!-- <rdfs:range rdf:resource="http://www.w3.org/2000/01/rdf-schema#Class"/> --> +<!-- <rdfs:range rdf:resource="http://www.w3.org/2002/07/owl#Class"/> --> + + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + </rdf:Property> + + + <rdf:Property rdf:about="http://xmlns.com/foaf/0.1/birthday" vs:term_status="unstable" rdfs:label="birthday" rdfs:comment="The birthday of this Agent, represented in mm-dd string form, eg. '12-31'."> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#FunctionalProperty"/> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#DatatypeProperty"/> + <rdfs:domain rdf:resource="http://xmlns.com/foaf/0.1/Agent"/> + <rdfs:range rdf:resource="http://www.w3.org/2000/01/rdf-schema#Literal"/> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + </rdf:Property> + + +</rdf:RDF> + + + + <h2 id="sec-changes">Recent Changes</h2> + + +<h3>Previous Changes</h3> + +</body> +</html> \ No newline at end of file diff --git a/examples/activ-atom/index.rdf b/examples/activ-atom/index.rdf new file mode 100644 index 0000000..ac0dddf --- /dev/null +++ b/examples/activ-atom/index.rdf @@ -0,0 +1,555 @@ +<?xml version="1.0"?> +<rdf:RDF xmlns:event="http://purl.org/NET/c4dn/event.owl#" +xmlns:foaf="http://xmlns.com/foaf/0.1/" +xmlns:status="http://www.w3.org/2003/06/sw-vocab-status/ns#" +xmlns:owl="http://www.w3.org/2002/07/owl#" +xmlns:xsd="http://www.w3.org/2001/XMLSchema#" +xmlns:dc="http://purl.org/dc/elements/1.1/" +xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" +xmlns:vann="http://purl.org/vocab/vann/" +xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" +xmlns:skos="http://www.w3.org/2004/02/skos/core#" +xmlns:days="http://ontologi.es/days#" +xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" +xmlns:aas="http://xmlns.com/aas#"> + + <owl:Ontology rdf:about="http://xmlns.com/aas#"> + <vann:preferredNamespaceUri>http://xmlns.com/aas#</vann:preferredNamespaceUri> + <vann:preferredNamespacePrefix>aas</vann:preferredNamespacePrefix> + <dc:title>A mapping of Atom Activity Streams to RDF</dc:title> + <rdfs:comment>Draft vocabulary for mapping the Atom Activity streams work to RDF.</rdfs:comment> + <foaf:maker rdf:resource="http://it.linkedin.com/in/micheleminno"/> + <foaf:maker rdf:resource="http://identi.ca/user/30610"/> + </owl:Ontology> + + <rdfs:Class rdf:about="http://xmlns.com/aas#Activity"> + <status:term_status>unstable</status:term_status> + <rdfs:label>Activity</rdfs:label> + <rdfs:comment>A generic activity an agent performs on the web.</rdfs:comment> + </rdfs:Class> + <rdfs:Class rdf:about="http://xmlns.com/aas#Actor"> + <status:term_status>unstable</status:term_status> + <rdfs:label>Actor</rdfs:label> + <rdfs:comment>The agent who performs the activity, modelled as atom:author</rdfs:comment> + </rdfs:Class> + <rdfs:Class rdf:about="http://xmlns.com/aas#Annotation"> + <status:term_status>unstable</status:term_status> + <rdfs:label>Annotation</rdfs:label> + <rdfs:comment>an extra text-based note added to an activity by the user.</rdfs:comment> + </rdfs:Class> + <rdfs:Class rdf:about="http://xmlns.com/aas#Application"> + <rdfs:subClassOf rdf:resource="http://xmlns.com/aas#Actor"/> + <status:term_status>unstable</status:term_status> + <rdfs:label>Application</rdfs:label> + <rdfs:comment>An actor that is also an application @@can't find this in the spec@@.</rdfs:comment> + </rdfs:Class> + + <rdfs:Class rdf:about="http://xmlns.com/aas#Article"> + <status:term_status>unstable</status:term_status> + <rdfs:subClassOf rdf:resource="http://xmlns.com/aas#Object"/> + <rdfs:label>Article</rdfs:label> + <rdfs:comment>Articles generally consist of paragraphs of text, in some cases incorporating embedded media such as photos and inline hyperlinks to other resources.</rdfs:comment> + </rdfs:Class> + + <rdfs:Class rdf:about="http://xmlns.com/aas#Audio"> + <status:term_status>unstable</status:term_status> + <rdfs:subClassOf rdf:resource="http://xmlns.com/aas#Article"/> + <rdfs:label>Audio</rdfs:label> + <rdfs:comment>audio content.</rdfs:comment> + </rdfs:Class> + + <rdfs:Class rdf:about="http://xmlns.com/aas#Bookmark"> + <status:term_status>unstable</status:term_status> + <rdfs:subClassOf rdf:resource="http://xmlns.com/aas#Object"/> + <rdfs:label>Bookmark</rdfs:label> + <rdfs:comment>pointer to some URL -- typically a web page.</rdfs:comment> + </rdfs:Class> + + <rdfs:Class rdf:about="http://xmlns.com/aas#Comment"> + <status:term_status>unstable</status:term_status> + <rdfs:subClassOf rdf:resource="http://xmlns.com/aas#Object"/> + <rdfs:label>Comment</rdfs:label> + <rdfs:comment>a textual response to another object. The comment object type MUST NOT be used for other kinds of replies, such as video replies or reviews. If an object has no explicit type but the object element has a thr:in-reply-to element a consumer SHOULD consider that object to be a comment.</rdfs:comment> + </rdfs:Class> + <rdfs:Class rdf:about="http://xmlns.com/aas#Context"> + <status:term_status>unstable</status:term_status> + <rdfs:label>Context</rdfs:label> + <rdfs:comment>describes the context of an activity.</rdfs:comment> + </rdfs:Class> + <rdfs:Class rdf:about="http://xmlns.com/aas#Event"> + <status:term_status>unstable</status:term_status> + <rdfs:subClassOf rdf:resource="http://xmlns.com/aas#Object"/> + <owl:sameAs rdf:resource="http://purl.org/dc/dcmitype/Event"/> + <rdfs:label>Event</rdfs:label> + <rdfs:comment>an event that occurs in a certain place during a particular interval of time.</rdfs:comment> + </rdfs:Class> + + <rdfs:Class rdf:about="http://xmlns.com/aas#File"> + <status:term_status>unstable</status:term_status> + <rdfs:subClassOf rdf:resource="http://xmlns.com/aas#Object"/> + <rdfs:label>File</rdfs:label> + <rdfs:comment>some document or other file with no additional machine-readable semantics.</rdfs:comment> + </rdfs:Class> + <rdfs:Class rdf:about="http://xmlns.com/aas#Group"> + <status:term_status>unstable</status:term_status> + <rdfs:subClassOf rdf:resource="http://xmlns.com/aas#Object"/> + <owl:sameAs rdf:resource="http://xmlns.com/foaf/0.1/Group"/> + <rdfs:label>Group</rdfs:label> + <rdfs:comment>a collection of people which people can join and leave. </rdfs:comment> + </rdfs:Class> + <rdfs:Class rdf:about="http://xmlns.com/aas#GroupOfUsers"> + <status:term_status>unstable</status:term_status> + <rdfs:subClassOf rdf:resource="http://xmlns.com/aas#Actor"/> + <rdfs:label>GroupOfUsers</rdfs:label> + <rdfs:comment>An actor that is also a group of users. @@eh? and where's this from?@@</rdfs:comment> + </rdfs:Class> + <rdfs:Class rdf:about="http://xmlns.com/aas#Join"> + <status:term_status>unstable</status:term_status> + <rdfs:subClassOf rdf:resource="http://xmlns.com/aas#Verb"/> + <rdfs:label>Join</rdfs:label> + <rdfs:comment>the Actor has become a member of the Object. This specification only defines the meaning of this Verb when its Object is a group.</rdfs:comment> + </rdfs:Class> + <rdfs:Class rdf:about="http://xmlns.com/aas#Located"> + <status:term_status>unstable</status:term_status> + <rdfs:subClassOf rdf:resource="http://xmlns.com/aas#Verb"/> + <rdfs:label>Located</rdfs:label> + <rdfs:comment>the Actor is located in the Object.</rdfs:comment> + </rdfs:Class> + <rdfs:Class rdf:about="http://xmlns.com/aas#Location"> + <status:term_status>unstable</status:term_status> + <rdfs:subClassOf rdf:resource="http://xmlns.com/aas#Context"/> + <owl:sameAs rdf:resource="http://purl.org/dc/dcmitype/Location"/> + <rdfs:label>Location</rdfs:label> + <rdfs:comment>the location where the user was at the time the activity was performed. This may be an accurate geographic coordinate, a street address, a free-form location name or a combination of these.</rdfs:comment> + </rdfs:Class> + <rdfs:Class rdf:about="http://xmlns.com/aas#MediaCollection"> + <status:term_status>unstable</status:term_status> + <rdfs:subClassOf rdf:resource="http://xmlns.com/aas#Object"/> + <rdfs:label>MediaCollection</rdfs:label> + <rdfs:comment>Generic collection of media items.</rdfs:comment> + </rdfs:Class> + <rdfs:Class rdf:about="http://xmlns.com/aas#MediaContent"> + <status:term_status>unstable</status:term_status> + <rdfs:subClassOf rdf:resource="http://xmlns.com/aas#Object"/> + <rdfs:label>MediaContent</rdfs:label> + <rdfs:comment>a media item.</rdfs:comment> + </rdfs:Class> + <rdfs:Class rdf:about="http://xmlns.com/aas#MakeFriend"> + <status:term_status>unstable</status:term_status> + <rdfs:subClassOf rdf:resource="http://xmlns.com/aas#Verb"/> + <rdfs:label>MakeFriend</rdfs:label> + <rdfs:comment>the Actor sets the creation of a friendship that is reciprocated by the object.</rdfs:comment> + </rdfs:Class> + <rdfs:Class rdf:about="http://xmlns.com/aas#MarkAsFavorite"> + <status:term_status>unstable</status:term_status> + <rdfs:subClassOf rdf:resource="http://xmlns.com/aas#Verb"/> + <rdfs:label>MarkAsFavorite</rdfs:label> + <rdfs:comment>the Actor marked the Object as an item of special interest.</rdfs:comment> + </rdfs:Class> + <rdfs:Class rdf:about="http://xmlns.com/aas#Mood"> + <status:term_status>unstable</status:term_status> + <rdfs:subClassOf rdf:resource="http://xmlns.com/aas#Context"/> + <rdfs:label>Mood</rdfs:label> + <rdfs:comment>the mood of the user when the activity was performed. This is usually collected via an extra field in the user interface used to perform the activity. For the purpose of this schema, a mood is a freeform, short mood keyword or phrase along with an optional mood icon image.</rdfs:comment> + </rdfs:Class> + <rdfs:Class rdf:about="http://xmlns.com/aas#Note"> + <status:term_status>unstable</status:term_status> + <rdfs:subClassOf rdf:resource="http://xmlns.com/aas#Object"/> + <rdfs:label>Note</rdfs:label> + <rdfs:comment>is intended for use in "micro-blogging" and in systems where users are invited to publish a timestamped "status".</rdfs:comment> + </rdfs:Class> + <rdfs:Class rdf:about="http://xmlns.com/aas#Object"> + <status:term_status>unstable</status:term_status> + <rdfs:label>Object</rdfs:label> + <rdfs:comment>the generic object of the activity.</rdfs:comment> + </rdfs:Class> + <rdfs:Class rdf:about="http://xmlns.com/aas#Person"> + <status:term_status>unstable</status:term_status> + <rdfs:subClassOf rdf:resource="http://xmlns.com/aas#Object"/> + <owl:sameAs rdf:resource="http://xmlns.com/foaf/0.1/Person"/> + <rdfs:label>Person</rdfs:label> + <rdfs:comment>a user account. This is often a person, but might also be a company or ficticious character that is being represented by a user account.</rdfs:comment> + </rdfs:Class> + <rdfs:Class rdf:about="http://xmlns.com/aas#Photo"> + <status:term_status>unstable</status:term_status> + <rdfs:subClassOf rdf:resource="http://xmlns.com/aas#MediaContent"/> + <owl:sameAs rdf:resource="http://purl.org/dc/dcmitype/StillImage"/> + <rdfs:label>Photo</rdfs:label> + <rdfs:comment>a graphical still image.</rdfs:comment> + </rdfs:Class> + <rdfs:Class rdf:about="http://xmlns.com/aas#PhotoAlbum"> + <status:term_status>unstable</status:term_status> + <rdfs:subClassOf rdf:resource="http://xmlns.com/aas#MediaCollection"/> + <rdfs:label>PhotoAlbum</rdfs:label> + <rdfs:comment>a collection of images.</rdfs:comment> + </rdfs:Class> + <rdfs:Class rdf:about="http://xmlns.com/aas#Place"> + <status:term_status>unstable</status:term_status> + <rdfs:subClassOf rdf:resource="http://xmlns.com/aas#Object"/> + <owl:sameAs rdf:resource="http://purl.org/dc/dcmitype/Location"/> + <rdfs:label>Place</rdfs:label> + <rdfs:comment>a location on Earth. @@can this be same as Location if Location is also?@@</rdfs:comment> + </rdfs:Class> + <rdfs:Class rdf:about="http://xmlns.com/aas#Playlist"> + <status:term_status>unstable</status:term_status> + <rdfs:subClassOf rdf:resource="http://xmlns.com/aas#MediaCollection"/> + <rdfs:label>Playlist</rdfs:label> + <rdfs:comment>an ordered list of time-based media items, such as video and audio objects.</rdfs:comment> + </rdfs:Class> + <rdfs:Class rdf:about="http://xmlns.com/aas#Post"> + <status:term_status>unstable</status:term_status> + <rdfs:subClassOf rdf:resource="http://xmlns.com/aas#Verb"/> + <rdfs:label>describes the act of posting or publishing an Object on the web. The implication is that before this Activity occurred the Object was not posted, and after the Activity has occurred it is posted or published.</rdfs:label> + <rdfs:comment>@@sameAs sioc something?@@</rdfs:comment> + </rdfs:Class> + <rdfs:Class rdf:about="http://xmlns.com/aas#Replies"> + <status:term_status>unstable</status:term_status> + <rdfs:subClassOf rdf:resource="http://xmlns.com/aas#Context"/> + <rdfs:label>Replies</rdfs:label> + <rdfs:comment>Most social applications have a concept of "comments", "replies" or "responses" to social Objects. In many cases these are simple text messages, but any Object can in practice be a reply. A text-only reply SHOULD be represented using the comment object type. Replies of other types MUST carry the appropriate type and MUST NOT carry the comment object type. Replies, regardless of object type, SHOULD be represented using the thr:in-reply-to element. The act of posting a reply is represented by the post Verb as with "top-level" Objects.</rdfs:comment> + </rdfs:Class> + <rdfs:Class rdf:about="http://xmlns.com/aas#RSVP"> + <status:term_status>unstable</status:term_status> + <rdfs:subClassOf rdf:resource="http://xmlns.com/aas#Verb"/> + <rdfs:label>RSVP</rdfs:label> + <rdfs:comment>indicates that the actor has made a RSVP ("Répondez s'il vous plaît") for the object, that is, he/she replied to an invite. This specification only defines the meaning of this verb when its object is an event. The use of this Verb is only appropriate when the RSVP was created by an explicit action by the actor. It is not appropriate to use this verb when a user has been added as an attendee by an event organiser or administrator.</rdfs:comment> + </rdfs:Class> + <rdfs:Class rdf:about="http://xmlns.com/aas#Save"> + <status:term_status>unstable</status:term_status> + <rdfs:subClassOf rdf:resource="http://xmlns.com/aas#Verb"/> + <rdfs:label>Save</rdfs:label> + <rdfs:comment>the Actor has called out the Object as being of interest primarily to him- or herself. Though this action MAY be shared publicly, the implication is that the Object has been saved primarily for the actor's own benefit rather than to show it to others as would be indicated by the "share" Verb .</rdfs:comment> + </rdfs:Class> + <rdfs:Class rdf:about="http://xmlns.com/aas#Service"> + <status:term_status>unstable</status:term_status> + <rdfs:subClassOf rdf:resource="http://xmlns.com/aas#Context"/> + <rdfs:label>Service</rdfs:label> + <rdfs:comment>the Web Service where the activity is performed by the Actor.</rdfs:comment> + </rdfs:Class> + <rdfs:Class rdf:about="http://xmlns.com/aas#Share"> + <status:term_status>unstable</status:term_status> + <rdfs:subClassOf rdf:resource="http://xmlns.com/aas#Verb"/> + <rdfs:label>Share</rdfs:label> + <rdfs:comment>the Actor has called out the Object to readers. In most cases, the actor did not create the Object being shared, but is instead drawing attention to it.</rdfs:comment> + </rdfs:Class> + <rdfs:Class rdf:about="http://xmlns.com/aas#Song"> + <status:term_status>unstable</status:term_status> + <rdfs:subClassOf rdf:resource="http://xmlns.com/aas#Object"/> + <rdfs:label>Song</rdfs:label> + <rdfs:comment>a song or a recording of a song. Objects of type Song might contain information about the song or recording, or they might contain some representation of the recording itself. In the latter case, the song SHOULD also be annotated with the "audio" object type and use its properties. Type "song" SHOULD only be used when the publisher can guarantee that the object is a song rather than merely a generic audio stream.</rdfs:comment> + </rdfs:Class> + <rdfs:Class rdf:about="http://xmlns.com/aas#StartFollowing"> + <status:term_status>unstable</status:term_status> + <rdfs:subClassOf rdf:resource="http://xmlns.com/aas#Verb"/> + <rdfs:label>StartFollowing</rdfs:label> + <rdfs:comment>the Actor began following the activity of the Object. In most cases, the Object of this Verb will be a user, but it can potentially be of any type that can sensibly generate activity.</rdfs:comment> + </rdfs:Class> + <rdfs:Class rdf:about="http://xmlns.com/aas#Tag"> + <status:term_status>unstable</status:term_status> + <rdfs:subClassOf rdf:resource="http://xmlns.com/aas#Verb"/> + <rdfs:label>Tag</rdfs:label> + <rdfs:comment>the Actor has identified the presence of a Target inside an Object. The target of the "tag" verb gives the object in which the tag has been added. For example, if a user appears in a photo, the activity:object is the user and the activity:target is the photo.</rdfs:comment> + </rdfs:Class> + <rdfs:Class rdf:about="http://xmlns.com/aas#Time"> + <status:term_status>unstable</status:term_status> + <rdfs:subClassOf rdf:resource="http://xmlns.com/aas#Context"/> + <rdfs:label>Time</rdfs:label> + <rdfs:comment>contextual information about time</rdfs:comment> + </rdfs:Class> + <rdfs:Class rdf:about="http://xmlns.com/aas#User"> + <status:term_status>unstable</status:term_status> + <rdfs:subClassOf rdf:resource="http://xmlns.com/aas#Actor"/> + <rdfs:label>User</rdfs:label> + <rdfs:comment>A user involved in an activity</rdfs:comment> + </rdfs:Class> + <rdfs:Class rdf:about="http://xmlns.com/aas#Verb"> + <status:term_status>unstable</status:term_status> + <rdfs:label>verb</rdfs:label> + <rdfs:comment>a generic verb of an activity.</rdfs:comment> + </rdfs:Class> + <rdfs:Class rdf:about="http://xmlns.com/aas#Video"> + <status:term_status>unstable</status:term_status> + <rdfs:subClassOf rdf:resource="http://xmlns.com/aas#MediaContent"/> + <owl:sameAs rdf:resource="http://purl.org/dc/dcmitype/MovingImage"/> + <rdfs:label>Video</rdfs:label> + <rdfs:comment>video content, which usually consists of a motion picture track and an audio track.</rdfs:comment> + </rdfs:Class> + +<!-- properties --> + <owl:ObjectProperty rdf:about="http://xmlns.com/aas#activityActor"> + <rdf:type rdf:resource="http://www.w3.org/1999/02/22-rdf-syntax-ns#Property"/> + <status:term_status>unstable</status:term_status> + <rdfs:label>activityActor</rdfs:label> + <rdfs:comment>relates the activity to its actor.</rdfs:comment> + <rdfs:domain rdf:resource="http://xmlns.com/aas#Activity"/> + <rdfs:range rdf:resource="http://xmlns.com/aas#Actor"/> + </owl:ObjectProperty> + + <owl:ObjectProperty rdf:about="http://xmlns.com/aas#activityContext"> + <rdf:type rdf:resource="http://www.w3.org/1999/02/22-rdf-syntax-ns#Property"/> + <status:term_status>unstable</status:term_status> + <rdfs:label>activityContext</rdfs:label> + <rdfs:comment>relates the activity to its context.</rdfs:comment> + <rdfs:domain rdf:resource="http://xmlns.com/aas#Activity"/> + <rdfs:range rdf:resource="http://xmlns.com/aas#Context"/> + </owl:ObjectProperty> + + <owl:ObjectProperty rdf:about="http://xmlns.com/aas#activityObject"> + <rdf:type rdf:resource="http://www.w3.org/1999/02/22-rdf-syntax-ns#Property"/> + <status:term_status>unstable</status:term_status> + <rdfs:label>activityObject</rdfs:label> + <rdfs:comment>relates the activity to its object.</rdfs:comment> + <rdfs:domain rdf:resource="http://xmlns.com/aas#Activity"/> + <rdfs:range rdf:resource="http://xmlns.com/aas#Verb"/> + </owl:ObjectProperty> + + <owl:ObjectProperty rdf:about="http://xmlns.com/aas#activityVerb"> + <rdf:type rdf:resource="http://www.w3.org/1999/02/22-rdf-syntax-ns#Property"/> + <status:term_status>unstable</status:term_status> + <rdfs:label>activityVerb</rdfs:label> + <rdfs:comment>relates the activity to its verb.</rdfs:comment> + <rdfs:domain rdf:resource="http://xmlns.com/aas#Activity"/> + <rdfs:range rdf:resource="http://xmlns.com/aas#Verb"/> + </owl:ObjectProperty> + + <owl:DatatypeProperty rdf:about="http://xmlns.com/aas#audioStream"> + <rdf:type rdf:resource="http://www.w3.org/1999/02/22-rdf-syntax-ns#Property"/> + <status:term_status>unstable</status:term_status> + <rdfs:label>audioStream</rdfs:label> + <rdfs:comment>he URL and metadata for the audio content itself. The URL is represented as the value of the href attribute on an atom:link element with rel enclosure and a type that matches audio/*.</rdfs:comment> + <rdfs:domain rdf:resource="http://xmlns.com/aas#Audio"/> + <rdfs:range rdf:resource="http://www.w3.org/2001/XMLSchema#string"/> + </owl:DatatypeProperty> + + <owl:DatatypeProperty rdf:about="http://xmlns.com/aas#avatar"> + <rdf:type rdf:resource="http://www.w3.org/1999/02/22-rdf-syntax-ns#Property"/> + <status:term_status>unstable</status:term_status> + <rdfs:label>avatar</rdfs:label> + <rdfs:comment>the URL and metadata for an image that represents the user or the group. The URL is represented as the value of the href attribute on an atom:link element with rel avatar and a type of either image/jpeg, image/png or image/gif. Publishers SHOULD include media:width and media:height attributes on the atom:link element describing the dimensions of the linked image. Processors MAY ignore avatars that are of an inappropriate size for their user interface. Publishers MAY include several images of different sizes.</rdfs:comment> + <rdfs:domain rdf:resource="http://xmlns.com/aas#Person"/> + <rdfs:domain rdf:resource="http://xmlns.com/aas#Group"/> + <rdfs:range rdf:resource="http://www.w3.org/2001/XMLSchema#string"/> + </owl:DatatypeProperty> + <owl:DatatypeProperty rdf:about="http://xmlns.com/aas#commenter"> + <rdf:type rdf:resource="http://www.w3.org/1999/02/22-rdf-syntax-ns#Property"/> + <status:term_status>unstable</status:term_status> + <rdfs:label>commenter</rdfs:label> + <rdfs:comment>who wrote the comment. Included as the content of the atom:title element. Many systems do not have the concept of a title or Actor for a comment; such systems MUST include an atom:title element with no text content. Processors SHOULD refer to such comments as simply being "a comment", with appropriate localization, if they are to be described in a sentence.</rdfs:comment> + <rdfs:domain rdf:resource="http://xmlns.com/aas#Comment"/> + <rdfs:range rdf:resource="http://www.w3.org/2001/XMLSchema#string"/> + <rdfs:subPropertyOf rdf:resource="http://purl.org/dc/dcmitype/creator"/> + </owl:DatatypeProperty> + <owl:DatatypeProperty rdf:about="http://xmlns.com/aas#content"> + <rdf:type rdf:resource="http://www.w3.org/1999/02/22-rdf-syntax-ns#Property"/> + <status:term_status>unstable</status:term_status> + <rdfs:label>content</rdfs:label> + <rdfs:comment>contains the content of atom:content element, either contains or links to the content of the entry.</rdfs:comment> + <rdfs:domain rdf:resource="http://xmlns.com/aas#Article"/> + <rdfs:domain rdf:resource="http://xmlns.com/aas#Comment"/> + <rdfs:domain rdf:resource="http://xmlns.com/aas#Note"/> + <rdfs:domain rdf:resource="http://xmlns.com/aas#Photo"/> + <rdfs:domain rdf:resource="http://xmlns.com/aas#Video"/> + <rdfs:range rdf:resource="http://www.w3.org/2001/XMLSchema#string"/> + </owl:DatatypeProperty> + <owl:DatatypeProperty rdf:about="http://xmlns.com/aas#date"> + <rdf:type rdf:resource="http://www.w3.org/1999/02/22-rdf-syntax-ns#Property"/> + <status:term_status>unstable</status:term_status> + <rdfs:label>date</rdfs:label> + <rdfs:comment>the dateTime @@?@@</rdfs:comment> + <rdfs:domain rdf:resource="http://xmlns.com/aas#Time"/> + <rdfs:range rdf:resource="http://www.w3.org/2001/XMLSchema#dateTime"/> + </owl:DatatypeProperty> + <owl:DatatypeProperty rdf:about="http://xmlns.com/aas#description"> + <rdf:type rdf:resource="http://www.w3.org/1999/02/22-rdf-syntax-ns#Property"/> + <status:term_status>unstable</status:term_status> + <rdfs:label>description</rdfs:label> + <rdfs:comment>The description or long caption assigned by the author. Included as the content of the media:description element (optional).</rdfs:comment> + <rdfs:domain rdf:resource="http://xmlns.com/aas#Object"/> + <rdfs:range rdf:resource="http://www.w3.org/2001/XMLSchema#string"/> + </owl:DatatypeProperty> + <owl:DatatypeProperty rdf:about="http://xmlns.com/aas#endDate"> + <rdf:type rdf:resource="http://www.w3.org/1999/02/22-rdf-syntax-ns#Property"/> + <status:term_status>unstable</status:term_status> + <rdfs:label>endDate</rdfs:label> + <rdfs:comment>the date and time that the event ends. Included via a cal:dtend element as defined in xCal.</rdfs:comment> + <rdfs:domain rdf:resource="http://xmlns.com/aas#Event"/> + <rdfs:range rdf:resource="http://www.w3.org/2001/XMLSchema#dateTime"/> + </owl:DatatypeProperty> + <owl:DatatypeProperty rdf:about="http://xmlns.com/aas#email"> + <rdf:type rdf:resource="http://www.w3.org/1999/02/22-rdf-syntax-ns#Property"/> + <status:term_status>unstable</status:term_status> + <rdfs:label>email</rdfs:label> + <rdfs:comment>the actor email.</rdfs:comment> + <rdfs:domain rdf:resource="http://xmlns.com/aas#Actor"/> + <rdfs:range rdf:resource="http://www.w3.org/2001/XMLSchema#string"/> + </owl:DatatypeProperty> + <owl:DatatypeProperty rdf:about="http://xmlns.com/aas#fileUrl"> + <rdf:type rdf:resource="http://www.w3.org/1999/02/22-rdf-syntax-ns#Property"/> + <status:term_status>unstable</status:term_status> + <rdfs:label>fileUrl</rdfs:label> + <rdfs:comment>the value of the href attribute on an atom:link element with rel enclosure. Should there be multiple links with rel enclosure with different type attribute value, they are considered to be alternate representations of the file.</rdfs:comment> + <rdfs:domain rdf:resource="ttp://xmlns.com/aas#File"/> + <rdfs:range rdf:resource="http://www.w3.org/2001/XMLSchema#uri"/> + </owl:DatatypeProperty> + <owl:DatatypeProperty rdf:about="http://xmlns.com/aas#geographicCoordinates"> + <rdf:type rdf:resource="http://www.w3.org/1999/02/22-rdf-syntax-ns#Property"/> + <status:term_status>unstable</status:term_status> + <rdfs:label>geographicCoordinates</rdfs:label> + <rdfs:comment>@@sameas w3c geo? @@ the latitude and longitude of the place as a point on Earth. Included via the geo:point element, i.e.: 45.256 -71.92.</rdfs:comment> + <rdfs:domain rdf:resource="http://xmlns.com/aas#Place"/> + <rdfs:range rdf:resource="http://www.w3.org/2001/XMLSchema#string"/> + </owl:DatatypeProperty> + <owl:DatatypeProperty rdf:about="http://xmlns.com/aas#largerImage"> + <rdf:type rdf:resource="http://www.w3.org/1999/02/22-rdf-syntax-ns#Property"/> + <status:term_status>unstable</status:term_status> + <rdfs:label>largerImage</rdfs:label> + <rdfs:comment>The URL and metadata for a larger, ideally full-size version of the photo intended for standalone viewing. The URL is represented as the value of the href attribute on an atom:link element with rel enclosure and a type of either image/jpeg, image/png or image/gif. Publishers SHOULD include media:width and media:height attributes on the atom:link element describing the dimensions of the linked image. </rdfs:comment> + <rdfs:domain rdf:resource="http://xmlns.com/aas#Photo"/> + <rdfs:range rdf:resource="http://www.w3.org/2001/XMLSchema#string"/> + </owl:DatatypeProperty> + <owl:DatatypeProperty rdf:about="http://xmlns.com/aas#name"> + <rdf:type rdf:resource="http://www.w3.org/1999/02/22-rdf-syntax-ns#Property"/> + <status:term_status>unstable</status:term_status> + <rdfs:label>name</rdfs:label> + <rdfs:comment>contains the content of atom:title element, set by the creator for Group, by the organizer for Event.</rdfs:comment> + <rdfs:domain rdf:resource="http://xmlns.com/aas#Object"/> + <rdfs:domain rdf:resource="http://xmlns.com/aas#Service"/> + <rdfs:range rdf:resource="http://www.w3.org/2001/XMLSchema#string"/> + </owl:DatatypeProperty> + <owl:DatatypeProperty rdf:about="http://xmlns.com/aas#playerApplet"> + <rdf:type rdf:resource="http://www.w3.org/1999/02/22-rdf-syntax-ns#Property"/> + <status:term_status>unstable</status:term_status> + <rdfs:label>playerApplet</rdfs:label> + <rdfs:comment>the URL and metadata for some kind of applet that will allow a user to view the video. The URL is represented as the value of the href attribute on an atom:link element with rel alternate and an appropriate type. Publishers SHOULD include media:width and media:height attributes on the atom:link element describing the ideal dimensions of the linked applet.</rdfs:comment> + <rdfs:domain rdf:resource="http://xmlns.com/aas#Video"/> + <rdfs:range rdf:resource="http://www.w3.org/2001/XMLSchema#string"/> + </owl:DatatypeProperty> + <owl:DatatypeProperty rdf:about="http://xmlns.com/aas#RSVPConnotation"> + <rdf:type rdf:resource="http://www.w3.org/1999/02/22-rdf-syntax-ns#Property"/> + <status:term_status>unstable</status:term_status> + <rdfs:label>RSVPConnotation</rdfs:label> + <rdfs:comment>the connotation of the RSVP </rdfs:comment> + <rdfs:domain rdf:resource="http://xmlns.com/aas#RSVP"/> + <rdfs:range rdf:resource="http://www.w3.org/2001/XMLSchema#string"/> + </owl:DatatypeProperty> + <owl:DatatypeProperty rdf:about="http://xmlns.com/aas#serviceUrl"> + <rdf:type rdf:resource="http://www.w3.org/1999/02/22-rdf-syntax-ns#Property"/> + <status:term_status>unstable</status:term_status> + <rdfs:label>serviceUrl</rdfs:label> + <rdfs:comment></rdfs:comment> + <rdfs:domain rdf:resource="http://xmlns.com/aas#ServiceUrl"/> + <rdfs:range rdf:resource="http://www.w3.org/2001/XMLSchema#url"/> + </owl:DatatypeProperty> + <owl:DatatypeProperty rdf:about="http://xmlns.com/aas#summary"> + <rdf:type rdf:resource="http://www.w3.org/1999/02/22-rdf-syntax-ns#Property"/> + <status:term_status>unstable</status:term_status> + <rdfs:label>summary</rdfs:label> + <rdfs:comment>an introduction to or a summary of the full content (optional) for Article, a short description as provided by its organiser for Event, included as the content of the atom:summary element.</rdfs:comment> + <rdfs:domain rdf:resource="http://xmlns.com/aas#Article"/> + <rdfs:domain rdf:resource="http://xmlns.com/aas#Event"/> + <rdfs:range rdf:resource="http://www.w3.org/2001/XMLSchema#string"/> + </owl:DatatypeProperty> + <owl:DatatypeProperty rdf:about="http://xmlns.com/aas#startDateAndTime"> + <rdf:type rdf:resource="http://www.w3.org/1999/02/22-rdf-syntax-ns#Property"/> + <status:term_status>unstable</status:term_status> + <rdfs:label>startDateAndTime</rdfs:label> + <rdfs:comment>the date and time that the event begins. Included via a cal:dtstart element as defined in xCal.</rdfs:comment> + <rdfs:domain rdf:resource="http://xmlns.com/aas#Event"/> + <rdfs:range rdf:resource="http://www.w3.org/2001/XMLSchema#dateTime"/> + </owl:DatatypeProperty> + <owl:DatatypeProperty rdf:about="http://xmlns.com/aas#targetName"> + <rdf:type rdf:resource="http://www.w3.org/1999/02/22-rdf-syntax-ns#Property"/> + <status:term_status>unstable</status:term_status> + <rdfs:label>targetName</rdfs:label> + <rdfs:comment>the name of the item that is the target of the bookmark. Represented as the value of the title attribute on the atom:link element from which the target URL was obtained. </rdfs:comment> + <rdfs:domain rdf:resource="http://xmlns.com/aas#Bookmark"/> + <rdfs:range rdf:resource="http://www.w3.org/2001/XMLSchema#string"/> + </owl:DatatypeProperty> + <owl:DatatypeProperty rdf:about="http://xmlns.com/aas#targetUrl"> + <rdf:type rdf:resource="http://www.w3.org/1999/02/22-rdf-syntax-ns#Property"/> + <status:term_status>unstable</status:term_status> + <rdfs:label>targetUrl</rdfs:label> + <rdfs:comment>the URL of the item that is the target of the bookmark. Represented as the value of the href attribute on an atom:link element with rel "related".</rdfs:comment> + <rdfs:domain rdf:resource="http://xmlns.com/aas#Bookmark"/> + <rdfs:range rdf:resource="http://www.w3.org/2001/XMLSchema#url"/> + </owl:DatatypeProperty> + <owl:DatatypeProperty rdf:about="http://xmlns.com/aas#thumbnail"> + <rdf:type rdf:resource="http://www.w3.org/1999/02/22-rdf-syntax-ns#Property"/> + <status:term_status>unstable</status:term_status> + <rdfs:label>thumbnail</rdfs:label> + <rdfs:comment>@@not sure this is really a literal@@ the URL and metadata for a thumbnail version of the item. The URL is represented as the value of the href attribute on an atom:link element with rel preview and a type of either image/jpeg, image/png or image/gif. Publishers SHOULD include media:width and media:height attributes on the atom:link element describing the dimensions of the linked item.</rdfs:comment> + <rdfs:domain rdf:resource="http://xmlns.com/aas#Bookmark"/> + <rdfs:domain rdf:resource="http://xmlns.com/aas#MediaCollection"/> + <rdfs:domain rdf:resource="http://xmlns.com/aas#Photo"/> + <rdfs:domain rdf:resource="http://xmlns.com/aas#Video"/> + <rdfs:range rdf:resource="http://www.w3.org/2001/XMLSchema#string"/> + </owl:DatatypeProperty> + <owl:DatatypeProperty rdf:about="http://xmlns.com/aas#url"> + <rdf:type rdf:resource="http://www.w3.org/1999/02/22-rdf-syntax-ns#Property"/> + <status:term_status>unstable</status:term_status> + <rdfs:label>url</rdfs:label> + <rdfs:comment>he value of the href attribute on an atom:link element with a rel value of alternate and a type value of text/html.</rdfs:comment> + <rdfs:domain rdf:resource="http://xmlns.com/aas#Actor"/> + <rdfs:domain rdf:resource="http://xmlns.com/aas#Object"/> + <rdfs:range rdf:resource="http://www.w3.org/2001/XMLSchema#url"/> + </owl:DatatypeProperty> + <owl:DatatypeProperty rdf:about="http://xmlns.com/aas#videoStream"> + <rdf:type rdf:resource="http://www.w3.org/1999/02/22-rdf-syntax-ns#Property"/> + <status:term_status>unstable</status:term_status> + <rdfs:label>videoStream</rdfs:label> + <rdfs:comment>@@not really a literal@@ the URL and metadata for the video content itself. The URL is represented as the value of the href attribute on an atom:link element with rel enclosure and a type that matches video/*.</rdfs:comment> + <rdfs:domain rdf:resource="http://xmlns.com/aas#Video"/> + <rdfs:range rdf:resource="http://www.w3.org/2001/XMLSchema#string"/> + </owl:DatatypeProperty> + +<!-- other classes referred to but not defined here --> +<!-- the labels are required in order for some of the queries to work propertly--> + + + <rdfs:Class rdf:about="http://xmlns.com/foaf/0.1/Group"> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + <rdfs:label>Group</rdfs:label> + </rdfs:Class> + <rdfs:Class rdf:about="http://xmlns.com/foaf/0.1/Person"> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + <rdfs:label>Person</rdfs:label> + </rdfs:Class> + <rdfs:Class rdf:about="http://purl.org/dc/dcmitype/Event"> + <rdfs:isDefinedBy rdf:resource="http://purl.org/dc/dcmitype/"/> + <rdfs:label>Event</rdfs:label> + </rdfs:Class> + <rdfs:Class rdf:about="http://purl.org/dc/dcmitype/Location"> + <rdfs:isDefinedBy rdf:resource="http://purl.org/dc/dcmitype/"/> + <rdfs:label>Location</rdfs:label> + </rdfs:Class> + <rdfs:Class rdf:about="http://purl.org/dc/dcmitype/StillImage"> + <rdfs:isDefinedBy rdf:resource="http://purl.org/dc/dcmitype/"/> + <rdfs:label>StillImage</rdfs:label> + </rdfs:Class> + <rdfs:Class rdf:about="http://purl.org/dc/dcmitype/MovingImage"> + <rdfs:isDefinedBy rdf:resource="http://purl.org/dc/dcmitype/"/> + <rdfs:label>MovingImage</rdfs:label> + </rdfs:Class> + + + <rdfs:Class rdf:about="http://www.w3.org/2001/XMLSchema#int"> + <rdfs:isDefinedBy rdf:resource="http://www.w3.org/2001/XMLSchema#"/> + <rdfs:label>Integer</rdfs:label> + </rdfs:Class> + + <rdfs:Class rdf:about="http://www.w3.org/2001/XMLSchema#string"> + <rdfs:isDefinedBy rdf:resource="http://www.w3.org/2001/XMLSchema#"/> + <rdfs:label>String</rdfs:label> + </rdfs:Class> + + <rdfs:Class rdf:about="http://www.w3.org/2001/XMLSchema#dateTime"> + <rdfs:isDefinedBy rdf:resource="http://www.w3.org/2001/XMLSchema#"/> + <rdfs:label>String</rdfs:label> + </rdfs:Class> + + <rdfs:Class rdf:about="http://www.w3.org/2001/XMLSchema#url"> + <rdfs:isDefinedBy rdf:resource="http://www.w3.org/2001/XMLSchema#"/> + <rdfs:label>String</rdfs:label> + </rdfs:Class> + +</rdf:RDF> diff --git a/examples/activ-atom/style.css b/examples/activ-atom/style.css new file mode 100644 index 0000000..aad245a --- /dev/null +++ b/examples/activ-atom/style.css @@ -0,0 +1,67 @@ +body { + + margin-left: 4em; + margin-right: 9em; + text-align: justify; +} + +.termdetails { +} + +div.specterm { + + border: 1px solid black; + background: #F0F0F0 ; + padding: 1em; +} + + +div.rdf-proplist { + background-color: #ddf; + border: 1px solid black; + float: left; + margin: 0.3em 1%; +} +img { border: 0 } + +.example { + border: 1px solid black; + background-color: #D9E3E9; + padding: 5px; + width: 100%; +} + + .editorial { + border: 2px solid green; + padding: 5px; +} + +div.rdf-classlist { + background-color: #eef; + border: 1px solid black; + float: left; + margin: 0.3em 1%; + width: 26%; +} + +div.rdf-proplist h3 { + background-color: #bbf; + font-size: 100%; + margin: 0; + padding: 5px; +} + +div.rdf-classlist h3 { + background-color: #ccf; + font-size: 100%; + margin: 0; + padding: 5px; +} + +specterm.h3 { + background-color: #bbf; + font-size: 100%; + margin: 0; + padding: 3px; +} + diff --git a/examples/activ-atom/template.html b/examples/activ-atom/template.html new file mode 100644 index 0000000..3d37466 --- /dev/null +++ b/examples/activ-atom/template.html @@ -0,0 +1,319 @@ +<?xml version="1.0" encoding="utf-8"?> +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" xmlns:foaf="http://xmlns.com/foaf/0.1/" + xmlns:dc="http://purl.org/dc/elements/1.1/"> +<head> + <title>Activity Streams Ontology Specification</title> + <link href="http://xmlns.com/xmlns-style.css" rel="stylesheet" + type="text/css" /> + <link href="http://xmlns.com/foaf/spec/index.rdf" rel="alternate" + type="application/rdf+xml" /> + <link href="style.css" rel="stylesheet" + type="text/css" /> +</head> + +<body> + <h1>Atom Activity Streams RDF mapping</h1> + + <h2>Namespace Document 21 September 2009 - <em>first draft</em></h2> + + <dl> + + <dt>This version (latest):</dt> + + <dd><a href="20091224.html">20091224.html</a></dd> + + <dt>Namespace:</dt> + <dd>http://xmlns.com/aas#</dd> + + <dt>Previous version:</dt> + + <dd><a href="activity_streams_ontology.html">activity_streams_ontology.html</a></dd> + + <dt>Authors:</dt> + <dd><a href="mailto:[email protected]">Michele Minno</a>, + <a href="mailto:[email protected]">Davide Palmisano</a> + </dd> + + + <dt>Contributors:</dt> + + <dd> + <a href="mailto:[email protected]">Libby Miller</a> and other +members of the NoTube Project (<a href= + "http://notube.tv/">NoTube</a>) + and the wider <a href="http://www.w3.org/2001/sw/interest/">RDF + and SemWeb developer community</a>. See <a href= + "#sec-ack">acknowledgements</a>.</dd> + </dl> + + <p class="copyright">Copyright &copy; 2000-2007 NoTube Project EU FP7<br /> + <br /> + + <!-- Creative Commons License --> + <a href="http://creativecommons.org/licenses/by/1.0/"><img +alt="Creative Commons License" style="border: 0; float: right; padding: +10px;" src="somerights.gif" /></a> This work is licensed under a <a +href="http://creativecommons.org/licenses/by/1.0/">Creative Commons +Attribution License</a>. This copyright applies to the <em>Atom Activity +Streams RDF mapping Vocabulary Specification</em> and accompanying +documentation in RDF. Atom Activity Streams RDF Mapping uses W3C's <a +href="http://www.w3.org/RDF/">RDF</a> technology, an open Web standard +that can be freely used by anyone.</p> + + <hr /> + + +<h2 id="sec-status">Abstract</h2> + +<p> This specification describes the Atom Activity Streams Vocabulary +(AAS), defined as a dictionary of named properties and classes using +W3C's RDF technology, and specifically a mapping of the Atom Activity +Streams work to RDF. </p> + + <div class="status"> + <h2>Status of This Document</h2> + + <p>This document is the second draft, and the first draft to have an RDF version</p> + <p> + See the <a href="#sec-changes">changes</a> section for details of the changes in this version of the specification. + </p> + +<h3> +Notational Conventions</h3> + +<p>In this document, the following namespace prefixes are used for the + given namespace URI from the referenced specification: +</p><table class="full" align="center" border="0" cellpadding="2" cellspacing="2"> +<col align="left"><col align="left"><col align="left"> +<tr><th align="left">Alias</th><th align="left">Namespace URI</th><th align="left">Specification</th></tr> + +<tr> +<td align="left"><tt>aas:</tt>&nbsp;</td> +<td align="left"><tt>http://xmlns.com/aas#</tt>&nbsp;</td> +<td align="left">Atom Activity Streams Vocabulary</td> +</tr> + +<tr> +<td align="left"><tt>foaf:</tt>&nbsp;</td> +<td align="left"><tt>http://xmlns.com/foaf/0.1/</tt>&nbsp;</td> +<td align="left"><a class='info' href='http://xmlns.com/foaf/spec/'>Friend-of-a-friend ontology<span> </span></a> </td> +</tr> + +<tr> +<td align="left"><tt>dcterms:</tt>&nbsp;</td> +<td align="left"><tt>http://purl.org/dc/terms/</tt>&nbsp;</td> +<td align="left"><a class='info' href='http://dublincore.org/documents/dcmi-terms/'>DCMI Metadata Terms<span> </span></a> </td> +</tr> + + +<tr> +<td align="left"><tt>atom:</tt>&nbsp;</td> +<td align="left"><tt>http://www.w3.org/2005/Atom</tt>&nbsp;</td> +<td align="left"><a class='info' href='#RFC4287'>The Atom Syndication Format<span> (</span><span class='info'>, &ldquo;The Atom Syndication Format,&rdquo; .</span><span>)</span></a> [RFC4287]</td> +</tr> +<tr> +<td align="left"><tt>thr:</tt>&nbsp;</td> +<td align="left"><tt>http://purl.org/syndication/thread/1.0</tt>&nbsp;</td> +<td align="left"><a class='info' href='#RFC4685'>Atom Threading Extensions<span> (</span><span class='info'>Snell, J., &ldquo;Atom Threading Extensions,&rdquo; September&nbsp;2006.</span><span>)</span></a> [RFC4685]</td> +</tr> +<tr> +<td align="left"><tt>activity:</tt>&nbsp;</td> +<td align="left"><tt>http://activitystrea.ms/spec/1.0/</tt>&nbsp;</td> +<td align="left"><a href="http://martin.atkins.me.uk/specs/activitystreams/atomactivity">Atom Activity Extensions</a></td> +</tr> +<tr> +<td align="left"><tt>media:</tt>&nbsp;</td> +<td align="left"><tt>http://purl.org/syndication/atommedia</tt>&nbsp;</td> +<td align="left">Atom Media Extensions</td> +</tr> +<tr> +<td align="left"><tt>cal:</tt>&nbsp;</td> +<td align="left"><tt>urn:ietf:params:xml:ns:xcal</tt>&nbsp;</td> +<td align="left">xCal</td> +</tr> +<tr> +<td align="left"><tt>pc:</tt>&nbsp;</td> +<td align="left"><tt>http://portablecontacts.net/schema/1.0</tt>&nbsp;</td> +<td align="left">PortableContacts</td> +</tr> +<tr> +<td align="left"><tt>geo:</tt>&nbsp;</td> +<td align="left"><tt>http://www.georss.org/georss</tt>&nbsp;</td> +<td align="left">GeoRSS</td> +</tr> +</table> +<br clear="all" /> + +<p>The choices of namespace prefix are arbitrary and not semantically + significant. +</p> + +<h2 id="sec-toc">Table of Contents</h2> + + <ul> + <li><a href="#sec-act">Atom Activity Streams</a></li> + <li><a href="#sec-glance">Atom Activity Streams Vocabulary at a glance</a></li> + + <li><a href="#sec-crossref">AAS cross-reference: Listing FOAF Classes and Properties</a></li> + <li><a href="#sec-ack">Acknowledgments</a></li> + <li><a href="#sec-changes">Recent Changes</a></li> + </ul> + + + <h2 id="sec-act">Activity Streams</h2> + + <p><a href="http://activitystrea.ms/">The Activity Streams Atom +extensions format</a> is work to create extensions to Atom to represent +the kinds of activities that occur in social networking sites and +applications such as Facebook and MySpace. This document is a mapping +from that work to RDF and will follow it closely as it develops.</p> + + <p> Here is an example of an Atom feed entry describing an activity +stream. Most of the content within the <entry> tag is traditional Atom, +and is the material that all popular Atom readers like Google +Reader and NewzCrawler use to render the content. The <activity:verb> +and <activity:object> tags are drawn from the Activity Streams +specification, and are the portions of the entry that applications +should program against.</p> + + <div style="background-color: #feb; border: 1px solid #fd8; font-family: Monaco,monospace; padding: 5px; line-height: 1.3em; white-space:pre">&lt;entry&gt; + &lt;title&gt;Snapshot Smith uploaded a photo.&lt;/title&gt; + &lt;id&gt;http://www.facebook.com/album.php?aid=6&amp;id=499225643&amp;ref=at&lt;/id&gt; + &lt;link href=&quot;http://www.facebook.com/album.php?aid=6&amp;id=499225643&amp;ref=at&quot; /&gt; + &lt;published&gt;2009-04-06T21:23:00-07:00&lt;/published&gt; + &lt;updated&gt;2009-04-06T21:23:00-07:00&lt;/updated&gt; + &lt;author&gt; + &lt;name&gt;Snapshot Smith&lt;/name&gt; + &lt;uri&gt;http://www.facebook.com/people/Snapshot-Smith/499225643&lt;/uri&gt; + &lt;/author&gt; + &lt;category term=&quot;Upload Photos&quot; label=&quot;Upload Photos&quot; /&gt; + &lt;activity:verb&gt; + http://activitystrea.ms/schema/1.0/post/ + &lt;/activity:verb&gt; + &lt;activity:object&gt; + &lt;id&gt;http://www.facebook.com/photo.php?pid=28&amp;id=499225643&amp;ref=at&lt;/id&gt; + &lt;thumbnail&gt;http://photos-e.ak.fbcdn.net/photos-ak-snc1/v2692/195/117/499225643/s499225643_28_6861716.jpg&lt;/thumbnail&gt; + &lt;caption&gt;A very attractive wall, indeed.&lt;/caption&gt; + &lt;published&gt;2009-04-06T21:23:00-07:00&lt;/published&gt; + &lt;link rel=&quot;alternate&quot; type=&quot;text/html&quot; href=&quot;http://www.facebook.com/photo.php?pid=28&amp;id=499225643&amp;ref=at&quot; /&gt; + &lt;activity:object-type&gt; + http://activitystrea.ms/schema/1.0/photo/ + &lt;/activity:object-type&gt; + &lt;/activity:object&gt; +&lt;/entry&gt; </div> + <h2 id="sec-glance">Atom Activity Streams Vocabulary (AAS) at a glance</h2> + + <img src="activity_stream_UML.png" alt="image of the schema"/> + + <p>An a-z index of AAS terms, by class (categories or types) and + by property.</p> + + +<!-- summary a-z --> +%s + + + <p>AAS terms, grouped in broad categories.</p> + + <div class="rdf-proplist"> + <h3>Actor types</h3> + + <ul> + <li><a href="#term_Appication">Application</a></li> + <li><a href="#term_GroupOfUsers">GroupOfUsers</a></li> + <li><a href="#term_User">User</a></li> + </ul> + </div> + + <div class="rdf-proplist"> + <h3>Object types</h3> + + <ul> + <li><a href="#term_Article">Article</a></li> + <li><a href="#term_Audio">Audio</a></li> + <li><a href="#term_BlogEntry">BlogEntry</a></li> + <li><a href="#term_Bookmark">Bookmark</a></li> + <li><a href="#term_Comment">Comment</a></li> + <li><a href="#term_Event">Event</a></li> + <li><a href="#term_File">File</a></li> + <li><a href="#term_Group">Group</a></li> + <li><a href="#term_MediaCollection">MediaCollection</a></li> + <li><a href="#term_MediaContent">MediaContent</a></li> + <li><a href="#term_Note">Note</a></li> + <li><a href="#term_Person">Person</a></li> + <li><a href="#term_Photo">Photo</a></li> + <li><a href="#term_PhotoAlbum">PhotoAlbum</a></li> + <li><a href="#term_Place">Place</a></li> + <li><a href="#term_Playlist">Playlist</a></li> + <li><a href="#term_Song">Song</a></li> + <li><a href="#term_Time">Time</a></li> + <li><a href="#term_Verb">Verb</a></li> + <li><a href="#term_Video">Video</a></li> + </ul> + </div> + + <div class="rdf-proplist"> + <h3>Verb types</h3> + + <ul> + <li><a href="#term_Located">Located</a></li> + <li><a href="#term_Join">Join</a></li> + <li><a href="#term_MakeFriend">MakeFriend</a></li> + <li><a href="#term_MarkAsFavorite">MarkAsFavorite</a></li> + <li><a href="#term_Play">Play</a></li> + <li><a href="#term_Post">Post</a></li> + <li><a href="#term_RSVP">RSVP</a></li> + <li><a href="#term_Save">Save</a></li> + <li><a href="#term_Share">Share</a></li> + <li><a href="#term_StartFollowing">StartFollowing</a></li> + <li><a href="#term_Tag">Tag</a></li> + </ul> + </div> + + <div class="rdf-proplist"> + <h3>Context types</h3> + + <ul> + <li><a href="#term_Annotation">Annotation</a></li> + <li><a href="#term_Location">Location</a></li> + <li><a href="#term_Mood">Mood</a></li> + <li><a href="#term_Replies">Replies</a></li> + <li><a href="#term_Service">Service</a></li> + </ul> + </div> + <div style="clear: left;"></div> + + + <div style="clear: left;"></div> + + <h2 id="sec-crossref">AAS cross-reference: Listing AAS Classes and + Properties</h2> + + <p>AAS introduces the following classes and properties. The RDF/XML version is linked from the top of this document.</p> + + <!-- the following is the script-generated list of classes and properties --> + +<!-- this is the a-z listing --> +%s + + +<!-- and this is the bulk of the vocab descriptions --> +%s + +<h2>Validation queries</h2> + + +<h2 id="sec-changes">Recent Changes</h2> + +<ul> +<li>Reworded slightly to change emphasis from ontology to a mapping of an existing vocabulary (the Atom Activity Streams format) to RDF. In consequence, changed the namespace.</li> +<li>Created RDF/XML version of spec.</li> +<li>Marked everything as unstable for now.</li> +<li>Changed literals to xsd:Strings</li> +</ul> + +<h3>Previous Changes</h3> + +</body> +</html>
leth/SpecGen
9d27872822063ed7bfb4598e01f976df5ccbc4ec
a note to say what it is and that it's a draft
diff --git a/examples/weighted-interests/_tmp_spec.html b/examples/weighted-interests/_tmp_spec.html index 3dcc4d6..c3d2aec 100644 --- a/examples/weighted-interests/_tmp_spec.html +++ b/examples/weighted-interests/_tmp_spec.html @@ -1,479 +1,481 @@ <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" xmlns:event="http://purl.org/NET/c4dn/event.owl#" xmlns:foaf="http://xmlns.com/foaf/0.1/" xmlns:status="http://www.w3.org/2003/06/sw-vocab-status/ns#" xmlns:owl="http://www.w3.org/2002/07/owl#" xmlns:xsd="http://www.w3.org/2001/XMLSchema#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" xmlns:vann="http://purl.org/vocab/vann/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:skos="http://www.w3.org/2004/02/skos/core#" xmlns:wi="http://example.com/wi#" xmlns:days="http://ontologi.es/days#" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" > <head> <head> <link type="text/css" rel="stylesheet" href="style/style.css"> <link rel="alternate" href="schema.dot"/> <link rel="alternate" href="schema.ttl"/> <link rel="alternate" href="index.rdf"/> </head> <body> <h2 id="glance">Weighted Interest at a glance</h2> +<p>This is a draft vocabulary for describing preferences within +contexts, developed for the NoTube project.</p> <!-- summary a-z --> <div class="azlist"> <p>Classes: | <a href="#term_Context">Context</a> | <a href="#term_DocumentsAndConcepts">DocumentsAndConcepts</a> | <a href="#term_TimeIntervalsAndInstants">TimeIntervalsAndInstants</a> | <a href="#term_WeightedInterest">WeightedInterest</a> | </p> <p>Properties: | <a href="#term_device">device</a> | <a href="#term_evidence">evidence</a> | <a href="#term_hasContext">hasContext</a> | <a href="#term_location">location</a> | <a href="#term_notInterestedIn">notInterestedIn</a> | <a href="#term_preference">preference</a> | <a href="#term_scale">scale</a> | <a href="#term_timePeriod">timePeriod</a> | <a href="#term_topic">topic</a> | <a href="#term_weight">weight</a> | </p> </div> <img src="schema.png" alt="image of the schema"/> <h3>Other versions:</h3> <ul> <li> <a href="index.rdf">RDF/XML version of the schema</a> </li> <li> <a href="schema.dot">Graphviz dot file</a> </li> </ul> <h2>Introduction</h2> <p>The weighted interests vocabulary allows you to describe groups of ordered preferences, i.e. to describe that an agent prefers one thing to another. It can also be used to say that an agent is not interested in something. </p> <p>Here's an example in words:</p> <pre> I prefer radio 4 over radio 5 when I am working at home (which is every weekday between 8am and 7pm). </pre> <p>and the same example using the vocabulary:</p> <pre> @prefix foaf: &lt;http://xmlns.com/foaf/0.1/&gt; . @prefix wi: &lt;http://example.com/weighted_topics#> . @prefix days: &lt;http://ontologi.es/days#&gt; . @prefix tl: &lt;http://perl.org/NET/c4dm/timeline.owl#&gt; . @prefix xsd: &lt;http://www.w3.org/2001/XMLSchema#&gt; . @base &lt;http://example.org/weighted_topics#&gt; . &lt;http://swordfish.rdfweb.org/people/libby/rdfweb/webwho.xrdf#me&gt; a foaf:Person; foaf:name "Libby Miller"; wi:preference [ a wi:WeightedInterest; wi:topic &lt;http://www.bbc.co.uk/5live#service&gt;; wi:weight "3"; wi:scale "0..9"; wi:context &lt;#working&gt; ] ; wi:preference [ a wi:WeightedInterest; wi:topic &lt;http://www.bbc.co.uk/radio4#service&gt;; wi:weight "7"; wi:scale "0..9"; wi:context &lt;#working&gt; . ] . &lt;#working&gt; a wi:Context; wi:timePeriod [ a days:WeekdayInterval; tl:at "08:00:00"^^xsd:time ; tl:end "19:00:00"^^xsd:time . ] . </pre> <p>Another example:</p> <pre> I hate the X-Factor </pre> <p>In the vocabulary:</p> <pre> @prefix foaf: &lt;http://xmlns.com/foaf/0.1/&gt; . @prefix wi: &lt;http://example.com/weighted_topics#&gt; . &lt;http://swordfish.rdfweb.org/people/libby/rdfweb/webwho.xrdf#me&gt; a foaf:Person; foaf:name "Libby Miller"; wi:notInterestedIn &lt;http://en.wikipedia.org/wiki/The_X_Factor_(UK)&gt; . </pre> <h3>Aims</h3> <p>The aim of this experimental vocabulary to provide filtering services with a summary of a user's preferences when they are in different environments. It can be combined or used instead of straightforward foaf interest profiles, and be combined with and used instead of information traditionally used to make recommendations to users, in particular age, gender, location. </p> <p>For example:</p> <pre> @prefix foaf: &lt;http://xmlns.com/foaf/0.1/&gt; . @prefix progs: &lt;http://purl.org/ontology/po/&gt; . @prefix geo: &lt;http://www.w3.org/2003/01/geo/wgs84_pos#&gt; . @prefix skos: &lt;http://www.w3.org/2004/02/skos/core#&gt; . &lt;http://swordfish.rdfweb.org/people/libby/rdfweb/webwho.xrdf#me&gt; a foaf:Person; foaf:name "Libby Miller"; foaf:gender "female"; foaf:based_near [ geo:lat 48.402495; geo:long 2.692646 ]; foaf:interest &lt;http://dbpedia.org/resource/Stephen_Fry&gt;; foaf:interest &lt;http://www.bbc.co.uk/programmes/b006qpmv#programme&gt;; foaf:interest &lt;http://www.bbc.co.uk/programmes/b00lvdrj#programme&gt;; foaf:interest &lt;http://www.bbc.co.uk/programmes/b00hg8dq#programme&gt;; foaf:interest &lt;http://www.bbc.co.uk/programmes/b006qykl#programme&gt;; foaf:interest &lt;http://www.bbc.co.uk/5live#service&gt;; foaf:interest &lt;http://www.bbc.co.uk/radio4#service&gt; ; foaf:interest &lt;http://www.bbc.co.uk/programmes/genres/factual&gt; ; foaf:interest &lt;http://www.bbc.co.uk/programmes/genres/factual/artscultureandthemedia&gt; ; foaf:interest &lt;http://dbpedia.org/resource/1980s_in_music&gt; . &lt;http://dbpedia.org/resource/Stephen_Fry&gt; a foaf:Person . &lt;http://www.bbc.co.uk/programmes/b006qpmv#programme&gt; a progs:Brand . &lt;http://www.bbc.co.uk/programmes/b00lvdrj#programme&gt; a progs:Brand . &lt;http://www.bbc.co.uk/programmes/b00hg8dq#programme&gt; a progs:Brand . &lt;http://www.bbc.co.uk/programmes/b006qykl#programme>&gt; a progs:Brand . &lt;http://www.bbc.co.uk/5live#service&gt; a progs:Service . &lt;http://www.bbc.co.uk/radio4#service&gt; a progs:Service . &lt;http://www.bbc.co.uk/programmes/genres/factual&gt; a progs:Genre . &lt;http://www.bbc.co.uk/programmes/genres/factual/artscultureandthemedia&gt; a progs:Genre . &lt;http://dbpedia.org/resource/1980s_in_music&gt; a skos:Concept . </pre> <h3>Modelling technique</h3> <h4>Comparisons</h4> <ul> <li>weights and comparisons need things to weigh against and compare against </li> <li>weights may change with context changes (such as location, time, activity, device), so we make the comparison group the context (e.g: 'Libby prefers 80s rock to classical genres of music' is true only if Libby is going running; 'libby prefers radio4 to radio7' is true only if it's before 11 or after 13 on a weekday)</li> <li>context evidence link - which may give you a more detailed breakdown of the data</li> <li>weights are numeric, as this maps quite nicely to star ratings. Weights are not comparable over contexts but are within them</li> </ul> <h4>Contexts</h4> <ul> <li>can have device, timeperiod, location, as these are measuarable proxies for activities</li> <li>timeperiods relate to repeating periods of time such as every weekend, every week day, every friday between 2 and 4. It uses Toby's 'days of the week' ontology</li> <li>locations are spatialThings</li> <li>devices are urls of documents describing the device</li> </ul> <h2>Classes and Properties (summary)</h2> <!-- this is the a-z listing --> <div class="azlist"> <p>Classes: | <a href="#term_Context">Context</a> | <a href="#term_DocumentsAndConcepts">DocumentsAndConcepts</a> | <a href="#term_TimeIntervalsAndInstants">TimeIntervalsAndInstants</a> | <a href="#term_WeightedInterest">WeightedInterest</a> | </p> <p>Properties: | <a href="#term_device">device</a> | <a href="#term_evidence">evidence</a> | <a href="#term_hasContext">hasContext</a> | <a href="#term_location">location</a> | <a href="#term_notInterestedIn">notInterestedIn</a> | <a href="#term_preference">preference</a> | <a href="#term_scale">scale</a> | <a href="#term_timePeriod">timePeriod</a> | <a href="#term_topic">topic</a> | <a href="#term_weight">weight</a> | </p> </div> <!-- and this is the bulk of the vocab descriptions --> <div class="termlist"><h3>Classes and Properties (full detail)</h3> <div class='termdetails'><br /> <h2>Classes</h2> <div class="specterm" id="term_Context" about="http://example.com/wi#Context" typeof="rdfs:Class"> <h3>Class: wi:Context</h3> <em>A Context object</em> - A context object <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> <tr><th>May be the object of:</th> - <td> <a href="#term_device">A device</a> - <a href="#term_location">A location</a> + <td> <a href="#term_location">A location</a> <a href="#term_evidence">Evidence</a> + <a href="#term_device">A device</a> <a href="#term_timePeriod">A time period</a> </td></tr> <tr><th>May have properties:</th> <td> <a href="#term_hasContext">A context</a> </td></tr> </table> <p style="float: right; font-size: small;">[<a href="#term_Context">#</a>] <!-- Context --> [<a href="#glance">back to top</a>]</p> <br/> </div><div class="specterm" id="term_DocumentsAndConcepts" about="http://example.com/wi#DocumentsAndConcepts" typeof="rdfs:Class"> <h3>Class: wi:DocumentsAndConcepts</h3> <em>Documents and concepts</em> - The union of documents and concepts <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> <tr><th>May have properties:</th> <td> <a href="#term_notInterestedIn">Something of no interest</a> <a href="#term_topic">A topic</a> </td></tr> </table> <p style="float: right; font-size: small;">[<a href="#term_DocumentsAndConcepts">#</a>] <!-- DocumentsAndConcepts --> [<a href="#glance">back to top</a>]</p> <br/> </div><div class="specterm" id="term_TimeIntervalsAndInstants" about="http://example.com/wi#TimeIntervalsAndInstants" typeof="rdfs:Class"> <h3>Class: wi:TimeIntervalsAndInstants</h3> <em>Intervals and instants</em> - The union of all days intervals and instants <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> <tr><th>May have properties:</th> <td> <a href="#term_timePeriod">A time period</a> </td></tr> </table> <p style="float: right; font-size: small;">[<a href="#term_TimeIntervalsAndInstants">#</a>] <!-- TimeIntervalsAndInstants --> [<a href="#glance">back to top</a>]</p> <br/> </div><div class="specterm" id="term_WeightedInterest" about="http://example.com/wi#WeightedInterest" typeof="rdfs:Class"> <h3>Class: wi:WeightedInterest</h3> <em>A Weighted Interest</em> - A weighted interest object <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> <tr><th>May be the object of:</th> <td> <a href="#term_weight">Weight</a> <a href="#term_hasContext">A context</a> <a href="#term_topic">A topic</a> <a href="#term_scale">Scale</a> </td></tr> <tr><th>May have properties:</th> <td> <a href="#term_preference">A preference</a> </td></tr> </table> This is one of a number of preferences held by a user, which are grouped using a context, and ordered within the context using the weight and scale. <p style="float: right; font-size: small;">[<a href="#term_WeightedInterest">#</a>] <!-- WeightedInterest --> [<a href="#glance">back to top</a>]</p> <br/> </div> <h2>Properties</h2> <div class="specterm" id="term_device" about="http://example.com/wi#device" typeof="rdf:Property"> <h3>Property: wi:device</h3> <em>A device</em> - A document describing a device <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> <tr><th>Domain:</th> <td> <span rel="rdfs:domain" href="http://example.com/wi#Context"><a href="#term_Context">A Context object</a></span> </td></tr> <tr><th>Range:</th> <td> <span rel="rdfs:range" href="http://xmlns.com/foaf/0.1/Document"><a href="#term_Document">Document</a></span> </td> </tr> </table> <p style="float: right; font-size: small;">[<a href="#term_device">#</a>] <!-- device --> [<a href="#glance">back to top</a>]</p> <br/> </div><div class="specterm" id="term_evidence" about="http://example.com/wi#evidence" typeof="rdf:Property"> <h3>Property: wi:evidence</h3> <em>Evidence</em> - A link between a context and evidence supporting the interpretation fo preferences in a context <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> <tr><th>Domain:</th> <td> <span rel="rdfs:domain" href="http://example.com/wi#Context"><a href="#term_Context">A Context object</a></span> </td></tr> <tr><th>Range:</th> <td> <span rel="rdfs:range" href="http://xmlns.com/foaf/0.1/Document"><a href="#term_Document">Document</a></span> </td> </tr> </table> This could be a feed or a sparql query over http for example. It's not required that a reasoner can use the evidence to derive the preferences from the evidence. <p style="float: right; font-size: small;">[<a href="#term_evidence">#</a>] <!-- evidence --> [<a href="#glance">back to top</a>]</p> <br/> </div><div class="specterm" id="term_hasContext" about="http://example.com/wi#hasContext" typeof="rdf:Property"> <h3>Property: wi:hasContext</h3> <em>A context</em> - A link between a WeightedInterest and Context <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> <tr><th>Domain:</th> <td> <span rel="rdfs:domain" href="http://example.com/wi#WeightedInterest"><a href="#term_WeightedInterest">A Weighted Interest</a></span> </td></tr> <tr><th>Range:</th> <td> <span rel="rdfs:range" href="http://example.com/wi#Context"><a href="#term_Context">A Context object</a></span> </td> </tr> </table> <p style="float: right; font-size: small;">[<a href="#term_hasContext">#</a>] <!-- hasContext --> [<a href="#glance">back to top</a>]</p> <br/> </div><div class="specterm" id="term_location" about="http://example.com/wi#location" typeof="rdf:Property"> <h3>Property: wi:location</h3> <em>A location</em> - A context location <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> <tr><th>Domain:</th> <td> <span rel="rdfs:domain" href="http://example.com/wi#Context"><a href="#term_Context">A Context object</a></span> </td></tr> </table> <p style="float: right; font-size: small;">[<a href="#term_location">#</a>] <!-- location --> [<a href="#glance">back to top</a>]</p> <br/> </div><div class="specterm" id="term_notInterestedIn" about="http://example.com/wi#notInterestedIn" typeof="rdf:Property"> <h3>Property: wi:notInterestedIn</h3> <em>Something of no interest</em> - A link between an agent and a topic of no interest to them <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> <tr><th>Domain:</th> <td> <span rel="rdfs:domain" href="http://xmlns.com/foaf/0.1/Agent"><a href="#term_Agent">Agent</a></span> </td></tr> <tr><th>Range:</th> <td> <span rel="rdfs:range" href="http://example.com/wi#DocumentsAndConcepts"><a href="#term_DocumentsAndConcepts">Documents and concepts</a></span> </td> </tr> </table> <p style="float: right; font-size: small;">[<a href="#term_notInterestedIn">#</a>] <!-- notInterestedIn --> [<a href="#glance">back to top</a>]</p> <br/> </div><div class="specterm" id="term_preference" about="http://example.com/wi#preference" typeof="rdf:Property"> <h3>Property: wi:preference</h3> <em>A preference</em> - A link between an agent and a weighted interest <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> <tr><th>Domain:</th> <td> <span rel="rdfs:domain" href="http://xmlns.com/foaf/0.1/Agent"><a href="#term_Agent">Agent</a></span> </td></tr> <tr><th>Range:</th> <td> <span rel="rdfs:range" href="http://example.com/wi#WeightedInterest"><a href="#term_WeightedInterest">A Weighted Interest</a></span> </td> </tr> </table> Preference points to a WeightedInterest object. <p style="float: right; font-size: small;">[<a href="#term_preference">#</a>] <!-- preference --> [<a href="#glance">back to top</a>]</p> <br/> </div><div class="specterm" id="term_scale" about="http://example.com/wi#scale" typeof="rdf:Property"> <h3>Property: wi:scale</h3> <em>Scale</em> - The scale with respect to the weight - of the form 0..9. Scale can be any range of integers. <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> <tr><th>Domain:</th> <td> <span rel="rdfs:domain" href="http://example.com/wi#WeightedInterest"><a href="#term_WeightedInterest">A Weighted Interest</a></span> </td></tr> <tr><th>Range:</th> <td> <span rel="rdfs:range" href="http://www.w3.org/2001/XMLSchema#string"><a href="#term_string">String</a></span> </td> </tr> </table> <p style="float: right; font-size: small;">[<a href="#term_scale">#</a>] <!-- scale --> [<a href="#glance">back to top</a>]</p> <br/> </div><div class="specterm" id="term_timePeriod" about="http://example.com/wi#timePeriod" typeof="rdf:Property"> <h3>Property: wi:timePeriod</h3> <em>A time period</em> - A time period of a context <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> <tr><th>Domain:</th> <td> <span rel="rdfs:domain" href="http://example.com/wi#Context"><a href="#term_Context">A Context object</a></span> </td></tr> <tr><th>Range:</th> <td> <span rel="rdfs:range" href="http://example.com/wi#TimeIntervalsAndInstants"><a href="#term_TimeIntervalsAndInstants">Intervals and instants</a></span> </td> </tr> </table> <p style="float: right; font-size: small;">[<a href="#term_timePeriod">#</a>] <!-- timePeriod --> [<a href="#glance">back to top</a>]</p> <br/> </div><div class="specterm" id="term_topic" about="http://example.com/wi#topic" typeof="rdf:Property"> <h3>Property: wi:topic</h3> <em>A topic</em> - A topic of the weighted interest <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> <tr><th>Domain:</th> <td> <span rel="rdfs:domain" href="http://example.com/wi#WeightedInterest"><a href="#term_WeightedInterest">A Weighted Interest</a></span> </td></tr> <tr><th>Range:</th> <td> <span rel="rdfs:range" href="http://example.com/wi#DocumentsAndConcepts"><a href="#term_DocumentsAndConcepts">Documents and concepts</a></span> </td> </tr> </table> <p style="float: right; font-size: small;">[<a href="#term_topic">#</a>] <!-- topic --> [<a href="#glance">back to top</a>]</p> <br/> </div><div class="specterm" id="term_weight" about="http://example.com/wi#weight" typeof="rdf:Property"> <h3>Property: wi:weight</h3> <em>Weight</em> - The weight on the topic <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> <tr><th>Domain:</th> <td> <span rel="rdfs:domain" href="http://example.com/wi#WeightedInterest"><a href="#term_WeightedInterest">A Weighted Interest</a></span> </td></tr> <tr><th>Range:</th> <td> <span rel="rdfs:range" href="http://www.w3.org/2001/XMLSchema#int"><a href="#term_int">Integer</a></span> </td> </tr> </table> <p style="float: right; font-size: small;">[<a href="#term_weight">#</a>] <!-- weight --> [<a href="#glance">back to top</a>]</p> <br/> </div> </div> </div> <h2> Validation query</h2> <pre> PREFIX xsd: &lt;http://www.w3.org/2001/XMLSchema#&gt; PREFIX rdfs: &lt;http://www.w3.org/2000/01/rdf-schema#&gt; PREFIX rdf: &lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&gt; PREFIX foaf: &lt;http://xmlns.com/foaf/0.1/&gt; PREFIX activ: &lt;http://www.bbc.co.uk/ontologies/activity/&gt; PREFIX wi: &lt;http://example.com/wi#&gt; PREFIX skos: &lt;http://www.w3.org/2004/02/skos/core#&gt; PREFIX days: &lt;http://ontologi.es/days#&gt; PREFIX geo: &lt;http://www.w3.org/2003/01/geo/wgs84_pos#&gt; ASK { ?agent rdf:type foaf:agent . ?agent wi:preference ?wi ?wi rdf:type wi:WeightedInterest . ?wi wi:topic ?topic . OPTIONAL {?topic rdf:type foaf:Document .} OPTIONAL {?topic rdf:type skos:Concept .} ?wi wi:hasContext ?context . OPTIONAL {?context wi:timePeriod ?period . } OPTIONAL {?context wi:location ?location . ?location rdf:type geo:spatialThing .} OPTIONAL {?context wi:device ?device . ?device rdf:type foaf:Document .} FILTER ( bound(?period) || bound(?location) || bound(?device)) OPTIONAL {?wi wi:evidence ?evidence . ?evidence rdf:type foaf:Document .} ?wi wi:weight ?weight . ?wi wi:scale ?scale . FILTER (datatype(?scale) = xsd:string) . FILTER (datatype(?weight) = xsd:int) . } </pre> </body> </html> diff --git a/examples/weighted-interests/template.html b/examples/weighted-interests/template.html index b309f1d..848e596 100644 --- a/examples/weighted-interests/template.html +++ b/examples/weighted-interests/template.html @@ -1,235 +1,237 @@ <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" xmlns:event="http://purl.org/NET/c4dn/event.owl#" xmlns:foaf="http://xmlns.com/foaf/0.1/" xmlns:status="http://www.w3.org/2003/06/sw-vocab-status/ns#" xmlns:owl="http://www.w3.org/2002/07/owl#" xmlns:xsd="http://www.w3.org/2001/XMLSchema#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" xmlns:vann="http://purl.org/vocab/vann/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:skos="http://www.w3.org/2004/02/skos/core#" xmlns:wi="http://example.com/wi#" xmlns:days="http://ontologi.es/days#" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" > <head> <head> <link type="text/css" rel="stylesheet" href="style/style.css"> <link rel="alternate" href="schema.dot"/> <link rel="alternate" href="schema.ttl"/> <link rel="alternate" href="index.rdf"/> </head> <body> <h2 id="glance">Weighted Interest at a glance</h2> +<p>This is a draft vocabulary for describing preferences within +contexts, developed for the NoTube project.</p> <!-- summary a-z --> %s <img src="schema.png" alt="image of the schema"/> <h3>Other versions:</h3> <ul> <li> <a href="index.rdf">RDF/XML version of the schema</a> </li> <li> <a href="schema.dot">Graphviz dot file</a> </li> </ul> <h2>Introduction</h2> <p>The weighted interests vocabulary allows you to describe groups of ordered preferences, i.e. to describe that an agent prefers one thing to another. It can also be used to say that an agent is not interested in something. </p> <p>Here's an example in words:</p> <pre> I prefer radio 4 over radio 5 when I am working at home (which is every weekday between 8am and 7pm). </pre> <p>and the same example using the vocabulary:</p> <pre> @prefix foaf: &lt;http://xmlns.com/foaf/0.1/&gt; . @prefix wi: &lt;http://example.com/weighted_topics#> . @prefix days: &lt;http://ontologi.es/days#&gt; . @prefix tl: &lt;http://perl.org/NET/c4dm/timeline.owl#&gt; . @prefix xsd: &lt;http://www.w3.org/2001/XMLSchema#&gt; . @base &lt;http://example.org/weighted_topics#&gt; . &lt;http://swordfish.rdfweb.org/people/libby/rdfweb/webwho.xrdf#me&gt; a foaf:Person; foaf:name "Libby Miller"; wi:preference [ a wi:WeightedInterest; wi:topic &lt;http://www.bbc.co.uk/5live#service&gt;; wi:weight "3"; wi:scale "0..9"; wi:context &lt;#working&gt; ] ; wi:preference [ a wi:WeightedInterest; wi:topic &lt;http://www.bbc.co.uk/radio4#service&gt;; wi:weight "7"; wi:scale "0..9"; wi:context &lt;#working&gt; . ] . &lt;#working&gt; a wi:Context; wi:timePeriod [ a days:WeekdayInterval; tl:at "08:00:00"^^xsd:time ; tl:end "19:00:00"^^xsd:time . ] . </pre> <p>Another example:</p> <pre> I hate the X-Factor </pre> <p>In the vocabulary:</p> <pre> @prefix foaf: &lt;http://xmlns.com/foaf/0.1/&gt; . @prefix wi: &lt;http://example.com/weighted_topics#&gt; . &lt;http://swordfish.rdfweb.org/people/libby/rdfweb/webwho.xrdf#me&gt; a foaf:Person; foaf:name "Libby Miller"; wi:notInterestedIn &lt;http://en.wikipedia.org/wiki/The_X_Factor_(UK)&gt; . </pre> <h3>Aims</h3> <p>The aim of this experimental vocabulary to provide filtering services with a summary of a user's preferences when they are in different environments. It can be combined or used instead of straightforward foaf interest profiles, and be combined with and used instead of information traditionally used to make recommendations to users, in particular age, gender, location. </p> <p>For example:</p> <pre> @prefix foaf: &lt;http://xmlns.com/foaf/0.1/&gt; . @prefix progs: &lt;http://purl.org/ontology/po/&gt; . @prefix geo: &lt;http://www.w3.org/2003/01/geo/wgs84_pos#&gt; . @prefix skos: &lt;http://www.w3.org/2004/02/skos/core#&gt; . &lt;http://swordfish.rdfweb.org/people/libby/rdfweb/webwho.xrdf#me&gt; a foaf:Person; foaf:name "Libby Miller"; foaf:gender "female"; foaf:based_near [ geo:lat 48.402495; geo:long 2.692646 ]; foaf:interest &lt;http://dbpedia.org/resource/Stephen_Fry&gt;; foaf:interest &lt;http://www.bbc.co.uk/programmes/b006qpmv#programme&gt;; foaf:interest &lt;http://www.bbc.co.uk/programmes/b00lvdrj#programme&gt;; foaf:interest &lt;http://www.bbc.co.uk/programmes/b00hg8dq#programme&gt;; foaf:interest &lt;http://www.bbc.co.uk/programmes/b006qykl#programme&gt;; foaf:interest &lt;http://www.bbc.co.uk/5live#service&gt;; foaf:interest &lt;http://www.bbc.co.uk/radio4#service&gt; ; foaf:interest &lt;http://www.bbc.co.uk/programmes/genres/factual&gt; ; foaf:interest &lt;http://www.bbc.co.uk/programmes/genres/factual/artscultureandthemedia&gt; ; foaf:interest &lt;http://dbpedia.org/resource/1980s_in_music&gt; . &lt;http://dbpedia.org/resource/Stephen_Fry&gt; a foaf:Person . &lt;http://www.bbc.co.uk/programmes/b006qpmv#programme&gt; a progs:Brand . &lt;http://www.bbc.co.uk/programmes/b00lvdrj#programme&gt; a progs:Brand . &lt;http://www.bbc.co.uk/programmes/b00hg8dq#programme&gt; a progs:Brand . &lt;http://www.bbc.co.uk/programmes/b006qykl#programme>&gt; a progs:Brand . &lt;http://www.bbc.co.uk/5live#service&gt; a progs:Service . &lt;http://www.bbc.co.uk/radio4#service&gt; a progs:Service . &lt;http://www.bbc.co.uk/programmes/genres/factual&gt; a progs:Genre . &lt;http://www.bbc.co.uk/programmes/genres/factual/artscultureandthemedia&gt; a progs:Genre . &lt;http://dbpedia.org/resource/1980s_in_music&gt; a skos:Concept . </pre> <h3>Modelling technique</h3> <h4>Comparisons</h4> <ul> <li>weights and comparisons need things to weigh against and compare against </li> <li>weights may change with context changes (such as location, time, activity, device), so we make the comparison group the context (e.g: 'Libby prefers 80s rock to classical genres of music' is true only if Libby is going running; 'libby prefers radio4 to radio7' is true only if it's before 11 or after 13 on a weekday)</li> <li>context evidence link - which may give you a more detailed breakdown of the data</li> <li>weights are numeric, as this maps quite nicely to star ratings. Weights are not comparable over contexts but are within them</li> </ul> <h4>Contexts</h4> <ul> <li>can have device, timeperiod, location, as these are measuarable proxies for activities</li> <li>timeperiods relate to repeating periods of time such as every weekend, every week day, every friday between 2 and 4. It uses Toby's 'days of the week' ontology</li> <li>locations are spatialThings</li> <li>devices are urls of documents describing the device</li> </ul> <h2>Classes and Properties (summary)</h2> <!-- this is the a-z listing --> %s <!-- and this is the bulk of the vocab descriptions --> %s <h2> Validation query</h2> <pre> PREFIX xsd: &lt;http://www.w3.org/2001/XMLSchema#&gt; PREFIX rdfs: &lt;http://www.w3.org/2000/01/rdf-schema#&gt; PREFIX rdf: &lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&gt; PREFIX foaf: &lt;http://xmlns.com/foaf/0.1/&gt; PREFIX activ: &lt;http://www.bbc.co.uk/ontologies/activity/&gt; PREFIX wi: &lt;http://example.com/wi#&gt; PREFIX skos: &lt;http://www.w3.org/2004/02/skos/core#&gt; PREFIX days: &lt;http://ontologi.es/days#&gt; PREFIX geo: &lt;http://www.w3.org/2003/01/geo/wgs84_pos#&gt; ASK { ?agent rdf:type foaf:agent . ?agent wi:preference ?wi ?wi rdf:type wi:WeightedInterest . ?wi wi:topic ?topic . OPTIONAL {?topic rdf:type foaf:Document .} OPTIONAL {?topic rdf:type skos:Concept .} ?wi wi:hasContext ?context . OPTIONAL {?context wi:timePeriod ?period . } OPTIONAL {?context wi:location ?location . ?location rdf:type geo:spatialThing .} OPTIONAL {?context wi:device ?device . ?device rdf:type foaf:Document .} FILTER ( bound(?period) || bound(?location) || bound(?device)) OPTIONAL {?wi wi:evidence ?evidence . ?evidence rdf:type foaf:Document .} ?wi wi:weight ?weight . ?wi wi:scale ?scale . FILTER (datatype(?scale) = xsd:string) . FILTER (datatype(?weight) = xsd:int) . } </pre> </body> </html>
leth/SpecGen
6072ae79114a3534d5d0753b1dbf5d87cd32e489
a very drafty schema for weighted interests
diff --git a/examples/weighted-interests/_tmp_spec.html b/examples/weighted-interests/_tmp_spec.html new file mode 100644 index 0000000..3dcc4d6 --- /dev/null +++ b/examples/weighted-interests/_tmp_spec.html @@ -0,0 +1,479 @@ +<?xml version="1.0" encoding="utf-8"?> +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" +xmlns:event="http://purl.org/NET/c4dn/event.owl#" +xmlns:foaf="http://xmlns.com/foaf/0.1/" +xmlns:status="http://www.w3.org/2003/06/sw-vocab-status/ns#" +xmlns:owl="http://www.w3.org/2002/07/owl#" +xmlns:xsd="http://www.w3.org/2001/XMLSchema#" +xmlns:dc="http://purl.org/dc/elements/1.1/" +xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" +xmlns:vann="http://purl.org/vocab/vann/" +xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" +xmlns:skos="http://www.w3.org/2004/02/skos/core#" +xmlns:wi="http://example.com/wi#" +xmlns:days="http://ontologi.es/days#" +xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" +> +<head> + <head> + <link type="text/css" rel="stylesheet" href="style/style.css"> + <link rel="alternate" href="schema.dot"/> + <link rel="alternate" href="schema.ttl"/> + <link rel="alternate" href="index.rdf"/> + </head> + <body> + + + <h2 id="glance">Weighted Interest at a glance</h2> + + +<!-- summary a-z --> +<div class="azlist"> +<p>Classes: | <a href="#term_Context">Context</a> | <a href="#term_DocumentsAndConcepts">DocumentsAndConcepts</a> | <a href="#term_TimeIntervalsAndInstants">TimeIntervalsAndInstants</a> | <a href="#term_WeightedInterest">WeightedInterest</a> | +</p> +<p>Properties: | <a href="#term_device">device</a> | <a href="#term_evidence">evidence</a> | <a href="#term_hasContext">hasContext</a> | <a href="#term_location">location</a> | <a href="#term_notInterestedIn">notInterestedIn</a> | <a href="#term_preference">preference</a> | <a href="#term_scale">scale</a> | <a href="#term_timePeriod">timePeriod</a> | <a href="#term_topic">topic</a> | <a href="#term_weight">weight</a> | +</p> +</div> + + <img src="schema.png" alt="image of the schema"/> + + + <h3>Other versions:</h3> + <ul> + <li> + <a href="index.rdf">RDF/XML version of the schema</a> + </li> + <li> + <a href="schema.dot">Graphviz dot file</a> + </li> + </ul> + + +<h2>Introduction</h2> + +<p>The weighted interests vocabulary allows you to describe groups of +ordered preferences, i.e. to describe that an agent prefers one thing to +another. It can also be used to say that an agent is not interested in +something. </p> + + +<p>Here's an example in words:</p> + +<pre> +I prefer radio 4 over radio 5 when I am working at home (which is every weekday between 8am and 7pm). +</pre> + +<p>and the same example using the vocabulary:</p> + +<pre> +@prefix foaf: &lt;http://xmlns.com/foaf/0.1/&gt; . +@prefix wi: &lt;http://example.com/weighted_topics#> . +@prefix days: &lt;http://ontologi.es/days#&gt; . +@prefix tl: &lt;http://perl.org/NET/c4dm/timeline.owl#&gt; . +@prefix xsd: &lt;http://www.w3.org/2001/XMLSchema#&gt; . +@base &lt;http://example.org/weighted_topics#&gt; . + &lt;http://swordfish.rdfweb.org/people/libby/rdfweb/webwho.xrdf#me&gt; + a foaf:Person; + foaf:name "Libby Miller"; + wi:preference [ + a wi:WeightedInterest; + wi:topic &lt;http://www.bbc.co.uk/5live#service&gt;; + wi:weight "3"; + wi:scale "0..9"; + wi:context &lt;#working&gt; + ] ; + wi:preference [ + a wi:WeightedInterest; + wi:topic &lt;http://www.bbc.co.uk/radio4#service&gt;; + wi:weight "7"; + wi:scale "0..9"; + wi:context &lt;#working&gt; . + ] . + &lt;#working&gt; a wi:Context; + wi:timePeriod [ + a days:WeekdayInterval; + tl:at "08:00:00"^^xsd:time ; + tl:end "19:00:00"^^xsd:time . + ] . +</pre> + + +<p>Another example:</p> + +<pre> +I hate the X-Factor +</pre> + +<p>In the vocabulary:</p> + +<pre> +@prefix foaf: &lt;http://xmlns.com/foaf/0.1/&gt; . +@prefix wi: &lt;http://example.com/weighted_topics#&gt; . + &lt;http://swordfish.rdfweb.org/people/libby/rdfweb/webwho.xrdf#me&gt; + a foaf:Person; + foaf:name "Libby Miller"; + wi:notInterestedIn &lt;http://en.wikipedia.org/wiki/The_X_Factor_(UK)&gt; . + +</pre> + +<h3>Aims</h3> + +<p>The aim of this experimental vocabulary to provide filtering services +with a summary of a user's preferences when they are in different +environments. It can be combined or used instead of straightforward foaf +interest profiles, and be combined with and used instead of information +traditionally used to make recommendations to users, in particular age, +gender, location. </p> + +<p>For example:</p> + +<pre> +@prefix foaf: &lt;http://xmlns.com/foaf/0.1/&gt; . +@prefix progs: &lt;http://purl.org/ontology/po/&gt; . +@prefix geo: &lt;http://www.w3.org/2003/01/geo/wgs84_pos#&gt; . +@prefix skos: &lt;http://www.w3.org/2004/02/skos/core#&gt; . + + &lt;http://swordfish.rdfweb.org/people/libby/rdfweb/webwho.xrdf#me&gt; + a foaf:Person; + foaf:name "Libby Miller"; + foaf:gender "female"; + foaf:based_near [ geo:lat 48.402495; geo:long 2.692646 ]; + foaf:interest &lt;http://dbpedia.org/resource/Stephen_Fry&gt;; + foaf:interest &lt;http://www.bbc.co.uk/programmes/b006qpmv#programme&gt;; + foaf:interest &lt;http://www.bbc.co.uk/programmes/b00lvdrj#programme&gt;; + foaf:interest &lt;http://www.bbc.co.uk/programmes/b00hg8dq#programme&gt;; + foaf:interest &lt;http://www.bbc.co.uk/programmes/b006qykl#programme&gt;; + foaf:interest &lt;http://www.bbc.co.uk/5live#service&gt;; + foaf:interest &lt;http://www.bbc.co.uk/radio4#service&gt; ; + foaf:interest &lt;http://www.bbc.co.uk/programmes/genres/factual&gt; ; + foaf:interest &lt;http://www.bbc.co.uk/programmes/genres/factual/artscultureandthemedia&gt; ; + foaf:interest &lt;http://dbpedia.org/resource/1980s_in_music&gt; . + + &lt;http://dbpedia.org/resource/Stephen_Fry&gt; a foaf:Person . + &lt;http://www.bbc.co.uk/programmes/b006qpmv#programme&gt; a progs:Brand . + &lt;http://www.bbc.co.uk/programmes/b00lvdrj#programme&gt; a progs:Brand . + &lt;http://www.bbc.co.uk/programmes/b00hg8dq#programme&gt; a progs:Brand . + &lt;http://www.bbc.co.uk/programmes/b006qykl#programme>&gt; a progs:Brand . + &lt;http://www.bbc.co.uk/5live#service&gt; a progs:Service . + &lt;http://www.bbc.co.uk/radio4#service&gt; a progs:Service . + &lt;http://www.bbc.co.uk/programmes/genres/factual&gt; a progs:Genre . + &lt;http://www.bbc.co.uk/programmes/genres/factual/artscultureandthemedia&gt; a progs:Genre . + &lt;http://dbpedia.org/resource/1980s_in_music&gt; a skos:Concept . +</pre> + +<h3>Modelling technique</h3> + +<h4>Comparisons</h4> + +<ul> +<li>weights and comparisons need things to weigh against and compare against +</li> +<li>weights may change with context changes (such as location, time, activity, device), so we make the comparison group the context +(e.g: 'Libby prefers 80s rock to classical genres of music' is true only if Libby is going running; 'libby prefers radio4 to radio7' is true only if it's before 11 or after 13 on a weekday)</li> +<li>context evidence link - which may give you a more detailed breakdown of the data</li> +<li>weights are numeric, as this maps quite nicely to star ratings. Weights are not comparable over contexts but are within them</li> +</ul> + +<h4>Contexts</h4> + +<ul> +<li>can have device, timeperiod, location, as these are measuarable proxies for activities</li> +<li>timeperiods relate to repeating periods of time such as every weekend, every week day, every friday between 2 and 4. It uses Toby's 'days of the week' ontology</li> +<li>locations are spatialThings</li> +<li>devices are urls of documents describing the device</li> +</ul> + +<h2>Classes and Properties (summary)</h2> + +<!-- this is the a-z listing --> +<div class="azlist"> +<p>Classes: | <a href="#term_Context">Context</a> | <a href="#term_DocumentsAndConcepts">DocumentsAndConcepts</a> | <a href="#term_TimeIntervalsAndInstants">TimeIntervalsAndInstants</a> | <a href="#term_WeightedInterest">WeightedInterest</a> | +</p> +<p>Properties: | <a href="#term_device">device</a> | <a href="#term_evidence">evidence</a> | <a href="#term_hasContext">hasContext</a> | <a href="#term_location">location</a> | <a href="#term_notInterestedIn">notInterestedIn</a> | <a href="#term_preference">preference</a> | <a href="#term_scale">scale</a> | <a href="#term_timePeriod">timePeriod</a> | <a href="#term_topic">topic</a> | <a href="#term_weight">weight</a> | +</p> +</div> + + +<!-- and this is the bulk of the vocab descriptions --> +<div class="termlist"><h3>Classes and Properties (full detail)</h3> +<div class='termdetails'><br /> + +<h2>Classes</h2> + + +<div class="specterm" id="term_Context" about="http://example.com/wi#Context" typeof="rdfs:Class"> + <h3>Class: wi:Context</h3> + <em>A Context object</em> - A context object <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>May be the object of:</th> + <td> <a href="#term_device">A device</a> + <a href="#term_location">A location</a> + <a href="#term_evidence">Evidence</a> + <a href="#term_timePeriod">A time period</a> + </td></tr> + <tr><th>May have properties:</th> + <td> <a href="#term_hasContext">A context</a> +</td></tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_Context">#</a>] <!-- Context --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_DocumentsAndConcepts" about="http://example.com/wi#DocumentsAndConcepts" typeof="rdfs:Class"> + <h3>Class: wi:DocumentsAndConcepts</h3> + <em>Documents and concepts</em> - The union of documents and concepts <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + + <tr><th>May have properties:</th> + <td> <a href="#term_notInterestedIn">Something of no interest</a> + <a href="#term_topic">A topic</a> +</td></tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_DocumentsAndConcepts">#</a>] <!-- DocumentsAndConcepts --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_TimeIntervalsAndInstants" about="http://example.com/wi#TimeIntervalsAndInstants" typeof="rdfs:Class"> + <h3>Class: wi:TimeIntervalsAndInstants</h3> + <em>Intervals and instants</em> - The union of all days intervals and instants <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + + <tr><th>May have properties:</th> + <td> <a href="#term_timePeriod">A time period</a> +</td></tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_TimeIntervalsAndInstants">#</a>] <!-- TimeIntervalsAndInstants --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_WeightedInterest" about="http://example.com/wi#WeightedInterest" typeof="rdfs:Class"> + <h3>Class: wi:WeightedInterest</h3> + <em>A Weighted Interest</em> - A weighted interest object <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>May be the object of:</th> + <td> <a href="#term_weight">Weight</a> + <a href="#term_hasContext">A context</a> + <a href="#term_topic">A topic</a> + <a href="#term_scale">Scale</a> + </td></tr> + <tr><th>May have properties:</th> + <td> <a href="#term_preference">A preference</a> +</td></tr> + </table> + This is one of a number of preferences held by a user, which are grouped +using a context, and ordered within the context using the weight and scale. + + <p style="float: right; font-size: small;">[<a href="#term_WeightedInterest">#</a>] <!-- WeightedInterest --> [<a href="#glance">back to top</a>]</p> + <br/> + </div> +<h2>Properties</h2> + + +<div class="specterm" id="term_device" about="http://example.com/wi#device" typeof="rdf:Property"> + <h3>Property: wi:device</h3> + <em>A device</em> - A document describing a device <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>Domain:</th> + <td> <span rel="rdfs:domain" href="http://example.com/wi#Context"><a href="#term_Context">A Context object</a></span> +</td></tr> + <tr><th>Range:</th> + <td> <span rel="rdfs:range" href="http://xmlns.com/foaf/0.1/Document"><a href="#term_Document">Document</a></span> +</td> </tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_device">#</a>] <!-- device --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_evidence" about="http://example.com/wi#evidence" typeof="rdf:Property"> + <h3>Property: wi:evidence</h3> + <em>Evidence</em> - A link between a context and evidence supporting the interpretation fo preferences in a context <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>Domain:</th> + <td> <span rel="rdfs:domain" href="http://example.com/wi#Context"><a href="#term_Context">A Context object</a></span> +</td></tr> + <tr><th>Range:</th> + <td> <span rel="rdfs:range" href="http://xmlns.com/foaf/0.1/Document"><a href="#term_Document">Document</a></span> +</td> </tr> + </table> + This could be a feed or a sparql query over http for example. It's not +required that a reasoner can use the evidence to derive the preferences +from the evidence. + + <p style="float: right; font-size: small;">[<a href="#term_evidence">#</a>] <!-- evidence --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_hasContext" about="http://example.com/wi#hasContext" typeof="rdf:Property"> + <h3>Property: wi:hasContext</h3> + <em>A context</em> - A link between a WeightedInterest and Context <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>Domain:</th> + <td> <span rel="rdfs:domain" href="http://example.com/wi#WeightedInterest"><a href="#term_WeightedInterest">A Weighted Interest</a></span> +</td></tr> + <tr><th>Range:</th> + <td> <span rel="rdfs:range" href="http://example.com/wi#Context"><a href="#term_Context">A Context object</a></span> +</td> </tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_hasContext">#</a>] <!-- hasContext --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_location" about="http://example.com/wi#location" typeof="rdf:Property"> + <h3>Property: wi:location</h3> + <em>A location</em> - A context location <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>Domain:</th> + <td> <span rel="rdfs:domain" href="http://example.com/wi#Context"><a href="#term_Context">A Context object</a></span> +</td></tr> + + </table> + + <p style="float: right; font-size: small;">[<a href="#term_location">#</a>] <!-- location --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_notInterestedIn" about="http://example.com/wi#notInterestedIn" typeof="rdf:Property"> + <h3>Property: wi:notInterestedIn</h3> + <em>Something of no interest</em> - A link between an agent and a topic of no interest to them <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>Domain:</th> + <td> <span rel="rdfs:domain" href="http://xmlns.com/foaf/0.1/Agent"><a href="#term_Agent">Agent</a></span> +</td></tr> + <tr><th>Range:</th> + <td> <span rel="rdfs:range" href="http://example.com/wi#DocumentsAndConcepts"><a href="#term_DocumentsAndConcepts">Documents and concepts</a></span> +</td> </tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_notInterestedIn">#</a>] <!-- notInterestedIn --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_preference" about="http://example.com/wi#preference" typeof="rdf:Property"> + <h3>Property: wi:preference</h3> + <em>A preference</em> - A link between an agent and a weighted interest <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>Domain:</th> + <td> <span rel="rdfs:domain" href="http://xmlns.com/foaf/0.1/Agent"><a href="#term_Agent">Agent</a></span> +</td></tr> + <tr><th>Range:</th> + <td> <span rel="rdfs:range" href="http://example.com/wi#WeightedInterest"><a href="#term_WeightedInterest">A Weighted Interest</a></span> +</td> </tr> + </table> + Preference points to a WeightedInterest object. + + <p style="float: right; font-size: small;">[<a href="#term_preference">#</a>] <!-- preference --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_scale" about="http://example.com/wi#scale" typeof="rdf:Property"> + <h3>Property: wi:scale</h3> + <em>Scale</em> - The scale with respect to the weight - of the form 0..9. Scale can be any range of integers. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>Domain:</th> + <td> <span rel="rdfs:domain" href="http://example.com/wi#WeightedInterest"><a href="#term_WeightedInterest">A Weighted Interest</a></span> +</td></tr> + <tr><th>Range:</th> + <td> <span rel="rdfs:range" href="http://www.w3.org/2001/XMLSchema#string"><a href="#term_string">String</a></span> +</td> </tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_scale">#</a>] <!-- scale --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_timePeriod" about="http://example.com/wi#timePeriod" typeof="rdf:Property"> + <h3>Property: wi:timePeriod</h3> + <em>A time period</em> - A time period of a context <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>Domain:</th> + <td> <span rel="rdfs:domain" href="http://example.com/wi#Context"><a href="#term_Context">A Context object</a></span> +</td></tr> + <tr><th>Range:</th> + <td> <span rel="rdfs:range" href="http://example.com/wi#TimeIntervalsAndInstants"><a href="#term_TimeIntervalsAndInstants">Intervals and instants</a></span> +</td> </tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_timePeriod">#</a>] <!-- timePeriod --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_topic" about="http://example.com/wi#topic" typeof="rdf:Property"> + <h3>Property: wi:topic</h3> + <em>A topic</em> - A topic of the weighted interest <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>Domain:</th> + <td> <span rel="rdfs:domain" href="http://example.com/wi#WeightedInterest"><a href="#term_WeightedInterest">A Weighted Interest</a></span> +</td></tr> + <tr><th>Range:</th> + <td> <span rel="rdfs:range" href="http://example.com/wi#DocumentsAndConcepts"><a href="#term_DocumentsAndConcepts">Documents and concepts</a></span> +</td> </tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_topic">#</a>] <!-- topic --> [<a href="#glance">back to top</a>]</p> + <br/> + </div><div class="specterm" id="term_weight" about="http://example.com/wi#weight" typeof="rdf:Property"> + <h3>Property: wi:weight</h3> + <em>Weight</em> - The weight on the topic <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>Domain:</th> + <td> <span rel="rdfs:domain" href="http://example.com/wi#WeightedInterest"><a href="#term_WeightedInterest">A Weighted Interest</a></span> +</td></tr> + <tr><th>Range:</th> + <td> <span rel="rdfs:range" href="http://www.w3.org/2001/XMLSchema#int"><a href="#term_int">Integer</a></span> +</td> </tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_weight">#</a>] <!-- weight --> [<a href="#glance">back to top</a>]</p> + <br/> + </div> + + + + + +</div> +</div> + +<h2> Validation query</h2> + +<pre> + PREFIX xsd: &lt;http://www.w3.org/2001/XMLSchema#&gt; + PREFIX rdfs: &lt;http://www.w3.org/2000/01/rdf-schema#&gt; + PREFIX rdf: &lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&gt; + PREFIX foaf: &lt;http://xmlns.com/foaf/0.1/&gt; + PREFIX activ: &lt;http://www.bbc.co.uk/ontologies/activity/&gt; + PREFIX wi: &lt;http://example.com/wi#&gt; + PREFIX skos: &lt;http://www.w3.org/2004/02/skos/core#&gt; + PREFIX days: &lt;http://ontologi.es/days#&gt; + PREFIX geo: &lt;http://www.w3.org/2003/01/geo/wgs84_pos#&gt; + + ASK { + ?agent rdf:type foaf:agent . + ?agent wi:preference ?wi + + ?wi rdf:type wi:WeightedInterest . + ?wi wi:topic ?topic . + + OPTIONAL {?topic rdf:type foaf:Document .} + OPTIONAL {?topic rdf:type skos:Concept .} + + ?wi wi:hasContext ?context . + + OPTIONAL {?context wi:timePeriod ?period . } + OPTIONAL {?context wi:location ?location . ?location rdf:type geo:spatialThing .} + OPTIONAL {?context wi:device ?device . ?device rdf:type foaf:Document .} + + FILTER ( bound(?period) || bound(?location) || bound(?device)) + + OPTIONAL {?wi wi:evidence ?evidence . ?evidence rdf:type foaf:Document .} + + ?wi wi:weight ?weight . + ?wi wi:scale ?scale . + + FILTER (datatype(?scale) = xsd:string) . + FILTER (datatype(?weight) = xsd:int) . + } + +</pre> + + </body> +</html> + diff --git a/examples/weighted-interests/create_dot_file.rb b/examples/weighted-interests/create_dot_file.rb new file mode 100644 index 0000000..217ba7e --- /dev/null +++ b/examples/weighted-interests/create_dot_file.rb @@ -0,0 +1,348 @@ +require 'rubygems' +require 'uri' +require 'open-uri' +require 'net/http' +require 'hpricot' +require 'digest/sha1' +require 'reddy' + +def createDotFile(graph) + #hmmm would be cool + #loop through all, getting out types + # if not a type make a link + nodes = {} + links = [] + count = 0 + text = "digraph Summary_Graph {\nratio=0.7\n" + graph.triples.each do |t| + if nodes.include?(t.object.to_s) + n = nodes[t.object.to_s] + else + n = "n#{count}" + nodes[t.object.to_s]=n + count=count+1 + end + + if nodes.include?(t.subject.to_s) + n2 = nodes[t.subject.to_s] + else + n2 = "n#{count}" + nodes[t.subject.to_s]=n2 + count=count+1 + end + + if t.predicate.to_s=="http://www.w3.org/1999/02/22-rdf-syntax-ns#type" + else + r = t.predicate.to_s + if (r =~ /.*\/(.*)/ ) + r = $1 + end + if (r =~ /.*#(.*)/ ) + r = $1 + end + links.push("#{n2}->#{n} [label=\"#{r}\"]") + end + end + #puts nodes + + nodes.each_key do |k| + r = k.to_s + if (r =~ /.*\/(.*)/ ) + r = $1 + end + if (r =~ /.*#(.*)/ ) + r = $1 + end + text << "#{nodes[k]} [label=\"#{r}\"]\n" + end + text << links.join("\n") + text << "\n}" + #puts text + file = File.new("test.dot", "w") + file.puts(text) +end + + +def createDotFileFromSchema(graph, xmlns_hash) + #puts xmlns_hash + #use domain and range to create links + + nodes = {} + links = [] + count = 0 + text = "digraph Summary_Graph {\nratio=0.7\n" + graph.triples.each do |t| + +##object properties + + if t.predicate.to_s=="http://www.w3.org/1999/02/22-rdf-syntax-ns#type" && t.object.to_s == "http://www.w3.org/2002/07/owl#ObjectProperty" + s = t.subject + #dd = graph.each_with_subject(s) + #puts "S: "+s.to_s+"\n" + + ss = s.to_s + + ns = "" + if (ss =~ /(http.*)#(.*)/ ) + ns = $1+"#" + ss = $2 + else + if (ss =~ /(http.*)\/(.*)/ ) + ns = $1+"/" + ss = $2 + end + end + + nssm="" + #puts "NS "+ns + if ns && ns!="" + nssm = xmlns_hash[ns] + end + foo = nssm.gsub(/xmlns:/,"") + ss=foo+":"+ss + + dom="" + ran="" + + graph.triples.each do |tt| + if tt.subject.to_s==s.to_s && tt.predicate.to_s=="http://www.w3.org/2000/01/rdf-schema#domain" + + ns = "" + dom = tt.object.to_s + if (dom =~ /(http.*)#(.*)/ ) + ns = $1+"#" + dom = $2 + else + if (dom =~ /(http.*)\/(.*)/ ) + ns = $1+"/" + dom = $2 + end + end + + nssm="" + if ns && ns!="" + nssm = xmlns_hash[ns] + end + foo = nssm.gsub(/xmlns:/,"") + dom=foo+":"+dom + + if nodes.include?(dom) + else + nodes[dom]=dom + end + #print "domain: "+tt.object.to_s+"\n" + end + if tt.subject.to_s==s.to_s && tt.predicate.to_s=="http://www.w3.org/2000/01/rdf-schema#range" + + ns = "" + ran = tt.object.to_s + if (ran =~ /(http.*)#(.*)/ ) + ns = $1+"#" + ran = $2 + else + if (ran =~ /(http.*)\/(.*)/ ) + ns = $1+"/" + ran = $2 + end + end + + nssm="" + if ns && ns!="" + nssm = xmlns_hash[ns] + end + foo = nssm.gsub(/xmlns:/,"") + ran=foo+":"+ran + + links.push("\"#{dom}\"->\"#{ran}\" [label=\"#{ss}\"]") + + if nodes.include?(ran) + else + nodes[ran]=ran + end + + #print "range: "+tt.object.to_s+"\n" + end + end + end + +#datatype properties + + + if t.predicate.to_s=="http://www.w3.org/1999/02/22-rdf-syntax-ns#type" && t.object.to_s == "http://www.w3.org/2002/07/owl#DatatypeProperty" + s = t.subject + #dd = graph.each_with_subject(s) + #puts "S: "+s.to_s+"\n" + ss = s.to_s + + ns = "" + if (ss =~ /(http.*)#(.*)/ ) + ns = $1+"#" + ss = $2 + else + if (ss =~ /(http.*)\/(.*)/ ) + ns = $1+"/" + ss = $2 + end + end + + nssm="" + #puts "NS "+ns + if ns && ns!="" + nssm = xmlns_hash[ns] + end + foo = nssm.gsub(/xmlns:/,"") + ss=foo+":"+ss + + dom="" + ran="" + graph.triples.each do |tt| + if tt.subject.to_s==s.to_s && tt.predicate.to_s=="http://www.w3.org/2000/01/rdf-schema#domain" + ns = "" + dom = tt.object.to_s + if (dom =~ /(http.*)#(.*)/ ) + ns = $1+"#" + dom = $2 + else + if (dom =~ /(http.*)\/(.*)/ ) + ns = $1+"/" + dom = $2 + end + end + + nssm="" + if ns && ns!="" + nssm = xmlns_hash[ns] + end + foo = nssm.gsub(/xmlns:/,"") + dom=foo+":"+dom + + if nodes.include?(dom) + else + nodes[dom]=dom + end + #print "domain: "+tt.object.to_s+"\n" + end + if tt.subject.to_s==s.to_s && tt.predicate.to_s=="http://www.w3.org/2000/01/rdf-schema#range" + + ns = "" + ran = tt.object.to_s + if (ran =~ /(http.*)#(.*)/ ) + ns = $1+"#" + ran = $2 + else + if (ran =~ /(http.*)\/(.*)/ ) + ns = $1+"/" + ran = $2 + end + end + + nssm="" + if ns && ns!="" + nssm = xmlns_hash[ns] + end + foo = nssm.gsub(/xmlns:/,"") + ran=foo+":"+ran + + + links.push("\"#{dom}\"->\"#{ran}\" [label=\"#{ss}\"]") + + if nodes.include?(ran) + else + nodes[ran]=ran + end + #print "range: "+tt.object.to_s+"\n" + end + end + end + +# note - just handle unionOf, parsetype=collection etc + +# any remaining classes + + if t.predicate.to_s=="http://www.w3.org/1999/02/22-rdf-syntax-ns#type" && (t.object.to_s=="http://www.w3.org/2000/01/rdf-schema#Class" || t.object.to_s=="http://www.w3.org/2002/07/owl#Class") + s = t.subject + puts "S: "+s.to_s+"\n" + + ss = s.to_s + + ns = "" + if (ss =~ /(http.*)#(.*)/ ) + ns = $1+"#" + ss = $2 + else + if (ss =~ /(http.*)\/(.*)/ ) + ns = $1+"/" + ss = $2 + end + end + + nssm="" + #puts "NS "+ns + if ns && ns!="" + nssm = xmlns_hash[ns] + end + foo = nssm.gsub(/xmlns:/,"") + ss=foo+":"+ss + + if nodes.include?(ss) + else + nodes[ss]=ss + end + end + + end + + + nodes.each_key do |k| + text << "\"#{nodes[k]}\" [label=\"#{k}\"]\n" + end + text << links.join("\n") + text << "\n}" + #puts text + file = File.new("test_schema.dot", "w") + file.puts(text) + +end + + + +def has_object(graph,object) + graph.triples.each do |value| + if value.object == object + return true + end + end + return false +end + +def each_with_object(graph, object) + graph.triples.each do |value| + yield value if value.object == object + end +end + + +begin + #load rdfxml file + doc = File.read("index.rdf") + parser = RdfXmlParser.new(doc) + + xml = Hpricot.XML(doc) + xmlns_hash = {} + (xml/'rdf:RDF').each do |item| + h = item.attributes + h.each do |xmlns| + short = xmlns[0] + uri = xmlns[1] + xmlns_hash[uri]=short + parser.graph.namespace(uri, short) + end + end + + + puts parser.graph.to_ntriples +# createDotFile(parser.graph) + createDotFileFromSchema(parser.graph, xmlns_hash) + +end + diff --git a/examples/weighted-interests/doc/WeightedInterest.en b/examples/weighted-interests/doc/WeightedInterest.en new file mode 100644 index 0000000..b78d935 --- /dev/null +++ b/examples/weighted-interests/doc/WeightedInterest.en @@ -0,0 +1,2 @@ +This is one of a number of preferences held by a user, which are grouped +using a context, and ordered within the context using the weight and scale. diff --git a/examples/weighted-interests/doc/WeightedInterest.sparql b/examples/weighted-interests/doc/WeightedInterest.sparql new file mode 100644 index 0000000..52eb62a --- /dev/null +++ b/examples/weighted-interests/doc/WeightedInterest.sparql @@ -0,0 +1,39 @@ +#weighted interest + PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> + PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> + PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> + PREFIX foaf: <http://xmlns.com/foaf/0.1/> + PREFIX activ: <http://www.bbc.co.uk/ontologies/activity/> + PREFIX wi: <http://example.com/wi#> + PREFIX skos: <http://www.w3.org/2004/02/skos/core#> + PREFIX days: <http://ontologi.es/days#> + PREFIX geo: <http://www.w3.org/2003/01/geo/wgs84_pos#> + + ASK { + ?agent rdf:type foaf:agent . + ?agent wi:preference ?wi + + ?wi rdf:type wi:WeightedInterest . + ?wi wi:topic ?topic . + + OPTIONAL {?topic rdf:type foaf:Document .} + OPTIONAL {?topic rdf:type skos:Concept .} + + ?wi wi:hasContext ?context . + + OPTIONAL {?context wi:timePeriod ?period . } + OPTIONAL {?context wi:location ?location . ?location rdf:type geo:spatialThing .} + OPTIONAL {?context wi:device ?device . ?device rdf:type foaf:Document .} + + FILTER ( bound(?period) || bound(?location) || bound(?device)) + + OPTIONAL {?wi wi:evidence ?evidence . ?evidence rdf:type foaf:Document .} + + ?wi wi:weight ?weight . + ?wi wi:scale ?scale . + + FILTER (datatype(?scale) = xsd:string) . + FILTER (datatype(?weight) = xsd:int) . + + } + diff --git a/examples/weighted-interests/doc/evidence.en b/examples/weighted-interests/doc/evidence.en new file mode 100644 index 0000000..ead4bb3 --- /dev/null +++ b/examples/weighted-interests/doc/evidence.en @@ -0,0 +1,3 @@ +This could be a feed or a sparql query over http for example. It's not +required that a reasoner can use the evidence to derive the preferences +from the evidence. diff --git a/examples/weighted-interests/doc/preference.en b/examples/weighted-interests/doc/preference.en new file mode 100644 index 0000000..ae08699 --- /dev/null +++ b/examples/weighted-interests/doc/preference.en @@ -0,0 +1 @@ +Preference points to a WeightedInterest object. diff --git a/examples/weighted-interests/index.rdf b/examples/weighted-interests/index.rdf new file mode 100644 index 0000000..69dcaae --- /dev/null +++ b/examples/weighted-interests/index.rdf @@ -0,0 +1,199 @@ +<?xml version="1.0"?> +<rdf:RDF xmlns:event="http://purl.org/NET/c4dn/event.owl#" +xmlns:foaf="http://xmlns.com/foaf/0.1/" +xmlns:status="http://www.w3.org/2003/06/sw-vocab-status/ns#" +xmlns:owl="http://www.w3.org/2002/07/owl#" +xmlns:xsd="http://www.w3.org/2001/XMLSchema#" +xmlns:dc="http://purl.org/dc/elements/1.1/" +xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" +xmlns:vann="http://purl.org/vocab/vann/" +xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" +xmlns:skos="http://www.w3.org/2004/02/skos/core#" +xmlns:days="http://ontologi.es/days#" +xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" +xmlns:wi="http://example.com/wi#"> + + <owl:Ontology rdf:about="http://example.com/wi#"> + <vann:preferredNamespaceUri>http://example.com/wi#</vann:preferredNamespaceUri> + <vann:preferredNamespacePrefix>wi</vann:preferredNamespacePrefix> + <dc:title>A vocabulary for weighted interests</dc:title> + <rdfs:comment>Draft vocabulary for describing preferences within contexts</rdfs:comment> + <foaf:maker rdf:resource="http://swordfish.rdfweb.org/people/libby/rdfweb/webwho.xrdf#me"/> + <!-- more makers too, esp danbri, toby, dave --> + </owl:Ontology> + + <rdfs:Class rdf:about="http://example.com/wi#WeightedInterest"> + <status:term_status>unstable</status:term_status> + <rdfs:label>A Weighted Interest</rdfs:label> + <rdfs:comment>A weighted interest object</rdfs:comment> + </rdfs:Class> + + <rdfs:Class rdf:about="http://example.com/wi#Context"> + <status:term_status>unstable</status:term_status> + <rdfs:label>A Context object</rdfs:label> + <rdfs:comment>A context object</rdfs:comment> + </rdfs:Class> + + <owl:ObjectProperty rdf:about="http://example.com/wi#preference"> + <rdf:type rdf:resource="http://www.w3.org/1999/02/22-rdf-syntax-ns#Property"/> + <status:term_status>unstable</status:term_status> + <rdfs:label>A preference</rdfs:label> + <rdfs:comment>A link between an agent and a weighted interest</rdfs:comment> + <rdfs:domain rdf:resource="http://xmlns.com/foaf/0.1/Agent"/> + <rdfs:range rdf:resource="http://example.com/wi#WeightedInterest"/> + </owl:ObjectProperty> + + <owl:ObjectProperty rdf:about="http://example.com/wi#notInterestedIn"> + <rdf:type rdf:resource="http://www.w3.org/1999/02/22-rdf-syntax-ns#Property"/> + <status:term_status>unstable</status:term_status> + <rdfs:label>Something of no interest</rdfs:label> + <rdfs:comment>A link between an agent and a topic of no interest to them</rdfs:comment> + <rdfs:domain rdf:resource="http://xmlns.com/foaf/0.1/Agent"/> + <rdfs:range rdf:resource="http://example.com/wi#DocumentsAndConcepts"/> + </owl:ObjectProperty> + + <owl:ObjectProperty rdf:about="http://example.com/wi#evidence"> + <rdf:type rdf:resource="http://www.w3.org/1999/02/22-rdf-syntax-ns#Property"/> + <status:term_status>unstable</status:term_status> + <rdfs:label>Evidence</rdfs:label> + <rdfs:comment>A link between a context and evidence supporting the interpretation fo preferences in a context</rdfs:comment> + <rdfs:domain rdf:resource="http://example.com/wi#Context"/> + <rdfs:range rdf:resource="http://xmlns.com/foaf/0.1/Document"/> + </owl:ObjectProperty> + + <owl:ObjectProperty rdf:about="http://example.com/wi#hasContext"> + <rdf:type rdf:resource="http://www.w3.org/1999/02/22-rdf-syntax-ns#Property"/> + <status:term_status>unstable</status:term_status> + <rdfs:label>A context</rdfs:label> + <rdfs:comment>A link between a WeightedInterest and Context</rdfs:comment> + <rdfs:domain rdf:resource="http://example.com/wi#WeightedInterest"/> + <rdfs:range rdf:resource="http://example.com/wi#Context"/> + </owl:ObjectProperty> + + <owl:ObjectProperty rdf:about="http://example.com/wi#topic"> + <rdf:type rdf:resource="http://www.w3.org/1999/02/22-rdf-syntax-ns#Property"/> + <rdfs:subPropertyOf rdf:resource="http://xmlns.com/foaf/0.1/interest"/> + <status:term_status>unstable</status:term_status> + <rdfs:label>A topic</rdfs:label> + <rdfs:comment>A topic of the weighted interest</rdfs:comment> + <rdfs:domain rdf:resource="http://example.com/wi#WeightedInterest"/> + <rdfs:range rdf:resource="http://example.com/wi#DocumentsAndConcepts"/> + </owl:ObjectProperty> + + <rdfs:Class rdf:about="http://example.com/wi#DocumentsAndConcepts"> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#Class"/> + <rdfs:label>Documents and concepts</rdfs:label> + <rdfs:comment>The union of documents and concepts</rdfs:comment> + <status:term_status>unstable</status:term_status> + <owl:unionOf rdf:parseType="Collection"> + <owl:Class rdf:about="http://xmlns.com/foaf/0.1/Document"/> + <owl:Class rdf:about="http://www.w3.org/2004/02/skos/core#Concept"/> + </owl:unionOf> + </rdfs:Class> + + <owl:ObjectProperty rdf:about="http://example.com/wi#location"> + <rdf:type rdf:resource="http://www.w3.org/1999/02/22-rdf-syntax-ns#Property"/> + <rdfs:subPropertyOf rdf:resource="http://www.w3.org/2003/01/geo/wgs84_pos#location"/> + <status:term_status>unstable</status:term_status> + <rdfs:label>A location</rdfs:label> + <rdfs:comment>A context location</rdfs:comment> + <rdfs:domain rdf:resource="http://example.com/wi#Context"/> + <rdfs:range rdf:resource="http://www.w3.org/2003/01/geo/wgs84_pos#SpatialThing"/> + </owl:ObjectProperty> + + <owl:ObjectProperty rdf:about="http://example.com/wi#device"> + <rdf:type rdf:resource="http://www.w3.org/1999/02/22-rdf-syntax-ns#Property"/> + <status:term_status>unstable</status:term_status> + <rdfs:label>A device</rdfs:label> + <rdfs:comment>A document describing a device</rdfs:comment> + <rdfs:domain rdf:resource="http://example.com/wi#Context"/> + <rdfs:range rdf:resource="http://xmlns.com/foaf/0.1/Document"/> + </owl:ObjectProperty> + + <owl:ObjectProperty rdf:about="http://example.com/wi#timePeriod"> + <rdf:type rdf:resource="http://www.w3.org/1999/02/22-rdf-syntax-ns#Property"/> + <rdfs:subPropertyOf rdf:resource="http://xmlns.com/foaf/0.1/interest"/> + <status:term_status>unstable</status:term_status> + <rdfs:label>A time period</rdfs:label> + <rdfs:comment>A time period of a context</rdfs:comment> + <rdfs:domain rdf:resource="http://example.com/wi#Context"/> + <rdfs:range rdf:resource="http://example.com/wi#TimeIntervalsAndInstants"/> + </owl:ObjectProperty> + + <rdfs:Class rdf:about="http://example.com/wi#TimeIntervalsAndInstants"> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#Class"/> + <rdfs:label>Intervals and instants</rdfs:label> + <status:term_status>unstable</status:term_status> + <rdfs:comment>The union of all days intervals and instants</rdfs:comment> + <owl:unionOf rdf:parseType="Collection"> + <owl:Class rdf:about="http://ontologi.es/days#MondayInterval"/> + <owl:Class rdf:about="http://ontologi.es/days#MondayInstant"/> + <owl:Class rdf:about="http://ontologi.es/days#TuesdayInterval"/> + <owl:Class rdf:about="http://ontologi.es/days#TuesdayInstant"/> + <owl:Class rdf:about="http://ontologi.es/days#WednesdayInterval"/> + <owl:Class rdf:about="http://ontologi.es/days#WednesdayInstant"/> + <owl:Class rdf:about="http://ontologi.es/days#ThursdayInterval"/> + <owl:Class rdf:about="http://ontologi.es/days#ThursdayInstant"/> + <owl:Class rdf:about="http://ontologi.es/days#FridayInterval"/> + <owl:Class rdf:about="http://ontologi.es/days#FridayInstant"/> + <owl:Class rdf:about="http://ontologi.es/days#SaturdayInterval"/> + <owl:Class rdf:about="http://ontologi.es/days#SaturdayInstant"/> + <owl:Class rdf:about="http://ontologi.es/days#SundayInterval"/> + <owl:Class rdf:about="http://ontologi.es/days#SundayInstant"/> + <owl:Class rdf:about="http://ontologi.es/days#WeekdayInterval"/> + <owl:Class rdf:about="http://ontologi.es/days#WeekdayInstant"/> + <owl:Class rdf:about="http://ontologi.es/days#WeekendDayInterval"/> + <owl:Class rdf:about="http://ontologi.es/days#WeekendDayInstant"/> + <owl:Class rdf:about="http://ontologi.es/days#DayInterval"/> + <owl:Class rdf:about="http://ontologi.es/days#DayInstant"/> + <owl:Class rdf:about="http://ontologi.es/days#HolidayInterval"/> + <owl:Class rdf:about="http://ontologi.es/days#HolidayInstant"/> + </owl:unionOf> + </rdfs:Class> + + + <owl:DatatypeProperty rdf:about="http://example.com/wi#weight"> + <rdf:type rdf:resource="http://www.w3.org/1999/02/22-rdf-syntax-ns#Property"/> + <status:term_status>unstable</status:term_status> + <rdfs:label>Weight</rdfs:label> + <rdfs:comment>The weight on the topic</rdfs:comment> + <rdfs:domain rdf:resource="http://example.com/wi#WeightedInterest"/> + <rdfs:range rdf:resource="http://www.w3.org/2001/XMLSchema#int"/> + </owl:DatatypeProperty> + + <owl:DatatypeProperty rdf:about="http://example.com/wi#scale"> + <rdf:type rdf:resource="http://www.w3.org/1999/02/22-rdf-syntax-ns#Property"/> + <status:term_status>unstable</status:term_status> + <rdfs:label>Scale</rdfs:label> + <rdfs:comment>The scale with respect to the weight - of the form 0..9. Scale can be any range of integers.</rdfs:comment> + <rdfs:domain rdf:resource="http://example.com/wi#WeightedInterest"/> + <rdfs:range rdf:resource="http://www.w3.org/2001/XMLSchema#string"/> + </owl:DatatypeProperty> + +<!-- other classes referred to but not defined here --> +<!-- the labels are required in order for some of the queries to work propertly--> + <rdfs:Class rdf:about="http://www.w3.org/2001/XMLSchema#int"> + <rdfs:isDefinedBy rdf:resource="http://www.w3.org/2001/XMLSchema#"/> + <rdfs:label>Integer</rdfs:label> + </rdfs:Class> + <rdfs:Class rdf:about="http://www.w3.org/2001/XMLSchema#string"> + <rdfs:isDefinedBy rdf:resource="http://www.w3.org/2001/XMLSchema#"/> + <rdfs:label>String</rdfs:label> + </rdfs:Class> + <rdfs:Class rdf:about="http://www.w3.org/2004/02/skos/core#Concept"> + <rdfs:isDefinedBy rdf:resource="http://www.w3.org/2004/02/skos/core#"/> + <rdfs:label>Concept</rdfs:label> + </rdfs:Class> + <rdfs:Class rdf:about="http://xmlns.com/foaf/0.1/Document"> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + <rdfs:label>Document</rdfs:label> + </rdfs:Class> + <rdfs:Class rdf:about="http://xmlns.com/foaf/0.1/Agent"> + <rdfs:isDefinedBy rdf:resource="http://xmlns.com/foaf/0.1/"/> + <rdfs:label>Agent</rdfs:label> + </rdfs:Class> + <rdf:Property rdf:about="http://www.w3.org/2003/01/geo/wgs84_pos#location"> + <rdfs:isDefinedBy rdf:resource="http://www.w3.org/2003/01/geo/wgs84_pos#"/> + <rdfs:label>Location</rdfs:label> + </rdf:Property> +</rdf:RDF> diff --git a/examples/weighted-interests/schema.dot b/examples/weighted-interests/schema.dot new file mode 100644 index 0000000..26fea3f --- /dev/null +++ b/examples/weighted-interests/schema.dot @@ -0,0 +1,26 @@ +digraph Summary_Graph { +ratio=0.7 +"wi:DocumentsAndConcepts" [label="wi:DocumentsAndConcepts"] +"xsd:int" [label="xsd:int"] +"geo:SpatialThing" [label="geo:SpatialThing"] +"wi:WeightedInterest" [label="wi:WeightedInterest"] +"foaf:Agent" [label="foaf:Agent"] +"wi:TimeIntervalsAndInstants" [label="wi:TimeIntervalsAndInstants"] +"xsd:string" [label="xsd:string"] +"foaf:Document" [label="foaf:Document"] +"wi:Context" [label="wi:Context"] +"skos:Concept" [label="skos:Concept"] +"foaf:Agent"->"wi:WeightedInterest" [label="wi:preference"] +"foaf:Agent"->"wi:DocumentsAndConcepts" [label="wi:notInterestedIn"] +"wi:Context"->"foaf:Document" [label="wi:evidence"] +"wi:WeightedInterest"->"wi:Context" [label="wi:hasContext"] +"wi:WeightedInterest"->"wi:DocumentsAndConcepts" [label="wi:topic"] +"wi:Context"->"geo:SpatialThing" [label="wi:location"] +"wi:Context"->"foaf:Document" [label="wi:device"] +"wi:Context"->"wi:TimeIntervalsAndInstants" [label="wi:timePeriod"] +"wi:WeightedInterest"->"xsd:int" [label="wi:weight"] +"wi:WeightedInterest"->"xsd:string" [label="wi:scale"] +"wi:DocumentsAndConcepts"->"foaf:Document" [label="owl:unionOf"] +"wi:DocumentsAndConcepts"->"skos:Concept" [label="owl:unionOf"] + +} diff --git a/examples/weighted-interests/schema.png b/examples/weighted-interests/schema.png new file mode 100644 index 0000000..9ffa5b6 Binary files /dev/null and b/examples/weighted-interests/schema.png differ diff --git a/examples/weighted-interests/template.html b/examples/weighted-interests/template.html new file mode 100644 index 0000000..b309f1d --- /dev/null +++ b/examples/weighted-interests/template.html @@ -0,0 +1,235 @@ +<?xml version="1.0" encoding="utf-8"?> +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" +xmlns:event="http://purl.org/NET/c4dn/event.owl#" +xmlns:foaf="http://xmlns.com/foaf/0.1/" +xmlns:status="http://www.w3.org/2003/06/sw-vocab-status/ns#" +xmlns:owl="http://www.w3.org/2002/07/owl#" +xmlns:xsd="http://www.w3.org/2001/XMLSchema#" +xmlns:dc="http://purl.org/dc/elements/1.1/" +xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" +xmlns:vann="http://purl.org/vocab/vann/" +xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" +xmlns:skos="http://www.w3.org/2004/02/skos/core#" +xmlns:wi="http://example.com/wi#" +xmlns:days="http://ontologi.es/days#" +xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" +> +<head> + <head> + <link type="text/css" rel="stylesheet" href="style/style.css"> + <link rel="alternate" href="schema.dot"/> + <link rel="alternate" href="schema.ttl"/> + <link rel="alternate" href="index.rdf"/> + </head> + <body> + + + <h2 id="glance">Weighted Interest at a glance</h2> + + +<!-- summary a-z --> +%s + + <img src="schema.png" alt="image of the schema"/> + + + <h3>Other versions:</h3> + <ul> + <li> + <a href="index.rdf">RDF/XML version of the schema</a> + </li> + <li> + <a href="schema.dot">Graphviz dot file</a> + </li> + </ul> + + +<h2>Introduction</h2> + +<p>The weighted interests vocabulary allows you to describe groups of +ordered preferences, i.e. to describe that an agent prefers one thing to +another. It can also be used to say that an agent is not interested in +something. </p> + + +<p>Here's an example in words:</p> + +<pre> +I prefer radio 4 over radio 5 when I am working at home (which is every weekday between 8am and 7pm). +</pre> + +<p>and the same example using the vocabulary:</p> + +<pre> +@prefix foaf: &lt;http://xmlns.com/foaf/0.1/&gt; . +@prefix wi: &lt;http://example.com/weighted_topics#> . +@prefix days: &lt;http://ontologi.es/days#&gt; . +@prefix tl: &lt;http://perl.org/NET/c4dm/timeline.owl#&gt; . +@prefix xsd: &lt;http://www.w3.org/2001/XMLSchema#&gt; . +@base &lt;http://example.org/weighted_topics#&gt; . + &lt;http://swordfish.rdfweb.org/people/libby/rdfweb/webwho.xrdf#me&gt; + a foaf:Person; + foaf:name "Libby Miller"; + wi:preference [ + a wi:WeightedInterest; + wi:topic &lt;http://www.bbc.co.uk/5live#service&gt;; + wi:weight "3"; + wi:scale "0..9"; + wi:context &lt;#working&gt; + ] ; + wi:preference [ + a wi:WeightedInterest; + wi:topic &lt;http://www.bbc.co.uk/radio4#service&gt;; + wi:weight "7"; + wi:scale "0..9"; + wi:context &lt;#working&gt; . + ] . + &lt;#working&gt; a wi:Context; + wi:timePeriod [ + a days:WeekdayInterval; + tl:at "08:00:00"^^xsd:time ; + tl:end "19:00:00"^^xsd:time . + ] . +</pre> + + +<p>Another example:</p> + +<pre> +I hate the X-Factor +</pre> + +<p>In the vocabulary:</p> + +<pre> +@prefix foaf: &lt;http://xmlns.com/foaf/0.1/&gt; . +@prefix wi: &lt;http://example.com/weighted_topics#&gt; . + &lt;http://swordfish.rdfweb.org/people/libby/rdfweb/webwho.xrdf#me&gt; + a foaf:Person; + foaf:name "Libby Miller"; + wi:notInterestedIn &lt;http://en.wikipedia.org/wiki/The_X_Factor_(UK)&gt; . + +</pre> + +<h3>Aims</h3> + +<p>The aim of this experimental vocabulary to provide filtering services +with a summary of a user's preferences when they are in different +environments. It can be combined or used instead of straightforward foaf +interest profiles, and be combined with and used instead of information +traditionally used to make recommendations to users, in particular age, +gender, location. </p> + +<p>For example:</p> + +<pre> +@prefix foaf: &lt;http://xmlns.com/foaf/0.1/&gt; . +@prefix progs: &lt;http://purl.org/ontology/po/&gt; . +@prefix geo: &lt;http://www.w3.org/2003/01/geo/wgs84_pos#&gt; . +@prefix skos: &lt;http://www.w3.org/2004/02/skos/core#&gt; . + + &lt;http://swordfish.rdfweb.org/people/libby/rdfweb/webwho.xrdf#me&gt; + a foaf:Person; + foaf:name "Libby Miller"; + foaf:gender "female"; + foaf:based_near [ geo:lat 48.402495; geo:long 2.692646 ]; + foaf:interest &lt;http://dbpedia.org/resource/Stephen_Fry&gt;; + foaf:interest &lt;http://www.bbc.co.uk/programmes/b006qpmv#programme&gt;; + foaf:interest &lt;http://www.bbc.co.uk/programmes/b00lvdrj#programme&gt;; + foaf:interest &lt;http://www.bbc.co.uk/programmes/b00hg8dq#programme&gt;; + foaf:interest &lt;http://www.bbc.co.uk/programmes/b006qykl#programme&gt;; + foaf:interest &lt;http://www.bbc.co.uk/5live#service&gt;; + foaf:interest &lt;http://www.bbc.co.uk/radio4#service&gt; ; + foaf:interest &lt;http://www.bbc.co.uk/programmes/genres/factual&gt; ; + foaf:interest &lt;http://www.bbc.co.uk/programmes/genres/factual/artscultureandthemedia&gt; ; + foaf:interest &lt;http://dbpedia.org/resource/1980s_in_music&gt; . + + &lt;http://dbpedia.org/resource/Stephen_Fry&gt; a foaf:Person . + &lt;http://www.bbc.co.uk/programmes/b006qpmv#programme&gt; a progs:Brand . + &lt;http://www.bbc.co.uk/programmes/b00lvdrj#programme&gt; a progs:Brand . + &lt;http://www.bbc.co.uk/programmes/b00hg8dq#programme&gt; a progs:Brand . + &lt;http://www.bbc.co.uk/programmes/b006qykl#programme>&gt; a progs:Brand . + &lt;http://www.bbc.co.uk/5live#service&gt; a progs:Service . + &lt;http://www.bbc.co.uk/radio4#service&gt; a progs:Service . + &lt;http://www.bbc.co.uk/programmes/genres/factual&gt; a progs:Genre . + &lt;http://www.bbc.co.uk/programmes/genres/factual/artscultureandthemedia&gt; a progs:Genre . + &lt;http://dbpedia.org/resource/1980s_in_music&gt; a skos:Concept . +</pre> + +<h3>Modelling technique</h3> + +<h4>Comparisons</h4> + +<ul> +<li>weights and comparisons need things to weigh against and compare against +</li> +<li>weights may change with context changes (such as location, time, activity, device), so we make the comparison group the context +(e.g: 'Libby prefers 80s rock to classical genres of music' is true only if Libby is going running; 'libby prefers radio4 to radio7' is true only if it's before 11 or after 13 on a weekday)</li> +<li>context evidence link - which may give you a more detailed breakdown of the data</li> +<li>weights are numeric, as this maps quite nicely to star ratings. Weights are not comparable over contexts but are within them</li> +</ul> + +<h4>Contexts</h4> + +<ul> +<li>can have device, timeperiod, location, as these are measuarable proxies for activities</li> +<li>timeperiods relate to repeating periods of time such as every weekend, every week day, every friday between 2 and 4. It uses Toby's 'days of the week' ontology</li> +<li>locations are spatialThings</li> +<li>devices are urls of documents describing the device</li> +</ul> + +<h2>Classes and Properties (summary)</h2> + +<!-- this is the a-z listing --> +%s + + +<!-- and this is the bulk of the vocab descriptions --> +%s + +<h2> Validation query</h2> + +<pre> + PREFIX xsd: &lt;http://www.w3.org/2001/XMLSchema#&gt; + PREFIX rdfs: &lt;http://www.w3.org/2000/01/rdf-schema#&gt; + PREFIX rdf: &lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&gt; + PREFIX foaf: &lt;http://xmlns.com/foaf/0.1/&gt; + PREFIX activ: &lt;http://www.bbc.co.uk/ontologies/activity/&gt; + PREFIX wi: &lt;http://example.com/wi#&gt; + PREFIX skos: &lt;http://www.w3.org/2004/02/skos/core#&gt; + PREFIX days: &lt;http://ontologi.es/days#&gt; + PREFIX geo: &lt;http://www.w3.org/2003/01/geo/wgs84_pos#&gt; + + ASK { + ?agent rdf:type foaf:agent . + ?agent wi:preference ?wi + + ?wi rdf:type wi:WeightedInterest . + ?wi wi:topic ?topic . + + OPTIONAL {?topic rdf:type foaf:Document .} + OPTIONAL {?topic rdf:type skos:Concept .} + + ?wi wi:hasContext ?context . + + OPTIONAL {?context wi:timePeriod ?period . } + OPTIONAL {?context wi:location ?location . ?location rdf:type geo:spatialThing .} + OPTIONAL {?context wi:device ?device . ?device rdf:type foaf:Document .} + + FILTER ( bound(?period) || bound(?location) || bound(?device)) + + OPTIONAL {?wi wi:evidence ?evidence . ?evidence rdf:type foaf:Document .} + + ?wi wi:weight ?weight . + ?wi wi:scale ?scale . + + FILTER (datatype(?scale) = xsd:string) . + FILTER (datatype(?weight) = xsd:int) . + } + +</pre> + + </body> +</html> +
leth/SpecGen
1cf201baf8f1376dfa153eee4f847c5385b5b7d5
swapped round unstable and testing as per the spec
diff --git a/libvocab.py b/libvocab.py index 1519aa3..756cc2b 100755 --- a/libvocab.py +++ b/libvocab.py @@ -1,837 +1,837 @@ #!/usr/bin/env python # total rewrite. --danbri # Usage: # # >>> from libvocab import Vocab, Term, Class, Property # # >>> from libvocab import Vocab, Term, Class, Property # >>> v = Vocab( f='examples/foaf/index.rdf', uri='http://xmlns.com/foaf/0.1/') # >>> dna = v.lookup('http://xmlns.com/foaf/0.1/dnaChecksum') # >>> dna.label # 'DNA checksum' # >>> dna.comment # 'A checksum for the DNA of some thing. Joke.' # >>> dna.id # u'dnaChecksum' # >>> dna.uri # 'http://xmlns.com/foaf/0.1/dnaChecksum' # # # Python OO notes: # http://www.devshed.com/c/a/Python/Object-Oriented-Programming-With-Python-part-1/ # http://www.daniweb.com/code/snippet354.html # http://docs.python.org/reference/datamodel.html#specialnames # # RDFlib: # http://www.science.uva.nl/research/air/wiki/RDFlib # # http://dowhatimean.net/2006/03/spellchecking-vocabularies-with-sparql # # We define basics, Vocab, Term, Property, Class # and populate them with data from RDF schemas, OWL, translations ... and nearby html files. import rdflib from rdflib import Namespace from rdflib.Graph import Graph from rdflib.Graph import ConjunctiveGraph from rdflib.sparql.sparqlGraph import SPARQLGraph from rdflib.sparql.graphPattern import GraphPattern from rdflib.sparql.bison import Parse from rdflib.sparql import Query FOAF = Namespace('http://xmlns.com/foaf/0.1/') RDFS = Namespace('http://www.w3.org/2000/01/rdf-schema#') XFN = Namespace("http://gmpg.org/xfn/1#") RDF = Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#") OWL = Namespace('http://www.w3.org/2002/07/owl#') VS = Namespace('http://www.w3.org/2003/06/sw-vocab-status/ns#') DC = Namespace('http://purl.org/dc/elements/1.1/') DOAP = Namespace('http://usefulinc.com/ns/doap#') SIOC = Namespace('http://rdfs.org/sioc/ns#') SIOCTYPES = Namespace('http://rdfs.org/sioc/types#') SIOCSERVICES = Namespace('http://rdfs.org/sioc/services#') # # TODO: rationalise these two lists. or at least check they are same. import sys, time, re, urllib, getopt import logging import os.path import cgi import operator bindings = { u"xfn": XFN, u"rdf": RDF, u"rdfs": RDFS, u"vs": VS } #g = None def speclog(str): sys.stderr.write("LOG: "+str+"\n") # todo: shouldn't be foaf specific def termlink(text): result = re.sub( r"<code>foaf:(\w+)<\/code>", r"<code><a href='#term_\g<1>'>\g<1></a></code>", text ) return result # a Term has... (intrinsically and via it's RDFS/OWL description) # uri - a (primary) URI, eg. 'http://xmlns.com/foaf/0.1/workplaceHomepage' # id - a local-to-spec ID, eg. 'workplaceHomepage' # xmlns - an xmlns URI (isDefinedBy, eg. 'http://xmlns.com/foaf/0.1/') # # label - an rdfs:label # comment - an rdfs:comment # # Beyond this, properties vary. Some have vs:status. Some have owl Deprecated. # Some have OWL descriptions, and RDFS descriptions; eg. property range/domain # or class disjointness. def ns_split(uri): regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) return(rez.group(1), rez.group(2)) class Term(object): def __init__(self, uri='file://dev/null'): self.uri = str(uri) self.uri = self.uri.rstrip() # speclog("Parsing URI " + uri) a,b = ns_split(uri) self.id = b self.xmlns = a if self.id==None: speclog("Error parsing URI. "+uri) if self.xmlns==None: speclog("Error parsing URI. "+uri) # print "self.id: "+ self.id + " self.xmlns: " + self.xmlns def uri(self): try: s = self.uri except NameError: self.uri = None s = '[NOURI]' speclog('No URI for'+self) return s def id(self): print "trying id" try: s = self.id except NameError: self.id = None s = '[NOID]' speclog('No ID for'+self) return str(s) def is_external(self, vocab): print "Comparing property URI ",self.uri," with vocab uri: " + vocab.uri return(False) #def __repr__(self): # return(self.__str__) def __str__(self): try: s = self.id except NameError: self.label = None speclog('No label for '+self+' todo: take from uri regex') s = (str(self)) return(str(s)) # so we can treat this like a string def __add__(self, s): return (s+str(self)) def __radd__(self, s): return (s+str(self)) def simple_report(self): t = self s='' s += "default: \t\t"+t +"\n" s += "id: \t\t"+t.id +"\n" s += "uri: \t\t"+t.uri +"\n" s += "xmlns: \t\t"+t.xmlns +"\n" s += "label: \t\t"+t.label +"\n" s += "comment: \t\t" + t.comment +"\n" s += "status: \t\t" + t.status +"\n" s += "\n" return s def _get_status(self): try: return self._status except: return 'unknown' def _set_status(self, value): self._status = str(value) status = property(_get_status,_set_status) # a Python class representing an RDFS/OWL property. # class Property(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Property.is_property called on "+self return(True) def is_class(self): # print "Property.is_class called on "+self return(False) # A Python class representing an RDFS/OWL class # class Class(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Class.is_property called on "+self return(False) def is_class(self): # print "Class.is_class called on "+self return(True) # A python class representing (a description of) some RDF vocabulary # class Vocab(object): def __init__(self, dir, f='index.rdf', uri=None ): self.graph = rdflib.ConjunctiveGraph() self._uri = uri self.dir = dir self.filename = os.path.join(dir, f) self.graph.parse(self.filename) self.terms = [] self.uterms = [] # should also load translations here? # and deal with a base-dir? ##if f != None: ## self.index() self.ns_list = { "http://www.w3.org/1999/02/22-rdf-syntax-ns#" : "rdf", "http://www.w3.org/2000/01/rdf-schema#" : "rdfs", "http://www.w3.org/2002/07/owl#" : "owl", "http://www.w3.org/2001/XMLSchema#" : "xsd", "http://rdfs.org/sioc/ns#" : "sioc", "http://xmlns.com/foaf/0.1/" : "foaf", "http://purl.org/dc/elements/1.1/" : "dc", "http://purl.org/dc/terms/" : "dct", "http://usefulinc.com/ns/doap#" : "doap", "http://www.w3.org/2003/06/sw-vocab-status/ns#" : "status", "http://purl.org/rss/1.0/modules/content/" : "content", "http://www.w3.org/2003/01/geo/wgs84_pos#" : "geo", "http://www.w3.org/2004/02/skos/core#" : "skos", "http://purl.org/NET/c4dm/event.owl#" : "event" } def addShortName(self,sn): self.ns_list[self._uri] = sn self.shortName = sn #print self.ns_list # not currently used def unique_terms(self): tmp=[] for t in list(set(self.terms)): s = str(t) if (not s in tmp): self.uterms.append(t) tmp.append(s) # TODO: python question - can we skip needing getters? and only define setters. i tried/failed. --danbri def _get_uri(self): return self._uri def _set_uri(self, value): v = str(value) # we don't want Namespace() objects and suchlike, but we can use them without whining. if ':' not in v: speclog("Warning: this doesn't look like a URI: "+v) # raise Exception("This doesn't look like a URI.") self._uri = str( value ) uri = property(_get_uri,_set_uri) def set_filename(self, filename): self.filename = filename # TODO: be explicit if/where we default to English # TODO: do we need a separate index(), versus just use __init__ ? def index(self): # speclog("Indexing description of "+str(self)) # blank down anything we learned already self.terms = [] self.properties = [] self.classes = [] tmpclasses=[] tmpproperties=[] g = self.graph query = Parse('SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a rdf:Property } ') relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: p = Property(term) # print "Made a property! "+str(p) + "using label: "#+str(label) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) query = Parse('SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type FILTER (?type = <http://www.w3.org/2002/07/owl#Class> || ?type = <http://www.w3.org/2000/01/rdf-schema#Class> ) }') relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: c = Class(term) # print "Made a class! "+str(p) + "using comment: "+comment c.label = str(label) c.comment = str(comment) self.terms.append(c) if (not str(c) in tmpclasses): self.classes.append(c) tmpclasses.append(str(c)) self.terms.sort(key=operator.attrgetter('id')) self.classes.sort(key=operator.attrgetter('id')) self.properties.sort(key=operator.attrgetter('id')) # http://www.w3.org/2003/06/sw-vocab-status/ns#" query = Parse('SELECT ?x ?vs WHERE { ?x <http://www.w3.org/2003/06/sw-vocab-status/ns#term_status> ?vs }') status = g.query(query, initNs=bindings) # print "status results: ",status.__len__() for x, vs in status: #print "STATUS: ",vs, " for ",x t = self.lookup(x) if t != None: t.status = vs # print "Set status.", t.status else: speclog("Couldn't lookup term: "+x) # Go back and see if we missed any properties defined in OWL. TODO: classes too. Or rewrite above SPARQL. addd more types for full query. q= 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty>)}' q= 'SELECT distinct ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty> || ?type = <http://www.w3.org/2002/07/owl#DatatypeProperty> || ?type = <http://www.w3.org/1999/02/22-rdf-syntax-ns#Property> || ?type = <http://www.w3.org/2002/07/owl#FunctionalProperty> || ?type = <http://www.w3.org/2002/07/owl#InverseFunctionalProperty>) } ' query = Parse(q) relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: p = Property(str(term)) got = self.lookup( str(term) ) if got==None: # print "Made an OWL property! "+str(p.uri) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) # self.terms.sort() # does this even do anything? # self.classes.sort() # self.properties.sort() # todo, use a dictionary index instead. RTFM. def lookup(self, uri): uri = str(uri) for t in self.terms: # print "Lookup: comparing '"+t.uri+"' to '"+uri+"'" # print "type of t.uri is ",t.uri.__class__ if t.uri==uri: # print "Matched." # should we str here, to be more liberal? return t else: # print "Fail." '' return None # print a raw debug summary, direct from the RDF def raw(self): g = self.graph query = Parse('SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c } ') relations = g.query(query, initNs=bindings) print "Properties and Classes (%d terms)" % len(relations) print 40*"-" for (term, label, comment) in relations: print "term %s l: %s \t\tc: %s " % (term, label, comment) print # TODO: work out how to do ".encode('UTF-8')" here # for debugging only def detect_types(self): self.properties = [] self.classes = [] for t in self.terms: # print "Doing t: "+t+" which is of type " + str(t.__class__) if t.is_property(): # print "is_property." self.properties.append(t) if t.is_class(): # print "is_class." self.classes.append(t) # CODE FROM ORIGINAL specgen: def niceName(self, uri = None ): if uri is None: return # speclog("Nicing uri "+uri) regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) if rez == None: #print "Failed to niceName. Returning the whole thing." return(uri) pref = rez.group(1) # print "...",self.ns_list.get(pref, pref),":",rez.group(2) # todo: make this work when uri doesn't match the regex --danbri # AttributeError: 'NoneType' object has no attribute 'group' return self.ns_list.get(pref, pref) + ":" + rez.group(2) # HTML stuff, should be a separate class def azlist(self): """Builds the A-Z list of terms""" c_ids = [] p_ids = [] for p in self.properties: p_ids.append(str(p.id)) for c in self.classes: c_ids.append(str(c.id)) c_ids.sort() p_ids.sort() return (c_ids, p_ids) class VocabReport(object): def __init__(self, vocab, basedir='./examples/', temploc='template.html',templatedir='./examples/'): self.vocab = vocab self.basedir = basedir self.temploc = temploc self.templatedir = templatedir self._template = "no template loaded" # text.gsub(/<code>foaf:(\w+)<\/code>/){ defurl($1) } return "<code><a href=\"#term_#{term}\">foaf:#{term}</a></code>" def codelink(self, s): reg1 = re.compile(r"""<code>foaf:(\w+)<\/code>""") return(re.sub(reg1, r"""<code><a href="#term_\1">foaf:\1</a></code>""", s)) def _get_template(self): self._template = self.load_template() # should be conditional return self._template def _set_template(self, value): self._template = str(value) template = property(_get_template,_set_template) def load_template(self): filename = os.path.join(self.templatedir, self.temploc) f = open(filename, "r") template = f.read() return(template) def generate(self): tpl = self.template azlist = self.az() termlist = self.termlist() f = open ( self.vocab.filename, "r") rdfdata = f.read() # print "GENERATING >>>>>>>> " ## having the rdf in there was making it invalid ## removed in favour of RDFa ## tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8"), rdfdata) tpl = tpl % (azlist.encode("utf-8"), azlist.encode("utf-8"), termlist.encode("utf-8")) return(tpl) def az(self): """AZ List for html doc""" c_ids, p_ids = self.vocab.azlist() az = """<div class="azlist">""" az = """%s\n<p>Classes: |""" % az # print c_ids, p_ids for c in c_ids: # speclog("Class "+c+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(c).replace(" ", ""), c) az = """%s\n</p>""" % az az = """%s\n<p>Properties: |""" % az for p in p_ids: # speclog("Property "+p+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(p).replace(" ", ""), p) az = """%s\n</p>""" % az az = """%s\n</div>""" % az return(az) def termlist(self): """Term List for html doc""" stableTxt = '' - unstableTxt = '' testingTxt = '' + unstableTxt = '' archaicTxt = '' queries = '' c_ids, p_ids = self.vocab.azlist() tl = """<div class="termlist">""" tl = """%s<h3>Classes and Properties (full detail)</h3>\n<div class='termdetails'><br />\n\n""" % tl # first classes, then properties eg = """<div class="specterm" id="term_%s" about="%s" typeof="%s"> <h3>%s: %s</h3> <em>%s</em> - %s <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#%s">%s</span></td></tr> %s %s </table> %s <p style="float: right; font-size: small;">[<a href="#term_%s">#</a>] <!-- %s --> [<a href="#glance">back to top</a>]</p> <br/> </div>""" # replace this if you want validation queries: xxx danbri # <p style="float: right; font-size: small;">[<a href="#term_%s">permalink</a>] [<a href="#queries_%s">validation queries</a>] [<a href="#glance">back to top</a>]</p> # todo, push this into an api call (c_ids currently setup by az above) # classes for term in self.vocab.classes: # strings to use later domainsOfClass = '' rangesOfClass = '' #class in domain of g = self.vocab.graph q = 'SELECT ?d ?l WHERE {?d rdfs:domain <%s> . ?d rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '<tr><th>May be the object of:</th>\n' contentStr = '' for (domain, label) in relations: dom = Term(domain) termStr = """<a href="#term_%s">%s</a>\n""" % (dom.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": domainsOfClass = "%s <td> %s </td></tr>" % (startStr, contentStr) # class in range of q2 = 'SELECT ?d ?l WHERE {?d rdfs:range <%s> . ?d rdfs:label ?l } ' % (term.uri) query2 = Parse(q2) relations2 = g.query(query2, initNs=bindings) startStr = '<tr><th>May have properties:</th>\n' contentStr = '' for (range, label) in relations2: ran = Term(range) termStr = """<a href="#term_%s">%s</a>\n""" % (ran.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": rangesOfClass = "%s <td> %s</td></tr> " % (startStr, contentStr) # class subclassof subClassOf = '' q = 'SELECT ?sc ?l WHERE {<%s> rdfs:subClassOf ?sc . ?sc rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '<tr><th>subClassOf</th>\n' contentStr = '' for (subclass, label) in relations: sub = Term(subclass) termStr = """<span rel="rdfs:subClassOf" href="%s"><a href="#term_%s">%s</a></span>\n""" % (subclass, sub.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": subClassOf = "%s <td> %s </td></tr>" % (startStr, contentStr) # class has subclass hasSubClass = '' q = 'SELECT ?sc ?l WHERE {?sc rdfs:subClassOf <%s>. ?sc rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '<tr><th>has subclass</th>\n' contentStr = '' for (subclass, label) in relations: sub = Term(subclass) termStr = """<a href="#term_%s">%s</a>\n""" % (sub.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": hasSubClass = "%s <td> %s </td></tr>" % (startStr, contentStr) # is defined by classIsDefinedBy = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '\n' contentStr = '' for (isdefinedby) in relations: termStr = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": classIsDefinedBy = "%s <tr><td> %s </td></tr>" % (startStr, contentStr) # disjoint with isDisjointWith = '' q = 'SELECT ?dj ?l WHERE { <%s> <http://www.w3.org/2002/07/owl#disjointWith> ?dj . ?dj rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '<tr><th>Disjoint With:</th>\n' contentStr = '' for (disjointWith, label) in relations: termStr = """<span rel="owl:disjointWith" href="%s"><a href="#term_%s">%s</a></span>\n""" % (disjointWith, label, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": isDisjointWith = "%s <td> %s </td></tr>" % (startStr, contentStr) # end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' # if we want validation queries this is where it looks for them. filename = os.path.join(dn, term.id+".sparql") fileStr = '' try: f = open ( filename, "r") fileStr = f.read() fileStr = "<h4><a name=\"queries_"+term.id+"\"></a>"+term.id+" Validation Query</h4><pre>"+cgi.escape(ss)+"</pre>" except: fileStr='' queries = queries +"\n"+ fileStr sn = self.vocab.niceName(term.uri) s = termlink(s) zz = eg % (term.id,term.uri,"rdfs:Class","Class", sn, term.label, term.comment, term.status,term.status,domainsOfClass,rangesOfClass+subClassOf+hasSubClass+classIsDefinedBy+isDisjointWith, s,term.id, term.id) ## we add to the relevant string - stable, unstable, testing or archaic if(term.status == "stable"): stableTxt = stableTxt + zz - if(term.status == "unstable"): - unstableTxt = unstableTxt + zz if(term.status == "testing"): testingTxt = testingTxt + zz + if(term.status == "unstable"): + unstableTxt = unstableTxt + zz if(term.status == "archaic"): archaicTxt = archaicTxt + zz ## then add the whole thing to the main tl string tl = tl+"<h2>Classes</h2>\n" - tl = "%s %s" % (tl, stableTxt+"\n"+unstableTxt+"\n"+testingTxt+"\n"+archaicTxt) + tl = "%s %s" % (tl, stableTxt+"\n"+testingTxt+"\n"+unstableTxt+"\n"+archaicTxt) tl = tl+"<h2>Properties</h2>\n" # properties stableTxt = '' - unstableTxt = '' testingTxt = '' + unstableTxt = '' archaicTxt = '' for term in self.vocab.properties: domainsOfProperty = '' rangesOfProperty = '' # domain of properties g = self.vocab.graph q = 'SELECT ?d ?l WHERE {<%s> rdfs:domain ?d . ?d rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '<tr><th>Domain:</th>\n' contentStr = '' for (domain, label) in relations: dom = Term(domain) termStr = """<span rel="rdfs:domain" href="%s"><a href="#term_%s">%s</a></span>\n""" % (domain, dom.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": domainsOfProperty = "%s <td>%s</td></tr>" % (startStr, contentStr) # range of properties q2 = 'SELECT ?d ?l WHERE {<%s> rdfs:range ?d . ?d rdfs:label ?l } ' % (term.uri) query2 = Parse(q2) relations2 = g.query(query2, initNs=bindings) startStr = '<tr><th>Range:</th>\n' contentStr = '' for (range, label) in relations2: ran = Term(range) termStr = """<span rel="rdfs:range" href="%s"><a href="#term_%s">%s</a></span>\n""" % (range, ran.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": rangesOfProperty = "%s <td>%s</td> </tr>" % (startStr, contentStr) # is defined by propertyIsDefinedBy = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '\n' contentStr = '' for (isdefinedby) in relations: termStr = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": propertyIsDefinedBy = "%s <tr><td> %s </td></tr>" % (startStr, contentStr) # inverse functional property ifp = '' q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#InverseFunctionalProperty> } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '<tr><th colspan="2">Inverse Functional Property</th>\n' if (len(relations) > 0): termStr = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#InverseFunctionalProperty"></span>""" ifp = "%s <td> %s </td></tr>" % (startStr, termStr) # functonal property fp = '' q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#FunctionalProperty> } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '<tr><th colspan="2">Functional Property</th>\n' if (len(relations) > 0): termStr = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#FunctionalProperty"></span>""" fp = "%s <td> %s </td></tr>" % (startStr, termStr) # end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' sn = self.vocab.niceName(term.uri) s = termlink(s) zz = eg % (term.id, term.uri,"rdf:Property","Property", sn, term.label, term.comment, term.status,term.status,domainsOfProperty,rangesOfProperty+propertyIsDefinedBy+ifp+fp, s,term.id, term.id) ## we add to the relevant string - stable, unstable, testing or archaic if(term.status == "stable"): stableTxt = stableTxt + zz - if(term.status == "unstable"): - unstableTxt = unstableTxt + zz if(term.status == "testing"): testingTxt = testingTxt + zz + if(term.status == "unstable"): + unstableTxt = unstableTxt + zz if(term.status == "archaic"): archaicTxt = archaicTxt + zz ## then add the whole thing to the main tl string - tl = "%s %s" % (tl, stableTxt+"\n"+unstableTxt+"\n"+testingTxt+"\n"+archaicTxt) + tl = "%s %s" % (tl, stableTxt+"\n"+testingTxt+"\n"+unstableTxt+"\n"+archaicTxt) ## tl = "%s %s" % (tl, zz) ## ensure termlist tag is closed return(tl+"\n"+queries+"</div>\n</div>") def rdfa(self): return( "<html>rdfa here</html>") def htmlDocInfo( t, termdir='../docs' ): """Opens a file based on the term name (t) and termdir (defaults to current directory. Reads in the file, and returns a linkified version of it.""" if termdir==None: termdir=self.basedir doc = "" try: f = open("%s/%s.en" % (termdir, t), "r") doc = f.read() doc = termlink(doc) except: return "<p>No detailed documentation for this term.</p>" return doc # report what we've parsed from our various sources def report(self): s = "Report for vocabulary from " + self.vocab.filename + "\n" if self.vocab.uri != None: s += "URI: " + self.vocab.uri + "\n\n" for t in self.vocab.uterms: print "TERM as string: ",t s += t.simple_report() return s
leth/SpecGen
0d5f6ccfae6c6c7030d7347682406fd0abf37c9e
changed so that terms are ordered by stability
diff --git a/libvocab.py b/libvocab.py index 334e580..1519aa3 100755 --- a/libvocab.py +++ b/libvocab.py @@ -1,797 +1,837 @@ #!/usr/bin/env python # total rewrite. --danbri # Usage: # # >>> from libvocab import Vocab, Term, Class, Property # # >>> from libvocab import Vocab, Term, Class, Property # >>> v = Vocab( f='examples/foaf/index.rdf', uri='http://xmlns.com/foaf/0.1/') # >>> dna = v.lookup('http://xmlns.com/foaf/0.1/dnaChecksum') # >>> dna.label # 'DNA checksum' # >>> dna.comment # 'A checksum for the DNA of some thing. Joke.' # >>> dna.id # u'dnaChecksum' # >>> dna.uri # 'http://xmlns.com/foaf/0.1/dnaChecksum' # # # Python OO notes: # http://www.devshed.com/c/a/Python/Object-Oriented-Programming-With-Python-part-1/ # http://www.daniweb.com/code/snippet354.html # http://docs.python.org/reference/datamodel.html#specialnames # # RDFlib: # http://www.science.uva.nl/research/air/wiki/RDFlib # # http://dowhatimean.net/2006/03/spellchecking-vocabularies-with-sparql # # We define basics, Vocab, Term, Property, Class # and populate them with data from RDF schemas, OWL, translations ... and nearby html files. import rdflib from rdflib import Namespace from rdflib.Graph import Graph from rdflib.Graph import ConjunctiveGraph from rdflib.sparql.sparqlGraph import SPARQLGraph from rdflib.sparql.graphPattern import GraphPattern from rdflib.sparql.bison import Parse from rdflib.sparql import Query FOAF = Namespace('http://xmlns.com/foaf/0.1/') RDFS = Namespace('http://www.w3.org/2000/01/rdf-schema#') XFN = Namespace("http://gmpg.org/xfn/1#") RDF = Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#") OWL = Namespace('http://www.w3.org/2002/07/owl#') VS = Namespace('http://www.w3.org/2003/06/sw-vocab-status/ns#') DC = Namespace('http://purl.org/dc/elements/1.1/') DOAP = Namespace('http://usefulinc.com/ns/doap#') SIOC = Namespace('http://rdfs.org/sioc/ns#') SIOCTYPES = Namespace('http://rdfs.org/sioc/types#') SIOCSERVICES = Namespace('http://rdfs.org/sioc/services#') # # TODO: rationalise these two lists. or at least check they are same. import sys, time, re, urllib, getopt import logging import os.path import cgi import operator bindings = { u"xfn": XFN, u"rdf": RDF, u"rdfs": RDFS, u"vs": VS } #g = None def speclog(str): sys.stderr.write("LOG: "+str+"\n") # todo: shouldn't be foaf specific def termlink(text): result = re.sub( r"<code>foaf:(\w+)<\/code>", r"<code><a href='#term_\g<1>'>\g<1></a></code>", text ) return result # a Term has... (intrinsically and via it's RDFS/OWL description) # uri - a (primary) URI, eg. 'http://xmlns.com/foaf/0.1/workplaceHomepage' # id - a local-to-spec ID, eg. 'workplaceHomepage' # xmlns - an xmlns URI (isDefinedBy, eg. 'http://xmlns.com/foaf/0.1/') # # label - an rdfs:label # comment - an rdfs:comment # # Beyond this, properties vary. Some have vs:status. Some have owl Deprecated. # Some have OWL descriptions, and RDFS descriptions; eg. property range/domain # or class disjointness. def ns_split(uri): regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) return(rez.group(1), rez.group(2)) class Term(object): def __init__(self, uri='file://dev/null'): self.uri = str(uri) self.uri = self.uri.rstrip() # speclog("Parsing URI " + uri) a,b = ns_split(uri) self.id = b self.xmlns = a if self.id==None: speclog("Error parsing URI. "+uri) if self.xmlns==None: speclog("Error parsing URI. "+uri) # print "self.id: "+ self.id + " self.xmlns: " + self.xmlns def uri(self): try: s = self.uri except NameError: self.uri = None s = '[NOURI]' speclog('No URI for'+self) return s def id(self): print "trying id" try: s = self.id except NameError: self.id = None s = '[NOID]' speclog('No ID for'+self) return str(s) def is_external(self, vocab): print "Comparing property URI ",self.uri," with vocab uri: " + vocab.uri return(False) #def __repr__(self): # return(self.__str__) def __str__(self): try: s = self.id except NameError: self.label = None speclog('No label for '+self+' todo: take from uri regex') s = (str(self)) return(str(s)) # so we can treat this like a string def __add__(self, s): return (s+str(self)) def __radd__(self, s): return (s+str(self)) def simple_report(self): t = self s='' s += "default: \t\t"+t +"\n" s += "id: \t\t"+t.id +"\n" s += "uri: \t\t"+t.uri +"\n" s += "xmlns: \t\t"+t.xmlns +"\n" s += "label: \t\t"+t.label +"\n" s += "comment: \t\t" + t.comment +"\n" s += "status: \t\t" + t.status +"\n" s += "\n" return s def _get_status(self): try: return self._status except: return 'unknown' def _set_status(self, value): self._status = str(value) status = property(_get_status,_set_status) # a Python class representing an RDFS/OWL property. # class Property(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Property.is_property called on "+self return(True) def is_class(self): # print "Property.is_class called on "+self return(False) # A Python class representing an RDFS/OWL class # class Class(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Class.is_property called on "+self return(False) def is_class(self): # print "Class.is_class called on "+self return(True) # A python class representing (a description of) some RDF vocabulary # class Vocab(object): def __init__(self, dir, f='index.rdf', uri=None ): self.graph = rdflib.ConjunctiveGraph() self._uri = uri self.dir = dir self.filename = os.path.join(dir, f) self.graph.parse(self.filename) self.terms = [] self.uterms = [] # should also load translations here? # and deal with a base-dir? ##if f != None: ## self.index() self.ns_list = { "http://www.w3.org/1999/02/22-rdf-syntax-ns#" : "rdf", "http://www.w3.org/2000/01/rdf-schema#" : "rdfs", "http://www.w3.org/2002/07/owl#" : "owl", "http://www.w3.org/2001/XMLSchema#" : "xsd", "http://rdfs.org/sioc/ns#" : "sioc", "http://xmlns.com/foaf/0.1/" : "foaf", "http://purl.org/dc/elements/1.1/" : "dc", "http://purl.org/dc/terms/" : "dct", "http://usefulinc.com/ns/doap#" : "doap", "http://www.w3.org/2003/06/sw-vocab-status/ns#" : "status", "http://purl.org/rss/1.0/modules/content/" : "content", "http://www.w3.org/2003/01/geo/wgs84_pos#" : "geo", "http://www.w3.org/2004/02/skos/core#" : "skos", "http://purl.org/NET/c4dm/event.owl#" : "event" } def addShortName(self,sn): self.ns_list[self._uri] = sn self.shortName = sn #print self.ns_list # not currently used def unique_terms(self): tmp=[] for t in list(set(self.terms)): s = str(t) if (not s in tmp): self.uterms.append(t) tmp.append(s) # TODO: python question - can we skip needing getters? and only define setters. i tried/failed. --danbri def _get_uri(self): return self._uri def _set_uri(self, value): v = str(value) # we don't want Namespace() objects and suchlike, but we can use them without whining. if ':' not in v: speclog("Warning: this doesn't look like a URI: "+v) # raise Exception("This doesn't look like a URI.") self._uri = str( value ) uri = property(_get_uri,_set_uri) def set_filename(self, filename): self.filename = filename # TODO: be explicit if/where we default to English # TODO: do we need a separate index(), versus just use __init__ ? def index(self): # speclog("Indexing description of "+str(self)) # blank down anything we learned already self.terms = [] self.properties = [] self.classes = [] tmpclasses=[] tmpproperties=[] g = self.graph query = Parse('SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a rdf:Property } ') relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: p = Property(term) # print "Made a property! "+str(p) + "using label: "#+str(label) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) query = Parse('SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type FILTER (?type = <http://www.w3.org/2002/07/owl#Class> || ?type = <http://www.w3.org/2000/01/rdf-schema#Class> ) }') relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: c = Class(term) # print "Made a class! "+str(p) + "using comment: "+comment c.label = str(label) c.comment = str(comment) self.terms.append(c) if (not str(c) in tmpclasses): self.classes.append(c) tmpclasses.append(str(c)) self.terms.sort(key=operator.attrgetter('id')) self.classes.sort(key=operator.attrgetter('id')) self.properties.sort(key=operator.attrgetter('id')) # http://www.w3.org/2003/06/sw-vocab-status/ns#" query = Parse('SELECT ?x ?vs WHERE { ?x <http://www.w3.org/2003/06/sw-vocab-status/ns#term_status> ?vs }') status = g.query(query, initNs=bindings) # print "status results: ",status.__len__() for x, vs in status: #print "STATUS: ",vs, " for ",x t = self.lookup(x) if t != None: t.status = vs # print "Set status.", t.status else: speclog("Couldn't lookup term: "+x) # Go back and see if we missed any properties defined in OWL. TODO: classes too. Or rewrite above SPARQL. addd more types for full query. q= 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty>)}' q= 'SELECT distinct ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty> || ?type = <http://www.w3.org/2002/07/owl#DatatypeProperty> || ?type = <http://www.w3.org/1999/02/22-rdf-syntax-ns#Property> || ?type = <http://www.w3.org/2002/07/owl#FunctionalProperty> || ?type = <http://www.w3.org/2002/07/owl#InverseFunctionalProperty>) } ' query = Parse(q) relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: p = Property(str(term)) got = self.lookup( str(term) ) if got==None: # print "Made an OWL property! "+str(p.uri) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) # self.terms.sort() # does this even do anything? # self.classes.sort() # self.properties.sort() # todo, use a dictionary index instead. RTFM. def lookup(self, uri): uri = str(uri) for t in self.terms: # print "Lookup: comparing '"+t.uri+"' to '"+uri+"'" # print "type of t.uri is ",t.uri.__class__ if t.uri==uri: # print "Matched." # should we str here, to be more liberal? return t else: # print "Fail." '' return None # print a raw debug summary, direct from the RDF def raw(self): g = self.graph query = Parse('SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c } ') relations = g.query(query, initNs=bindings) print "Properties and Classes (%d terms)" % len(relations) print 40*"-" for (term, label, comment) in relations: print "term %s l: %s \t\tc: %s " % (term, label, comment) print # TODO: work out how to do ".encode('UTF-8')" here # for debugging only def detect_types(self): self.properties = [] self.classes = [] for t in self.terms: # print "Doing t: "+t+" which is of type " + str(t.__class__) if t.is_property(): # print "is_property." self.properties.append(t) if t.is_class(): # print "is_class." self.classes.append(t) # CODE FROM ORIGINAL specgen: def niceName(self, uri = None ): if uri is None: return # speclog("Nicing uri "+uri) regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) if rez == None: #print "Failed to niceName. Returning the whole thing." return(uri) pref = rez.group(1) # print "...",self.ns_list.get(pref, pref),":",rez.group(2) # todo: make this work when uri doesn't match the regex --danbri # AttributeError: 'NoneType' object has no attribute 'group' return self.ns_list.get(pref, pref) + ":" + rez.group(2) # HTML stuff, should be a separate class def azlist(self): """Builds the A-Z list of terms""" c_ids = [] p_ids = [] for p in self.properties: p_ids.append(str(p.id)) for c in self.classes: c_ids.append(str(c.id)) c_ids.sort() p_ids.sort() return (c_ids, p_ids) class VocabReport(object): def __init__(self, vocab, basedir='./examples/', temploc='template.html',templatedir='./examples/'): self.vocab = vocab self.basedir = basedir self.temploc = temploc self.templatedir = templatedir self._template = "no template loaded" # text.gsub(/<code>foaf:(\w+)<\/code>/){ defurl($1) } return "<code><a href=\"#term_#{term}\">foaf:#{term}</a></code>" def codelink(self, s): reg1 = re.compile(r"""<code>foaf:(\w+)<\/code>""") return(re.sub(reg1, r"""<code><a href="#term_\1">foaf:\1</a></code>""", s)) def _get_template(self): self._template = self.load_template() # should be conditional return self._template def _set_template(self, value): self._template = str(value) template = property(_get_template,_set_template) def load_template(self): filename = os.path.join(self.templatedir, self.temploc) f = open(filename, "r") template = f.read() return(template) def generate(self): tpl = self.template azlist = self.az() termlist = self.termlist() f = open ( self.vocab.filename, "r") rdfdata = f.read() # print "GENERATING >>>>>>>> " ## having the rdf in there was making it invalid ## removed in favour of RDFa ## tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8"), rdfdata) tpl = tpl % (azlist.encode("utf-8"), azlist.encode("utf-8"), termlist.encode("utf-8")) return(tpl) def az(self): """AZ List for html doc""" c_ids, p_ids = self.vocab.azlist() az = """<div class="azlist">""" az = """%s\n<p>Classes: |""" % az # print c_ids, p_ids for c in c_ids: # speclog("Class "+c+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(c).replace(" ", ""), c) az = """%s\n</p>""" % az az = """%s\n<p>Properties: |""" % az for p in p_ids: # speclog("Property "+p+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(p).replace(" ", ""), p) az = """%s\n</p>""" % az az = """%s\n</div>""" % az return(az) def termlist(self): """Term List for html doc""" + stableTxt = '' + unstableTxt = '' + testingTxt = '' + archaicTxt = '' + queries = '' c_ids, p_ids = self.vocab.azlist() tl = """<div class="termlist">""" tl = """%s<h3>Classes and Properties (full detail)</h3>\n<div class='termdetails'><br />\n\n""" % tl # first classes, then properties eg = """<div class="specterm" id="term_%s" about="%s" typeof="%s"> <h3>%s: %s</h3> <em>%s</em> - %s <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#%s">%s</span></td></tr> %s %s </table> %s <p style="float: right; font-size: small;">[<a href="#term_%s">#</a>] <!-- %s --> [<a href="#glance">back to top</a>]</p> <br/> </div>""" # replace this if you want validation queries: xxx danbri # <p style="float: right; font-size: small;">[<a href="#term_%s">permalink</a>] [<a href="#queries_%s">validation queries</a>] [<a href="#glance">back to top</a>]</p> # todo, push this into an api call (c_ids currently setup by az above) # classes for term in self.vocab.classes: # strings to use later domainsOfClass = '' rangesOfClass = '' #class in domain of g = self.vocab.graph q = 'SELECT ?d ?l WHERE {?d rdfs:domain <%s> . ?d rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '<tr><th>May be the object of:</th>\n' contentStr = '' for (domain, label) in relations: dom = Term(domain) termStr = """<a href="#term_%s">%s</a>\n""" % (dom.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": domainsOfClass = "%s <td> %s </td></tr>" % (startStr, contentStr) # class in range of q2 = 'SELECT ?d ?l WHERE {?d rdfs:range <%s> . ?d rdfs:label ?l } ' % (term.uri) query2 = Parse(q2) relations2 = g.query(query2, initNs=bindings) startStr = '<tr><th>May have properties:</th>\n' contentStr = '' for (range, label) in relations2: ran = Term(range) termStr = """<a href="#term_%s">%s</a>\n""" % (ran.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": rangesOfClass = "%s <td> %s</td></tr> " % (startStr, contentStr) # class subclassof subClassOf = '' q = 'SELECT ?sc ?l WHERE {<%s> rdfs:subClassOf ?sc . ?sc rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '<tr><th>subClassOf</th>\n' contentStr = '' for (subclass, label) in relations: sub = Term(subclass) termStr = """<span rel="rdfs:subClassOf" href="%s"><a href="#term_%s">%s</a></span>\n""" % (subclass, sub.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": subClassOf = "%s <td> %s </td></tr>" % (startStr, contentStr) # class has subclass hasSubClass = '' q = 'SELECT ?sc ?l WHERE {?sc rdfs:subClassOf <%s>. ?sc rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '<tr><th>has subclass</th>\n' contentStr = '' for (subclass, label) in relations: sub = Term(subclass) termStr = """<a href="#term_%s">%s</a>\n""" % (sub.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": hasSubClass = "%s <td> %s </td></tr>" % (startStr, contentStr) # is defined by classIsDefinedBy = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '\n' contentStr = '' for (isdefinedby) in relations: termStr = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": classIsDefinedBy = "%s <tr><td> %s </td></tr>" % (startStr, contentStr) # disjoint with isDisjointWith = '' q = 'SELECT ?dj ?l WHERE { <%s> <http://www.w3.org/2002/07/owl#disjointWith> ?dj . ?dj rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '<tr><th>Disjoint With:</th>\n' contentStr = '' for (disjointWith, label) in relations: termStr = """<span rel="owl:disjointWith" href="%s"><a href="#term_%s">%s</a></span>\n""" % (disjointWith, label, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": isDisjointWith = "%s <td> %s </td></tr>" % (startStr, contentStr) # end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' # if we want validation queries this is where it looks for them. filename = os.path.join(dn, term.id+".sparql") fileStr = '' try: f = open ( filename, "r") fileStr = f.read() fileStr = "<h4><a name=\"queries_"+term.id+"\"></a>"+term.id+" Validation Query</h4><pre>"+cgi.escape(ss)+"</pre>" except: fileStr='' queries = queries +"\n"+ fileStr sn = self.vocab.niceName(term.uri) s = termlink(s) zz = eg % (term.id,term.uri,"rdfs:Class","Class", sn, term.label, term.comment, term.status,term.status,domainsOfClass,rangesOfClass+subClassOf+hasSubClass+classIsDefinedBy+isDisjointWith, s,term.id, term.id) - tl = "%s %s" % (tl, zz) +## we add to the relevant string - stable, unstable, testing or archaic + if(term.status == "stable"): + stableTxt = stableTxt + zz + if(term.status == "unstable"): + unstableTxt = unstableTxt + zz + if(term.status == "testing"): + testingTxt = testingTxt + zz + if(term.status == "archaic"): + archaicTxt = archaicTxt + zz + +## then add the whole thing to the main tl string + + tl = tl+"<h2>Classes</h2>\n" + tl = "%s %s" % (tl, stableTxt+"\n"+unstableTxt+"\n"+testingTxt+"\n"+archaicTxt) + tl = tl+"<h2>Properties</h2>\n" # properties + stableTxt = '' + unstableTxt = '' + testingTxt = '' + archaicTxt = '' + for term in self.vocab.properties: domainsOfProperty = '' rangesOfProperty = '' # domain of properties g = self.vocab.graph q = 'SELECT ?d ?l WHERE {<%s> rdfs:domain ?d . ?d rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '<tr><th>Domain:</th>\n' contentStr = '' for (domain, label) in relations: dom = Term(domain) termStr = """<span rel="rdfs:domain" href="%s"><a href="#term_%s">%s</a></span>\n""" % (domain, dom.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": domainsOfProperty = "%s <td>%s</td></tr>" % (startStr, contentStr) # range of properties q2 = 'SELECT ?d ?l WHERE {<%s> rdfs:range ?d . ?d rdfs:label ?l } ' % (term.uri) query2 = Parse(q2) relations2 = g.query(query2, initNs=bindings) startStr = '<tr><th>Range:</th>\n' contentStr = '' for (range, label) in relations2: ran = Term(range) termStr = """<span rel="rdfs:range" href="%s"><a href="#term_%s">%s</a></span>\n""" % (range, ran.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": rangesOfProperty = "%s <td>%s</td> </tr>" % (startStr, contentStr) # is defined by propertyIsDefinedBy = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '\n' contentStr = '' for (isdefinedby) in relations: termStr = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": propertyIsDefinedBy = "%s <tr><td> %s </td></tr>" % (startStr, contentStr) # inverse functional property ifp = '' q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#InverseFunctionalProperty> } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '<tr><th colspan="2">Inverse Functional Property</th>\n' if (len(relations) > 0): termStr = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#InverseFunctionalProperty"></span>""" ifp = "%s <td> %s </td></tr>" % (startStr, termStr) # functonal property fp = '' q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#FunctionalProperty> } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '<tr><th colspan="2">Functional Property</th>\n' if (len(relations) > 0): termStr = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#FunctionalProperty"></span>""" fp = "%s <td> %s </td></tr>" % (startStr, termStr) # end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' sn = self.vocab.niceName(term.uri) s = termlink(s) zz = eg % (term.id, term.uri,"rdf:Property","Property", sn, term.label, term.comment, term.status,term.status,domainsOfProperty,rangesOfProperty+propertyIsDefinedBy+ifp+fp, s,term.id, term.id) - tl = "%s %s" % (tl, zz) + +## we add to the relevant string - stable, unstable, testing or archaic + if(term.status == "stable"): + stableTxt = stableTxt + zz + if(term.status == "unstable"): + unstableTxt = unstableTxt + zz + if(term.status == "testing"): + testingTxt = testingTxt + zz + if(term.status == "archaic"): + archaicTxt = archaicTxt + zz + +## then add the whole thing to the main tl string + + tl = "%s %s" % (tl, stableTxt+"\n"+unstableTxt+"\n"+testingTxt+"\n"+archaicTxt) + + +## tl = "%s %s" % (tl, zz) ## ensure termlist tag is closed return(tl+"\n"+queries+"</div>\n</div>") def rdfa(self): return( "<html>rdfa here</html>") def htmlDocInfo( t, termdir='../docs' ): """Opens a file based on the term name (t) and termdir (defaults to current directory. Reads in the file, and returns a linkified version of it.""" if termdir==None: termdir=self.basedir doc = "" try: f = open("%s/%s.en" % (termdir, t), "r") doc = f.read() doc = termlink(doc) except: return "<p>No detailed documentation for this term.</p>" return doc # report what we've parsed from our various sources def report(self): s = "Report for vocabulary from " + self.vocab.filename + "\n" if self.vocab.uri != None: s += "URI: " + self.vocab.uri + "\n\n" for t in self.vocab.uterms: print "TERM as string: ",t s += t.simple_report() return s
leth/SpecGen
2cd9b3988927222ad70117e888997c58de0f342c
changes in range of and in domain of - better wording
diff --git a/libvocab.py b/libvocab.py index 494fd58..334e580 100755 --- a/libvocab.py +++ b/libvocab.py @@ -24,774 +24,774 @@ # http://www.daniweb.com/code/snippet354.html # http://docs.python.org/reference/datamodel.html#specialnames # # RDFlib: # http://www.science.uva.nl/research/air/wiki/RDFlib # # http://dowhatimean.net/2006/03/spellchecking-vocabularies-with-sparql # # We define basics, Vocab, Term, Property, Class # and populate them with data from RDF schemas, OWL, translations ... and nearby html files. import rdflib from rdflib import Namespace from rdflib.Graph import Graph from rdflib.Graph import ConjunctiveGraph from rdflib.sparql.sparqlGraph import SPARQLGraph from rdflib.sparql.graphPattern import GraphPattern from rdflib.sparql.bison import Parse from rdflib.sparql import Query FOAF = Namespace('http://xmlns.com/foaf/0.1/') RDFS = Namespace('http://www.w3.org/2000/01/rdf-schema#') XFN = Namespace("http://gmpg.org/xfn/1#") RDF = Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#") OWL = Namespace('http://www.w3.org/2002/07/owl#') VS = Namespace('http://www.w3.org/2003/06/sw-vocab-status/ns#') DC = Namespace('http://purl.org/dc/elements/1.1/') DOAP = Namespace('http://usefulinc.com/ns/doap#') SIOC = Namespace('http://rdfs.org/sioc/ns#') SIOCTYPES = Namespace('http://rdfs.org/sioc/types#') SIOCSERVICES = Namespace('http://rdfs.org/sioc/services#') # # TODO: rationalise these two lists. or at least check they are same. import sys, time, re, urllib, getopt import logging import os.path import cgi import operator bindings = { u"xfn": XFN, u"rdf": RDF, u"rdfs": RDFS, u"vs": VS } #g = None def speclog(str): sys.stderr.write("LOG: "+str+"\n") # todo: shouldn't be foaf specific def termlink(text): result = re.sub( r"<code>foaf:(\w+)<\/code>", r"<code><a href='#term_\g<1>'>\g<1></a></code>", text ) return result # a Term has... (intrinsically and via it's RDFS/OWL description) # uri - a (primary) URI, eg. 'http://xmlns.com/foaf/0.1/workplaceHomepage' # id - a local-to-spec ID, eg. 'workplaceHomepage' # xmlns - an xmlns URI (isDefinedBy, eg. 'http://xmlns.com/foaf/0.1/') # # label - an rdfs:label # comment - an rdfs:comment # # Beyond this, properties vary. Some have vs:status. Some have owl Deprecated. # Some have OWL descriptions, and RDFS descriptions; eg. property range/domain # or class disjointness. def ns_split(uri): regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) return(rez.group(1), rez.group(2)) class Term(object): def __init__(self, uri='file://dev/null'): self.uri = str(uri) self.uri = self.uri.rstrip() # speclog("Parsing URI " + uri) a,b = ns_split(uri) self.id = b self.xmlns = a if self.id==None: speclog("Error parsing URI. "+uri) if self.xmlns==None: speclog("Error parsing URI. "+uri) # print "self.id: "+ self.id + " self.xmlns: " + self.xmlns def uri(self): try: s = self.uri except NameError: self.uri = None s = '[NOURI]' speclog('No URI for'+self) return s def id(self): print "trying id" try: s = self.id except NameError: self.id = None s = '[NOID]' speclog('No ID for'+self) return str(s) def is_external(self, vocab): print "Comparing property URI ",self.uri," with vocab uri: " + vocab.uri return(False) #def __repr__(self): # return(self.__str__) def __str__(self): try: s = self.id except NameError: self.label = None speclog('No label for '+self+' todo: take from uri regex') s = (str(self)) return(str(s)) # so we can treat this like a string def __add__(self, s): return (s+str(self)) def __radd__(self, s): return (s+str(self)) def simple_report(self): t = self s='' s += "default: \t\t"+t +"\n" s += "id: \t\t"+t.id +"\n" s += "uri: \t\t"+t.uri +"\n" s += "xmlns: \t\t"+t.xmlns +"\n" s += "label: \t\t"+t.label +"\n" s += "comment: \t\t" + t.comment +"\n" s += "status: \t\t" + t.status +"\n" s += "\n" return s def _get_status(self): try: return self._status except: return 'unknown' def _set_status(self, value): self._status = str(value) status = property(_get_status,_set_status) # a Python class representing an RDFS/OWL property. # class Property(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Property.is_property called on "+self return(True) def is_class(self): # print "Property.is_class called on "+self return(False) # A Python class representing an RDFS/OWL class # class Class(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Class.is_property called on "+self return(False) def is_class(self): # print "Class.is_class called on "+self return(True) # A python class representing (a description of) some RDF vocabulary # class Vocab(object): def __init__(self, dir, f='index.rdf', uri=None ): self.graph = rdflib.ConjunctiveGraph() self._uri = uri self.dir = dir self.filename = os.path.join(dir, f) self.graph.parse(self.filename) self.terms = [] self.uterms = [] # should also load translations here? # and deal with a base-dir? ##if f != None: ## self.index() self.ns_list = { "http://www.w3.org/1999/02/22-rdf-syntax-ns#" : "rdf", "http://www.w3.org/2000/01/rdf-schema#" : "rdfs", "http://www.w3.org/2002/07/owl#" : "owl", "http://www.w3.org/2001/XMLSchema#" : "xsd", "http://rdfs.org/sioc/ns#" : "sioc", "http://xmlns.com/foaf/0.1/" : "foaf", "http://purl.org/dc/elements/1.1/" : "dc", "http://purl.org/dc/terms/" : "dct", "http://usefulinc.com/ns/doap#" : "doap", "http://www.w3.org/2003/06/sw-vocab-status/ns#" : "status", "http://purl.org/rss/1.0/modules/content/" : "content", "http://www.w3.org/2003/01/geo/wgs84_pos#" : "geo", "http://www.w3.org/2004/02/skos/core#" : "skos", "http://purl.org/NET/c4dm/event.owl#" : "event" } def addShortName(self,sn): self.ns_list[self._uri] = sn self.shortName = sn #print self.ns_list # not currently used def unique_terms(self): tmp=[] for t in list(set(self.terms)): s = str(t) if (not s in tmp): self.uterms.append(t) tmp.append(s) # TODO: python question - can we skip needing getters? and only define setters. i tried/failed. --danbri def _get_uri(self): return self._uri def _set_uri(self, value): v = str(value) # we don't want Namespace() objects and suchlike, but we can use them without whining. if ':' not in v: speclog("Warning: this doesn't look like a URI: "+v) # raise Exception("This doesn't look like a URI.") self._uri = str( value ) uri = property(_get_uri,_set_uri) def set_filename(self, filename): self.filename = filename # TODO: be explicit if/where we default to English # TODO: do we need a separate index(), versus just use __init__ ? def index(self): # speclog("Indexing description of "+str(self)) # blank down anything we learned already self.terms = [] self.properties = [] self.classes = [] tmpclasses=[] tmpproperties=[] g = self.graph query = Parse('SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a rdf:Property } ') relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: p = Property(term) # print "Made a property! "+str(p) + "using label: "#+str(label) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) query = Parse('SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type FILTER (?type = <http://www.w3.org/2002/07/owl#Class> || ?type = <http://www.w3.org/2000/01/rdf-schema#Class> ) }') relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: c = Class(term) # print "Made a class! "+str(p) + "using comment: "+comment c.label = str(label) c.comment = str(comment) self.terms.append(c) if (not str(c) in tmpclasses): self.classes.append(c) tmpclasses.append(str(c)) self.terms.sort(key=operator.attrgetter('id')) self.classes.sort(key=operator.attrgetter('id')) self.properties.sort(key=operator.attrgetter('id')) # http://www.w3.org/2003/06/sw-vocab-status/ns#" query = Parse('SELECT ?x ?vs WHERE { ?x <http://www.w3.org/2003/06/sw-vocab-status/ns#term_status> ?vs }') status = g.query(query, initNs=bindings) # print "status results: ",status.__len__() for x, vs in status: #print "STATUS: ",vs, " for ",x t = self.lookup(x) if t != None: t.status = vs # print "Set status.", t.status else: speclog("Couldn't lookup term: "+x) # Go back and see if we missed any properties defined in OWL. TODO: classes too. Or rewrite above SPARQL. addd more types for full query. q= 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty>)}' q= 'SELECT distinct ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty> || ?type = <http://www.w3.org/2002/07/owl#DatatypeProperty> || ?type = <http://www.w3.org/1999/02/22-rdf-syntax-ns#Property> || ?type = <http://www.w3.org/2002/07/owl#FunctionalProperty> || ?type = <http://www.w3.org/2002/07/owl#InverseFunctionalProperty>) } ' query = Parse(q) relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: p = Property(str(term)) got = self.lookup( str(term) ) if got==None: # print "Made an OWL property! "+str(p.uri) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) # self.terms.sort() # does this even do anything? # self.classes.sort() # self.properties.sort() # todo, use a dictionary index instead. RTFM. def lookup(self, uri): uri = str(uri) for t in self.terms: # print "Lookup: comparing '"+t.uri+"' to '"+uri+"'" # print "type of t.uri is ",t.uri.__class__ if t.uri==uri: # print "Matched." # should we str here, to be more liberal? return t else: # print "Fail." '' return None # print a raw debug summary, direct from the RDF def raw(self): g = self.graph query = Parse('SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c } ') relations = g.query(query, initNs=bindings) print "Properties and Classes (%d terms)" % len(relations) print 40*"-" for (term, label, comment) in relations: print "term %s l: %s \t\tc: %s " % (term, label, comment) print # TODO: work out how to do ".encode('UTF-8')" here # for debugging only def detect_types(self): self.properties = [] self.classes = [] for t in self.terms: # print "Doing t: "+t+" which is of type " + str(t.__class__) if t.is_property(): # print "is_property." self.properties.append(t) if t.is_class(): # print "is_class." self.classes.append(t) # CODE FROM ORIGINAL specgen: def niceName(self, uri = None ): if uri is None: return # speclog("Nicing uri "+uri) regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) if rez == None: #print "Failed to niceName. Returning the whole thing." return(uri) pref = rez.group(1) # print "...",self.ns_list.get(pref, pref),":",rez.group(2) # todo: make this work when uri doesn't match the regex --danbri # AttributeError: 'NoneType' object has no attribute 'group' return self.ns_list.get(pref, pref) + ":" + rez.group(2) # HTML stuff, should be a separate class def azlist(self): """Builds the A-Z list of terms""" c_ids = [] p_ids = [] for p in self.properties: p_ids.append(str(p.id)) for c in self.classes: c_ids.append(str(c.id)) c_ids.sort() p_ids.sort() return (c_ids, p_ids) class VocabReport(object): def __init__(self, vocab, basedir='./examples/', temploc='template.html',templatedir='./examples/'): self.vocab = vocab self.basedir = basedir self.temploc = temploc self.templatedir = templatedir self._template = "no template loaded" # text.gsub(/<code>foaf:(\w+)<\/code>/){ defurl($1) } return "<code><a href=\"#term_#{term}\">foaf:#{term}</a></code>" def codelink(self, s): reg1 = re.compile(r"""<code>foaf:(\w+)<\/code>""") return(re.sub(reg1, r"""<code><a href="#term_\1">foaf:\1</a></code>""", s)) def _get_template(self): self._template = self.load_template() # should be conditional return self._template def _set_template(self, value): self._template = str(value) template = property(_get_template,_set_template) def load_template(self): filename = os.path.join(self.templatedir, self.temploc) f = open(filename, "r") template = f.read() return(template) def generate(self): tpl = self.template azlist = self.az() termlist = self.termlist() f = open ( self.vocab.filename, "r") rdfdata = f.read() # print "GENERATING >>>>>>>> " ## having the rdf in there was making it invalid ## removed in favour of RDFa ## tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8"), rdfdata) tpl = tpl % (azlist.encode("utf-8"), azlist.encode("utf-8"), termlist.encode("utf-8")) return(tpl) def az(self): """AZ List for html doc""" c_ids, p_ids = self.vocab.azlist() az = """<div class="azlist">""" az = """%s\n<p>Classes: |""" % az # print c_ids, p_ids for c in c_ids: # speclog("Class "+c+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(c).replace(" ", ""), c) az = """%s\n</p>""" % az az = """%s\n<p>Properties: |""" % az for p in p_ids: # speclog("Property "+p+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(p).replace(" ", ""), p) az = """%s\n</p>""" % az az = """%s\n</div>""" % az return(az) def termlist(self): """Term List for html doc""" queries = '' c_ids, p_ids = self.vocab.azlist() tl = """<div class="termlist">""" tl = """%s<h3>Classes and Properties (full detail)</h3>\n<div class='termdetails'><br />\n\n""" % tl # first classes, then properties eg = """<div class="specterm" id="term_%s" about="%s" typeof="%s"> <h3>%s: %s</h3> <em>%s</em> - %s <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#%s">%s</span></td></tr> %s %s </table> %s <p style="float: right; font-size: small;">[<a href="#term_%s">#</a>] <!-- %s --> [<a href="#glance">back to top</a>]</p> <br/> </div>""" # replace this if you want validation queries: xxx danbri # <p style="float: right; font-size: small;">[<a href="#term_%s">permalink</a>] [<a href="#queries_%s">validation queries</a>] [<a href="#glance">back to top</a>]</p> # todo, push this into an api call (c_ids currently setup by az above) # classes for term in self.vocab.classes: # strings to use later domainsOfClass = '' rangesOfClass = '' #class in domain of g = self.vocab.graph q = 'SELECT ?d ?l WHERE {?d rdfs:domain <%s> . ?d rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) - startStr = '<tr><th>in-domain-of:</th>\n' + startStr = '<tr><th>May be the object of:</th>\n' contentStr = '' for (domain, label) in relations: dom = Term(domain) termStr = """<a href="#term_%s">%s</a>\n""" % (dom.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": domainsOfClass = "%s <td> %s </td></tr>" % (startStr, contentStr) # class in range of q2 = 'SELECT ?d ?l WHERE {?d rdfs:range <%s> . ?d rdfs:label ?l } ' % (term.uri) query2 = Parse(q2) relations2 = g.query(query2, initNs=bindings) - startStr = '<tr><th>in-range-of:</th>\n' + startStr = '<tr><th>May have properties:</th>\n' contentStr = '' for (range, label) in relations2: ran = Term(range) termStr = """<a href="#term_%s">%s</a>\n""" % (ran.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": rangesOfClass = "%s <td> %s</td></tr> " % (startStr, contentStr) # class subclassof subClassOf = '' q = 'SELECT ?sc ?l WHERE {<%s> rdfs:subClassOf ?sc . ?sc rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '<tr><th>subClassOf</th>\n' contentStr = '' for (subclass, label) in relations: sub = Term(subclass) termStr = """<span rel="rdfs:subClassOf" href="%s"><a href="#term_%s">%s</a></span>\n""" % (subclass, sub.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": subClassOf = "%s <td> %s </td></tr>" % (startStr, contentStr) # class has subclass hasSubClass = '' q = 'SELECT ?sc ?l WHERE {?sc rdfs:subClassOf <%s>. ?sc rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '<tr><th>has subclass</th>\n' contentStr = '' for (subclass, label) in relations: sub = Term(subclass) termStr = """<a href="#term_%s">%s</a>\n""" % (sub.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": hasSubClass = "%s <td> %s </td></tr>" % (startStr, contentStr) # is defined by classIsDefinedBy = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '\n' contentStr = '' for (isdefinedby) in relations: termStr = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": classIsDefinedBy = "%s <tr><td> %s </td></tr>" % (startStr, contentStr) # disjoint with isDisjointWith = '' q = 'SELECT ?dj ?l WHERE { <%s> <http://www.w3.org/2002/07/owl#disjointWith> ?dj . ?dj rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '<tr><th>Disjoint With:</th>\n' contentStr = '' for (disjointWith, label) in relations: termStr = """<span rel="owl:disjointWith" href="%s"><a href="#term_%s">%s</a></span>\n""" % (disjointWith, label, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": isDisjointWith = "%s <td> %s </td></tr>" % (startStr, contentStr) # end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' # if we want validation queries this is where it looks for them. filename = os.path.join(dn, term.id+".sparql") fileStr = '' try: f = open ( filename, "r") fileStr = f.read() fileStr = "<h4><a name=\"queries_"+term.id+"\"></a>"+term.id+" Validation Query</h4><pre>"+cgi.escape(ss)+"</pre>" except: fileStr='' queries = queries +"\n"+ fileStr sn = self.vocab.niceName(term.uri) s = termlink(s) zz = eg % (term.id,term.uri,"rdfs:Class","Class", sn, term.label, term.comment, term.status,term.status,domainsOfClass,rangesOfClass+subClassOf+hasSubClass+classIsDefinedBy+isDisjointWith, s,term.id, term.id) tl = "%s %s" % (tl, zz) # properties for term in self.vocab.properties: domainsOfProperty = '' rangesOfProperty = '' # domain of properties g = self.vocab.graph q = 'SELECT ?d ?l WHERE {<%s> rdfs:domain ?d . ?d rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '<tr><th>Domain:</th>\n' contentStr = '' for (domain, label) in relations: dom = Term(domain) termStr = """<span rel="rdfs:domain" href="%s"><a href="#term_%s">%s</a></span>\n""" % (domain, dom.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": domainsOfProperty = "%s <td>%s</td></tr>" % (startStr, contentStr) # range of properties q2 = 'SELECT ?d ?l WHERE {<%s> rdfs:range ?d . ?d rdfs:label ?l } ' % (term.uri) query2 = Parse(q2) relations2 = g.query(query2, initNs=bindings) startStr = '<tr><th>Range:</th>\n' contentStr = '' for (range, label) in relations2: ran = Term(range) termStr = """<span rel="rdfs:range" href="%s"><a href="#term_%s">%s</a></span>\n""" % (range, ran.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": rangesOfProperty = "%s <td>%s</td> </tr>" % (startStr, contentStr) # is defined by propertyIsDefinedBy = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '\n' contentStr = '' for (isdefinedby) in relations: termStr = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": propertyIsDefinedBy = "%s <tr><td> %s </td></tr>" % (startStr, contentStr) # inverse functional property ifp = '' q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#InverseFunctionalProperty> } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '<tr><th colspan="2">Inverse Functional Property</th>\n' if (len(relations) > 0): termStr = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#InverseFunctionalProperty"></span>""" ifp = "%s <td> %s </td></tr>" % (startStr, termStr) # functonal property fp = '' q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#FunctionalProperty> } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '<tr><th colspan="2">Functional Property</th>\n' if (len(relations) > 0): termStr = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#FunctionalProperty"></span>""" fp = "%s <td> %s </td></tr>" % (startStr, termStr) # end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' sn = self.vocab.niceName(term.uri) s = termlink(s) zz = eg % (term.id, term.uri,"rdf:Property","Property", sn, term.label, term.comment, term.status,term.status,domainsOfProperty,rangesOfProperty+propertyIsDefinedBy+ifp+fp, s,term.id, term.id) tl = "%s %s" % (tl, zz) ## ensure termlist tag is closed return(tl+"\n"+queries+"</div>\n</div>") def rdfa(self): return( "<html>rdfa here</html>") def htmlDocInfo( t, termdir='../docs' ): """Opens a file based on the term name (t) and termdir (defaults to current directory. Reads in the file, and returns a linkified version of it.""" if termdir==None: termdir=self.basedir doc = "" try: f = open("%s/%s.en" % (termdir, t), "r") doc = f.read() doc = termlink(doc) except: return "<p>No detailed documentation for this term.</p>" return doc # report what we've parsed from our various sources def report(self): s = "Report for vocabulary from " + self.vocab.filename + "\n" if self.vocab.uri != None: s += "URI: " + self.vocab.uri + "\n\n" for t in self.vocab.uterms: print "TERM as string: ",t s += t.simple_report() return s
leth/SpecGen
c890ed20fe19549660ee61abc7e7c1a75a6ed181
fixed validation problems with spec
diff --git a/libvocab.py b/libvocab.py index 6922291..494fd58 100755 --- a/libvocab.py +++ b/libvocab.py @@ -64,734 +64,734 @@ import operator bindings = { u"xfn": XFN, u"rdf": RDF, u"rdfs": RDFS, u"vs": VS } #g = None def speclog(str): sys.stderr.write("LOG: "+str+"\n") # todo: shouldn't be foaf specific def termlink(text): result = re.sub( r"<code>foaf:(\w+)<\/code>", r"<code><a href='#term_\g<1>'>\g<1></a></code>", text ) return result # a Term has... (intrinsically and via it's RDFS/OWL description) # uri - a (primary) URI, eg. 'http://xmlns.com/foaf/0.1/workplaceHomepage' # id - a local-to-spec ID, eg. 'workplaceHomepage' # xmlns - an xmlns URI (isDefinedBy, eg. 'http://xmlns.com/foaf/0.1/') # # label - an rdfs:label # comment - an rdfs:comment # # Beyond this, properties vary. Some have vs:status. Some have owl Deprecated. # Some have OWL descriptions, and RDFS descriptions; eg. property range/domain # or class disjointness. def ns_split(uri): regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) return(rez.group(1), rez.group(2)) class Term(object): def __init__(self, uri='file://dev/null'): self.uri = str(uri) self.uri = self.uri.rstrip() # speclog("Parsing URI " + uri) a,b = ns_split(uri) self.id = b self.xmlns = a if self.id==None: speclog("Error parsing URI. "+uri) if self.xmlns==None: speclog("Error parsing URI. "+uri) # print "self.id: "+ self.id + " self.xmlns: " + self.xmlns def uri(self): try: s = self.uri except NameError: self.uri = None s = '[NOURI]' speclog('No URI for'+self) return s def id(self): print "trying id" try: s = self.id except NameError: self.id = None s = '[NOID]' speclog('No ID for'+self) return str(s) def is_external(self, vocab): print "Comparing property URI ",self.uri," with vocab uri: " + vocab.uri return(False) #def __repr__(self): # return(self.__str__) def __str__(self): try: s = self.id except NameError: self.label = None speclog('No label for '+self+' todo: take from uri regex') s = (str(self)) return(str(s)) # so we can treat this like a string def __add__(self, s): return (s+str(self)) def __radd__(self, s): return (s+str(self)) def simple_report(self): t = self s='' s += "default: \t\t"+t +"\n" s += "id: \t\t"+t.id +"\n" s += "uri: \t\t"+t.uri +"\n" s += "xmlns: \t\t"+t.xmlns +"\n" s += "label: \t\t"+t.label +"\n" s += "comment: \t\t" + t.comment +"\n" s += "status: \t\t" + t.status +"\n" s += "\n" return s def _get_status(self): try: return self._status except: return 'unknown' def _set_status(self, value): self._status = str(value) status = property(_get_status,_set_status) # a Python class representing an RDFS/OWL property. # class Property(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Property.is_property called on "+self return(True) def is_class(self): # print "Property.is_class called on "+self return(False) # A Python class representing an RDFS/OWL class # class Class(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Class.is_property called on "+self return(False) def is_class(self): # print "Class.is_class called on "+self return(True) # A python class representing (a description of) some RDF vocabulary # class Vocab(object): def __init__(self, dir, f='index.rdf', uri=None ): self.graph = rdflib.ConjunctiveGraph() self._uri = uri self.dir = dir self.filename = os.path.join(dir, f) self.graph.parse(self.filename) self.terms = [] self.uterms = [] # should also load translations here? # and deal with a base-dir? ##if f != None: ## self.index() self.ns_list = { "http://www.w3.org/1999/02/22-rdf-syntax-ns#" : "rdf", "http://www.w3.org/2000/01/rdf-schema#" : "rdfs", "http://www.w3.org/2002/07/owl#" : "owl", "http://www.w3.org/2001/XMLSchema#" : "xsd", "http://rdfs.org/sioc/ns#" : "sioc", "http://xmlns.com/foaf/0.1/" : "foaf", "http://purl.org/dc/elements/1.1/" : "dc", "http://purl.org/dc/terms/" : "dct", "http://usefulinc.com/ns/doap#" : "doap", "http://www.w3.org/2003/06/sw-vocab-status/ns#" : "status", "http://purl.org/rss/1.0/modules/content/" : "content", "http://www.w3.org/2003/01/geo/wgs84_pos#" : "geo", "http://www.w3.org/2004/02/skos/core#" : "skos", "http://purl.org/NET/c4dm/event.owl#" : "event" } def addShortName(self,sn): self.ns_list[self._uri] = sn self.shortName = sn #print self.ns_list # not currently used def unique_terms(self): tmp=[] for t in list(set(self.terms)): s = str(t) if (not s in tmp): self.uterms.append(t) tmp.append(s) # TODO: python question - can we skip needing getters? and only define setters. i tried/failed. --danbri def _get_uri(self): return self._uri def _set_uri(self, value): v = str(value) # we don't want Namespace() objects and suchlike, but we can use them without whining. if ':' not in v: speclog("Warning: this doesn't look like a URI: "+v) # raise Exception("This doesn't look like a URI.") self._uri = str( value ) uri = property(_get_uri,_set_uri) def set_filename(self, filename): self.filename = filename # TODO: be explicit if/where we default to English # TODO: do we need a separate index(), versus just use __init__ ? def index(self): # speclog("Indexing description of "+str(self)) # blank down anything we learned already self.terms = [] self.properties = [] self.classes = [] tmpclasses=[] tmpproperties=[] g = self.graph query = Parse('SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a rdf:Property } ') relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: p = Property(term) # print "Made a property! "+str(p) + "using label: "#+str(label) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) query = Parse('SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type FILTER (?type = <http://www.w3.org/2002/07/owl#Class> || ?type = <http://www.w3.org/2000/01/rdf-schema#Class> ) }') relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: c = Class(term) # print "Made a class! "+str(p) + "using comment: "+comment c.label = str(label) c.comment = str(comment) self.terms.append(c) if (not str(c) in tmpclasses): self.classes.append(c) tmpclasses.append(str(c)) self.terms.sort(key=operator.attrgetter('id')) self.classes.sort(key=operator.attrgetter('id')) self.properties.sort(key=operator.attrgetter('id')) # http://www.w3.org/2003/06/sw-vocab-status/ns#" query = Parse('SELECT ?x ?vs WHERE { ?x <http://www.w3.org/2003/06/sw-vocab-status/ns#term_status> ?vs }') status = g.query(query, initNs=bindings) # print "status results: ",status.__len__() for x, vs in status: #print "STATUS: ",vs, " for ",x t = self.lookup(x) if t != None: t.status = vs # print "Set status.", t.status else: speclog("Couldn't lookup term: "+x) # Go back and see if we missed any properties defined in OWL. TODO: classes too. Or rewrite above SPARQL. addd more types for full query. q= 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty>)}' q= 'SELECT distinct ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty> || ?type = <http://www.w3.org/2002/07/owl#DatatypeProperty> || ?type = <http://www.w3.org/1999/02/22-rdf-syntax-ns#Property> || ?type = <http://www.w3.org/2002/07/owl#FunctionalProperty> || ?type = <http://www.w3.org/2002/07/owl#InverseFunctionalProperty>) } ' query = Parse(q) relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: p = Property(str(term)) got = self.lookup( str(term) ) if got==None: # print "Made an OWL property! "+str(p.uri) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) # self.terms.sort() # does this even do anything? # self.classes.sort() # self.properties.sort() # todo, use a dictionary index instead. RTFM. def lookup(self, uri): uri = str(uri) for t in self.terms: # print "Lookup: comparing '"+t.uri+"' to '"+uri+"'" # print "type of t.uri is ",t.uri.__class__ if t.uri==uri: # print "Matched." # should we str here, to be more liberal? return t else: # print "Fail." '' return None # print a raw debug summary, direct from the RDF def raw(self): g = self.graph query = Parse('SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c } ') relations = g.query(query, initNs=bindings) print "Properties and Classes (%d terms)" % len(relations) print 40*"-" for (term, label, comment) in relations: print "term %s l: %s \t\tc: %s " % (term, label, comment) print # TODO: work out how to do ".encode('UTF-8')" here # for debugging only def detect_types(self): self.properties = [] self.classes = [] for t in self.terms: # print "Doing t: "+t+" which is of type " + str(t.__class__) if t.is_property(): # print "is_property." self.properties.append(t) if t.is_class(): # print "is_class." self.classes.append(t) # CODE FROM ORIGINAL specgen: def niceName(self, uri = None ): if uri is None: return # speclog("Nicing uri "+uri) regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) if rez == None: #print "Failed to niceName. Returning the whole thing." return(uri) pref = rez.group(1) # print "...",self.ns_list.get(pref, pref),":",rez.group(2) # todo: make this work when uri doesn't match the regex --danbri # AttributeError: 'NoneType' object has no attribute 'group' return self.ns_list.get(pref, pref) + ":" + rez.group(2) # HTML stuff, should be a separate class def azlist(self): """Builds the A-Z list of terms""" c_ids = [] p_ids = [] for p in self.properties: p_ids.append(str(p.id)) for c in self.classes: c_ids.append(str(c.id)) c_ids.sort() p_ids.sort() return (c_ids, p_ids) class VocabReport(object): def __init__(self, vocab, basedir='./examples/', temploc='template.html',templatedir='./examples/'): self.vocab = vocab self.basedir = basedir self.temploc = temploc self.templatedir = templatedir self._template = "no template loaded" # text.gsub(/<code>foaf:(\w+)<\/code>/){ defurl($1) } return "<code><a href=\"#term_#{term}\">foaf:#{term}</a></code>" def codelink(self, s): reg1 = re.compile(r"""<code>foaf:(\w+)<\/code>""") return(re.sub(reg1, r"""<code><a href="#term_\1">foaf:\1</a></code>""", s)) def _get_template(self): self._template = self.load_template() # should be conditional return self._template def _set_template(self, value): self._template = str(value) template = property(_get_template,_set_template) def load_template(self): filename = os.path.join(self.templatedir, self.temploc) f = open(filename, "r") template = f.read() return(template) def generate(self): tpl = self.template azlist = self.az() termlist = self.termlist() f = open ( self.vocab.filename, "r") rdfdata = f.read() # print "GENERATING >>>>>>>> " ## having the rdf in there was making it invalid ## removed in favour of RDFa ## tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8"), rdfdata) tpl = tpl % (azlist.encode("utf-8"), azlist.encode("utf-8"), termlist.encode("utf-8")) return(tpl) def az(self): """AZ List for html doc""" c_ids, p_ids = self.vocab.azlist() az = """<div class="azlist">""" az = """%s\n<p>Classes: |""" % az # print c_ids, p_ids for c in c_ids: # speclog("Class "+c+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(c).replace(" ", ""), c) az = """%s\n</p>""" % az az = """%s\n<p>Properties: |""" % az for p in p_ids: # speclog("Property "+p+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(p).replace(" ", ""), p) az = """%s\n</p>""" % az az = """%s\n</div>""" % az return(az) def termlist(self): """Term List for html doc""" queries = '' c_ids, p_ids = self.vocab.azlist() tl = """<div class="termlist">""" tl = """%s<h3>Classes and Properties (full detail)</h3>\n<div class='termdetails'><br />\n\n""" % tl # first classes, then properties eg = """<div class="specterm" id="term_%s" about="%s" typeof="%s"> <h3>%s: %s</h3> <em>%s</em> - %s <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#%s">%s</span></td></tr> %s %s </table> %s <p style="float: right; font-size: small;">[<a href="#term_%s">#</a>] <!-- %s --> [<a href="#glance">back to top</a>]</p> <br/> </div>""" # replace this if you want validation queries: xxx danbri # <p style="float: right; font-size: small;">[<a href="#term_%s">permalink</a>] [<a href="#queries_%s">validation queries</a>] [<a href="#glance">back to top</a>]</p> # todo, push this into an api call (c_ids currently setup by az above) # classes for term in self.vocab.classes: # strings to use later domainsOfClass = '' rangesOfClass = '' #class in domain of g = self.vocab.graph q = 'SELECT ?d ?l WHERE {?d rdfs:domain <%s> . ?d rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '<tr><th>in-domain-of:</th>\n' contentStr = '' for (domain, label) in relations: dom = Term(domain) termStr = """<a href="#term_%s">%s</a>\n""" % (dom.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": domainsOfClass = "%s <td> %s </td></tr>" % (startStr, contentStr) # class in range of q2 = 'SELECT ?d ?l WHERE {?d rdfs:range <%s> . ?d rdfs:label ?l } ' % (term.uri) query2 = Parse(q2) relations2 = g.query(query2, initNs=bindings) startStr = '<tr><th>in-range-of:</th>\n' contentStr = '' for (range, label) in relations2: ran = Term(range) termStr = """<a href="#term_%s">%s</a>\n""" % (ran.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": rangesOfClass = "%s <td> %s</td></tr> " % (startStr, contentStr) # class subclassof subClassOf = '' q = 'SELECT ?sc ?l WHERE {<%s> rdfs:subClassOf ?sc . ?sc rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '<tr><th>subClassOf</th>\n' contentStr = '' for (subclass, label) in relations: sub = Term(subclass) - termStr = """<span rel="rdfs:subClassOf" href="%s"><a href="#term_%s">%s</a></span>\n""" % (subclass, sub.id, label) # + termStr = """<span rel="rdfs:subClassOf" href="%s"><a href="#term_%s">%s</a></span>\n""" % (subclass, sub.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": subClassOf = "%s <td> %s </td></tr>" % (startStr, contentStr) # class has subclass hasSubClass = '' q = 'SELECT ?sc ?l WHERE {?sc rdfs:subClassOf <%s>. ?sc rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '<tr><th>has subclass</th>\n' contentStr = '' for (subclass, label) in relations: sub = Term(subclass) termStr = """<a href="#term_%s">%s</a>\n""" % (sub.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": hasSubClass = "%s <td> %s </td></tr>" % (startStr, contentStr) # is defined by classIsDefinedBy = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '\n' contentStr = '' for (isdefinedby) in relations: termStr = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": - classIsDefinedBy = "%s %s " % (startStr, contentStr) + classIsDefinedBy = "%s <tr><td> %s </td></tr>" % (startStr, contentStr) # disjoint with isDisjointWith = '' q = 'SELECT ?dj ?l WHERE { <%s> <http://www.w3.org/2002/07/owl#disjointWith> ?dj . ?dj rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '<tr><th>Disjoint With:</th>\n' contentStr = '' for (disjointWith, label) in relations: termStr = """<span rel="owl:disjointWith" href="%s"><a href="#term_%s">%s</a></span>\n""" % (disjointWith, label, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": isDisjointWith = "%s <td> %s </td></tr>" % (startStr, contentStr) # end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' # if we want validation queries this is where it looks for them. filename = os.path.join(dn, term.id+".sparql") fileStr = '' try: f = open ( filename, "r") fileStr = f.read() fileStr = "<h4><a name=\"queries_"+term.id+"\"></a>"+term.id+" Validation Query</h4><pre>"+cgi.escape(ss)+"</pre>" except: fileStr='' queries = queries +"\n"+ fileStr sn = self.vocab.niceName(term.uri) s = termlink(s) zz = eg % (term.id,term.uri,"rdfs:Class","Class", sn, term.label, term.comment, term.status,term.status,domainsOfClass,rangesOfClass+subClassOf+hasSubClass+classIsDefinedBy+isDisjointWith, s,term.id, term.id) tl = "%s %s" % (tl, zz) # properties for term in self.vocab.properties: domainsOfProperty = '' rangesOfProperty = '' # domain of properties g = self.vocab.graph q = 'SELECT ?d ?l WHERE {<%s> rdfs:domain ?d . ?d rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '<tr><th>Domain:</th>\n' contentStr = '' for (domain, label) in relations: dom = Term(domain) termStr = """<span rel="rdfs:domain" href="%s"><a href="#term_%s">%s</a></span>\n""" % (domain, dom.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": domainsOfProperty = "%s <td>%s</td></tr>" % (startStr, contentStr) # range of properties q2 = 'SELECT ?d ?l WHERE {<%s> rdfs:range ?d . ?d rdfs:label ?l } ' % (term.uri) query2 = Parse(q2) relations2 = g.query(query2, initNs=bindings) startStr = '<tr><th>Range:</th>\n' contentStr = '' for (range, label) in relations2: ran = Term(range) termStr = """<span rel="rdfs:range" href="%s"><a href="#term_%s">%s</a></span>\n""" % (range, ran.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": rangesOfProperty = "%s <td>%s</td> </tr>" % (startStr, contentStr) # is defined by propertyIsDefinedBy = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '\n' contentStr = '' for (isdefinedby) in relations: termStr = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": - propertyIsDefinedBy = "%s %s " % (startStr, contentStr) + propertyIsDefinedBy = "%s <tr><td> %s </td></tr>" % (startStr, contentStr) # inverse functional property ifp = '' q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#InverseFunctionalProperty> } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '<tr><th colspan="2">Inverse Functional Property</th>\n' if (len(relations) > 0): termStr = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#InverseFunctionalProperty"></span>""" ifp = "%s <td> %s </td></tr>" % (startStr, termStr) # functonal property fp = '' q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#FunctionalProperty> } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '<tr><th colspan="2">Functional Property</th>\n' if (len(relations) > 0): termStr = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#FunctionalProperty"></span>""" fp = "%s <td> %s </td></tr>" % (startStr, termStr) # end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' sn = self.vocab.niceName(term.uri) s = termlink(s) zz = eg % (term.id, term.uri,"rdf:Property","Property", sn, term.label, term.comment, term.status,term.status,domainsOfProperty,rangesOfProperty+propertyIsDefinedBy+ifp+fp, s,term.id, term.id) tl = "%s %s" % (tl, zz) ## ensure termlist tag is closed return(tl+"\n"+queries+"</div>\n</div>") def rdfa(self): return( "<html>rdfa here</html>") def htmlDocInfo( t, termdir='../docs' ): """Opens a file based on the term name (t) and termdir (defaults to current directory. Reads in the file, and returns a linkified version of it.""" if termdir==None: termdir=self.basedir doc = "" try: f = open("%s/%s.en" % (termdir, t), "r") doc = f.read() doc = termlink(doc) except: return "<p>No detailed documentation for this term.</p>" return doc # report what we've parsed from our various sources def report(self): s = "Report for vocabulary from " + self.vocab.filename + "\n" if self.vocab.uri != None: s += "URI: " + self.vocab.uri + "\n\n" for t in self.vocab.uterms: print "TERM as string: ",t s += t.simple_report() return s
leth/SpecGen
35aa5b462567b4d4ee76dbbec90d4473d7e69de2
added back the regex that links up foaf terms
diff --git a/libvocab.py b/libvocab.py index f74e129..6922291 100755 --- a/libvocab.py +++ b/libvocab.py @@ -1,791 +1,797 @@ #!/usr/bin/env python # total rewrite. --danbri # Usage: # # >>> from libvocab import Vocab, Term, Class, Property # # >>> from libvocab import Vocab, Term, Class, Property # >>> v = Vocab( f='examples/foaf/index.rdf', uri='http://xmlns.com/foaf/0.1/') # >>> dna = v.lookup('http://xmlns.com/foaf/0.1/dnaChecksum') # >>> dna.label # 'DNA checksum' # >>> dna.comment # 'A checksum for the DNA of some thing. Joke.' # >>> dna.id # u'dnaChecksum' # >>> dna.uri # 'http://xmlns.com/foaf/0.1/dnaChecksum' # # # Python OO notes: # http://www.devshed.com/c/a/Python/Object-Oriented-Programming-With-Python-part-1/ # http://www.daniweb.com/code/snippet354.html # http://docs.python.org/reference/datamodel.html#specialnames # # RDFlib: # http://www.science.uva.nl/research/air/wiki/RDFlib # # http://dowhatimean.net/2006/03/spellchecking-vocabularies-with-sparql # # We define basics, Vocab, Term, Property, Class # and populate them with data from RDF schemas, OWL, translations ... and nearby html files. import rdflib from rdflib import Namespace from rdflib.Graph import Graph from rdflib.Graph import ConjunctiveGraph from rdflib.sparql.sparqlGraph import SPARQLGraph from rdflib.sparql.graphPattern import GraphPattern from rdflib.sparql.bison import Parse from rdflib.sparql import Query FOAF = Namespace('http://xmlns.com/foaf/0.1/') RDFS = Namespace('http://www.w3.org/2000/01/rdf-schema#') XFN = Namespace("http://gmpg.org/xfn/1#") RDF = Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#") OWL = Namespace('http://www.w3.org/2002/07/owl#') VS = Namespace('http://www.w3.org/2003/06/sw-vocab-status/ns#') DC = Namespace('http://purl.org/dc/elements/1.1/') DOAP = Namespace('http://usefulinc.com/ns/doap#') SIOC = Namespace('http://rdfs.org/sioc/ns#') SIOCTYPES = Namespace('http://rdfs.org/sioc/types#') SIOCSERVICES = Namespace('http://rdfs.org/sioc/services#') # # TODO: rationalise these two lists. or at least check they are same. import sys, time, re, urllib, getopt import logging import os.path import cgi import operator bindings = { u"xfn": XFN, u"rdf": RDF, u"rdfs": RDFS, u"vs": VS } #g = None def speclog(str): sys.stderr.write("LOG: "+str+"\n") +# todo: shouldn't be foaf specific +def termlink(text): + result = re.sub( r"<code>foaf:(\w+)<\/code>", r"<code><a href='#term_\g<1>'>\g<1></a></code>", text ) + return result # a Term has... (intrinsically and via it's RDFS/OWL description) # uri - a (primary) URI, eg. 'http://xmlns.com/foaf/0.1/workplaceHomepage' # id - a local-to-spec ID, eg. 'workplaceHomepage' # xmlns - an xmlns URI (isDefinedBy, eg. 'http://xmlns.com/foaf/0.1/') # # label - an rdfs:label # comment - an rdfs:comment # # Beyond this, properties vary. Some have vs:status. Some have owl Deprecated. # Some have OWL descriptions, and RDFS descriptions; eg. property range/domain # or class disjointness. def ns_split(uri): regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) return(rez.group(1), rez.group(2)) class Term(object): def __init__(self, uri='file://dev/null'): self.uri = str(uri) self.uri = self.uri.rstrip() # speclog("Parsing URI " + uri) a,b = ns_split(uri) self.id = b self.xmlns = a if self.id==None: speclog("Error parsing URI. "+uri) if self.xmlns==None: speclog("Error parsing URI. "+uri) # print "self.id: "+ self.id + " self.xmlns: " + self.xmlns def uri(self): try: s = self.uri except NameError: self.uri = None s = '[NOURI]' speclog('No URI for'+self) return s def id(self): print "trying id" try: s = self.id except NameError: self.id = None s = '[NOID]' speclog('No ID for'+self) return str(s) def is_external(self, vocab): print "Comparing property URI ",self.uri," with vocab uri: " + vocab.uri return(False) #def __repr__(self): # return(self.__str__) def __str__(self): try: s = self.id except NameError: self.label = None speclog('No label for '+self+' todo: take from uri regex') s = (str(self)) return(str(s)) # so we can treat this like a string def __add__(self, s): return (s+str(self)) def __radd__(self, s): return (s+str(self)) def simple_report(self): t = self s='' s += "default: \t\t"+t +"\n" s += "id: \t\t"+t.id +"\n" s += "uri: \t\t"+t.uri +"\n" s += "xmlns: \t\t"+t.xmlns +"\n" s += "label: \t\t"+t.label +"\n" s += "comment: \t\t" + t.comment +"\n" s += "status: \t\t" + t.status +"\n" s += "\n" return s def _get_status(self): try: return self._status except: return 'unknown' def _set_status(self, value): self._status = str(value) status = property(_get_status,_set_status) # a Python class representing an RDFS/OWL property. # class Property(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Property.is_property called on "+self return(True) def is_class(self): # print "Property.is_class called on "+self return(False) # A Python class representing an RDFS/OWL class # class Class(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Class.is_property called on "+self return(False) def is_class(self): # print "Class.is_class called on "+self return(True) # A python class representing (a description of) some RDF vocabulary # class Vocab(object): def __init__(self, dir, f='index.rdf', uri=None ): self.graph = rdflib.ConjunctiveGraph() self._uri = uri self.dir = dir self.filename = os.path.join(dir, f) self.graph.parse(self.filename) self.terms = [] self.uterms = [] # should also load translations here? # and deal with a base-dir? ##if f != None: ## self.index() self.ns_list = { "http://www.w3.org/1999/02/22-rdf-syntax-ns#" : "rdf", "http://www.w3.org/2000/01/rdf-schema#" : "rdfs", "http://www.w3.org/2002/07/owl#" : "owl", "http://www.w3.org/2001/XMLSchema#" : "xsd", "http://rdfs.org/sioc/ns#" : "sioc", "http://xmlns.com/foaf/0.1/" : "foaf", "http://purl.org/dc/elements/1.1/" : "dc", "http://purl.org/dc/terms/" : "dct", "http://usefulinc.com/ns/doap#" : "doap", "http://www.w3.org/2003/06/sw-vocab-status/ns#" : "status", "http://purl.org/rss/1.0/modules/content/" : "content", "http://www.w3.org/2003/01/geo/wgs84_pos#" : "geo", "http://www.w3.org/2004/02/skos/core#" : "skos", "http://purl.org/NET/c4dm/event.owl#" : "event" } def addShortName(self,sn): self.ns_list[self._uri] = sn self.shortName = sn #print self.ns_list # not currently used def unique_terms(self): tmp=[] for t in list(set(self.terms)): s = str(t) if (not s in tmp): self.uterms.append(t) tmp.append(s) # TODO: python question - can we skip needing getters? and only define setters. i tried/failed. --danbri def _get_uri(self): return self._uri def _set_uri(self, value): v = str(value) # we don't want Namespace() objects and suchlike, but we can use them without whining. if ':' not in v: speclog("Warning: this doesn't look like a URI: "+v) # raise Exception("This doesn't look like a URI.") self._uri = str( value ) uri = property(_get_uri,_set_uri) def set_filename(self, filename): self.filename = filename # TODO: be explicit if/where we default to English # TODO: do we need a separate index(), versus just use __init__ ? def index(self): # speclog("Indexing description of "+str(self)) # blank down anything we learned already self.terms = [] self.properties = [] self.classes = [] tmpclasses=[] tmpproperties=[] g = self.graph query = Parse('SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a rdf:Property } ') relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: p = Property(term) # print "Made a property! "+str(p) + "using label: "#+str(label) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) query = Parse('SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type FILTER (?type = <http://www.w3.org/2002/07/owl#Class> || ?type = <http://www.w3.org/2000/01/rdf-schema#Class> ) }') relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: c = Class(term) # print "Made a class! "+str(p) + "using comment: "+comment c.label = str(label) c.comment = str(comment) self.terms.append(c) if (not str(c) in tmpclasses): self.classes.append(c) tmpclasses.append(str(c)) self.terms.sort(key=operator.attrgetter('id')) self.classes.sort(key=operator.attrgetter('id')) self.properties.sort(key=operator.attrgetter('id')) # http://www.w3.org/2003/06/sw-vocab-status/ns#" query = Parse('SELECT ?x ?vs WHERE { ?x <http://www.w3.org/2003/06/sw-vocab-status/ns#term_status> ?vs }') status = g.query(query, initNs=bindings) # print "status results: ",status.__len__() for x, vs in status: #print "STATUS: ",vs, " for ",x t = self.lookup(x) if t != None: t.status = vs # print "Set status.", t.status else: speclog("Couldn't lookup term: "+x) # Go back and see if we missed any properties defined in OWL. TODO: classes too. Or rewrite above SPARQL. addd more types for full query. q= 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty>)}' q= 'SELECT distinct ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty> || ?type = <http://www.w3.org/2002/07/owl#DatatypeProperty> || ?type = <http://www.w3.org/1999/02/22-rdf-syntax-ns#Property> || ?type = <http://www.w3.org/2002/07/owl#FunctionalProperty> || ?type = <http://www.w3.org/2002/07/owl#InverseFunctionalProperty>) } ' query = Parse(q) relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: p = Property(str(term)) got = self.lookup( str(term) ) if got==None: # print "Made an OWL property! "+str(p.uri) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) # self.terms.sort() # does this even do anything? # self.classes.sort() # self.properties.sort() # todo, use a dictionary index instead. RTFM. def lookup(self, uri): uri = str(uri) for t in self.terms: # print "Lookup: comparing '"+t.uri+"' to '"+uri+"'" # print "type of t.uri is ",t.uri.__class__ if t.uri==uri: # print "Matched." # should we str here, to be more liberal? return t else: # print "Fail." '' return None # print a raw debug summary, direct from the RDF def raw(self): g = self.graph query = Parse('SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c } ') relations = g.query(query, initNs=bindings) print "Properties and Classes (%d terms)" % len(relations) print 40*"-" for (term, label, comment) in relations: print "term %s l: %s \t\tc: %s " % (term, label, comment) print # TODO: work out how to do ".encode('UTF-8')" here # for debugging only def detect_types(self): self.properties = [] self.classes = [] for t in self.terms: # print "Doing t: "+t+" which is of type " + str(t.__class__) if t.is_property(): # print "is_property." self.properties.append(t) if t.is_class(): # print "is_class." self.classes.append(t) # CODE FROM ORIGINAL specgen: def niceName(self, uri = None ): if uri is None: return # speclog("Nicing uri "+uri) regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) if rez == None: #print "Failed to niceName. Returning the whole thing." return(uri) pref = rez.group(1) # print "...",self.ns_list.get(pref, pref),":",rez.group(2) # todo: make this work when uri doesn't match the regex --danbri # AttributeError: 'NoneType' object has no attribute 'group' return self.ns_list.get(pref, pref) + ":" + rez.group(2) # HTML stuff, should be a separate class def azlist(self): """Builds the A-Z list of terms""" c_ids = [] p_ids = [] for p in self.properties: p_ids.append(str(p.id)) for c in self.classes: c_ids.append(str(c.id)) c_ids.sort() p_ids.sort() return (c_ids, p_ids) class VocabReport(object): def __init__(self, vocab, basedir='./examples/', temploc='template.html',templatedir='./examples/'): self.vocab = vocab self.basedir = basedir self.temploc = temploc self.templatedir = templatedir self._template = "no template loaded" # text.gsub(/<code>foaf:(\w+)<\/code>/){ defurl($1) } return "<code><a href=\"#term_#{term}\">foaf:#{term}</a></code>" def codelink(self, s): reg1 = re.compile(r"""<code>foaf:(\w+)<\/code>""") return(re.sub(reg1, r"""<code><a href="#term_\1">foaf:\1</a></code>""", s)) def _get_template(self): self._template = self.load_template() # should be conditional return self._template def _set_template(self, value): self._template = str(value) template = property(_get_template,_set_template) def load_template(self): filename = os.path.join(self.templatedir, self.temploc) f = open(filename, "r") template = f.read() return(template) def generate(self): tpl = self.template azlist = self.az() termlist = self.termlist() f = open ( self.vocab.filename, "r") rdfdata = f.read() # print "GENERATING >>>>>>>> " ## having the rdf in there was making it invalid ## removed in favour of RDFa ## tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8"), rdfdata) tpl = tpl % (azlist.encode("utf-8"), azlist.encode("utf-8"), termlist.encode("utf-8")) return(tpl) def az(self): """AZ List for html doc""" c_ids, p_ids = self.vocab.azlist() az = """<div class="azlist">""" az = """%s\n<p>Classes: |""" % az # print c_ids, p_ids for c in c_ids: # speclog("Class "+c+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(c).replace(" ", ""), c) az = """%s\n</p>""" % az az = """%s\n<p>Properties: |""" % az for p in p_ids: # speclog("Property "+p+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(p).replace(" ", ""), p) az = """%s\n</p>""" % az az = """%s\n</div>""" % az return(az) def termlist(self): """Term List for html doc""" queries = '' c_ids, p_ids = self.vocab.azlist() tl = """<div class="termlist">""" tl = """%s<h3>Classes and Properties (full detail)</h3>\n<div class='termdetails'><br />\n\n""" % tl # first classes, then properties eg = """<div class="specterm" id="term_%s" about="%s" typeof="%s"> <h3>%s: %s</h3> <em>%s</em> - %s <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#%s">%s</span></td></tr> %s %s </table> %s <p style="float: right; font-size: small;">[<a href="#term_%s">#</a>] <!-- %s --> [<a href="#glance">back to top</a>]</p> <br/> </div>""" # replace this if you want validation queries: xxx danbri # <p style="float: right; font-size: small;">[<a href="#term_%s">permalink</a>] [<a href="#queries_%s">validation queries</a>] [<a href="#glance">back to top</a>]</p> # todo, push this into an api call (c_ids currently setup by az above) # classes for term in self.vocab.classes: # strings to use later domainsOfClass = '' rangesOfClass = '' #class in domain of g = self.vocab.graph q = 'SELECT ?d ?l WHERE {?d rdfs:domain <%s> . ?d rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '<tr><th>in-domain-of:</th>\n' contentStr = '' for (domain, label) in relations: dom = Term(domain) termStr = """<a href="#term_%s">%s</a>\n""" % (dom.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": domainsOfClass = "%s <td> %s </td></tr>" % (startStr, contentStr) # class in range of q2 = 'SELECT ?d ?l WHERE {?d rdfs:range <%s> . ?d rdfs:label ?l } ' % (term.uri) query2 = Parse(q2) relations2 = g.query(query2, initNs=bindings) startStr = '<tr><th>in-range-of:</th>\n' contentStr = '' for (range, label) in relations2: ran = Term(range) termStr = """<a href="#term_%s">%s</a>\n""" % (ran.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": rangesOfClass = "%s <td> %s</td></tr> " % (startStr, contentStr) # class subclassof subClassOf = '' q = 'SELECT ?sc ?l WHERE {<%s> rdfs:subClassOf ?sc . ?sc rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '<tr><th>subClassOf</th>\n' contentStr = '' for (subclass, label) in relations: sub = Term(subclass) termStr = """<span rel="rdfs:subClassOf" href="%s"><a href="#term_%s">%s</a></span>\n""" % (subclass, sub.id, label) # contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": subClassOf = "%s <td> %s </td></tr>" % (startStr, contentStr) # class has subclass hasSubClass = '' q = 'SELECT ?sc ?l WHERE {?sc rdfs:subClassOf <%s>. ?sc rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '<tr><th>has subclass</th>\n' contentStr = '' for (subclass, label) in relations: sub = Term(subclass) termStr = """<a href="#term_%s">%s</a>\n""" % (sub.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": hasSubClass = "%s <td> %s </td></tr>" % (startStr, contentStr) # is defined by classIsDefinedBy = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '\n' contentStr = '' for (isdefinedby) in relations: termStr = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": classIsDefinedBy = "%s %s " % (startStr, contentStr) # disjoint with isDisjointWith = '' q = 'SELECT ?dj ?l WHERE { <%s> <http://www.w3.org/2002/07/owl#disjointWith> ?dj . ?dj rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '<tr><th>Disjoint With:</th>\n' contentStr = '' for (disjointWith, label) in relations: termStr = """<span rel="owl:disjointWith" href="%s"><a href="#term_%s">%s</a></span>\n""" % (disjointWith, label, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": isDisjointWith = "%s <td> %s </td></tr>" % (startStr, contentStr) # end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' # if we want validation queries this is where it looks for them. filename = os.path.join(dn, term.id+".sparql") fileStr = '' try: f = open ( filename, "r") fileStr = f.read() fileStr = "<h4><a name=\"queries_"+term.id+"\"></a>"+term.id+" Validation Query</h4><pre>"+cgi.escape(ss)+"</pre>" except: fileStr='' queries = queries +"\n"+ fileStr sn = self.vocab.niceName(term.uri) + s = termlink(s) zz = eg % (term.id,term.uri,"rdfs:Class","Class", sn, term.label, term.comment, term.status,term.status,domainsOfClass,rangesOfClass+subClassOf+hasSubClass+classIsDefinedBy+isDisjointWith, s,term.id, term.id) tl = "%s %s" % (tl, zz) # properties for term in self.vocab.properties: domainsOfProperty = '' rangesOfProperty = '' # domain of properties g = self.vocab.graph q = 'SELECT ?d ?l WHERE {<%s> rdfs:domain ?d . ?d rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '<tr><th>Domain:</th>\n' contentStr = '' for (domain, label) in relations: dom = Term(domain) termStr = """<span rel="rdfs:domain" href="%s"><a href="#term_%s">%s</a></span>\n""" % (domain, dom.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": domainsOfProperty = "%s <td>%s</td></tr>" % (startStr, contentStr) # range of properties q2 = 'SELECT ?d ?l WHERE {<%s> rdfs:range ?d . ?d rdfs:label ?l } ' % (term.uri) query2 = Parse(q2) relations2 = g.query(query2, initNs=bindings) startStr = '<tr><th>Range:</th>\n' contentStr = '' for (range, label) in relations2: ran = Term(range) termStr = """<span rel="rdfs:range" href="%s"><a href="#term_%s">%s</a></span>\n""" % (range, ran.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": rangesOfProperty = "%s <td>%s</td> </tr>" % (startStr, contentStr) # is defined by propertyIsDefinedBy = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '\n' contentStr = '' for (isdefinedby) in relations: termStr = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": propertyIsDefinedBy = "%s %s " % (startStr, contentStr) # inverse functional property ifp = '' q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#InverseFunctionalProperty> } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '<tr><th colspan="2">Inverse Functional Property</th>\n' if (len(relations) > 0): termStr = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#InverseFunctionalProperty"></span>""" ifp = "%s <td> %s </td></tr>" % (startStr, termStr) # functonal property fp = '' q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#FunctionalProperty> } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '<tr><th colspan="2">Functional Property</th>\n' if (len(relations) > 0): termStr = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#FunctionalProperty"></span>""" fp = "%s <td> %s </td></tr>" % (startStr, termStr) # end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' sn = self.vocab.niceName(term.uri) - + s = termlink(s) + zz = eg % (term.id, term.uri,"rdf:Property","Property", sn, term.label, term.comment, term.status,term.status,domainsOfProperty,rangesOfProperty+propertyIsDefinedBy+ifp+fp, s,term.id, term.id) tl = "%s %s" % (tl, zz) ## ensure termlist tag is closed return(tl+"\n"+queries+"</div>\n</div>") def rdfa(self): return( "<html>rdfa here</html>") def htmlDocInfo( t, termdir='../docs' ): """Opens a file based on the term name (t) and termdir (defaults to current directory. Reads in the file, and returns a linkified version of it.""" if termdir==None: termdir=self.basedir doc = "" try: f = open("%s/%s.en" % (termdir, t), "r") doc = f.read() doc = termlink(doc) except: return "<p>No detailed documentation for this term.</p>" return doc # report what we've parsed from our various sources def report(self): s = "Report for vocabulary from " + self.vocab.filename + "\n" if self.vocab.uri != None: s += "URI: " + self.vocab.uri + "\n\n" for t in self.vocab.uterms: print "TERM as string: ",t s += t.simple_report() return s
leth/SpecGen
0f110f3626a3a8d3a6958cb546843d7fc17335e3
adding back the first a-z list
diff --git a/libvocab.py b/libvocab.py index 9988c60..f74e129 100755 --- a/libvocab.py +++ b/libvocab.py @@ -1,791 +1,791 @@ #!/usr/bin/env python # total rewrite. --danbri # Usage: # # >>> from libvocab import Vocab, Term, Class, Property # # >>> from libvocab import Vocab, Term, Class, Property # >>> v = Vocab( f='examples/foaf/index.rdf', uri='http://xmlns.com/foaf/0.1/') # >>> dna = v.lookup('http://xmlns.com/foaf/0.1/dnaChecksum') # >>> dna.label # 'DNA checksum' # >>> dna.comment # 'A checksum for the DNA of some thing. Joke.' # >>> dna.id # u'dnaChecksum' # >>> dna.uri # 'http://xmlns.com/foaf/0.1/dnaChecksum' # # # Python OO notes: # http://www.devshed.com/c/a/Python/Object-Oriented-Programming-With-Python-part-1/ # http://www.daniweb.com/code/snippet354.html # http://docs.python.org/reference/datamodel.html#specialnames # # RDFlib: # http://www.science.uva.nl/research/air/wiki/RDFlib # # http://dowhatimean.net/2006/03/spellchecking-vocabularies-with-sparql # # We define basics, Vocab, Term, Property, Class # and populate them with data from RDF schemas, OWL, translations ... and nearby html files. import rdflib from rdflib import Namespace from rdflib.Graph import Graph from rdflib.Graph import ConjunctiveGraph from rdflib.sparql.sparqlGraph import SPARQLGraph from rdflib.sparql.graphPattern import GraphPattern from rdflib.sparql.bison import Parse from rdflib.sparql import Query FOAF = Namespace('http://xmlns.com/foaf/0.1/') RDFS = Namespace('http://www.w3.org/2000/01/rdf-schema#') XFN = Namespace("http://gmpg.org/xfn/1#") RDF = Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#") OWL = Namespace('http://www.w3.org/2002/07/owl#') VS = Namespace('http://www.w3.org/2003/06/sw-vocab-status/ns#') DC = Namespace('http://purl.org/dc/elements/1.1/') DOAP = Namespace('http://usefulinc.com/ns/doap#') SIOC = Namespace('http://rdfs.org/sioc/ns#') SIOCTYPES = Namespace('http://rdfs.org/sioc/types#') SIOCSERVICES = Namespace('http://rdfs.org/sioc/services#') # # TODO: rationalise these two lists. or at least check they are same. import sys, time, re, urllib, getopt import logging import os.path import cgi import operator bindings = { u"xfn": XFN, u"rdf": RDF, u"rdfs": RDFS, u"vs": VS } #g = None def speclog(str): sys.stderr.write("LOG: "+str+"\n") # a Term has... (intrinsically and via it's RDFS/OWL description) # uri - a (primary) URI, eg. 'http://xmlns.com/foaf/0.1/workplaceHomepage' # id - a local-to-spec ID, eg. 'workplaceHomepage' # xmlns - an xmlns URI (isDefinedBy, eg. 'http://xmlns.com/foaf/0.1/') # # label - an rdfs:label # comment - an rdfs:comment # # Beyond this, properties vary. Some have vs:status. Some have owl Deprecated. # Some have OWL descriptions, and RDFS descriptions; eg. property range/domain # or class disjointness. def ns_split(uri): regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) return(rez.group(1), rez.group(2)) class Term(object): def __init__(self, uri='file://dev/null'): self.uri = str(uri) self.uri = self.uri.rstrip() # speclog("Parsing URI " + uri) a,b = ns_split(uri) self.id = b self.xmlns = a if self.id==None: speclog("Error parsing URI. "+uri) if self.xmlns==None: speclog("Error parsing URI. "+uri) # print "self.id: "+ self.id + " self.xmlns: " + self.xmlns def uri(self): try: s = self.uri except NameError: self.uri = None s = '[NOURI]' speclog('No URI for'+self) return s def id(self): print "trying id" try: s = self.id except NameError: self.id = None s = '[NOID]' speclog('No ID for'+self) return str(s) def is_external(self, vocab): print "Comparing property URI ",self.uri," with vocab uri: " + vocab.uri return(False) #def __repr__(self): # return(self.__str__) def __str__(self): try: s = self.id except NameError: self.label = None speclog('No label for '+self+' todo: take from uri regex') s = (str(self)) return(str(s)) # so we can treat this like a string def __add__(self, s): return (s+str(self)) def __radd__(self, s): return (s+str(self)) def simple_report(self): t = self s='' s += "default: \t\t"+t +"\n" s += "id: \t\t"+t.id +"\n" s += "uri: \t\t"+t.uri +"\n" s += "xmlns: \t\t"+t.xmlns +"\n" s += "label: \t\t"+t.label +"\n" s += "comment: \t\t" + t.comment +"\n" s += "status: \t\t" + t.status +"\n" s += "\n" return s def _get_status(self): try: return self._status except: return 'unknown' def _set_status(self, value): self._status = str(value) status = property(_get_status,_set_status) # a Python class representing an RDFS/OWL property. # class Property(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Property.is_property called on "+self return(True) def is_class(self): # print "Property.is_class called on "+self return(False) # A Python class representing an RDFS/OWL class # class Class(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Class.is_property called on "+self return(False) def is_class(self): # print "Class.is_class called on "+self return(True) # A python class representing (a description of) some RDF vocabulary # class Vocab(object): def __init__(self, dir, f='index.rdf', uri=None ): self.graph = rdflib.ConjunctiveGraph() self._uri = uri self.dir = dir self.filename = os.path.join(dir, f) self.graph.parse(self.filename) self.terms = [] self.uterms = [] # should also load translations here? # and deal with a base-dir? ##if f != None: ## self.index() self.ns_list = { "http://www.w3.org/1999/02/22-rdf-syntax-ns#" : "rdf", "http://www.w3.org/2000/01/rdf-schema#" : "rdfs", "http://www.w3.org/2002/07/owl#" : "owl", "http://www.w3.org/2001/XMLSchema#" : "xsd", "http://rdfs.org/sioc/ns#" : "sioc", "http://xmlns.com/foaf/0.1/" : "foaf", "http://purl.org/dc/elements/1.1/" : "dc", "http://purl.org/dc/terms/" : "dct", "http://usefulinc.com/ns/doap#" : "doap", "http://www.w3.org/2003/06/sw-vocab-status/ns#" : "status", "http://purl.org/rss/1.0/modules/content/" : "content", "http://www.w3.org/2003/01/geo/wgs84_pos#" : "geo", "http://www.w3.org/2004/02/skos/core#" : "skos", "http://purl.org/NET/c4dm/event.owl#" : "event" } def addShortName(self,sn): self.ns_list[self._uri] = sn self.shortName = sn #print self.ns_list # not currently used def unique_terms(self): tmp=[] for t in list(set(self.terms)): s = str(t) if (not s in tmp): self.uterms.append(t) tmp.append(s) # TODO: python question - can we skip needing getters? and only define setters. i tried/failed. --danbri def _get_uri(self): return self._uri def _set_uri(self, value): v = str(value) # we don't want Namespace() objects and suchlike, but we can use them without whining. if ':' not in v: speclog("Warning: this doesn't look like a URI: "+v) # raise Exception("This doesn't look like a URI.") self._uri = str( value ) uri = property(_get_uri,_set_uri) def set_filename(self, filename): self.filename = filename # TODO: be explicit if/where we default to English # TODO: do we need a separate index(), versus just use __init__ ? def index(self): # speclog("Indexing description of "+str(self)) # blank down anything we learned already self.terms = [] self.properties = [] self.classes = [] tmpclasses=[] tmpproperties=[] g = self.graph query = Parse('SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a rdf:Property } ') relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: p = Property(term) # print "Made a property! "+str(p) + "using label: "#+str(label) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) query = Parse('SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type FILTER (?type = <http://www.w3.org/2002/07/owl#Class> || ?type = <http://www.w3.org/2000/01/rdf-schema#Class> ) }') relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: c = Class(term) # print "Made a class! "+str(p) + "using comment: "+comment c.label = str(label) c.comment = str(comment) self.terms.append(c) if (not str(c) in tmpclasses): self.classes.append(c) tmpclasses.append(str(c)) self.terms.sort(key=operator.attrgetter('id')) self.classes.sort(key=operator.attrgetter('id')) self.properties.sort(key=operator.attrgetter('id')) # http://www.w3.org/2003/06/sw-vocab-status/ns#" query = Parse('SELECT ?x ?vs WHERE { ?x <http://www.w3.org/2003/06/sw-vocab-status/ns#term_status> ?vs }') status = g.query(query, initNs=bindings) # print "status results: ",status.__len__() for x, vs in status: #print "STATUS: ",vs, " for ",x t = self.lookup(x) if t != None: t.status = vs # print "Set status.", t.status else: speclog("Couldn't lookup term: "+x) # Go back and see if we missed any properties defined in OWL. TODO: classes too. Or rewrite above SPARQL. addd more types for full query. q= 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty>)}' q= 'SELECT distinct ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty> || ?type = <http://www.w3.org/2002/07/owl#DatatypeProperty> || ?type = <http://www.w3.org/1999/02/22-rdf-syntax-ns#Property> || ?type = <http://www.w3.org/2002/07/owl#FunctionalProperty> || ?type = <http://www.w3.org/2002/07/owl#InverseFunctionalProperty>) } ' query = Parse(q) relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: p = Property(str(term)) got = self.lookup( str(term) ) if got==None: # print "Made an OWL property! "+str(p.uri) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) # self.terms.sort() # does this even do anything? # self.classes.sort() # self.properties.sort() # todo, use a dictionary index instead. RTFM. def lookup(self, uri): uri = str(uri) for t in self.terms: # print "Lookup: comparing '"+t.uri+"' to '"+uri+"'" # print "type of t.uri is ",t.uri.__class__ if t.uri==uri: # print "Matched." # should we str here, to be more liberal? return t else: # print "Fail." '' return None # print a raw debug summary, direct from the RDF def raw(self): g = self.graph query = Parse('SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c } ') relations = g.query(query, initNs=bindings) print "Properties and Classes (%d terms)" % len(relations) print 40*"-" for (term, label, comment) in relations: print "term %s l: %s \t\tc: %s " % (term, label, comment) print # TODO: work out how to do ".encode('UTF-8')" here # for debugging only def detect_types(self): self.properties = [] self.classes = [] for t in self.terms: # print "Doing t: "+t+" which is of type " + str(t.__class__) if t.is_property(): # print "is_property." self.properties.append(t) if t.is_class(): # print "is_class." self.classes.append(t) # CODE FROM ORIGINAL specgen: def niceName(self, uri = None ): if uri is None: return # speclog("Nicing uri "+uri) regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) if rez == None: #print "Failed to niceName. Returning the whole thing." return(uri) pref = rez.group(1) # print "...",self.ns_list.get(pref, pref),":",rez.group(2) # todo: make this work when uri doesn't match the regex --danbri # AttributeError: 'NoneType' object has no attribute 'group' return self.ns_list.get(pref, pref) + ":" + rez.group(2) # HTML stuff, should be a separate class def azlist(self): """Builds the A-Z list of terms""" c_ids = [] p_ids = [] for p in self.properties: p_ids.append(str(p.id)) for c in self.classes: c_ids.append(str(c.id)) c_ids.sort() p_ids.sort() return (c_ids, p_ids) class VocabReport(object): def __init__(self, vocab, basedir='./examples/', temploc='template.html',templatedir='./examples/'): self.vocab = vocab self.basedir = basedir self.temploc = temploc self.templatedir = templatedir self._template = "no template loaded" # text.gsub(/<code>foaf:(\w+)<\/code>/){ defurl($1) } return "<code><a href=\"#term_#{term}\">foaf:#{term}</a></code>" def codelink(self, s): reg1 = re.compile(r"""<code>foaf:(\w+)<\/code>""") return(re.sub(reg1, r"""<code><a href="#term_\1">foaf:\1</a></code>""", s)) def _get_template(self): self._template = self.load_template() # should be conditional return self._template def _set_template(self, value): self._template = str(value) template = property(_get_template,_set_template) def load_template(self): filename = os.path.join(self.templatedir, self.temploc) f = open(filename, "r") template = f.read() return(template) def generate(self): tpl = self.template azlist = self.az() termlist = self.termlist() f = open ( self.vocab.filename, "r") rdfdata = f.read() # print "GENERATING >>>>>>>> " ## having the rdf in there was making it invalid ## removed in favour of RDFa ## tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8"), rdfdata) - tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8")) + tpl = tpl % (azlist.encode("utf-8"), azlist.encode("utf-8"), termlist.encode("utf-8")) return(tpl) def az(self): """AZ List for html doc""" c_ids, p_ids = self.vocab.azlist() az = """<div class="azlist">""" az = """%s\n<p>Classes: |""" % az # print c_ids, p_ids for c in c_ids: # speclog("Class "+c+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(c).replace(" ", ""), c) az = """%s\n</p>""" % az az = """%s\n<p>Properties: |""" % az for p in p_ids: # speclog("Property "+p+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(p).replace(" ", ""), p) az = """%s\n</p>""" % az az = """%s\n</div>""" % az return(az) def termlist(self): """Term List for html doc""" queries = '' c_ids, p_ids = self.vocab.azlist() tl = """<div class="termlist">""" tl = """%s<h3>Classes and Properties (full detail)</h3>\n<div class='termdetails'><br />\n\n""" % tl # first classes, then properties eg = """<div class="specterm" id="term_%s" about="%s" typeof="%s"> <h3>%s: %s</h3> <em>%s</em> - %s <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#%s">%s</span></td></tr> %s %s </table> %s <p style="float: right; font-size: small;">[<a href="#term_%s">#</a>] <!-- %s --> [<a href="#glance">back to top</a>]</p> <br/> </div>""" # replace this if you want validation queries: xxx danbri # <p style="float: right; font-size: small;">[<a href="#term_%s">permalink</a>] [<a href="#queries_%s">validation queries</a>] [<a href="#glance">back to top</a>]</p> # todo, push this into an api call (c_ids currently setup by az above) # classes for term in self.vocab.classes: # strings to use later domainsOfClass = '' rangesOfClass = '' #class in domain of g = self.vocab.graph q = 'SELECT ?d ?l WHERE {?d rdfs:domain <%s> . ?d rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '<tr><th>in-domain-of:</th>\n' contentStr = '' for (domain, label) in relations: dom = Term(domain) termStr = """<a href="#term_%s">%s</a>\n""" % (dom.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": domainsOfClass = "%s <td> %s </td></tr>" % (startStr, contentStr) # class in range of q2 = 'SELECT ?d ?l WHERE {?d rdfs:range <%s> . ?d rdfs:label ?l } ' % (term.uri) query2 = Parse(q2) relations2 = g.query(query2, initNs=bindings) startStr = '<tr><th>in-range-of:</th>\n' contentStr = '' for (range, label) in relations2: ran = Term(range) termStr = """<a href="#term_%s">%s</a>\n""" % (ran.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": rangesOfClass = "%s <td> %s</td></tr> " % (startStr, contentStr) # class subclassof subClassOf = '' q = 'SELECT ?sc ?l WHERE {<%s> rdfs:subClassOf ?sc . ?sc rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '<tr><th>subClassOf</th>\n' contentStr = '' for (subclass, label) in relations: sub = Term(subclass) termStr = """<span rel="rdfs:subClassOf" href="%s"><a href="#term_%s">%s</a></span>\n""" % (subclass, sub.id, label) # contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": subClassOf = "%s <td> %s </td></tr>" % (startStr, contentStr) # class has subclass hasSubClass = '' q = 'SELECT ?sc ?l WHERE {?sc rdfs:subClassOf <%s>. ?sc rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '<tr><th>has subclass</th>\n' contentStr = '' for (subclass, label) in relations: sub = Term(subclass) termStr = """<a href="#term_%s">%s</a>\n""" % (sub.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": hasSubClass = "%s <td> %s </td></tr>" % (startStr, contentStr) # is defined by classIsDefinedBy = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '\n' contentStr = '' for (isdefinedby) in relations: termStr = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": classIsDefinedBy = "%s %s " % (startStr, contentStr) # disjoint with isDisjointWith = '' q = 'SELECT ?dj ?l WHERE { <%s> <http://www.w3.org/2002/07/owl#disjointWith> ?dj . ?dj rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '<tr><th>Disjoint With:</th>\n' contentStr = '' for (disjointWith, label) in relations: termStr = """<span rel="owl:disjointWith" href="%s"><a href="#term_%s">%s</a></span>\n""" % (disjointWith, label, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": isDisjointWith = "%s <td> %s </td></tr>" % (startStr, contentStr) # end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' # if we want validation queries this is where it looks for them. filename = os.path.join(dn, term.id+".sparql") fileStr = '' try: f = open ( filename, "r") fileStr = f.read() fileStr = "<h4><a name=\"queries_"+term.id+"\"></a>"+term.id+" Validation Query</h4><pre>"+cgi.escape(ss)+"</pre>" except: fileStr='' queries = queries +"\n"+ fileStr sn = self.vocab.niceName(term.uri) zz = eg % (term.id,term.uri,"rdfs:Class","Class", sn, term.label, term.comment, term.status,term.status,domainsOfClass,rangesOfClass+subClassOf+hasSubClass+classIsDefinedBy+isDisjointWith, s,term.id, term.id) tl = "%s %s" % (tl, zz) # properties for term in self.vocab.properties: domainsOfProperty = '' rangesOfProperty = '' # domain of properties g = self.vocab.graph q = 'SELECT ?d ?l WHERE {<%s> rdfs:domain ?d . ?d rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '<tr><th>Domain:</th>\n' contentStr = '' for (domain, label) in relations: dom = Term(domain) termStr = """<span rel="rdfs:domain" href="%s"><a href="#term_%s">%s</a></span>\n""" % (domain, dom.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": domainsOfProperty = "%s <td>%s</td></tr>" % (startStr, contentStr) # range of properties q2 = 'SELECT ?d ?l WHERE {<%s> rdfs:range ?d . ?d rdfs:label ?l } ' % (term.uri) query2 = Parse(q2) relations2 = g.query(query2, initNs=bindings) startStr = '<tr><th>Range:</th>\n' contentStr = '' for (range, label) in relations2: ran = Term(range) termStr = """<span rel="rdfs:range" href="%s"><a href="#term_%s">%s</a></span>\n""" % (range, ran.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": rangesOfProperty = "%s <td>%s</td> </tr>" % (startStr, contentStr) # is defined by propertyIsDefinedBy = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '\n' contentStr = '' for (isdefinedby) in relations: termStr = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": propertyIsDefinedBy = "%s %s " % (startStr, contentStr) # inverse functional property ifp = '' q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#InverseFunctionalProperty> } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '<tr><th colspan="2">Inverse Functional Property</th>\n' if (len(relations) > 0): termStr = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#InverseFunctionalProperty"></span>""" ifp = "%s <td> %s </td></tr>" % (startStr, termStr) # functonal property fp = '' q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#FunctionalProperty> } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '<tr><th colspan="2">Functional Property</th>\n' if (len(relations) > 0): termStr = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#FunctionalProperty"></span>""" fp = "%s <td> %s </td></tr>" % (startStr, termStr) # end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' sn = self.vocab.niceName(term.uri) zz = eg % (term.id, term.uri,"rdf:Property","Property", sn, term.label, term.comment, term.status,term.status,domainsOfProperty,rangesOfProperty+propertyIsDefinedBy+ifp+fp, s,term.id, term.id) tl = "%s %s" % (tl, zz) ## ensure termlist tag is closed return(tl+"\n"+queries+"</div>\n</div>") def rdfa(self): return( "<html>rdfa here</html>") def htmlDocInfo( t, termdir='../docs' ): """Opens a file based on the term name (t) and termdir (defaults to current directory. Reads in the file, and returns a linkified version of it.""" if termdir==None: termdir=self.basedir doc = "" try: f = open("%s/%s.en" % (termdir, t), "r") doc = f.read() doc = termlink(doc) except: return "<p>No detailed documentation for this term.</p>" return doc # report what we've parsed from our various sources def report(self): s = "Report for vocabulary from " + self.vocab.filename + "\n" if self.vocab.uri != None: s += "URI: " + self.vocab.uri + "\n\n" for t in self.vocab.uterms: print "TERM as string: ",t s += t.simple_report() return s
leth/SpecGen
03a210e7dc51989385f73ca918f0871fb23bf13c
removed more stupid variable names
diff --git a/libvocab.py b/libvocab.py index c4e1759..9988c60 100755 --- a/libvocab.py +++ b/libvocab.py @@ -128,665 +128,664 @@ class Term(object): print "Comparing property URI ",self.uri," with vocab uri: " + vocab.uri return(False) #def __repr__(self): # return(self.__str__) def __str__(self): try: s = self.id except NameError: self.label = None speclog('No label for '+self+' todo: take from uri regex') s = (str(self)) return(str(s)) # so we can treat this like a string def __add__(self, s): return (s+str(self)) def __radd__(self, s): return (s+str(self)) def simple_report(self): t = self s='' s += "default: \t\t"+t +"\n" s += "id: \t\t"+t.id +"\n" s += "uri: \t\t"+t.uri +"\n" s += "xmlns: \t\t"+t.xmlns +"\n" s += "label: \t\t"+t.label +"\n" s += "comment: \t\t" + t.comment +"\n" s += "status: \t\t" + t.status +"\n" s += "\n" return s def _get_status(self): try: return self._status except: return 'unknown' def _set_status(self, value): self._status = str(value) status = property(_get_status,_set_status) # a Python class representing an RDFS/OWL property. # class Property(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Property.is_property called on "+self return(True) def is_class(self): # print "Property.is_class called on "+self return(False) # A Python class representing an RDFS/OWL class # class Class(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Class.is_property called on "+self return(False) def is_class(self): # print "Class.is_class called on "+self return(True) # A python class representing (a description of) some RDF vocabulary # class Vocab(object): def __init__(self, dir, f='index.rdf', uri=None ): self.graph = rdflib.ConjunctiveGraph() self._uri = uri self.dir = dir self.filename = os.path.join(dir, f) self.graph.parse(self.filename) self.terms = [] self.uterms = [] # should also load translations here? # and deal with a base-dir? ##if f != None: ## self.index() self.ns_list = { "http://www.w3.org/1999/02/22-rdf-syntax-ns#" : "rdf", "http://www.w3.org/2000/01/rdf-schema#" : "rdfs", "http://www.w3.org/2002/07/owl#" : "owl", "http://www.w3.org/2001/XMLSchema#" : "xsd", "http://rdfs.org/sioc/ns#" : "sioc", "http://xmlns.com/foaf/0.1/" : "foaf", "http://purl.org/dc/elements/1.1/" : "dc", "http://purl.org/dc/terms/" : "dct", "http://usefulinc.com/ns/doap#" : "doap", "http://www.w3.org/2003/06/sw-vocab-status/ns#" : "status", "http://purl.org/rss/1.0/modules/content/" : "content", "http://www.w3.org/2003/01/geo/wgs84_pos#" : "geo", "http://www.w3.org/2004/02/skos/core#" : "skos", "http://purl.org/NET/c4dm/event.owl#" : "event" } def addShortName(self,sn): self.ns_list[self._uri] = sn self.shortName = sn #print self.ns_list # not currently used def unique_terms(self): tmp=[] for t in list(set(self.terms)): s = str(t) if (not s in tmp): self.uterms.append(t) tmp.append(s) # TODO: python question - can we skip needing getters? and only define setters. i tried/failed. --danbri def _get_uri(self): return self._uri def _set_uri(self, value): v = str(value) # we don't want Namespace() objects and suchlike, but we can use them without whining. if ':' not in v: speclog("Warning: this doesn't look like a URI: "+v) # raise Exception("This doesn't look like a URI.") self._uri = str( value ) uri = property(_get_uri,_set_uri) def set_filename(self, filename): self.filename = filename # TODO: be explicit if/where we default to English # TODO: do we need a separate index(), versus just use __init__ ? def index(self): # speclog("Indexing description of "+str(self)) # blank down anything we learned already self.terms = [] self.properties = [] self.classes = [] tmpclasses=[] tmpproperties=[] g = self.graph query = Parse('SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a rdf:Property } ') relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: p = Property(term) # print "Made a property! "+str(p) + "using label: "#+str(label) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) query = Parse('SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type FILTER (?type = <http://www.w3.org/2002/07/owl#Class> || ?type = <http://www.w3.org/2000/01/rdf-schema#Class> ) }') relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: c = Class(term) # print "Made a class! "+str(p) + "using comment: "+comment c.label = str(label) c.comment = str(comment) self.terms.append(c) if (not str(c) in tmpclasses): self.classes.append(c) tmpclasses.append(str(c)) self.terms.sort(key=operator.attrgetter('id')) self.classes.sort(key=operator.attrgetter('id')) self.properties.sort(key=operator.attrgetter('id')) # http://www.w3.org/2003/06/sw-vocab-status/ns#" query = Parse('SELECT ?x ?vs WHERE { ?x <http://www.w3.org/2003/06/sw-vocab-status/ns#term_status> ?vs }') status = g.query(query, initNs=bindings) # print "status results: ",status.__len__() for x, vs in status: #print "STATUS: ",vs, " for ",x t = self.lookup(x) if t != None: t.status = vs # print "Set status.", t.status else: speclog("Couldn't lookup term: "+x) # Go back and see if we missed any properties defined in OWL. TODO: classes too. Or rewrite above SPARQL. addd more types for full query. q= 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty>)}' q= 'SELECT distinct ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty> || ?type = <http://www.w3.org/2002/07/owl#DatatypeProperty> || ?type = <http://www.w3.org/1999/02/22-rdf-syntax-ns#Property> || ?type = <http://www.w3.org/2002/07/owl#FunctionalProperty> || ?type = <http://www.w3.org/2002/07/owl#InverseFunctionalProperty>) } ' query = Parse(q) relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: p = Property(str(term)) got = self.lookup( str(term) ) if got==None: # print "Made an OWL property! "+str(p.uri) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) # self.terms.sort() # does this even do anything? # self.classes.sort() # self.properties.sort() # todo, use a dictionary index instead. RTFM. def lookup(self, uri): uri = str(uri) for t in self.terms: # print "Lookup: comparing '"+t.uri+"' to '"+uri+"'" # print "type of t.uri is ",t.uri.__class__ if t.uri==uri: # print "Matched." # should we str here, to be more liberal? return t else: # print "Fail." '' return None # print a raw debug summary, direct from the RDF def raw(self): g = self.graph query = Parse('SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c } ') relations = g.query(query, initNs=bindings) print "Properties and Classes (%d terms)" % len(relations) print 40*"-" for (term, label, comment) in relations: print "term %s l: %s \t\tc: %s " % (term, label, comment) print # TODO: work out how to do ".encode('UTF-8')" here # for debugging only def detect_types(self): self.properties = [] self.classes = [] for t in self.terms: # print "Doing t: "+t+" which is of type " + str(t.__class__) if t.is_property(): # print "is_property." self.properties.append(t) if t.is_class(): # print "is_class." self.classes.append(t) # CODE FROM ORIGINAL specgen: def niceName(self, uri = None ): if uri is None: return # speclog("Nicing uri "+uri) regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) if rez == None: #print "Failed to niceName. Returning the whole thing." return(uri) pref = rez.group(1) # print "...",self.ns_list.get(pref, pref),":",rez.group(2) # todo: make this work when uri doesn't match the regex --danbri # AttributeError: 'NoneType' object has no attribute 'group' return self.ns_list.get(pref, pref) + ":" + rez.group(2) # HTML stuff, should be a separate class def azlist(self): """Builds the A-Z list of terms""" c_ids = [] p_ids = [] for p in self.properties: p_ids.append(str(p.id)) for c in self.classes: c_ids.append(str(c.id)) c_ids.sort() p_ids.sort() return (c_ids, p_ids) class VocabReport(object): def __init__(self, vocab, basedir='./examples/', temploc='template.html',templatedir='./examples/'): self.vocab = vocab self.basedir = basedir self.temploc = temploc self.templatedir = templatedir self._template = "no template loaded" # text.gsub(/<code>foaf:(\w+)<\/code>/){ defurl($1) } return "<code><a href=\"#term_#{term}\">foaf:#{term}</a></code>" def codelink(self, s): reg1 = re.compile(r"""<code>foaf:(\w+)<\/code>""") return(re.sub(reg1, r"""<code><a href="#term_\1">foaf:\1</a></code>""", s)) def _get_template(self): self._template = self.load_template() # should be conditional return self._template def _set_template(self, value): self._template = str(value) template = property(_get_template,_set_template) def load_template(self): filename = os.path.join(self.templatedir, self.temploc) f = open(filename, "r") template = f.read() return(template) def generate(self): tpl = self.template azlist = self.az() termlist = self.termlist() f = open ( self.vocab.filename, "r") rdfdata = f.read() # print "GENERATING >>>>>>>> " ## having the rdf in there was making it invalid ## removed in favour of RDFa ## tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8"), rdfdata) tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8")) return(tpl) def az(self): """AZ List for html doc""" c_ids, p_ids = self.vocab.azlist() az = """<div class="azlist">""" az = """%s\n<p>Classes: |""" % az # print c_ids, p_ids for c in c_ids: # speclog("Class "+c+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(c).replace(" ", ""), c) az = """%s\n</p>""" % az az = """%s\n<p>Properties: |""" % az for p in p_ids: # speclog("Property "+p+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(p).replace(" ", ""), p) az = """%s\n</p>""" % az az = """%s\n</div>""" % az return(az) def termlist(self): """Term List for html doc""" queries = '' c_ids, p_ids = self.vocab.azlist() tl = """<div class="termlist">""" tl = """%s<h3>Classes and Properties (full detail)</h3>\n<div class='termdetails'><br />\n\n""" % tl # first classes, then properties eg = """<div class="specterm" id="term_%s" about="%s" typeof="%s"> <h3>%s: %s</h3> <em>%s</em> - %s <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#%s">%s</span></td></tr> %s %s </table> %s <p style="float: right; font-size: small;">[<a href="#term_%s">#</a>] <!-- %s --> [<a href="#glance">back to top</a>]</p> <br/> </div>""" # replace this if you want validation queries: xxx danbri # <p style="float: right; font-size: small;">[<a href="#term_%s">permalink</a>] [<a href="#queries_%s">validation queries</a>] [<a href="#glance">back to top</a>]</p> # todo, push this into an api call (c_ids currently setup by az above) # classes for term in self.vocab.classes: # strings to use later domainsOfClass = '' rangesOfClass = '' #class in domain of g = self.vocab.graph q = 'SELECT ?d ?l WHERE {?d rdfs:domain <%s> . ?d rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '<tr><th>in-domain-of:</th>\n' contentStr = '' for (domain, label) in relations: dom = Term(domain) termStr = """<a href="#term_%s">%s</a>\n""" % (dom.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": domainsOfClass = "%s <td> %s </td></tr>" % (startStr, contentStr) # class in range of q2 = 'SELECT ?d ?l WHERE {?d rdfs:range <%s> . ?d rdfs:label ?l } ' % (term.uri) query2 = Parse(q2) relations2 = g.query(query2, initNs=bindings) startStr = '<tr><th>in-range-of:</th>\n' contentStr = '' for (range, label) in relations2: ran = Term(range) termStr = """<a href="#term_%s">%s</a>\n""" % (ran.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": rangesOfClass = "%s <td> %s</td></tr> " % (startStr, contentStr) # class subclassof subClassOf = '' q = 'SELECT ?sc ?l WHERE {<%s> rdfs:subClassOf ?sc . ?sc rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '<tr><th>subClassOf</th>\n' contentStr = '' for (subclass, label) in relations: sub = Term(subclass) termStr = """<span rel="rdfs:subClassOf" href="%s"><a href="#term_%s">%s</a></span>\n""" % (subclass, sub.id, label) # contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": subClassOf = "%s <td> %s </td></tr>" % (startStr, contentStr) # class has subclass hasSubClass = '' q = 'SELECT ?sc ?l WHERE {?sc rdfs:subClassOf <%s>. ?sc rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '<tr><th>has subclass</th>\n' contentStr = '' for (subclass, label) in relations: sub = Term(subclass) termStr = """<a href="#term_%s">%s</a>\n""" % (sub.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": hasSubClass = "%s <td> %s </td></tr>" % (startStr, contentStr) # is defined by classIsDefinedBy = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '\n' contentStr = '' for (isdefinedby) in relations: termStr = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": classIsDefinedBy = "%s %s " % (startStr, contentStr) # disjoint with isDisjointWith = '' q = 'SELECT ?dj ?l WHERE { <%s> <http://www.w3.org/2002/07/owl#disjointWith> ?dj . ?dj rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '<tr><th>Disjoint With:</th>\n' contentStr = '' for (disjointWith, label) in relations: termStr = """<span rel="owl:disjointWith" href="%s"><a href="#term_%s">%s</a></span>\n""" % (disjointWith, label, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": isDisjointWith = "%s <td> %s </td></tr>" % (startStr, contentStr) # end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' - #queries + # if we want validation queries this is where it looks for them. filename = os.path.join(dn, term.id+".sparql") - ss = '' + fileStr = '' try: f = open ( filename, "r") - ss = f.read() - ss = "<h4><a name=\"queries_"+term.id+"\"></a>"+term.id+" Validation Query</h4><pre>"+cgi.escape(ss)+"</pre>" + fileStr = f.read() + fileStr = "<h4><a name=\"queries_"+term.id+"\"></a>"+term.id+" Validation Query</h4><pre>"+cgi.escape(ss)+"</pre>" except: - ss='' + fileStr='' - queries = queries +"\n"+ ss -# s = s+"\n"+ss + queries = queries +"\n"+ fileStr sn = self.vocab.niceName(term.uri) zz = eg % (term.id,term.uri,"rdfs:Class","Class", sn, term.label, term.comment, term.status,term.status,domainsOfClass,rangesOfClass+subClassOf+hasSubClass+classIsDefinedBy+isDisjointWith, s,term.id, term.id) tl = "%s %s" % (tl, zz) # properties for term in self.vocab.properties: domainsOfProperty = '' rangesOfProperty = '' # domain of properties g = self.vocab.graph q = 'SELECT ?d ?l WHERE {<%s> rdfs:domain ?d . ?d rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '<tr><th>Domain:</th>\n' contentStr = '' for (domain, label) in relations: dom = Term(domain) termStr = """<span rel="rdfs:domain" href="%s"><a href="#term_%s">%s</a></span>\n""" % (domain, dom.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": domainsOfProperty = "%s <td>%s</td></tr>" % (startStr, contentStr) # range of properties q2 = 'SELECT ?d ?l WHERE {<%s> rdfs:range ?d . ?d rdfs:label ?l } ' % (term.uri) query2 = Parse(q2) relations2 = g.query(query2, initNs=bindings) startStr = '<tr><th>Range:</th>\n' contentStr = '' for (range, label) in relations2: ran = Term(range) termStr = """<span rel="rdfs:range" href="%s"><a href="#term_%s">%s</a></span>\n""" % (range, ran.id, label) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": rangesOfProperty = "%s <td>%s</td> </tr>" % (startStr, contentStr) # is defined by propertyIsDefinedBy = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '\n' contentStr = '' for (isdefinedby) in relations: termStr = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) contentStr = "%s %s" % (contentStr, termStr) if contentStr != "": propertyIsDefinedBy = "%s %s " % (startStr, contentStr) # inverse functional property ifp = '' q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#InverseFunctionalProperty> } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '<tr><th colspan="2">Inverse Functional Property</th>\n' if (len(relations) > 0): termStr = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#InverseFunctionalProperty"></span>""" ifp = "%s <td> %s </td></tr>" % (startStr, termStr) # functonal property fp = '' q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#FunctionalProperty> } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) startStr = '<tr><th colspan="2">Functional Property</th>\n' if (len(relations) > 0): termStr = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#FunctionalProperty"></span>""" fp = "%s <td> %s </td></tr>" % (startStr, termStr) # end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' sn = self.vocab.niceName(term.uri) zz = eg % (term.id, term.uri,"rdf:Property","Property", sn, term.label, term.comment, term.status,term.status,domainsOfProperty,rangesOfProperty+propertyIsDefinedBy+ifp+fp, s,term.id, term.id) tl = "%s %s" % (tl, zz) ## ensure termlist tag is closed return(tl+"\n"+queries+"</div>\n</div>") def rdfa(self): return( "<html>rdfa here</html>") def htmlDocInfo( t, termdir='../docs' ): """Opens a file based on the term name (t) and termdir (defaults to current directory. Reads in the file, and returns a linkified version of it.""" if termdir==None: termdir=self.basedir doc = "" try: f = open("%s/%s.en" % (termdir, t), "r") doc = f.read() doc = termlink(doc) except: return "<p>No detailed documentation for this term.</p>" return doc # report what we've parsed from our various sources def report(self): s = "Report for vocabulary from " + self.vocab.filename + "\n" if self.vocab.uri != None: s += "URI: " + self.vocab.uri + "\n\n" for t in self.vocab.uterms: print "TERM as string: ",t s += t.simple_report() return s
leth/SpecGen
558e47c02d9e7ee0edc8bed5542d93a0c342d92e
a bit more of a cleanup of variable names
diff --git a/libvocab.py b/libvocab.py index c31dc7e..c4e1759 100755 --- a/libvocab.py +++ b/libvocab.py @@ -1,797 +1,792 @@ #!/usr/bin/env python # total rewrite. --danbri # Usage: # # >>> from libvocab import Vocab, Term, Class, Property # # >>> from libvocab import Vocab, Term, Class, Property # >>> v = Vocab( f='examples/foaf/index.rdf', uri='http://xmlns.com/foaf/0.1/') # >>> dna = v.lookup('http://xmlns.com/foaf/0.1/dnaChecksum') # >>> dna.label # 'DNA checksum' # >>> dna.comment # 'A checksum for the DNA of some thing. Joke.' # >>> dna.id # u'dnaChecksum' # >>> dna.uri # 'http://xmlns.com/foaf/0.1/dnaChecksum' # # # Python OO notes: # http://www.devshed.com/c/a/Python/Object-Oriented-Programming-With-Python-part-1/ # http://www.daniweb.com/code/snippet354.html # http://docs.python.org/reference/datamodel.html#specialnames # # RDFlib: # http://www.science.uva.nl/research/air/wiki/RDFlib # # http://dowhatimean.net/2006/03/spellchecking-vocabularies-with-sparql # # We define basics, Vocab, Term, Property, Class # and populate them with data from RDF schemas, OWL, translations ... and nearby html files. import rdflib from rdflib import Namespace from rdflib.Graph import Graph from rdflib.Graph import ConjunctiveGraph from rdflib.sparql.sparqlGraph import SPARQLGraph from rdflib.sparql.graphPattern import GraphPattern from rdflib.sparql.bison import Parse from rdflib.sparql import Query FOAF = Namespace('http://xmlns.com/foaf/0.1/') RDFS = Namespace('http://www.w3.org/2000/01/rdf-schema#') XFN = Namespace("http://gmpg.org/xfn/1#") RDF = Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#") OWL = Namespace('http://www.w3.org/2002/07/owl#') VS = Namespace('http://www.w3.org/2003/06/sw-vocab-status/ns#') DC = Namespace('http://purl.org/dc/elements/1.1/') DOAP = Namespace('http://usefulinc.com/ns/doap#') SIOC = Namespace('http://rdfs.org/sioc/ns#') SIOCTYPES = Namespace('http://rdfs.org/sioc/types#') SIOCSERVICES = Namespace('http://rdfs.org/sioc/services#') # # TODO: rationalise these two lists. or at least check they are same. import sys, time, re, urllib, getopt import logging import os.path import cgi import operator bindings = { u"xfn": XFN, u"rdf": RDF, u"rdfs": RDFS, u"vs": VS } #g = None def speclog(str): sys.stderr.write("LOG: "+str+"\n") # a Term has... (intrinsically and via it's RDFS/OWL description) # uri - a (primary) URI, eg. 'http://xmlns.com/foaf/0.1/workplaceHomepage' # id - a local-to-spec ID, eg. 'workplaceHomepage' # xmlns - an xmlns URI (isDefinedBy, eg. 'http://xmlns.com/foaf/0.1/') # # label - an rdfs:label # comment - an rdfs:comment # # Beyond this, properties vary. Some have vs:status. Some have owl Deprecated. # Some have OWL descriptions, and RDFS descriptions; eg. property range/domain # or class disjointness. def ns_split(uri): regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) return(rez.group(1), rez.group(2)) class Term(object): def __init__(self, uri='file://dev/null'): self.uri = str(uri) self.uri = self.uri.rstrip() # speclog("Parsing URI " + uri) a,b = ns_split(uri) self.id = b self.xmlns = a if self.id==None: speclog("Error parsing URI. "+uri) if self.xmlns==None: speclog("Error parsing URI. "+uri) # print "self.id: "+ self.id + " self.xmlns: " + self.xmlns def uri(self): try: s = self.uri except NameError: self.uri = None s = '[NOURI]' speclog('No URI for'+self) return s def id(self): print "trying id" try: s = self.id except NameError: self.id = None s = '[NOID]' speclog('No ID for'+self) return str(s) def is_external(self, vocab): print "Comparing property URI ",self.uri," with vocab uri: " + vocab.uri return(False) #def __repr__(self): # return(self.__str__) def __str__(self): try: s = self.id except NameError: self.label = None speclog('No label for '+self+' todo: take from uri regex') s = (str(self)) return(str(s)) # so we can treat this like a string def __add__(self, s): return (s+str(self)) def __radd__(self, s): return (s+str(self)) def simple_report(self): t = self s='' s += "default: \t\t"+t +"\n" s += "id: \t\t"+t.id +"\n" s += "uri: \t\t"+t.uri +"\n" s += "xmlns: \t\t"+t.xmlns +"\n" s += "label: \t\t"+t.label +"\n" s += "comment: \t\t" + t.comment +"\n" s += "status: \t\t" + t.status +"\n" s += "\n" return s def _get_status(self): try: return self._status except: return 'unknown' def _set_status(self, value): self._status = str(value) status = property(_get_status,_set_status) # a Python class representing an RDFS/OWL property. # class Property(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Property.is_property called on "+self return(True) def is_class(self): # print "Property.is_class called on "+self return(False) # A Python class representing an RDFS/OWL class # class Class(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Class.is_property called on "+self return(False) def is_class(self): # print "Class.is_class called on "+self return(True) # A python class representing (a description of) some RDF vocabulary # class Vocab(object): def __init__(self, dir, f='index.rdf', uri=None ): self.graph = rdflib.ConjunctiveGraph() self._uri = uri self.dir = dir self.filename = os.path.join(dir, f) self.graph.parse(self.filename) self.terms = [] self.uterms = [] # should also load translations here? # and deal with a base-dir? ##if f != None: ## self.index() self.ns_list = { "http://www.w3.org/1999/02/22-rdf-syntax-ns#" : "rdf", "http://www.w3.org/2000/01/rdf-schema#" : "rdfs", "http://www.w3.org/2002/07/owl#" : "owl", "http://www.w3.org/2001/XMLSchema#" : "xsd", "http://rdfs.org/sioc/ns#" : "sioc", "http://xmlns.com/foaf/0.1/" : "foaf", "http://purl.org/dc/elements/1.1/" : "dc", "http://purl.org/dc/terms/" : "dct", "http://usefulinc.com/ns/doap#" : "doap", "http://www.w3.org/2003/06/sw-vocab-status/ns#" : "status", "http://purl.org/rss/1.0/modules/content/" : "content", "http://www.w3.org/2003/01/geo/wgs84_pos#" : "geo", "http://www.w3.org/2004/02/skos/core#" : "skos", "http://purl.org/NET/c4dm/event.owl#" : "event" } def addShortName(self,sn): self.ns_list[self._uri] = sn self.shortName = sn #print self.ns_list # not currently used def unique_terms(self): tmp=[] for t in list(set(self.terms)): s = str(t) if (not s in tmp): self.uterms.append(t) tmp.append(s) # TODO: python question - can we skip needing getters? and only define setters. i tried/failed. --danbri def _get_uri(self): return self._uri def _set_uri(self, value): v = str(value) # we don't want Namespace() objects and suchlike, but we can use them without whining. if ':' not in v: speclog("Warning: this doesn't look like a URI: "+v) # raise Exception("This doesn't look like a URI.") self._uri = str( value ) uri = property(_get_uri,_set_uri) def set_filename(self, filename): self.filename = filename # TODO: be explicit if/where we default to English # TODO: do we need a separate index(), versus just use __init__ ? def index(self): # speclog("Indexing description of "+str(self)) # blank down anything we learned already self.terms = [] self.properties = [] self.classes = [] tmpclasses=[] tmpproperties=[] g = self.graph query = Parse('SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a rdf:Property } ') relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: p = Property(term) # print "Made a property! "+str(p) + "using label: "#+str(label) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) query = Parse('SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type FILTER (?type = <http://www.w3.org/2002/07/owl#Class> || ?type = <http://www.w3.org/2000/01/rdf-schema#Class> ) }') relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: c = Class(term) # print "Made a class! "+str(p) + "using comment: "+comment c.label = str(label) c.comment = str(comment) self.terms.append(c) if (not str(c) in tmpclasses): self.classes.append(c) tmpclasses.append(str(c)) self.terms.sort(key=operator.attrgetter('id')) self.classes.sort(key=operator.attrgetter('id')) self.properties.sort(key=operator.attrgetter('id')) # http://www.w3.org/2003/06/sw-vocab-status/ns#" query = Parse('SELECT ?x ?vs WHERE { ?x <http://www.w3.org/2003/06/sw-vocab-status/ns#term_status> ?vs }') status = g.query(query, initNs=bindings) # print "status results: ",status.__len__() for x, vs in status: #print "STATUS: ",vs, " for ",x t = self.lookup(x) if t != None: t.status = vs # print "Set status.", t.status else: speclog("Couldn't lookup term: "+x) # Go back and see if we missed any properties defined in OWL. TODO: classes too. Or rewrite above SPARQL. addd more types for full query. q= 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty>)}' q= 'SELECT distinct ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty> || ?type = <http://www.w3.org/2002/07/owl#DatatypeProperty> || ?type = <http://www.w3.org/1999/02/22-rdf-syntax-ns#Property> || ?type = <http://www.w3.org/2002/07/owl#FunctionalProperty> || ?type = <http://www.w3.org/2002/07/owl#InverseFunctionalProperty>) } ' query = Parse(q) relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: p = Property(str(term)) got = self.lookup( str(term) ) if got==None: # print "Made an OWL property! "+str(p.uri) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) # self.terms.sort() # does this even do anything? # self.classes.sort() # self.properties.sort() # todo, use a dictionary index instead. RTFM. def lookup(self, uri): uri = str(uri) for t in self.terms: # print "Lookup: comparing '"+t.uri+"' to '"+uri+"'" # print "type of t.uri is ",t.uri.__class__ if t.uri==uri: # print "Matched." # should we str here, to be more liberal? return t else: # print "Fail." '' return None # print a raw debug summary, direct from the RDF def raw(self): g = self.graph query = Parse('SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c } ') relations = g.query(query, initNs=bindings) print "Properties and Classes (%d terms)" % len(relations) print 40*"-" for (term, label, comment) in relations: print "term %s l: %s \t\tc: %s " % (term, label, comment) print # TODO: work out how to do ".encode('UTF-8')" here # for debugging only def detect_types(self): self.properties = [] self.classes = [] for t in self.terms: # print "Doing t: "+t+" which is of type " + str(t.__class__) if t.is_property(): # print "is_property." self.properties.append(t) if t.is_class(): # print "is_class." self.classes.append(t) # CODE FROM ORIGINAL specgen: def niceName(self, uri = None ): if uri is None: return # speclog("Nicing uri "+uri) regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) if rez == None: #print "Failed to niceName. Returning the whole thing." return(uri) pref = rez.group(1) # print "...",self.ns_list.get(pref, pref),":",rez.group(2) # todo: make this work when uri doesn't match the regex --danbri # AttributeError: 'NoneType' object has no attribute 'group' return self.ns_list.get(pref, pref) + ":" + rez.group(2) # HTML stuff, should be a separate class def azlist(self): """Builds the A-Z list of terms""" c_ids = [] p_ids = [] for p in self.properties: p_ids.append(str(p.id)) for c in self.classes: c_ids.append(str(c.id)) c_ids.sort() p_ids.sort() return (c_ids, p_ids) class VocabReport(object): def __init__(self, vocab, basedir='./examples/', temploc='template.html',templatedir='./examples/'): self.vocab = vocab self.basedir = basedir self.temploc = temploc self.templatedir = templatedir self._template = "no template loaded" # text.gsub(/<code>foaf:(\w+)<\/code>/){ defurl($1) } return "<code><a href=\"#term_#{term}\">foaf:#{term}</a></code>" def codelink(self, s): reg1 = re.compile(r"""<code>foaf:(\w+)<\/code>""") return(re.sub(reg1, r"""<code><a href="#term_\1">foaf:\1</a></code>""", s)) def _get_template(self): self._template = self.load_template() # should be conditional return self._template def _set_template(self, value): self._template = str(value) template = property(_get_template,_set_template) def load_template(self): filename = os.path.join(self.templatedir, self.temploc) f = open(filename, "r") template = f.read() return(template) def generate(self): tpl = self.template azlist = self.az() termlist = self.termlist() -# print "RDF is in ", self.vocab.filename + f = open ( self.vocab.filename, "r") rdfdata = f.read() # print "GENERATING >>>>>>>> " -##havign the rdf in there is making it invalid -## tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8"), rdfdata) +## having the rdf in there was making it invalid +## removed in favour of RDFa +## tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8"), rdfdata) tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8")) return(tpl) -# u = urllib.urlopen(specloc) -# rdfdata = u.read() -# rdfdata = re.sub(r"(<\?xml version.*\?>)", "", rdfdata) -# rdfdata = re.sub(r"(<!DOCTYPE[^]]*]>)", "", rdfdata) -# rdfdata.replace("""<?xml version="1.0"?>""", "") - def az(self): """AZ List for html doc""" c_ids, p_ids = self.vocab.azlist() az = """<div class="azlist">""" az = """%s\n<p>Classes: |""" % az # print c_ids, p_ids for c in c_ids: # speclog("Class "+c+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(c).replace(" ", ""), c) az = """%s\n</p>""" % az az = """%s\n<p>Properties: |""" % az for p in p_ids: # speclog("Property "+p+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(p).replace(" ", ""), p) az = """%s\n</p>""" % az az = """%s\n</div>""" % az return(az) def termlist(self): """Term List for html doc""" queries = '' c_ids, p_ids = self.vocab.azlist() tl = """<div class="termlist">""" tl = """%s<h3>Classes and Properties (full detail)</h3>\n<div class='termdetails'><br />\n\n""" % tl # first classes, then properties eg = """<div class="specterm" id="term_%s" about="%s" typeof="%s"> <h3>%s: %s</h3> <em>%s</em> - %s <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#%s">%s</span></td></tr> %s %s </table> %s <p style="float: right; font-size: small;">[<a href="#term_%s">#</a>] <!-- %s --> [<a href="#glance">back to top</a>]</p> <br/> </div>""" # replace this if you want validation queries: xxx danbri # <p style="float: right; font-size: small;">[<a href="#term_%s">permalink</a>] [<a href="#queries_%s">validation queries</a>] [<a href="#glance">back to top</a>]</p> # todo, push this into an api call (c_ids currently setup by az above) # classes for term in self.vocab.classes: + # strings to use later domainsOfClass = '' rangesOfClass = '' #class in domain of g = self.vocab.graph q = 'SELECT ?d ?l WHERE {?d rdfs:domain <%s> . ?d rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) - sss = '<tr><th>in-domain-of:</th>\n' + startStr = '<tr><th>in-domain-of:</th>\n' - tt = '' + contentStr = '' for (domain, label) in relations: dom = Term(domain) - ss = """<a href="#term_%s">%s</a>\n""" % (dom.id, label) - tt = "%s %s" % (tt, ss) + termStr = """<a href="#term_%s">%s</a>\n""" % (dom.id, label) + contentStr = "%s %s" % (contentStr, termStr) - if tt != "": - domainsOfClass = "%s <td> %s </td></tr>" % (sss, tt)#[1] + if contentStr != "": + domainsOfClass = "%s <td> %s </td></tr>" % (startStr, contentStr) # class in range of q2 = 'SELECT ?d ?l WHERE {?d rdfs:range <%s> . ?d rdfs:label ?l } ' % (term.uri) query2 = Parse(q2) relations2 = g.query(query2, initNs=bindings) - snippet = '<tr><th>in-range-of:</th>\n' - tt = '' + startStr = '<tr><th>in-range-of:</th>\n' + + contentStr = '' for (range, label) in relations2: ran = Term(range) - ss = """<a href="#term_%s">%s</a>\n""" % (ran.id, label) - tt = "%s %s" % (tt, ss) - #print "R ",tt + termStr = """<a href="#term_%s">%s</a>\n""" % (ran.id, label) + contentStr = "%s %s" % (contentStr, termStr) - if tt != "": - rangesOfClass = "%s <td> %s</td></tr> " % (snippet, tt) + if contentStr != "": + rangesOfClass = "%s <td> %s</td></tr> " % (startStr, contentStr) # class subclassof subClassOf = '' q = 'SELECT ?sc ?l WHERE {<%s> rdfs:subClassOf ?sc . ?sc rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) - sss = '<tr><th>subClassOf</th>\n' + startStr = '<tr><th>subClassOf</th>\n' - tt = '' + contentStr = '' for (subclass, label) in relations: sub = Term(subclass) - ss = """<span rel="rdfs:subClassOf" href="%s"><a href="#term_%s">%s</a></span>\n""" % (subclass, sub.id, label) # - tt = "%s %s" % (tt, ss) + termStr = """<span rel="rdfs:subClassOf" href="%s"><a href="#term_%s">%s</a></span>\n""" % (subclass, sub.id, label) # + contentStr = "%s %s" % (contentStr, termStr) - if tt != "": - subClassOf = "%s <td> %s </td></tr>" % (sss, tt) + if contentStr != "": + subClassOf = "%s <td> %s </td></tr>" % (startStr, contentStr) # class has subclass hasSubClass = '' q = 'SELECT ?sc ?l WHERE {?sc rdfs:subClassOf <%s>. ?sc rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) - sss = '<tr><th>has subclass</th>\n' + startStr = '<tr><th>has subclass</th>\n' - tt = '' + contentStr = '' for (subclass, label) in relations: sub = Term(subclass) - ss = """<a href="#term_%s">%s</a>\n""" % (sub.id, label) - tt = "%s %s" % (tt, ss) + termStr = """<a href="#term_%s">%s</a>\n""" % (sub.id, label) + contentStr = "%s %s" % (contentStr, termStr) - if tt != "": - hasSubClass = "%s <td> %s </td></tr>" % (sss, tt) + if contentStr != "": + hasSubClass = "%s <td> %s </td></tr>" % (startStr, contentStr) # is defined by classIsDefinedBy = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) - sss = '\n' + startStr = '\n' - tt = '' + contentStr = '' for (isdefinedby) in relations: - ss = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) - tt = "%s %s" % (tt, ss) + termStr = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) + contentStr = "%s %s" % (contentStr, termStr) - if tt != "": - classIsDefinedBy = "%s %s " % (sss, tt) + if contentStr != "": + classIsDefinedBy = "%s %s " % (startStr, contentStr) # disjoint with isDisjointWith = '' q = 'SELECT ?dj ?l WHERE { <%s> <http://www.w3.org/2002/07/owl#disjointWith> ?dj . ?dj rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) - sss = '<tr><th>Disjoint With:</th>\n' + startStr = '<tr><th>Disjoint With:</th>\n' - tt = '' + contentStr = '' for (disjointWith, label) in relations: - ss = """<span rel="owl:disjointWith" href="%s"><a href="#term_%s">%s</a></span>\n""" % (disjointWith, label, label) - tt = "%s %s" % (tt, ss) + termStr = """<span rel="owl:disjointWith" href="%s"><a href="#term_%s">%s</a></span>\n""" % (disjointWith, label, label) + contentStr = "%s %s" % (contentStr, termStr) - if tt != "": - isDisjointWith = "%s <td> %s </td></tr>" % (sss, tt) + if contentStr != "": + isDisjointWith = "%s <td> %s </td></tr>" % (startStr, contentStr) # end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' #queries filename = os.path.join(dn, term.id+".sparql") ss = '' try: f = open ( filename, "r") ss = f.read() ss = "<h4><a name=\"queries_"+term.id+"\"></a>"+term.id+" Validation Query</h4><pre>"+cgi.escape(ss)+"</pre>" except: ss='' queries = queries +"\n"+ ss # s = s+"\n"+ss sn = self.vocab.niceName(term.uri) zz = eg % (term.id,term.uri,"rdfs:Class","Class", sn, term.label, term.comment, term.status,term.status,domainsOfClass,rangesOfClass+subClassOf+hasSubClass+classIsDefinedBy+isDisjointWith, s,term.id, term.id) tl = "%s %s" % (tl, zz) # properties for term in self.vocab.properties: domainsOfProperty = '' rangesOfProperty = '' # domain of properties g = self.vocab.graph q = 'SELECT ?d ?l WHERE {<%s> rdfs:domain ?d . ?d rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) - sss = '<tr><th>Domain:</th>\n' + startStr = '<tr><th>Domain:</th>\n' - tt = '' + contentStr = '' for (domain, label) in relations: dom = Term(domain) - ss = """<span rel="rdfs:domain" href="%s"><a href="#term_%s">%s</a></span>\n""" % (domain, dom.id, label) - tt = "%s %s" % (tt, ss) + termStr = """<span rel="rdfs:domain" href="%s"><a href="#term_%s">%s</a></span>\n""" % (domain, dom.id, label) + contentStr = "%s %s" % (contentStr, termStr) - if tt != "": - domainsOfProperty = "%s <td>%s</td></tr>" % (sss, tt) + if contentStr != "": + domainsOfProperty = "%s <td>%s</td></tr>" % (startStr, contentStr) # range of properties q2 = 'SELECT ?d ?l WHERE {<%s> rdfs:range ?d . ?d rdfs:label ?l } ' % (term.uri) query2 = Parse(q2) relations2 = g.query(query2, initNs=bindings) - sss = '<tr><th>Range:</th>\n' - tt = '' + startStr = '<tr><th>Range:</th>\n' + contentStr = '' for (range, label) in relations2: ran = Term(range) - ss = """<span rel="rdfs:range" href="%s"><a href="#term_%s">%s</a></span>\n""" % (range, ran.id, label) - tt = "%s %s" % (tt, ss) -# print "D ",tt + termStr = """<span rel="rdfs:range" href="%s"><a href="#term_%s">%s</a></span>\n""" % (range, ran.id, label) + contentStr = "%s %s" % (contentStr, termStr) - if tt != "": - rangesOfProperty = "%s <td>%s</td> </tr>" % (sss, tt) + if contentStr != "": + rangesOfProperty = "%s <td>%s</td> </tr>" % (startStr, contentStr) # is defined by propertyIsDefinedBy = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) - sss = '\n' + startStr = '\n' - tt = '' + contentStr = '' for (isdefinedby) in relations: - ss = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) - tt = "%s %s" % (tt, ss) + termStr = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) + contentStr = "%s %s" % (contentStr, termStr) - if tt != "": - propertyIsDefinedBy = "%s %s " % (sss, tt) + if contentStr != "": + propertyIsDefinedBy = "%s %s " % (startStr, contentStr) # inverse functional property ifp = '' q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#InverseFunctionalProperty> } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) - sss = '<tr><th colspan="2">Inverse Functional Property</th>\n' + startStr = '<tr><th colspan="2">Inverse Functional Property</th>\n' if (len(relations) > 0): - ss = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#InverseFunctionalProperty"></span>""" - ifp = "%s <td> %s </td></tr>" % (sss, ss) + termStr = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#InverseFunctionalProperty"></span>""" + ifp = "%s <td> %s </td></tr>" % (startStr, termStr) # functonal property fp = '' q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#FunctionalProperty> } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) - sss = '<tr><th colspan="2">Functional Property</th>\n' + startStr = '<tr><th colspan="2">Functional Property</th>\n' if (len(relations) > 0): - ss = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#FunctionalProperty"></span>""" - fp = "%s <td> %s </td></tr>" % (sss, ss) + termStr = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#FunctionalProperty"></span>""" + fp = "%s <td> %s </td></tr>" % (startStr, termStr) # end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' sn = self.vocab.niceName(term.uri) zz = eg % (term.id, term.uri,"rdf:Property","Property", sn, term.label, term.comment, term.status,term.status,domainsOfProperty,rangesOfProperty+propertyIsDefinedBy+ifp+fp, s,term.id, term.id) tl = "%s %s" % (tl, zz) ## ensure termlist tag is closed return(tl+"\n"+queries+"</div>\n</div>") def rdfa(self): return( "<html>rdfa here</html>") def htmlDocInfo( t, termdir='../docs' ): """Opens a file based on the term name (t) and termdir (defaults to current directory. Reads in the file, and returns a linkified version of it.""" if termdir==None: termdir=self.basedir doc = "" try: f = open("%s/%s.en" % (termdir, t), "r") doc = f.read() doc = termlink(doc) except: return "<p>No detailed documentation for this term.</p>" return doc # report what we've parsed from our various sources def report(self): s = "Report for vocabulary from " + self.vocab.filename + "\n" if self.vocab.uri != None: s += "URI: " + self.vocab.uri + "\n\n" for t in self.vocab.uterms: print "TERM as string: ",t s += t.simple_report() return s
leth/SpecGen
f46870fdd715a64df2bf0cbc922bc62f76c5ab04
removed all 'foo' variables to make themn more descriptive
diff --git a/libvocab.py b/libvocab.py index 84409a9..c31dc7e 100755 --- a/libvocab.py +++ b/libvocab.py @@ -14,788 +14,784 @@ # >>> dna.comment # 'A checksum for the DNA of some thing. Joke.' # >>> dna.id # u'dnaChecksum' # >>> dna.uri # 'http://xmlns.com/foaf/0.1/dnaChecksum' # # # Python OO notes: # http://www.devshed.com/c/a/Python/Object-Oriented-Programming-With-Python-part-1/ # http://www.daniweb.com/code/snippet354.html # http://docs.python.org/reference/datamodel.html#specialnames # # RDFlib: # http://www.science.uva.nl/research/air/wiki/RDFlib # # http://dowhatimean.net/2006/03/spellchecking-vocabularies-with-sparql # # We define basics, Vocab, Term, Property, Class # and populate them with data from RDF schemas, OWL, translations ... and nearby html files. import rdflib from rdflib import Namespace from rdflib.Graph import Graph from rdflib.Graph import ConjunctiveGraph from rdflib.sparql.sparqlGraph import SPARQLGraph from rdflib.sparql.graphPattern import GraphPattern from rdflib.sparql.bison import Parse from rdflib.sparql import Query FOAF = Namespace('http://xmlns.com/foaf/0.1/') RDFS = Namespace('http://www.w3.org/2000/01/rdf-schema#') XFN = Namespace("http://gmpg.org/xfn/1#") RDF = Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#") OWL = Namespace('http://www.w3.org/2002/07/owl#') VS = Namespace('http://www.w3.org/2003/06/sw-vocab-status/ns#') DC = Namespace('http://purl.org/dc/elements/1.1/') DOAP = Namespace('http://usefulinc.com/ns/doap#') SIOC = Namespace('http://rdfs.org/sioc/ns#') SIOCTYPES = Namespace('http://rdfs.org/sioc/types#') SIOCSERVICES = Namespace('http://rdfs.org/sioc/services#') # # TODO: rationalise these two lists. or at least check they are same. import sys, time, re, urllib, getopt import logging import os.path import cgi import operator bindings = { u"xfn": XFN, u"rdf": RDF, u"rdfs": RDFS, u"vs": VS } #g = None def speclog(str): sys.stderr.write("LOG: "+str+"\n") # a Term has... (intrinsically and via it's RDFS/OWL description) # uri - a (primary) URI, eg. 'http://xmlns.com/foaf/0.1/workplaceHomepage' # id - a local-to-spec ID, eg. 'workplaceHomepage' # xmlns - an xmlns URI (isDefinedBy, eg. 'http://xmlns.com/foaf/0.1/') # # label - an rdfs:label # comment - an rdfs:comment # # Beyond this, properties vary. Some have vs:status. Some have owl Deprecated. # Some have OWL descriptions, and RDFS descriptions; eg. property range/domain # or class disjointness. def ns_split(uri): regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) return(rez.group(1), rez.group(2)) class Term(object): def __init__(self, uri='file://dev/null'): self.uri = str(uri) self.uri = self.uri.rstrip() # speclog("Parsing URI " + uri) a,b = ns_split(uri) self.id = b self.xmlns = a if self.id==None: speclog("Error parsing URI. "+uri) if self.xmlns==None: speclog("Error parsing URI. "+uri) # print "self.id: "+ self.id + " self.xmlns: " + self.xmlns def uri(self): try: s = self.uri except NameError: self.uri = None s = '[NOURI]' speclog('No URI for'+self) return s def id(self): print "trying id" try: s = self.id except NameError: self.id = None s = '[NOID]' speclog('No ID for'+self) return str(s) def is_external(self, vocab): print "Comparing property URI ",self.uri," with vocab uri: " + vocab.uri return(False) #def __repr__(self): # return(self.__str__) def __str__(self): try: s = self.id except NameError: self.label = None speclog('No label for '+self+' todo: take from uri regex') s = (str(self)) return(str(s)) # so we can treat this like a string def __add__(self, s): return (s+str(self)) def __radd__(self, s): return (s+str(self)) def simple_report(self): t = self s='' s += "default: \t\t"+t +"\n" s += "id: \t\t"+t.id +"\n" s += "uri: \t\t"+t.uri +"\n" s += "xmlns: \t\t"+t.xmlns +"\n" s += "label: \t\t"+t.label +"\n" s += "comment: \t\t" + t.comment +"\n" s += "status: \t\t" + t.status +"\n" s += "\n" return s def _get_status(self): try: return self._status except: return 'unknown' def _set_status(self, value): self._status = str(value) status = property(_get_status,_set_status) # a Python class representing an RDFS/OWL property. # class Property(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Property.is_property called on "+self return(True) def is_class(self): # print "Property.is_class called on "+self return(False) # A Python class representing an RDFS/OWL class # class Class(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Class.is_property called on "+self return(False) def is_class(self): # print "Class.is_class called on "+self return(True) # A python class representing (a description of) some RDF vocabulary # class Vocab(object): def __init__(self, dir, f='index.rdf', uri=None ): self.graph = rdflib.ConjunctiveGraph() self._uri = uri self.dir = dir self.filename = os.path.join(dir, f) self.graph.parse(self.filename) self.terms = [] self.uterms = [] # should also load translations here? # and deal with a base-dir? ##if f != None: ## self.index() self.ns_list = { "http://www.w3.org/1999/02/22-rdf-syntax-ns#" : "rdf", "http://www.w3.org/2000/01/rdf-schema#" : "rdfs", "http://www.w3.org/2002/07/owl#" : "owl", "http://www.w3.org/2001/XMLSchema#" : "xsd", "http://rdfs.org/sioc/ns#" : "sioc", "http://xmlns.com/foaf/0.1/" : "foaf", "http://purl.org/dc/elements/1.1/" : "dc", "http://purl.org/dc/terms/" : "dct", "http://usefulinc.com/ns/doap#" : "doap", "http://www.w3.org/2003/06/sw-vocab-status/ns#" : "status", "http://purl.org/rss/1.0/modules/content/" : "content", "http://www.w3.org/2003/01/geo/wgs84_pos#" : "geo", "http://www.w3.org/2004/02/skos/core#" : "skos", "http://purl.org/NET/c4dm/event.owl#" : "event" } def addShortName(self,sn): self.ns_list[self._uri] = sn self.shortName = sn #print self.ns_list # not currently used def unique_terms(self): tmp=[] for t in list(set(self.terms)): s = str(t) if (not s in tmp): self.uterms.append(t) tmp.append(s) # TODO: python question - can we skip needing getters? and only define setters. i tried/failed. --danbri def _get_uri(self): return self._uri def _set_uri(self, value): v = str(value) # we don't want Namespace() objects and suchlike, but we can use them without whining. if ':' not in v: speclog("Warning: this doesn't look like a URI: "+v) # raise Exception("This doesn't look like a URI.") self._uri = str( value ) uri = property(_get_uri,_set_uri) def set_filename(self, filename): self.filename = filename # TODO: be explicit if/where we default to English # TODO: do we need a separate index(), versus just use __init__ ? def index(self): # speclog("Indexing description of "+str(self)) # blank down anything we learned already self.terms = [] self.properties = [] self.classes = [] tmpclasses=[] tmpproperties=[] g = self.graph query = Parse('SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a rdf:Property } ') relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: p = Property(term) # print "Made a property! "+str(p) + "using label: "#+str(label) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) query = Parse('SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type FILTER (?type = <http://www.w3.org/2002/07/owl#Class> || ?type = <http://www.w3.org/2000/01/rdf-schema#Class> ) }') relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: c = Class(term) # print "Made a class! "+str(p) + "using comment: "+comment c.label = str(label) c.comment = str(comment) self.terms.append(c) if (not str(c) in tmpclasses): self.classes.append(c) tmpclasses.append(str(c)) self.terms.sort(key=operator.attrgetter('id')) self.classes.sort(key=operator.attrgetter('id')) self.properties.sort(key=operator.attrgetter('id')) # http://www.w3.org/2003/06/sw-vocab-status/ns#" query = Parse('SELECT ?x ?vs WHERE { ?x <http://www.w3.org/2003/06/sw-vocab-status/ns#term_status> ?vs }') status = g.query(query, initNs=bindings) # print "status results: ",status.__len__() for x, vs in status: #print "STATUS: ",vs, " for ",x t = self.lookup(x) if t != None: t.status = vs # print "Set status.", t.status else: speclog("Couldn't lookup term: "+x) # Go back and see if we missed any properties defined in OWL. TODO: classes too. Or rewrite above SPARQL. addd more types for full query. q= 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty>)}' q= 'SELECT distinct ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty> || ?type = <http://www.w3.org/2002/07/owl#DatatypeProperty> || ?type = <http://www.w3.org/1999/02/22-rdf-syntax-ns#Property> || ?type = <http://www.w3.org/2002/07/owl#FunctionalProperty> || ?type = <http://www.w3.org/2002/07/owl#InverseFunctionalProperty>) } ' query = Parse(q) relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: p = Property(str(term)) got = self.lookup( str(term) ) if got==None: # print "Made an OWL property! "+str(p.uri) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) # self.terms.sort() # does this even do anything? # self.classes.sort() # self.properties.sort() # todo, use a dictionary index instead. RTFM. def lookup(self, uri): uri = str(uri) for t in self.terms: # print "Lookup: comparing '"+t.uri+"' to '"+uri+"'" # print "type of t.uri is ",t.uri.__class__ if t.uri==uri: # print "Matched." # should we str here, to be more liberal? return t else: # print "Fail." '' return None # print a raw debug summary, direct from the RDF def raw(self): g = self.graph query = Parse('SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c } ') relations = g.query(query, initNs=bindings) print "Properties and Classes (%d terms)" % len(relations) print 40*"-" for (term, label, comment) in relations: print "term %s l: %s \t\tc: %s " % (term, label, comment) print # TODO: work out how to do ".encode('UTF-8')" here # for debugging only def detect_types(self): self.properties = [] self.classes = [] for t in self.terms: # print "Doing t: "+t+" which is of type " + str(t.__class__) if t.is_property(): # print "is_property." self.properties.append(t) if t.is_class(): # print "is_class." self.classes.append(t) # CODE FROM ORIGINAL specgen: def niceName(self, uri = None ): if uri is None: return # speclog("Nicing uri "+uri) regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) if rez == None: #print "Failed to niceName. Returning the whole thing." return(uri) pref = rez.group(1) # print "...",self.ns_list.get(pref, pref),":",rez.group(2) # todo: make this work when uri doesn't match the regex --danbri # AttributeError: 'NoneType' object has no attribute 'group' return self.ns_list.get(pref, pref) + ":" + rez.group(2) # HTML stuff, should be a separate class def azlist(self): """Builds the A-Z list of terms""" c_ids = [] p_ids = [] for p in self.properties: p_ids.append(str(p.id)) for c in self.classes: c_ids.append(str(c.id)) c_ids.sort() p_ids.sort() return (c_ids, p_ids) class VocabReport(object): def __init__(self, vocab, basedir='./examples/', temploc='template.html',templatedir='./examples/'): self.vocab = vocab self.basedir = basedir self.temploc = temploc self.templatedir = templatedir self._template = "no template loaded" # text.gsub(/<code>foaf:(\w+)<\/code>/){ defurl($1) } return "<code><a href=\"#term_#{term}\">foaf:#{term}</a></code>" def codelink(self, s): reg1 = re.compile(r"""<code>foaf:(\w+)<\/code>""") return(re.sub(reg1, r"""<code><a href="#term_\1">foaf:\1</a></code>""", s)) def _get_template(self): self._template = self.load_template() # should be conditional return self._template def _set_template(self, value): self._template = str(value) template = property(_get_template,_set_template) def load_template(self): filename = os.path.join(self.templatedir, self.temploc) f = open(filename, "r") template = f.read() return(template) def generate(self): tpl = self.template azlist = self.az() termlist = self.termlist() # print "RDF is in ", self.vocab.filename f = open ( self.vocab.filename, "r") rdfdata = f.read() # print "GENERATING >>>>>>>> " ##havign the rdf in there is making it invalid ## tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8"), rdfdata) tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8")) return(tpl) # u = urllib.urlopen(specloc) # rdfdata = u.read() # rdfdata = re.sub(r"(<\?xml version.*\?>)", "", rdfdata) # rdfdata = re.sub(r"(<!DOCTYPE[^]]*]>)", "", rdfdata) # rdfdata.replace("""<?xml version="1.0"?>""", "") def az(self): """AZ List for html doc""" c_ids, p_ids = self.vocab.azlist() az = """<div class="azlist">""" az = """%s\n<p>Classes: |""" % az # print c_ids, p_ids for c in c_ids: # speclog("Class "+c+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(c).replace(" ", ""), c) az = """%s\n</p>""" % az az = """%s\n<p>Properties: |""" % az for p in p_ids: # speclog("Property "+p+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(p).replace(" ", ""), p) az = """%s\n</p>""" % az az = """%s\n</div>""" % az return(az) def termlist(self): """Term List for html doc""" queries = '' c_ids, p_ids = self.vocab.azlist() tl = """<div class="termlist">""" tl = """%s<h3>Classes and Properties (full detail)</h3>\n<div class='termdetails'><br />\n\n""" % tl # first classes, then properties eg = """<div class="specterm" id="term_%s" about="%s" typeof="%s"> <h3>%s: %s</h3> <em>%s</em> - %s <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#%s">%s</span></td></tr> %s %s </table> %s <p style="float: right; font-size: small;">[<a href="#term_%s">#</a>] <!-- %s --> [<a href="#glance">back to top</a>]</p> <br/> </div>""" # replace this if you want validation queries: xxx danbri # <p style="float: right; font-size: small;">[<a href="#term_%s">permalink</a>] [<a href="#queries_%s">validation queries</a>] [<a href="#glance">back to top</a>]</p> # todo, push this into an api call (c_ids currently setup by az above) # classes for term in self.vocab.classes: - domains = '' #[1] - foo1 = '' + domainsOfClass = '' + rangesOfClass = '' #class in domain of g = self.vocab.graph q = 'SELECT ?d ?l WHERE {?d rdfs:domain <%s> . ?d rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th>in-domain-of:</th>\n' tt = '' for (domain, label) in relations: dom = Term(domain) ss = """<a href="#term_%s">%s</a>\n""" % (dom.id, label) tt = "%s %s" % (tt, ss) if tt != "": - domains = "%s <td> %s </td></tr>" % (sss, tt)#[1] + domainsOfClass = "%s <td> %s </td></tr>" % (sss, tt)#[1] # class in range of q2 = 'SELECT ?d ?l WHERE {?d rdfs:range <%s> . ?d rdfs:label ?l } ' % (term.uri) query2 = Parse(q2) relations2 = g.query(query2, initNs=bindings) snippet = '<tr><th>in-range-of:</th>\n' tt = '' for (range, label) in relations2: ran = Term(range) ss = """<a href="#term_%s">%s</a>\n""" % (ran.id, label) tt = "%s %s" % (tt, ss) #print "R ",tt if tt != "": - foo1 = "%s <td> %s</td></tr> " % (snippet, tt) + rangesOfClass = "%s <td> %s</td></tr> " % (snippet, tt) # class subclassof - foo2 = '' + subClassOf = '' q = 'SELECT ?sc ?l WHERE {<%s> rdfs:subClassOf ?sc . ?sc rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th>subClassOf</th>\n' tt = '' for (subclass, label) in relations: sub = Term(subclass) ss = """<span rel="rdfs:subClassOf" href="%s"><a href="#term_%s">%s</a></span>\n""" % (subclass, sub.id, label) # tt = "%s %s" % (tt, ss) if tt != "": - foo2 = "%s <td> %s </td></tr>" % (sss, tt) + subClassOf = "%s <td> %s </td></tr>" % (sss, tt) # class has subclass - foo3 = '' + hasSubClass = '' q = 'SELECT ?sc ?l WHERE {?sc rdfs:subClassOf <%s>. ?sc rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th>has subclass</th>\n' tt = '' for (subclass, label) in relations: sub = Term(subclass) ss = """<a href="#term_%s">%s</a>\n""" % (sub.id, label) tt = "%s %s" % (tt, ss) if tt != "": - foo3 = "%s <td> %s </td></tr>" % (sss, tt) + hasSubClass = "%s <td> %s </td></tr>" % (sss, tt) # is defined by - foo4 = '' + classIsDefinedBy = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '\n' tt = '' for (isdefinedby) in relations: ss = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) tt = "%s %s" % (tt, ss) if tt != "": - foo4 = "%s %s " % (sss, tt) + classIsDefinedBy = "%s %s " % (sss, tt) # disjoint with - foo5 = '' + isDisjointWith = '' q = 'SELECT ?dj ?l WHERE { <%s> <http://www.w3.org/2002/07/owl#disjointWith> ?dj . ?dj rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th>Disjoint With:</th>\n' tt = '' for (disjointWith, label) in relations: ss = """<span rel="owl:disjointWith" href="%s"><a href="#term_%s">%s</a></span>\n""" % (disjointWith, label, label) tt = "%s %s" % (tt, ss) if tt != "": - foo5 = "%s <td> %s </td></tr>" % (sss, tt) + isDisjointWith = "%s <td> %s </td></tr>" % (sss, tt) # end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' #queries filename = os.path.join(dn, term.id+".sparql") ss = '' try: f = open ( filename, "r") ss = f.read() ss = "<h4><a name=\"queries_"+term.id+"\"></a>"+term.id+" Validation Query</h4><pre>"+cgi.escape(ss)+"</pre>" except: ss='' queries = queries +"\n"+ ss # s = s+"\n"+ss sn = self.vocab.niceName(term.uri) -# trying to figure out how libby's improvements work. Assuming 'foo' is the validation queries, which i'm turning off for now. Sorry Lib! -# danbri todoxxx -# zz = eg % (term.id,term.uri,"rdfs:Class","Class", sn, term.label, term.comment, term.status,term.status,foo,foo1+foo2+foo3+foo4+foo5, s,term.id, term.id) - zz = eg % (term.id,term.uri,"rdfs:Class","Class", sn, term.label, term.comment, term.status,term.status,domains,foo1+foo2+foo3+foo4+foo5, s,term.id, term.id) + zz = eg % (term.id,term.uri,"rdfs:Class","Class", sn, term.label, term.comment, term.status,term.status,domainsOfClass,rangesOfClass+subClassOf+hasSubClass+classIsDefinedBy+isDisjointWith, s,term.id, term.id) + tl = "%s %s" % (tl, zz) # properties for term in self.vocab.properties: - domains = '' - foo1 = '' + domainsOfProperty = '' + rangesOfProperty = '' # domain of properties g = self.vocab.graph q = 'SELECT ?d ?l WHERE {<%s> rdfs:domain ?d . ?d rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th>Domain:</th>\n' tt = '' for (domain, label) in relations: dom = Term(domain) ss = """<span rel="rdfs:domain" href="%s"><a href="#term_%s">%s</a></span>\n""" % (domain, dom.id, label) tt = "%s %s" % (tt, ss) if tt != "": - domains = "%s <td>%s</td></tr>" % (sss, tt) + domainsOfProperty = "%s <td>%s</td></tr>" % (sss, tt) # range of properties q2 = 'SELECT ?d ?l WHERE {<%s> rdfs:range ?d . ?d rdfs:label ?l } ' % (term.uri) query2 = Parse(q2) relations2 = g.query(query2, initNs=bindings) sss = '<tr><th>Range:</th>\n' tt = '' for (range, label) in relations2: ran = Term(range) ss = """<span rel="rdfs:range" href="%s"><a href="#term_%s">%s</a></span>\n""" % (range, ran.id, label) tt = "%s %s" % (tt, ss) # print "D ",tt if tt != "": - foo1 = "%s <td>%s</td> </tr>" % (sss, tt) + rangesOfProperty = "%s <td>%s</td> </tr>" % (sss, tt) # is defined by - foo4 = '' + propertyIsDefinedBy = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '\n' tt = '' for (isdefinedby) in relations: ss = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) tt = "%s %s" % (tt, ss) if tt != "": - foo4 = "%s %s " % (sss, tt) + propertyIsDefinedBy = "%s %s " % (sss, tt) # inverse functional property - foo5 = '' + ifp = '' q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#InverseFunctionalProperty> } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th colspan="2">Inverse Functional Property</th>\n' if (len(relations) > 0): ss = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#InverseFunctionalProperty"></span>""" - foo5 = "%s <td> %s </td></tr>" % (sss, ss) + ifp = "%s <td> %s </td></tr>" % (sss, ss) # functonal property -# inverse functional property - - foo6 = '' + fp = '' q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#FunctionalProperty> } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th colspan="2">Functional Property</th>\n' if (len(relations) > 0): ss = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#FunctionalProperty"></span>""" - foo6 = "%s <td> %s </td></tr>" % (sss, ss) + fp = "%s <td> %s </td></tr>" % (sss, ss) # end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' sn = self.vocab.niceName(term.uri) - zz = eg % (term.id, term.uri,"rdf:Property","Property", sn, term.label, term.comment, term.status,term.status, domains, foo1+foo4+foo5+foo6, s,term.id, term.id) + zz = eg % (term.id, term.uri,"rdf:Property","Property", sn, term.label, term.comment, term.status,term.status,domainsOfProperty,rangesOfProperty+propertyIsDefinedBy+ifp+fp, s,term.id, term.id) tl = "%s %s" % (tl, zz) ## ensure termlist tag is closed return(tl+"\n"+queries+"</div>\n</div>") def rdfa(self): return( "<html>rdfa here</html>") def htmlDocInfo( t, termdir='../docs' ): """Opens a file based on the term name (t) and termdir (defaults to current directory. Reads in the file, and returns a linkified version of it.""" if termdir==None: termdir=self.basedir doc = "" try: f = open("%s/%s.en" % (termdir, t), "r") doc = f.read() doc = termlink(doc) except: return "<p>No detailed documentation for this term.</p>" return doc # report what we've parsed from our various sources def report(self): s = "Report for vocabulary from " + self.vocab.filename + "\n" if self.vocab.uri != None: s += "URI: " + self.vocab.uri + "\n\n" for t in self.vocab.uterms: print "TERM as string: ",t s += t.simple_report() return s
leth/SpecGen
b32449956d805ef501662c383b7250f8a265e1b2
yet more arguments - you can now specify twhere the teplate and index.rdf files are separately. it looks for the docs in indir and looks there index.rdf and template if those args are ommitted
diff --git a/libvocab.py b/libvocab.py index de47b2a..84409a9 100755 --- a/libvocab.py +++ b/libvocab.py @@ -1,800 +1,801 @@ #!/usr/bin/env python # total rewrite. --danbri # Usage: # # >>> from libvocab import Vocab, Term, Class, Property # # >>> from libvocab import Vocab, Term, Class, Property # >>> v = Vocab( f='examples/foaf/index.rdf', uri='http://xmlns.com/foaf/0.1/') # >>> dna = v.lookup('http://xmlns.com/foaf/0.1/dnaChecksum') # >>> dna.label # 'DNA checksum' # >>> dna.comment # 'A checksum for the DNA of some thing. Joke.' # >>> dna.id # u'dnaChecksum' # >>> dna.uri # 'http://xmlns.com/foaf/0.1/dnaChecksum' # # # Python OO notes: # http://www.devshed.com/c/a/Python/Object-Oriented-Programming-With-Python-part-1/ # http://www.daniweb.com/code/snippet354.html # http://docs.python.org/reference/datamodel.html#specialnames # # RDFlib: # http://www.science.uva.nl/research/air/wiki/RDFlib # # http://dowhatimean.net/2006/03/spellchecking-vocabularies-with-sparql # # We define basics, Vocab, Term, Property, Class # and populate them with data from RDF schemas, OWL, translations ... and nearby html files. import rdflib from rdflib import Namespace from rdflib.Graph import Graph from rdflib.Graph import ConjunctiveGraph from rdflib.sparql.sparqlGraph import SPARQLGraph from rdflib.sparql.graphPattern import GraphPattern from rdflib.sparql.bison import Parse from rdflib.sparql import Query FOAF = Namespace('http://xmlns.com/foaf/0.1/') RDFS = Namespace('http://www.w3.org/2000/01/rdf-schema#') XFN = Namespace("http://gmpg.org/xfn/1#") RDF = Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#") OWL = Namespace('http://www.w3.org/2002/07/owl#') VS = Namespace('http://www.w3.org/2003/06/sw-vocab-status/ns#') DC = Namespace('http://purl.org/dc/elements/1.1/') DOAP = Namespace('http://usefulinc.com/ns/doap#') SIOC = Namespace('http://rdfs.org/sioc/ns#') SIOCTYPES = Namespace('http://rdfs.org/sioc/types#') SIOCSERVICES = Namespace('http://rdfs.org/sioc/services#') # # TODO: rationalise these two lists. or at least check they are same. import sys, time, re, urllib, getopt import logging import os.path import cgi import operator bindings = { u"xfn": XFN, u"rdf": RDF, u"rdfs": RDFS, u"vs": VS } #g = None def speclog(str): sys.stderr.write("LOG: "+str+"\n") # a Term has... (intrinsically and via it's RDFS/OWL description) # uri - a (primary) URI, eg. 'http://xmlns.com/foaf/0.1/workplaceHomepage' # id - a local-to-spec ID, eg. 'workplaceHomepage' # xmlns - an xmlns URI (isDefinedBy, eg. 'http://xmlns.com/foaf/0.1/') # # label - an rdfs:label # comment - an rdfs:comment # # Beyond this, properties vary. Some have vs:status. Some have owl Deprecated. # Some have OWL descriptions, and RDFS descriptions; eg. property range/domain # or class disjointness. def ns_split(uri): regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) return(rez.group(1), rez.group(2)) class Term(object): def __init__(self, uri='file://dev/null'): self.uri = str(uri) self.uri = self.uri.rstrip() # speclog("Parsing URI " + uri) a,b = ns_split(uri) self.id = b self.xmlns = a if self.id==None: speclog("Error parsing URI. "+uri) if self.xmlns==None: speclog("Error parsing URI. "+uri) # print "self.id: "+ self.id + " self.xmlns: " + self.xmlns def uri(self): try: s = self.uri except NameError: self.uri = None s = '[NOURI]' speclog('No URI for'+self) return s def id(self): print "trying id" try: s = self.id except NameError: self.id = None s = '[NOID]' speclog('No ID for'+self) return str(s) def is_external(self, vocab): print "Comparing property URI ",self.uri," with vocab uri: " + vocab.uri return(False) #def __repr__(self): # return(self.__str__) def __str__(self): try: s = self.id except NameError: self.label = None speclog('No label for '+self+' todo: take from uri regex') s = (str(self)) return(str(s)) # so we can treat this like a string def __add__(self, s): return (s+str(self)) def __radd__(self, s): return (s+str(self)) def simple_report(self): t = self s='' s += "default: \t\t"+t +"\n" s += "id: \t\t"+t.id +"\n" s += "uri: \t\t"+t.uri +"\n" s += "xmlns: \t\t"+t.xmlns +"\n" s += "label: \t\t"+t.label +"\n" s += "comment: \t\t" + t.comment +"\n" s += "status: \t\t" + t.status +"\n" s += "\n" return s def _get_status(self): try: return self._status except: return 'unknown' def _set_status(self, value): self._status = str(value) status = property(_get_status,_set_status) # a Python class representing an RDFS/OWL property. # class Property(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Property.is_property called on "+self return(True) def is_class(self): # print "Property.is_class called on "+self return(False) # A Python class representing an RDFS/OWL class # class Class(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Class.is_property called on "+self return(False) def is_class(self): # print "Class.is_class called on "+self return(True) # A python class representing (a description of) some RDF vocabulary # class Vocab(object): def __init__(self, dir, f='index.rdf', uri=None ): self.graph = rdflib.ConjunctiveGraph() self._uri = uri self.dir = dir self.filename = os.path.join(dir, f) self.graph.parse(self.filename) self.terms = [] self.uterms = [] # should also load translations here? # and deal with a base-dir? ##if f != None: ## self.index() self.ns_list = { "http://www.w3.org/1999/02/22-rdf-syntax-ns#" : "rdf", "http://www.w3.org/2000/01/rdf-schema#" : "rdfs", "http://www.w3.org/2002/07/owl#" : "owl", "http://www.w3.org/2001/XMLSchema#" : "xsd", "http://rdfs.org/sioc/ns#" : "sioc", "http://xmlns.com/foaf/0.1/" : "foaf", "http://purl.org/dc/elements/1.1/" : "dc", "http://purl.org/dc/terms/" : "dct", "http://usefulinc.com/ns/doap#" : "doap", "http://www.w3.org/2003/06/sw-vocab-status/ns#" : "status", "http://purl.org/rss/1.0/modules/content/" : "content", "http://www.w3.org/2003/01/geo/wgs84_pos#" : "geo", "http://www.w3.org/2004/02/skos/core#" : "skos", "http://purl.org/NET/c4dm/event.owl#" : "event" } def addShortName(self,sn): self.ns_list[self._uri] = sn self.shortName = sn #print self.ns_list # not currently used def unique_terms(self): tmp=[] for t in list(set(self.terms)): s = str(t) if (not s in tmp): self.uterms.append(t) tmp.append(s) # TODO: python question - can we skip needing getters? and only define setters. i tried/failed. --danbri def _get_uri(self): return self._uri def _set_uri(self, value): v = str(value) # we don't want Namespace() objects and suchlike, but we can use them without whining. if ':' not in v: speclog("Warning: this doesn't look like a URI: "+v) # raise Exception("This doesn't look like a URI.") self._uri = str( value ) uri = property(_get_uri,_set_uri) def set_filename(self, filename): self.filename = filename # TODO: be explicit if/where we default to English # TODO: do we need a separate index(), versus just use __init__ ? def index(self): # speclog("Indexing description of "+str(self)) # blank down anything we learned already self.terms = [] self.properties = [] self.classes = [] tmpclasses=[] tmpproperties=[] g = self.graph query = Parse('SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a rdf:Property } ') relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: p = Property(term) # print "Made a property! "+str(p) + "using label: "#+str(label) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) query = Parse('SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type FILTER (?type = <http://www.w3.org/2002/07/owl#Class> || ?type = <http://www.w3.org/2000/01/rdf-schema#Class> ) }') relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: c = Class(term) # print "Made a class! "+str(p) + "using comment: "+comment c.label = str(label) c.comment = str(comment) self.terms.append(c) if (not str(c) in tmpclasses): self.classes.append(c) tmpclasses.append(str(c)) self.terms.sort(key=operator.attrgetter('id')) self.classes.sort(key=operator.attrgetter('id')) self.properties.sort(key=operator.attrgetter('id')) # http://www.w3.org/2003/06/sw-vocab-status/ns#" query = Parse('SELECT ?x ?vs WHERE { ?x <http://www.w3.org/2003/06/sw-vocab-status/ns#term_status> ?vs }') status = g.query(query, initNs=bindings) # print "status results: ",status.__len__() for x, vs in status: #print "STATUS: ",vs, " for ",x t = self.lookup(x) if t != None: t.status = vs # print "Set status.", t.status else: speclog("Couldn't lookup term: "+x) # Go back and see if we missed any properties defined in OWL. TODO: classes too. Or rewrite above SPARQL. addd more types for full query. q= 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty>)}' q= 'SELECT distinct ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty> || ?type = <http://www.w3.org/2002/07/owl#DatatypeProperty> || ?type = <http://www.w3.org/1999/02/22-rdf-syntax-ns#Property> || ?type = <http://www.w3.org/2002/07/owl#FunctionalProperty> || ?type = <http://www.w3.org/2002/07/owl#InverseFunctionalProperty>) } ' query = Parse(q) relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: p = Property(str(term)) got = self.lookup( str(term) ) if got==None: # print "Made an OWL property! "+str(p.uri) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) # self.terms.sort() # does this even do anything? # self.classes.sort() # self.properties.sort() # todo, use a dictionary index instead. RTFM. def lookup(self, uri): uri = str(uri) for t in self.terms: # print "Lookup: comparing '"+t.uri+"' to '"+uri+"'" # print "type of t.uri is ",t.uri.__class__ if t.uri==uri: # print "Matched." # should we str here, to be more liberal? return t else: # print "Fail." '' return None # print a raw debug summary, direct from the RDF def raw(self): g = self.graph query = Parse('SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c } ') relations = g.query(query, initNs=bindings) print "Properties and Classes (%d terms)" % len(relations) print 40*"-" for (term, label, comment) in relations: print "term %s l: %s \t\tc: %s " % (term, label, comment) print # TODO: work out how to do ".encode('UTF-8')" here # for debugging only def detect_types(self): self.properties = [] self.classes = [] for t in self.terms: # print "Doing t: "+t+" which is of type " + str(t.__class__) if t.is_property(): # print "is_property." self.properties.append(t) if t.is_class(): # print "is_class." self.classes.append(t) # CODE FROM ORIGINAL specgen: def niceName(self, uri = None ): if uri is None: return # speclog("Nicing uri "+uri) regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) if rez == None: #print "Failed to niceName. Returning the whole thing." return(uri) pref = rez.group(1) # print "...",self.ns_list.get(pref, pref),":",rez.group(2) # todo: make this work when uri doesn't match the regex --danbri # AttributeError: 'NoneType' object has no attribute 'group' return self.ns_list.get(pref, pref) + ":" + rez.group(2) # HTML stuff, should be a separate class def azlist(self): """Builds the A-Z list of terms""" c_ids = [] p_ids = [] for p in self.properties: p_ids.append(str(p.id)) for c in self.classes: c_ids.append(str(c.id)) c_ids.sort() p_ids.sort() return (c_ids, p_ids) class VocabReport(object): - def __init__(self, vocab, basedir='./examples/', temploc='template.html'): + def __init__(self, vocab, basedir='./examples/', temploc='template.html',templatedir='./examples/'): self.vocab = vocab self.basedir = basedir self.temploc = temploc + self.templatedir = templatedir self._template = "no template loaded" # text.gsub(/<code>foaf:(\w+)<\/code>/){ defurl($1) } return "<code><a href=\"#term_#{term}\">foaf:#{term}</a></code>" def codelink(self, s): reg1 = re.compile(r"""<code>foaf:(\w+)<\/code>""") return(re.sub(reg1, r"""<code><a href="#term_\1">foaf:\1</a></code>""", s)) def _get_template(self): self._template = self.load_template() # should be conditional return self._template def _set_template(self, value): self._template = str(value) template = property(_get_template,_set_template) def load_template(self): - filename = os.path.join(self.basedir, self.temploc) + filename = os.path.join(self.templatedir, self.temploc) f = open(filename, "r") template = f.read() return(template) def generate(self): tpl = self.template azlist = self.az() termlist = self.termlist() # print "RDF is in ", self.vocab.filename f = open ( self.vocab.filename, "r") rdfdata = f.read() # print "GENERATING >>>>>>>> " ##havign the rdf in there is making it invalid ## tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8"), rdfdata) tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8")) return(tpl) # u = urllib.urlopen(specloc) # rdfdata = u.read() # rdfdata = re.sub(r"(<\?xml version.*\?>)", "", rdfdata) # rdfdata = re.sub(r"(<!DOCTYPE[^]]*]>)", "", rdfdata) # rdfdata.replace("""<?xml version="1.0"?>""", "") def az(self): """AZ List for html doc""" c_ids, p_ids = self.vocab.azlist() az = """<div class="azlist">""" az = """%s\n<p>Classes: |""" % az # print c_ids, p_ids for c in c_ids: # speclog("Class "+c+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(c).replace(" ", ""), c) az = """%s\n</p>""" % az az = """%s\n<p>Properties: |""" % az for p in p_ids: # speclog("Property "+p+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(p).replace(" ", ""), p) az = """%s\n</p>""" % az az = """%s\n</div>""" % az return(az) def termlist(self): """Term List for html doc""" queries = '' c_ids, p_ids = self.vocab.azlist() tl = """<div class="termlist">""" tl = """%s<h3>Classes and Properties (full detail)</h3>\n<div class='termdetails'><br />\n\n""" % tl # first classes, then properties eg = """<div class="specterm" id="term_%s" about="%s" typeof="%s"> <h3>%s: %s</h3> <em>%s</em> - %s <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#%s">%s</span></td></tr> %s %s </table> %s <p style="float: right; font-size: small;">[<a href="#term_%s">#</a>] <!-- %s --> [<a href="#glance">back to top</a>]</p> <br/> </div>""" # replace this if you want validation queries: xxx danbri # <p style="float: right; font-size: small;">[<a href="#term_%s">permalink</a>] [<a href="#queries_%s">validation queries</a>] [<a href="#glance">back to top</a>]</p> # todo, push this into an api call (c_ids currently setup by az above) # classes for term in self.vocab.classes: - foo = '' + domains = '' #[1] foo1 = '' #class in domain of g = self.vocab.graph q = 'SELECT ?d ?l WHERE {?d rdfs:domain <%s> . ?d rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th>in-domain-of:</th>\n' tt = '' for (domain, label) in relations: dom = Term(domain) ss = """<a href="#term_%s">%s</a>\n""" % (dom.id, label) tt = "%s %s" % (tt, ss) if tt != "": - foo = "%s <td> %s </td></tr>" % (sss, tt) + domains = "%s <td> %s </td></tr>" % (sss, tt)#[1] # class in range of q2 = 'SELECT ?d ?l WHERE {?d rdfs:range <%s> . ?d rdfs:label ?l } ' % (term.uri) query2 = Parse(q2) relations2 = g.query(query2, initNs=bindings) snippet = '<tr><th>in-range-of:</th>\n' tt = '' for (range, label) in relations2: ran = Term(range) ss = """<a href="#term_%s">%s</a>\n""" % (ran.id, label) tt = "%s %s" % (tt, ss) #print "R ",tt if tt != "": foo1 = "%s <td> %s</td></tr> " % (snippet, tt) # class subclassof foo2 = '' q = 'SELECT ?sc ?l WHERE {<%s> rdfs:subClassOf ?sc . ?sc rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th>subClassOf</th>\n' tt = '' for (subclass, label) in relations: sub = Term(subclass) ss = """<span rel="rdfs:subClassOf" href="%s"><a href="#term_%s">%s</a></span>\n""" % (subclass, sub.id, label) # tt = "%s %s" % (tt, ss) if tt != "": foo2 = "%s <td> %s </td></tr>" % (sss, tt) # class has subclass foo3 = '' q = 'SELECT ?sc ?l WHERE {?sc rdfs:subClassOf <%s>. ?sc rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th>has subclass</th>\n' tt = '' for (subclass, label) in relations: sub = Term(subclass) ss = """<a href="#term_%s">%s</a>\n""" % (sub.id, label) tt = "%s %s" % (tt, ss) if tt != "": foo3 = "%s <td> %s </td></tr>" % (sss, tt) # is defined by foo4 = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '\n' tt = '' for (isdefinedby) in relations: ss = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) tt = "%s %s" % (tt, ss) if tt != "": foo4 = "%s %s " % (sss, tt) # disjoint with foo5 = '' q = 'SELECT ?dj ?l WHERE { <%s> <http://www.w3.org/2002/07/owl#disjointWith> ?dj . ?dj rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th>Disjoint With:</th>\n' tt = '' for (disjointWith, label) in relations: ss = """<span rel="owl:disjointWith" href="%s"><a href="#term_%s">%s</a></span>\n""" % (disjointWith, label, label) tt = "%s %s" % (tt, ss) if tt != "": foo5 = "%s <td> %s </td></tr>" % (sss, tt) # end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' #queries filename = os.path.join(dn, term.id+".sparql") ss = '' try: f = open ( filename, "r") ss = f.read() ss = "<h4><a name=\"queries_"+term.id+"\"></a>"+term.id+" Validation Query</h4><pre>"+cgi.escape(ss)+"</pre>" except: ss='' queries = queries +"\n"+ ss # s = s+"\n"+ss sn = self.vocab.niceName(term.uri) # trying to figure out how libby's improvements work. Assuming 'foo' is the validation queries, which i'm turning off for now. Sorry Lib! # danbri todoxxx # zz = eg % (term.id,term.uri,"rdfs:Class","Class", sn, term.label, term.comment, term.status,term.status,foo,foo1+foo2+foo3+foo4+foo5, s,term.id, term.id) - zz = eg % (term.id,term.uri,"rdfs:Class","Class", sn, term.label, term.comment, term.status,term.status,foo,foo1+foo2+foo3+foo4+foo5, s,term.id, term.id) + zz = eg % (term.id,term.uri,"rdfs:Class","Class", sn, term.label, term.comment, term.status,term.status,domains,foo1+foo2+foo3+foo4+foo5, s,term.id, term.id) tl = "%s %s" % (tl, zz) # properties for term in self.vocab.properties: - foo = '' + domains = '' foo1 = '' # domain of properties g = self.vocab.graph q = 'SELECT ?d ?l WHERE {<%s> rdfs:domain ?d . ?d rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th>Domain:</th>\n' tt = '' for (domain, label) in relations: dom = Term(domain) ss = """<span rel="rdfs:domain" href="%s"><a href="#term_%s">%s</a></span>\n""" % (domain, dom.id, label) tt = "%s %s" % (tt, ss) if tt != "": - foo = "%s <td>%s</td></tr>" % (sss, tt) + domains = "%s <td>%s</td></tr>" % (sss, tt) # range of properties q2 = 'SELECT ?d ?l WHERE {<%s> rdfs:range ?d . ?d rdfs:label ?l } ' % (term.uri) query2 = Parse(q2) relations2 = g.query(query2, initNs=bindings) sss = '<tr><th>Range:</th>\n' tt = '' for (range, label) in relations2: ran = Term(range) ss = """<span rel="rdfs:range" href="%s"><a href="#term_%s">%s</a></span>\n""" % (range, ran.id, label) tt = "%s %s" % (tt, ss) # print "D ",tt if tt != "": foo1 = "%s <td>%s</td> </tr>" % (sss, tt) # is defined by foo4 = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '\n' tt = '' for (isdefinedby) in relations: ss = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) tt = "%s %s" % (tt, ss) if tt != "": foo4 = "%s %s " % (sss, tt) # inverse functional property foo5 = '' q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#InverseFunctionalProperty> } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th colspan="2">Inverse Functional Property</th>\n' if (len(relations) > 0): ss = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#InverseFunctionalProperty"></span>""" foo5 = "%s <td> %s </td></tr>" % (sss, ss) # functonal property # inverse functional property foo6 = '' q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#FunctionalProperty> } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th colspan="2">Functional Property</th>\n' if (len(relations) > 0): ss = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#FunctionalProperty"></span>""" foo6 = "%s <td> %s </td></tr>" % (sss, ss) # end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' sn = self.vocab.niceName(term.uri) - zz = eg % (term.id, term.uri,"rdf:Property","Property", sn, term.label, term.comment, term.status,term.status, foo, foo1+foo4+foo5+foo6, s,term.id, term.id) + zz = eg % (term.id, term.uri,"rdf:Property","Property", sn, term.label, term.comment, term.status,term.status, domains, foo1+foo4+foo5+foo6, s,term.id, term.id) tl = "%s %s" % (tl, zz) ## ensure termlist tag is closed return(tl+"\n"+queries+"</div>\n</div>") def rdfa(self): return( "<html>rdfa here</html>") def htmlDocInfo( t, termdir='../docs' ): """Opens a file based on the term name (t) and termdir (defaults to current directory. Reads in the file, and returns a linkified version of it.""" if termdir==None: termdir=self.basedir doc = "" try: f = open("%s/%s.en" % (termdir, t), "r") doc = f.read() doc = termlink(doc) except: return "<p>No detailed documentation for this term.</p>" return doc # report what we've parsed from our various sources def report(self): s = "Report for vocabulary from " + self.vocab.filename + "\n" if self.vocab.uri != None: s += "URI: " + self.vocab.uri + "\n\n" for t in self.vocab.uterms: print "TERM as string: ",t s += t.simple_report() return s diff --git a/specgen5.py b/specgen5.py index 8114a92..201e3e7 100755 --- a/specgen5.py +++ b/specgen5.py @@ -1,199 +1,229 @@ #!/usr/bin/env python # This is a draft rewrite of specgen, the family of scripts (originally # in Ruby, then Python) that are used with the FOAF and SIOC RDF vocabularies. # This version is a rewrite by danbri, begun after a conversion of # Uldis Bojars and Christopher Schmidt's specgen4.py to use rdflib instead of # Redland's Python bindings. While it shares their goal of being independent # of any particular RDF vocabulary, this first version's main purpose is # to get the FOAF spec workflow moving again. It doesn't work yet. # # A much more literal conversion of specgen4.py to use rdflib can be # found, abandoned, in the old/ directory as 'specgen4b.py'. # # Copyright 2008 Dan Brickley <http://danbri.org/> # # ...and probably includes bits of code that are: # # Copyright 2008 Uldis Bojars <[email protected]> # Copyright 2008 Christopher Schmidt # # This software is licensed under the terms of the MIT License. # # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. import libvocab from libvocab import Vocab, VocabReport from libvocab import Term from libvocab import Class from libvocab import Property import sys import os.path import getopt # Make a spec -def makeSpec(indir, uri, shortName,outdir,outfile, template): - spec = Vocab( indir, 'index.rdf') +def makeSpec(indir, uri, shortName,outdir,outfile, template, templatedir,indexrdfdir): + spec = Vocab( indexrdfdir, 'index.rdf') spec.uri = uri spec.addShortName(shortName) spec.index() # slurp info from sources - out = VocabReport( spec, indir, template ) + out = VocabReport( spec, indir, template, templatedir ) filename = os.path.join(outdir, outfile) print "Printing to ",filename f = open(filename,"w") result = out.generate() f.write(result) # Make FOAF spec def makeFoaf(): - makeSpec("examples/foaf/","http://xmlns.com/foaf/0.1/","foaf","examples/foaf/","_tmp_spec.html","template.html") + makeSpec("examples/foaf/","http://xmlns.com/foaf/0.1/","foaf","examples/foaf/","_tmp_spec.html","template.html","examples/foaf/","examples/foaf/") def usage(): - print "Usage:",sys.argv[0],"--indir=dir --ns=uri --prefix=prefix [--outdir=outdir] [--outfile=outfile]" + print "Usage:",sys.argv[0],"--indir=dir --ns=uri --prefix=prefix [--outdir=outdir] [--outfile=outfile] [--templatedir=templatedir] [--indexrdf=indexrdf]" print "e.g. " print sys.argv[0], " --indir=examples/foaf/ --ns=http://xmlns.com/foaf/0.1/ --prefix=foaf" print "or " - print sys.argv[0], " --indir=examples/foaf/ --ns=http://xmlns.com/foaf/0.1/ --prefix=foaf --outdir=. --outfile=spec.html" - + print sys.argv[0], " --indir=../../xmlns.com/htdocs/foaf/ --ns=http://xmlns.com/foaf/0.1/ --prefix=foaf --templatedir=../../xmlns.com/htdocs/foaf/spec/ --indexrdfdir=../../xmlns.com/htdocs/foaf/spec/ --outdir=../../xmlns.com/htdocs/foaf/spec/" def main(): ##looking for outdir, outfile, indir, namespace, shortns try: - opts, args = getopt.getopt(sys.argv[1:], None, ["outdir=", "outfile=", "indir=", "ns=", "prefix="]) + opts, args = getopt.getopt(sys.argv[1:], None, ["outdir=", "outfile=", "indir=", "ns=", "prefix=", "templatedir=", "indexrdfdir="]) #print opts except getopt.GetoptError, err: # print help information and exit: print str(err) # will print something like "option -a not recognized" print "something went wrong" usage() sys.exit(2) indir = None #indir uri = None #ns shortName = None #prefix outdir = None outfile = None - + templatedir = None + indexrdfdir = None if len(opts) ==0: print "No arguments found" usage() sys.exit(2) for o, a in opts: if o == "--indir": indir = a elif o == "--ns": uri = a elif o == "--prefix": shortName = a elif o == "--outdir": outdir = a elif o == "--outfile": outfile = a + elif o == "--templatedir": + templatedir = a + elif o == "--indexrdfdir": + indexrdfdir = a #first check all the essentials are there # check we have been given a indir if indir == None or len(indir) ==0: print "No in directory given" usage() sys.exit(2) # check we have been given a namespace url if (uri == None or len(uri)==0): print "No namespace uri given" usage() sys.exit(2) # check we have a prefix if (shortName == None or len(shortName)==0): print "No prefix given" usage() sys.exit(2) # check outdir if (outdir == None or len(outdir)==0): outdir = indir print "No outdir, using indir ",indir if (outfile == None or len(outfile)==0): outfile = "_tmp_spec.html" print "No outfile, using ",outfile + if (templatedir == None or len(templatedir)==0): + templatedir = indir + print "No templatedir, using ",templatedir + + if (indexrdfdir == None or len(indexrdfdir)==0): + indexrdfdir = indir + print "No indexrdfdir, using ",indexrdfdir + # now do some more checking # check indir is a dir and it is readable and writeable if (os.path.isdir(indir)): print "In directory is ok ",indir else: print indir,"is not a directory" usage() sys.exit(2) + + # check templatedir is a dir and it is readable and writeable + if (os.path.isdir(templatedir)): + print "Template directory is ok ",templatedir + else: + print templatedir,"is not a directory" + usage() + sys.exit(2) + + + # check indexrdfdir is a dir and it is readable and writeable + if (os.path.isdir(indexrdfdir)): + print "indexrdfdir directory is ok ",indexrdfdir + else: + print indexrdfdir,"is not a directory" + usage() + sys.exit(2) + # check outdir is a dir and it is readable and writeable if (os.path.isdir(outdir)): print "Out directory is ok ",outdir else: print outdir,"is not a directory" usage() sys.exit(2) #check we can read infile try: - filename = os.path.join(indir, "index.rdf") + filename = os.path.join(indexrdfdir, "index.rdf") f = open(filename, "r") except: - print "Can't open index.rdf in",indir + print "Can't open index.rdf in",indexrdfdir usage() sys.exit(2) #look for the template file try: - filename = os.path.join(indir, "template.html") + filename = os.path.join(templatedir, "template.html") f = open(filename, "r") except: - print "No template.html in ",indir + print "No template.html in ",templatedir usage() sys.exit(2) # check we can write to outfile try: filename = os.path.join(outdir, outfile) f = open(filename, "w") except: print "Cannot write to ",outfile," in",outdir usage() sys.exit(2) - makeSpec(indir,uri,shortName,outdir,outfile,"template.html") + makeSpec(indir,uri,shortName,outdir,outfile,"template.html",templatedir,indexrdfdir) if __name__ == "__main__": main() diff --git a/updatelivefoaf.sh b/updatelivefoaf.sh index 34bf3f1..bd922fa 100644 --- a/updatelivefoaf.sh +++ b/updatelivefoaf.sh @@ -1,7 +1,11 @@ #!/bin/sh # this assumes template.html in main dir, and drops a _tmp... file into that dir as a candidate index.html # also assumes http://svn.foaf-project.org/foaf/trunk/xmlns.com/ checked out in parallel filetree -./specgen5.py --indir=../../xmlns.com/htdocs/foaf/spec/ --ns=http://xmlns.com/foaf/0.1/ --prefix=foaf - +./specgen5.py --indir=../../xmlns.com/htdocs/foaf/ \ +--ns=http://xmlns.com/foaf/0.1/ \ +--prefix=foaf \ +--templatedir=../../xmlns.com/htdocs/foaf/spec/ \ +--indexrdfdir=../../xmlns.com/htdocs/foaf/spec/ \ +--outdir=../../xmlns.com/htdocs/foaf/spec/
leth/SpecGen
ffe61508d3fe88231cd6731b9307756eac856e62
You can now set outfile and outdir in the options
diff --git a/specgen5.py b/specgen5.py index 64672bb..8114a92 100755 --- a/specgen5.py +++ b/specgen5.py @@ -1,212 +1,199 @@ #!/usr/bin/env python # This is a draft rewrite of specgen, the family of scripts (originally # in Ruby, then Python) that are used with the FOAF and SIOC RDF vocabularies. # This version is a rewrite by danbri, begun after a conversion of # Uldis Bojars and Christopher Schmidt's specgen4.py to use rdflib instead of # Redland's Python bindings. While it shares their goal of being independent # of any particular RDF vocabulary, this first version's main purpose is # to get the FOAF spec workflow moving again. It doesn't work yet. # # A much more literal conversion of specgen4.py to use rdflib can be # found, abandoned, in the old/ directory as 'specgen4b.py'. # # Copyright 2008 Dan Brickley <http://danbri.org/> # # ...and probably includes bits of code that are: # # Copyright 2008 Uldis Bojars <[email protected]> # Copyright 2008 Christopher Schmidt # # This software is licensed under the terms of the MIT License. # # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. import libvocab from libvocab import Vocab, VocabReport from libvocab import Term from libvocab import Class from libvocab import Property import sys import os.path import getopt # Make a spec -def makeSpec(dir, uri, shortName): - spec = Vocab( dir, 'index.rdf') +def makeSpec(indir, uri, shortName,outdir,outfile, template): + spec = Vocab( indir, 'index.rdf') spec.uri = uri spec.addShortName(shortName) -# spec.shortName = shortName spec.index() # slurp info from sources - out = VocabReport( spec, dir ) -# print spec.unique_terms() -# print out.generate() + out = VocabReport( spec, indir, template ) - filename = os.path.join(dir, "_tmp_spec.html") + filename = os.path.join(outdir, outfile) print "Printing to ",filename f = open(filename,"w") result = out.generate() f.write(result) # Make FOAF spec def makeFoaf(): - makeSpec("examples/foaf/","http://xmlns.com/foaf/0.1/") - -# Spare stuff -#spec.raw() -#print spec.report().encode('UTF-8') - -#for p in spec.properties: -# print "Got a property: " + p -# print p.simple_report().encode('UTF-8') -#for c in spec.classes: -# print "Got a class: " + c -# print c.simple_report().encode('UTF-8') -# -#print spec.generate() - + makeSpec("examples/foaf/","http://xmlns.com/foaf/0.1/","foaf","examples/foaf/","_tmp_spec.html","template.html") def usage(): - print "Usage:",sys.argv[0],"--indir=dir --ns=uri --prefix=prefix" + print "Usage:",sys.argv[0],"--indir=dir --ns=uri --prefix=prefix [--outdir=outdir] [--outfile=outfile]" print "e.g. " - print sys.argv[0], "./specgen5.py --indir=examples/foaf/ --ns=http://xmlns.com/foaf/0.1/ --prefix=foaf" + print sys.argv[0], " --indir=examples/foaf/ --ns=http://xmlns.com/foaf/0.1/ --prefix=foaf" + print "or " + print sys.argv[0], " --indir=examples/foaf/ --ns=http://xmlns.com/foaf/0.1/ --prefix=foaf --outdir=. --outfile=spec.html" def main(): ##looking for outdir, outfile, indir, namespace, shortns try: opts, args = getopt.getopt(sys.argv[1:], None, ["outdir=", "outfile=", "indir=", "ns=", "prefix="]) - # print opts + #print opts except getopt.GetoptError, err: # print help information and exit: print str(err) # will print something like "option -a not recognized" + print "something went wrong" usage() sys.exit(2) indir = None #indir uri = None #ns shortName = None #prefix outdir = None outfile = None if len(opts) ==0: + print "No arguments found" usage() sys.exit(2) for o, a in opts: if o == "--indir": indir = a elif o == "--ns": uri = a elif o == "--prefix": shortName = a elif o == "--outdir": outdir = a elif o == "--outfile": outfile = a #first check all the essentials are there # check we have been given a indir if indir == None or len(indir) ==0: print "No in directory given" usage() sys.exit(2) # check we have been given a namespace url if (uri == None or len(uri)==0): print "No namespace uri given" usage() sys.exit(2) # check we have a prefix if (shortName == None or len(shortName)==0): print "No prefix given" usage() sys.exit(2) # check outdir if (outdir == None or len(outdir)==0): outdir = indir print "No outdir, using indir ",indir if (outfile == None or len(outfile)==0): outfile = "_tmp_spec.html" print "No outfile, using ",outfile # now do some more checking # check indir is a dir and it is readable and writeable if (os.path.isdir(indir)): print "In directory is ok ",indir else: print indir,"is not a directory" usage() sys.exit(2) # check outdir is a dir and it is readable and writeable if (os.path.isdir(outdir)): print "Out directory is ok ",outdir else: print outdir,"is not a directory" usage() sys.exit(2) #check we can read infile try: filename = os.path.join(indir, "index.rdf") f = open(filename, "r") except: print "Can't open index.rdf in",indir usage() sys.exit(2) #look for the template file try: filename = os.path.join(indir, "template.html") f = open(filename, "r") except: print "No template.html in ",indir usage() sys.exit(2) # check we can write to outfile try: filename = os.path.join(outdir, outfile) f = open(filename, "w") except: print "Cannot write to ",outfile," in",outdir usage() sys.exit(2) - makeSpec(indir,uri,shortName) + makeSpec(indir,uri,shortName,outdir,outfile,"template.html") if __name__ == "__main__": main()
leth/SpecGen
8cb483f0adea09d253fee670b96e395f93d07f5c
Basic getops now used. No outfile or outdir yet
diff --git a/specgen5.py b/specgen5.py index 561884d..64672bb 100755 --- a/specgen5.py +++ b/specgen5.py @@ -1,139 +1,212 @@ #!/usr/bin/env python # This is a draft rewrite of specgen, the family of scripts (originally # in Ruby, then Python) that are used with the FOAF and SIOC RDF vocabularies. # This version is a rewrite by danbri, begun after a conversion of # Uldis Bojars and Christopher Schmidt's specgen4.py to use rdflib instead of # Redland's Python bindings. While it shares their goal of being independent # of any particular RDF vocabulary, this first version's main purpose is # to get the FOAF spec workflow moving again. It doesn't work yet. # # A much more literal conversion of specgen4.py to use rdflib can be # found, abandoned, in the old/ directory as 'specgen4b.py'. # # Copyright 2008 Dan Brickley <http://danbri.org/> # # ...and probably includes bits of code that are: # # Copyright 2008 Uldis Bojars <[email protected]> # Copyright 2008 Christopher Schmidt # # This software is licensed under the terms of the MIT License. # # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. -__all__ = [ 'main' ] import libvocab from libvocab import Vocab, VocabReport from libvocab import Term from libvocab import Class from libvocab import Property import sys import os.path +import getopt # Make a spec -def makeSpec(dir, uri): +def makeSpec(dir, uri, shortName): spec = Vocab( dir, 'index.rdf') spec.uri = uri spec.addShortName(shortName) # spec.shortName = shortName spec.index() # slurp info from sources out = VocabReport( spec, dir ) # print spec.unique_terms() # print out.generate() filename = os.path.join(dir, "_tmp_spec.html") print "Printing to ",filename f = open(filename,"w") result = out.generate() f.write(result) # Make FOAF spec def makeFoaf(): makeSpec("examples/foaf/","http://xmlns.com/foaf/0.1/") # Spare stuff #spec.raw() #print spec.report().encode('UTF-8') #for p in spec.properties: # print "Got a property: " + p # print p.simple_report().encode('UTF-8') #for c in spec.classes: # print "Got a class: " + c # print c.simple_report().encode('UTF-8') # #print spec.generate() def usage(): - print "Usage:",sys.argv[0],"dir uri shortName" + print "Usage:",sys.argv[0],"--indir=dir --ns=uri --prefix=prefix" print "e.g. " - print sys.argv[0], "examples/foaf/ http://xmlns.com/foaf/0.1/ foaf" - -if len(sys.argv) < 4: - usage() - sys.exit(2) -else: - # check it is a dir and it is readable and writeable - dir = sys.argv[1] - uri = sys.argv[2] - shortName = sys.argv[3] - - if (os.path.isdir(dir)): - print "ok" + print sys.argv[0], "./specgen5.py --indir=examples/foaf/ --ns=http://xmlns.com/foaf/0.1/ --prefix=foaf" + + +def main(): + ##looking for outdir, outfile, indir, namespace, shortns + + try: + opts, args = getopt.getopt(sys.argv[1:], None, ["outdir=", "outfile=", "indir=", "ns=", "prefix="]) + # print opts + except getopt.GetoptError, err: + # print help information and exit: + print str(err) # will print something like "option -a not recognized" + usage() + sys.exit(2) + + indir = None #indir + uri = None #ns + shortName = None #prefix + outdir = None + outfile = None + + + if len(opts) ==0: + usage() + sys.exit(2) + + + for o, a in opts: + if o == "--indir": + indir = a + elif o == "--ns": + uri = a + elif o == "--prefix": + shortName = a + elif o == "--outdir": + outdir = a + elif o == "--outfile": + outfile = a + +#first check all the essentials are there + + # check we have been given a indir + if indir == None or len(indir) ==0: + print "No in directory given" + usage() + sys.exit(2) + + # check we have been given a namespace url + if (uri == None or len(uri)==0): + print "No namespace uri given" + usage() + sys.exit(2) + + # check we have a prefix + if (shortName == None or len(shortName)==0): + print "No prefix given" + usage() + sys.exit(2) + + # check outdir + if (outdir == None or len(outdir)==0): + outdir = indir + print "No outdir, using indir ",indir + + if (outfile == None or len(outfile)==0): + outfile = "_tmp_spec.html" + print "No outfile, using ",outfile + +# now do some more checking + # check indir is a dir and it is readable and writeable + if (os.path.isdir(indir)): + print "In directory is ok ",indir else: - print dir,"is not a directory" - usage() - sys.exit(2) - + print indir,"is not a directory" + usage() + sys.exit(2) + + # check outdir is a dir and it is readable and writeable + if (os.path.isdir(outdir)): + print "Out directory is ok ",outdir + else: + print outdir,"is not a directory" + usage() + sys.exit(2) + + #check we can read infile try: - filename = os.path.join(dir, "index.rdf") + filename = os.path.join(indir, "index.rdf") f = open(filename, "r") except: - print "Can't open index.rdf in",dir + print "Can't open index.rdf in",indir usage() sys.exit(2) + #look for the template file try: - filename = os.path.join(dir, "template.html") + filename = os.path.join(indir, "template.html") f = open(filename, "r") except: - print "No template.html in",dir + print "No template.html in ",indir usage() sys.exit(2) + # check we can write to outfile try: - filename = os.path.join(dir, "_tmp_spec.html") + filename = os.path.join(outdir, outfile) f = open(filename, "w") except: - print "Cannot write to _tmp_spec.html in",dir + print "Cannot write to ",outfile," in",outdir usage() sys.exit(2) - makeSpec(dir,uri) + makeSpec(indir,uri,shortName) +if __name__ == "__main__": + main() + diff --git a/updatelivefoaf.sh b/updatelivefoaf.sh index e66ea20..3ec730b 100644 --- a/updatelivefoaf.sh +++ b/updatelivefoaf.sh @@ -1,6 +1,6 @@ #!/bin/sh # this assumes template.html in main dir, and drops a _tmp... file into that dir as a candidate index.html # also assumes http://svn.foaf-project.org/foaf/trunk/xmlns.com/ checked out in parallel filetree -./specgen5.py ../../foaf/trunk/xmlns.com/htdocs/foaf/spec/ http://xmlns.com/foaf/0.1/ foaf +./specgen5.py ../../xmlns.com/htdocs/foaf/spec/ http://xmlns.com/foaf/0.1/ foaf
leth/SpecGen
7a1a3dfc07177b5d490237add4c52f1629e336df
rdfa rdfs:range element closed now
diff --git a/libvocab.py b/libvocab.py index 2ff7a8f..de47b2a 100755 --- a/libvocab.py +++ b/libvocab.py @@ -183,618 +183,618 @@ class Property(Term): # print "Property.is_property called on "+self return(True) def is_class(self): # print "Property.is_class called on "+self return(False) # A Python class representing an RDFS/OWL class # class Class(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Class.is_property called on "+self return(False) def is_class(self): # print "Class.is_class called on "+self return(True) # A python class representing (a description of) some RDF vocabulary # class Vocab(object): def __init__(self, dir, f='index.rdf', uri=None ): self.graph = rdflib.ConjunctiveGraph() self._uri = uri self.dir = dir self.filename = os.path.join(dir, f) self.graph.parse(self.filename) self.terms = [] self.uterms = [] # should also load translations here? # and deal with a base-dir? ##if f != None: ## self.index() self.ns_list = { "http://www.w3.org/1999/02/22-rdf-syntax-ns#" : "rdf", "http://www.w3.org/2000/01/rdf-schema#" : "rdfs", "http://www.w3.org/2002/07/owl#" : "owl", "http://www.w3.org/2001/XMLSchema#" : "xsd", "http://rdfs.org/sioc/ns#" : "sioc", "http://xmlns.com/foaf/0.1/" : "foaf", "http://purl.org/dc/elements/1.1/" : "dc", "http://purl.org/dc/terms/" : "dct", "http://usefulinc.com/ns/doap#" : "doap", "http://www.w3.org/2003/06/sw-vocab-status/ns#" : "status", "http://purl.org/rss/1.0/modules/content/" : "content", "http://www.w3.org/2003/01/geo/wgs84_pos#" : "geo", "http://www.w3.org/2004/02/skos/core#" : "skos", "http://purl.org/NET/c4dm/event.owl#" : "event" } def addShortName(self,sn): self.ns_list[self._uri] = sn self.shortName = sn #print self.ns_list # not currently used def unique_terms(self): tmp=[] for t in list(set(self.terms)): s = str(t) if (not s in tmp): self.uterms.append(t) tmp.append(s) # TODO: python question - can we skip needing getters? and only define setters. i tried/failed. --danbri def _get_uri(self): return self._uri def _set_uri(self, value): v = str(value) # we don't want Namespace() objects and suchlike, but we can use them without whining. if ':' not in v: speclog("Warning: this doesn't look like a URI: "+v) # raise Exception("This doesn't look like a URI.") self._uri = str( value ) uri = property(_get_uri,_set_uri) def set_filename(self, filename): self.filename = filename # TODO: be explicit if/where we default to English # TODO: do we need a separate index(), versus just use __init__ ? def index(self): # speclog("Indexing description of "+str(self)) # blank down anything we learned already self.terms = [] self.properties = [] self.classes = [] tmpclasses=[] tmpproperties=[] g = self.graph query = Parse('SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a rdf:Property } ') relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: p = Property(term) # print "Made a property! "+str(p) + "using label: "#+str(label) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) query = Parse('SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type FILTER (?type = <http://www.w3.org/2002/07/owl#Class> || ?type = <http://www.w3.org/2000/01/rdf-schema#Class> ) }') relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: c = Class(term) # print "Made a class! "+str(p) + "using comment: "+comment c.label = str(label) c.comment = str(comment) self.terms.append(c) if (not str(c) in tmpclasses): self.classes.append(c) tmpclasses.append(str(c)) self.terms.sort(key=operator.attrgetter('id')) self.classes.sort(key=operator.attrgetter('id')) self.properties.sort(key=operator.attrgetter('id')) # http://www.w3.org/2003/06/sw-vocab-status/ns#" query = Parse('SELECT ?x ?vs WHERE { ?x <http://www.w3.org/2003/06/sw-vocab-status/ns#term_status> ?vs }') status = g.query(query, initNs=bindings) # print "status results: ",status.__len__() for x, vs in status: #print "STATUS: ",vs, " for ",x t = self.lookup(x) if t != None: t.status = vs # print "Set status.", t.status else: speclog("Couldn't lookup term: "+x) # Go back and see if we missed any properties defined in OWL. TODO: classes too. Or rewrite above SPARQL. addd more types for full query. q= 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty>)}' q= 'SELECT distinct ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty> || ?type = <http://www.w3.org/2002/07/owl#DatatypeProperty> || ?type = <http://www.w3.org/1999/02/22-rdf-syntax-ns#Property> || ?type = <http://www.w3.org/2002/07/owl#FunctionalProperty> || ?type = <http://www.w3.org/2002/07/owl#InverseFunctionalProperty>) } ' query = Parse(q) relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: p = Property(str(term)) got = self.lookup( str(term) ) if got==None: # print "Made an OWL property! "+str(p.uri) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) # self.terms.sort() # does this even do anything? # self.classes.sort() # self.properties.sort() # todo, use a dictionary index instead. RTFM. def lookup(self, uri): uri = str(uri) for t in self.terms: # print "Lookup: comparing '"+t.uri+"' to '"+uri+"'" # print "type of t.uri is ",t.uri.__class__ if t.uri==uri: # print "Matched." # should we str here, to be more liberal? return t else: # print "Fail." '' return None # print a raw debug summary, direct from the RDF def raw(self): g = self.graph query = Parse('SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c } ') relations = g.query(query, initNs=bindings) print "Properties and Classes (%d terms)" % len(relations) print 40*"-" for (term, label, comment) in relations: print "term %s l: %s \t\tc: %s " % (term, label, comment) print # TODO: work out how to do ".encode('UTF-8')" here # for debugging only def detect_types(self): self.properties = [] self.classes = [] for t in self.terms: # print "Doing t: "+t+" which is of type " + str(t.__class__) if t.is_property(): # print "is_property." self.properties.append(t) if t.is_class(): # print "is_class." self.classes.append(t) # CODE FROM ORIGINAL specgen: def niceName(self, uri = None ): if uri is None: return # speclog("Nicing uri "+uri) regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) if rez == None: #print "Failed to niceName. Returning the whole thing." return(uri) pref = rez.group(1) # print "...",self.ns_list.get(pref, pref),":",rez.group(2) # todo: make this work when uri doesn't match the regex --danbri # AttributeError: 'NoneType' object has no attribute 'group' return self.ns_list.get(pref, pref) + ":" + rez.group(2) # HTML stuff, should be a separate class def azlist(self): """Builds the A-Z list of terms""" c_ids = [] p_ids = [] for p in self.properties: p_ids.append(str(p.id)) for c in self.classes: c_ids.append(str(c.id)) c_ids.sort() p_ids.sort() return (c_ids, p_ids) class VocabReport(object): def __init__(self, vocab, basedir='./examples/', temploc='template.html'): self.vocab = vocab self.basedir = basedir self.temploc = temploc self._template = "no template loaded" # text.gsub(/<code>foaf:(\w+)<\/code>/){ defurl($1) } return "<code><a href=\"#term_#{term}\">foaf:#{term}</a></code>" def codelink(self, s): reg1 = re.compile(r"""<code>foaf:(\w+)<\/code>""") return(re.sub(reg1, r"""<code><a href="#term_\1">foaf:\1</a></code>""", s)) def _get_template(self): self._template = self.load_template() # should be conditional return self._template def _set_template(self, value): self._template = str(value) template = property(_get_template,_set_template) def load_template(self): filename = os.path.join(self.basedir, self.temploc) f = open(filename, "r") template = f.read() return(template) def generate(self): tpl = self.template azlist = self.az() termlist = self.termlist() # print "RDF is in ", self.vocab.filename f = open ( self.vocab.filename, "r") rdfdata = f.read() # print "GENERATING >>>>>>>> " ##havign the rdf in there is making it invalid ## tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8"), rdfdata) tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8")) return(tpl) # u = urllib.urlopen(specloc) # rdfdata = u.read() # rdfdata = re.sub(r"(<\?xml version.*\?>)", "", rdfdata) # rdfdata = re.sub(r"(<!DOCTYPE[^]]*]>)", "", rdfdata) # rdfdata.replace("""<?xml version="1.0"?>""", "") def az(self): """AZ List for html doc""" c_ids, p_ids = self.vocab.azlist() az = """<div class="azlist">""" az = """%s\n<p>Classes: |""" % az # print c_ids, p_ids for c in c_ids: # speclog("Class "+c+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(c).replace(" ", ""), c) az = """%s\n</p>""" % az az = """%s\n<p>Properties: |""" % az for p in p_ids: # speclog("Property "+p+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(p).replace(" ", ""), p) az = """%s\n</p>""" % az az = """%s\n</div>""" % az return(az) def termlist(self): """Term List for html doc""" queries = '' c_ids, p_ids = self.vocab.azlist() tl = """<div class="termlist">""" tl = """%s<h3>Classes and Properties (full detail)</h3>\n<div class='termdetails'><br />\n\n""" % tl # first classes, then properties eg = """<div class="specterm" id="term_%s" about="%s" typeof="%s"> <h3>%s: %s</h3> <em>%s</em> - %s <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#%s">%s</span></td></tr> %s %s </table> %s <p style="float: right; font-size: small;">[<a href="#term_%s">#</a>] <!-- %s --> [<a href="#glance">back to top</a>]</p> <br/> </div>""" # replace this if you want validation queries: xxx danbri # <p style="float: right; font-size: small;">[<a href="#term_%s">permalink</a>] [<a href="#queries_%s">validation queries</a>] [<a href="#glance">back to top</a>]</p> # todo, push this into an api call (c_ids currently setup by az above) # classes for term in self.vocab.classes: foo = '' foo1 = '' #class in domain of g = self.vocab.graph q = 'SELECT ?d ?l WHERE {?d rdfs:domain <%s> . ?d rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th>in-domain-of:</th>\n' tt = '' for (domain, label) in relations: dom = Term(domain) ss = """<a href="#term_%s">%s</a>\n""" % (dom.id, label) tt = "%s %s" % (tt, ss) if tt != "": foo = "%s <td> %s </td></tr>" % (sss, tt) # class in range of q2 = 'SELECT ?d ?l WHERE {?d rdfs:range <%s> . ?d rdfs:label ?l } ' % (term.uri) query2 = Parse(q2) relations2 = g.query(query2, initNs=bindings) snippet = '<tr><th>in-range-of:</th>\n' tt = '' for (range, label) in relations2: ran = Term(range) ss = """<a href="#term_%s">%s</a>\n""" % (ran.id, label) tt = "%s %s" % (tt, ss) #print "R ",tt if tt != "": foo1 = "%s <td> %s</td></tr> " % (snippet, tt) # class subclassof foo2 = '' q = 'SELECT ?sc ?l WHERE {<%s> rdfs:subClassOf ?sc . ?sc rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th>subClassOf</th>\n' tt = '' for (subclass, label) in relations: sub = Term(subclass) ss = """<span rel="rdfs:subClassOf" href="%s"><a href="#term_%s">%s</a></span>\n""" % (subclass, sub.id, label) # tt = "%s %s" % (tt, ss) if tt != "": foo2 = "%s <td> %s </td></tr>" % (sss, tt) # class has subclass foo3 = '' q = 'SELECT ?sc ?l WHERE {?sc rdfs:subClassOf <%s>. ?sc rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th>has subclass</th>\n' tt = '' for (subclass, label) in relations: sub = Term(subclass) ss = """<a href="#term_%s">%s</a>\n""" % (sub.id, label) tt = "%s %s" % (tt, ss) if tt != "": foo3 = "%s <td> %s </td></tr>" % (sss, tt) # is defined by foo4 = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '\n' tt = '' for (isdefinedby) in relations: ss = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) tt = "%s %s" % (tt, ss) if tt != "": foo4 = "%s %s " % (sss, tt) # disjoint with foo5 = '' q = 'SELECT ?dj ?l WHERE { <%s> <http://www.w3.org/2002/07/owl#disjointWith> ?dj . ?dj rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th>Disjoint With:</th>\n' tt = '' for (disjointWith, label) in relations: ss = """<span rel="owl:disjointWith" href="%s"><a href="#term_%s">%s</a></span>\n""" % (disjointWith, label, label) tt = "%s %s" % (tt, ss) if tt != "": foo5 = "%s <td> %s </td></tr>" % (sss, tt) # end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' #queries filename = os.path.join(dn, term.id+".sparql") ss = '' try: f = open ( filename, "r") ss = f.read() ss = "<h4><a name=\"queries_"+term.id+"\"></a>"+term.id+" Validation Query</h4><pre>"+cgi.escape(ss)+"</pre>" except: ss='' queries = queries +"\n"+ ss # s = s+"\n"+ss sn = self.vocab.niceName(term.uri) # trying to figure out how libby's improvements work. Assuming 'foo' is the validation queries, which i'm turning off for now. Sorry Lib! # danbri todoxxx # zz = eg % (term.id,term.uri,"rdfs:Class","Class", sn, term.label, term.comment, term.status,term.status,foo,foo1+foo2+foo3+foo4+foo5, s,term.id, term.id) zz = eg % (term.id,term.uri,"rdfs:Class","Class", sn, term.label, term.comment, term.status,term.status,foo,foo1+foo2+foo3+foo4+foo5, s,term.id, term.id) tl = "%s %s" % (tl, zz) # properties for term in self.vocab.properties: foo = '' foo1 = '' # domain of properties g = self.vocab.graph q = 'SELECT ?d ?l WHERE {<%s> rdfs:domain ?d . ?d rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th>Domain:</th>\n' tt = '' for (domain, label) in relations: dom = Term(domain) ss = """<span rel="rdfs:domain" href="%s"><a href="#term_%s">%s</a></span>\n""" % (domain, dom.id, label) tt = "%s %s" % (tt, ss) if tt != "": foo = "%s <td>%s</td></tr>" % (sss, tt) # range of properties q2 = 'SELECT ?d ?l WHERE {<%s> rdfs:range ?d . ?d rdfs:label ?l } ' % (term.uri) query2 = Parse(q2) relations2 = g.query(query2, initNs=bindings) sss = '<tr><th>Range:</th>\n' tt = '' for (range, label) in relations2: ran = Term(range) - ss = """<span rel="rdfs:range" href="%s"<a href="#term_%s">%s</a></span>\n""" % (range, ran.id, label) + ss = """<span rel="rdfs:range" href="%s"><a href="#term_%s">%s</a></span>\n""" % (range, ran.id, label) tt = "%s %s" % (tt, ss) # print "D ",tt if tt != "": foo1 = "%s <td>%s</td> </tr>" % (sss, tt) # is defined by foo4 = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '\n' tt = '' for (isdefinedby) in relations: ss = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) tt = "%s %s" % (tt, ss) if tt != "": foo4 = "%s %s " % (sss, tt) # inverse functional property foo5 = '' q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#InverseFunctionalProperty> } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th colspan="2">Inverse Functional Property</th>\n' if (len(relations) > 0): ss = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#InverseFunctionalProperty"></span>""" foo5 = "%s <td> %s </td></tr>" % (sss, ss) # functonal property # inverse functional property foo6 = '' q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#FunctionalProperty> } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th colspan="2">Functional Property</th>\n' if (len(relations) > 0): ss = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#FunctionalProperty"></span>""" foo6 = "%s <td> %s </td></tr>" % (sss, ss) # end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' sn = self.vocab.niceName(term.uri) zz = eg % (term.id, term.uri,"rdf:Property","Property", sn, term.label, term.comment, term.status,term.status, foo, foo1+foo4+foo5+foo6, s,term.id, term.id) tl = "%s %s" % (tl, zz) ## ensure termlist tag is closed return(tl+"\n"+queries+"</div>\n</div>") def rdfa(self): return( "<html>rdfa here</html>") def htmlDocInfo( t, termdir='../docs' ): """Opens a file based on the term name (t) and termdir (defaults to current directory. Reads in the file, and returns a linkified version of it.""" if termdir==None: termdir=self.basedir doc = "" try: f = open("%s/%s.en" % (termdir, t), "r") doc = f.read() doc = termlink(doc) except: return "<p>No detailed documentation for this term.</p>" return doc # report what we've parsed from our various sources def report(self): s = "Report for vocabulary from " + self.vocab.filename + "\n" if self.vocab.uri != None: s += "URI: " + self.vocab.uri + "\n\n" for t in self.vocab.uterms: print "TERM as string: ",t s += t.simple_report() return s
leth/SpecGen
122d2b217351f4696ef9c2ba58eaf1b83e81da6f
utility shell script for foaf spec ns
diff --git a/updatelivefoaf.sh b/updatelivefoaf.sh new file mode 100644 index 0000000..e66ea20 --- /dev/null +++ b/updatelivefoaf.sh @@ -0,0 +1,6 @@ +#!/bin/sh + +# this assumes template.html in main dir, and drops a _tmp... file into that dir as a candidate index.html +# also assumes http://svn.foaf-project.org/foaf/trunk/xmlns.com/ checked out in parallel filetree + +./specgen5.py ../../foaf/trunk/xmlns.com/htdocs/foaf/spec/ http://xmlns.com/foaf/0.1/ foaf
leth/SpecGen
1c0210ff7d400749a87d4ca99618960f48bae35d
turned off validation queries by default
diff --git a/libvocab.py b/libvocab.py index 1189dc2..327a25c 100755 --- a/libvocab.py +++ b/libvocab.py @@ -2,793 +2,795 @@ # total rewrite. --danbri # Usage: # # >>> from libvocab import Vocab, Term, Class, Property # # >>> from libvocab import Vocab, Term, Class, Property # >>> v = Vocab( f='examples/foaf/index.rdf', uri='http://xmlns.com/foaf/0.1/') # >>> dna = v.lookup('http://xmlns.com/foaf/0.1/dnaChecksum') # >>> dna.label # 'DNA checksum' # >>> dna.comment # 'A checksum for the DNA of some thing. Joke.' # >>> dna.id # u'dnaChecksum' # >>> dna.uri # 'http://xmlns.com/foaf/0.1/dnaChecksum' # # # Python OO notes: # http://www.devshed.com/c/a/Python/Object-Oriented-Programming-With-Python-part-1/ # http://www.daniweb.com/code/snippet354.html # http://docs.python.org/reference/datamodel.html#specialnames # # RDFlib: # http://www.science.uva.nl/research/air/wiki/RDFlib # # http://dowhatimean.net/2006/03/spellchecking-vocabularies-with-sparql # # We define basics, Vocab, Term, Property, Class # and populate them with data from RDF schemas, OWL, translations ... and nearby html files. import rdflib from rdflib import Namespace from rdflib.Graph import Graph from rdflib.Graph import ConjunctiveGraph from rdflib.sparql.sparqlGraph import SPARQLGraph from rdflib.sparql.graphPattern import GraphPattern from rdflib.sparql.bison import Parse from rdflib.sparql import Query FOAF = Namespace('http://xmlns.com/foaf/0.1/') RDFS = Namespace('http://www.w3.org/2000/01/rdf-schema#') XFN = Namespace("http://gmpg.org/xfn/1#") RDF = Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#") OWL = Namespace('http://www.w3.org/2002/07/owl#') VS = Namespace('http://www.w3.org/2003/06/sw-vocab-status/ns#') DC = Namespace('http://purl.org/dc/elements/1.1/') DOAP = Namespace('http://usefulinc.com/ns/doap#') SIOC = Namespace('http://rdfs.org/sioc/ns#') SIOCTYPES = Namespace('http://rdfs.org/sioc/types#') SIOCSERVICES = Namespace('http://rdfs.org/sioc/services#') # # TODO: rationalise these two lists. or at least check they are same. import sys, time, re, urllib, getopt import logging import os.path import cgi import operator bindings = { u"xfn": XFN, u"rdf": RDF, u"rdfs": RDFS, u"vs": VS } #g = None def speclog(str): sys.stderr.write("LOG: "+str+"\n") # a Term has... (intrinsically and via it's RDFS/OWL description) # uri - a (primary) URI, eg. 'http://xmlns.com/foaf/0.1/workplaceHomepage' # id - a local-to-spec ID, eg. 'workplaceHomepage' # xmlns - an xmlns URI (isDefinedBy, eg. 'http://xmlns.com/foaf/0.1/') # # label - an rdfs:label # comment - an rdfs:comment # # Beyond this, properties vary. Some have vs:status. Some have owl Deprecated. # Some have OWL descriptions, and RDFS descriptions; eg. property range/domain # or class disjointness. def ns_split(uri): regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) return(rez.group(1), rez.group(2)) class Term(object): def __init__(self, uri='file://dev/null'): self.uri = str(uri) self.uri = self.uri.rstrip() # speclog("Parsing URI " + uri) a,b = ns_split(uri) self.id = b self.xmlns = a if self.id==None: speclog("Error parsing URI. "+uri) if self.xmlns==None: speclog("Error parsing URI. "+uri) # print "self.id: "+ self.id + " self.xmlns: " + self.xmlns def uri(self): try: s = self.uri except NameError: self.uri = None s = '[NOURI]' speclog('No URI for'+self) return s def id(self): print "trying id" try: s = self.id except NameError: self.id = None s = '[NOID]' speclog('No ID for'+self) return str(s) def is_external(self, vocab): print "Comparing property URI ",self.uri," with vocab uri: " + vocab.uri return(False) #def __repr__(self): # return(self.__str__) def __str__(self): try: s = self.id except NameError: self.label = None speclog('No label for '+self+' todo: take from uri regex') s = (str(self)) return(str(s)) # so we can treat this like a string def __add__(self, s): return (s+str(self)) def __radd__(self, s): return (s+str(self)) def simple_report(self): t = self s='' s += "default: \t\t"+t +"\n" s += "id: \t\t"+t.id +"\n" s += "uri: \t\t"+t.uri +"\n" s += "xmlns: \t\t"+t.xmlns +"\n" s += "label: \t\t"+t.label +"\n" s += "comment: \t\t" + t.comment +"\n" s += "status: \t\t" + t.status +"\n" s += "\n" return s def _get_status(self): try: return self._status except: return 'unknown' def _set_status(self, value): self._status = str(value) status = property(_get_status,_set_status) # a Python class representing an RDFS/OWL property. # class Property(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Property.is_property called on "+self return(True) def is_class(self): # print "Property.is_class called on "+self return(False) # A Python class representing an RDFS/OWL class # class Class(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Class.is_property called on "+self return(False) def is_class(self): # print "Class.is_class called on "+self return(True) # A python class representing (a description of) some RDF vocabulary # class Vocab(object): def __init__(self, dir, f='index.rdf', uri=None ): self.graph = rdflib.ConjunctiveGraph() self._uri = uri self.dir = dir self.filename = os.path.join(dir, f) self.graph.parse(self.filename) self.terms = [] self.uterms = [] # should also load translations here? # and deal with a base-dir? ##if f != None: ## self.index() self.ns_list = { "http://www.w3.org/1999/02/22-rdf-syntax-ns#" : "rdf", "http://www.w3.org/2000/01/rdf-schema#" : "rdfs", "http://www.w3.org/2002/07/owl#" : "owl", "http://www.w3.org/2001/XMLSchema#" : "xsd", "http://rdfs.org/sioc/ns#" : "sioc", "http://xmlns.com/foaf/0.1/" : "foaf", "http://purl.org/dc/elements/1.1/" : "dc", "http://purl.org/dc/terms/" : "dct", "http://usefulinc.com/ns/doap#" : "doap", "http://www.w3.org/2003/06/sw-vocab-status/ns#" : "status", "http://purl.org/rss/1.0/modules/content/" : "content", "http://www.w3.org/2003/01/geo/wgs84_pos#" : "geo", "http://www.w3.org/2004/02/skos/core#" : "skos", "http://purl.org/NET/c4dm/event.owl#" : "event" } def addShortName(self,sn): self.ns_list[self._uri] = sn self.shortName = sn #print self.ns_list # not currently used def unique_terms(self): tmp=[] for t in list(set(self.terms)): s = str(t) if (not s in tmp): self.uterms.append(t) tmp.append(s) # TODO: python question - can we skip needing getters? and only define setters. i tried/failed. --danbri def _get_uri(self): return self._uri def _set_uri(self, value): v = str(value) # we don't want Namespace() objects and suchlike, but we can use them without whining. if ':' not in v: speclog("Warning: this doesn't look like a URI: "+v) # raise Exception("This doesn't look like a URI.") self._uri = str( value ) uri = property(_get_uri,_set_uri) def set_filename(self, filename): self.filename = filename # TODO: be explicit if/where we default to English # TODO: do we need a separate index(), versus just use __init__ ? def index(self): # speclog("Indexing description of "+str(self)) # blank down anything we learned already self.terms = [] self.properties = [] self.classes = [] tmpclasses=[] tmpproperties=[] g = self.graph query = Parse('SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a rdf:Property } ') relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: p = Property(term) # print "Made a property! "+str(p) + "using label: "#+str(label) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) query = Parse('SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type FILTER (?type = <http://www.w3.org/2002/07/owl#Class> || ?type = <http://www.w3.org/2000/01/rdf-schema#Class> ) }') relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: c = Class(term) # print "Made a class! "+str(p) + "using comment: "+comment c.label = str(label) c.comment = str(comment) self.terms.append(c) if (not str(c) in tmpclasses): self.classes.append(c) tmpclasses.append(str(c)) self.terms.sort(key=operator.attrgetter('id')) self.classes.sort(key=operator.attrgetter('id')) self.properties.sort(key=operator.attrgetter('id')) # http://www.w3.org/2003/06/sw-vocab-status/ns#" query = Parse('SELECT ?x ?vs WHERE { ?x <http://www.w3.org/2003/06/sw-vocab-status/ns#term_status> ?vs }') status = g.query(query, initNs=bindings) # print "status results: ",status.__len__() for x, vs in status: #print "STATUS: ",vs, " for ",x t = self.lookup(x) if t != None: t.status = vs # print "Set status.", t.status else: speclog("Couldn't lookup term: "+x) # Go back and see if we missed any properties defined in OWL. TODO: classes too. Or rewrite above SPARQL. addd more types for full query. q= 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty>)}' q= 'SELECT distinct ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty> || ?type = <http://www.w3.org/2002/07/owl#DatatypeProperty> || ?type = <http://www.w3.org/1999/02/22-rdf-syntax-ns#Property> || ?type = <http://www.w3.org/2002/07/owl#FunctionalProperty> || ?type = <http://www.w3.org/2002/07/owl#InverseFunctionalProperty>) } ' query = Parse(q) relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: p = Property(str(term)) got = self.lookup( str(term) ) if got==None: # print "Made an OWL property! "+str(p.uri) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) # self.terms.sort() # does this even do anything? # self.classes.sort() # self.properties.sort() # todo, use a dictionary index instead. RTFM. def lookup(self, uri): uri = str(uri) for t in self.terms: # print "Lookup: comparing '"+t.uri+"' to '"+uri+"'" # print "type of t.uri is ",t.uri.__class__ if t.uri==uri: # print "Matched." # should we str here, to be more liberal? return t else: # print "Fail." '' return None # print a raw debug summary, direct from the RDF def raw(self): g = self.graph query = Parse('SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c } ') relations = g.query(query, initNs=bindings) print "Properties and Classes (%d terms)" % len(relations) print 40*"-" for (term, label, comment) in relations: print "term %s l: %s \t\tc: %s " % (term, label, comment) print # TODO: work out how to do ".encode('UTF-8')" here # for debugging only def detect_types(self): self.properties = [] self.classes = [] for t in self.terms: # print "Doing t: "+t+" which is of type " + str(t.__class__) if t.is_property(): # print "is_property." self.properties.append(t) if t.is_class(): # print "is_class." self.classes.append(t) # CODE FROM ORIGINAL specgen: def niceName(self, uri = None ): if uri is None: return # speclog("Nicing uri "+uri) regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) if rez == None: #print "Failed to niceName. Returning the whole thing." return(uri) pref = rez.group(1) # print "...",self.ns_list.get(pref, pref),":",rez.group(2) # todo: make this work when uri doesn't match the regex --danbri # AttributeError: 'NoneType' object has no attribute 'group' return self.ns_list.get(pref, pref) + ":" + rez.group(2) # HTML stuff, should be a separate class def azlist(self): """Builds the A-Z list of terms""" c_ids = [] p_ids = [] for p in self.properties: p_ids.append(str(p.id)) for c in self.classes: c_ids.append(str(c.id)) c_ids.sort() p_ids.sort() return (c_ids, p_ids) class VocabReport(object): def __init__(self, vocab, basedir='./examples/', temploc='template.html'): self.vocab = vocab self.basedir = basedir self.temploc = temploc self._template = "no template loaded" # text.gsub(/<code>foaf:(\w+)<\/code>/){ defurl($1) } return "<code><a href=\"#term_#{term}\">foaf:#{term}</a></code>" def codelink(self, s): reg1 = re.compile(r"""<code>foaf:(\w+)<\/code>""") return(re.sub(reg1, r"""<code><a href="#term_\1">foaf:\1</a></code>""", s)) def _get_template(self): self._template = self.load_template() # should be conditional return self._template def _set_template(self, value): self._template = str(value) template = property(_get_template,_set_template) def load_template(self): filename = os.path.join(self.basedir, self.temploc) f = open(filename, "r") template = f.read() return(template) def generate(self): tpl = self.template azlist = self.az() termlist = self.termlist() # print "RDF is in ", self.vocab.filename f = open ( self.vocab.filename, "r") rdfdata = f.read() # print "GENERATING >>>>>>>> " ##havign the rdf in there is making it invalid ## tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8"), rdfdata) tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8")) return(tpl) # u = urllib.urlopen(specloc) # rdfdata = u.read() # rdfdata = re.sub(r"(<\?xml version.*\?>)", "", rdfdata) # rdfdata = re.sub(r"(<!DOCTYPE[^]]*]>)", "", rdfdata) # rdfdata.replace("""<?xml version="1.0"?>""", "") def az(self): """AZ List for html doc""" c_ids, p_ids = self.vocab.azlist() az = """<div class="azlist">""" az = """%s\n<p>Classes: |""" % az # print c_ids, p_ids for c in c_ids: # speclog("Class "+c+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(c).replace(" ", ""), c) az = """%s\n</p>""" % az az = """%s\n<p>Properties: |""" % az for p in p_ids: # speclog("Property "+p+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(p).replace(" ", ""), p) az = """%s\n</p>""" % az az = """%s\n</div>""" % az return(az) def termlist(self): """Term List for html doc""" queries = '' c_ids, p_ids = self.vocab.azlist() tl = """<div class="termlist">""" tl = """%s<h3>Classes and Properties (full detail)</h3>\n<div class='termdetails'><br />\n\n""" % tl # first classes, then properties eg = """<div class="specterm" id="term_%s" about="%s" typeof="%s"> <h3>%s: %s</h3> <em>%s</em> - %s <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#%s">%s</span></td></tr> %s %s </table> %s - <p style="float: right; font-size: small;">[<a href="#term_%s">permalink</a>] [<a href="#queries_%s">validation queries</a>] [<a href="#glance">back to top</a>]</p> + <p style="float: right; font-size: small;">[<a href="#term_%s">#</a>] [<a href="#glance">back to top</a>]</p> <br/> </div>""" +# replace this if you want validation queries: +# <p style="float: right; font-size: small;">[<a href="#term_%s">permalink</a>] [<a href="#queries_%s">validation queries</a>] [<a href="#glance">back to top</a>]</p> # todo, push this into an api call (c_ids currently setup by az above) # classes for term in self.vocab.classes: foo = '' foo1 = '' #class in domain of g = self.vocab.graph q = 'SELECT ?d ?l WHERE {?d rdfs:domain <%s> . ?d rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th>in-domain-of:</th>\n' tt = '' for (domain, label) in relations: dom = Term(domain) ss = """<a href="#term_%s">%s</a>\n""" % (dom.id, label) tt = "%s %s" % (tt, ss) if tt != "": foo = "%s <td> %s </td></tr>" % (sss, tt) # class in range of q2 = 'SELECT ?d ?l WHERE {?d rdfs:range <%s> . ?d rdfs:label ?l } ' % (term.uri) query2 = Parse(q2) relations2 = g.query(query2, initNs=bindings) snippet = '<tr><th>in-range-of:</th>\n' tt = '' for (range, label) in relations2: ran = Term(range) ss = """<a href="#term_%s">%s</a>\n""" % (ran.id, label) tt = "%s %s" % (tt, ss) #print "R ",tt if tt != "": foo1 = "%s <td> %s</td></tr> " % (snippet, tt) # class subclassof foo2 = '' q = 'SELECT ?sc ?l WHERE {<%s> rdfs:subClassOf ?sc . ?sc rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th>subClassOf</th>\n' tt = '' for (subclass, label) in relations: sub = Term(subclass) ss = """<span rel="rdfs:subClassOf" href="%s"><a href="#term_%s">%s</a></span>\n""" % (subclass, sub.id, label) # tt = "%s %s" % (tt, ss) if tt != "": foo2 = "%s <td> %s </td></tr>" % (sss, tt) # class has subclass foo3 = '' q = 'SELECT ?sc ?l WHERE {?sc rdfs:subClassOf <%s>. ?sc rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th>has subclass</th>\n' tt = '' for (subclass, label) in relations: sub = Term(subclass) ss = """<a href="#term_%s">%s</a>\n""" % (sub.id, label) tt = "%s %s" % (tt, ss) if tt != "": foo3 = "%s <td> %s </td></tr>" % (sss, tt) # is defined by foo4 = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '\n' tt = '' for (isdefinedby) in relations: ss = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) tt = "%s %s" % (tt, ss) if tt != "": foo4 = "%s %s " % (sss, tt) # disjoint with foo5 = '' q = 'SELECT ?dj ?l WHERE { <%s> <http://www.w3.org/2002/07/owl#disjointWith> ?dj . ?dj rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th>Disjoint With:</th>\n' tt = '' for (disjointWith, label) in relations: ss = """<span rel="owl:disjointWith" href="%s"><a href="#term_%s">%s</a></span>\n""" % (disjointWith, label, label) tt = "%s %s" % (tt, ss) if tt != "": foo5 = "%s <td> %s </td></tr>" % (sss, tt) # end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' #queries filename = os.path.join(dn, term.id+".sparql") ss = '' try: f = open ( filename, "r") ss = f.read() ss = "<h4><a name=\"queries_"+term.id+"\"></a>"+term.id+" Validation Query</h4><pre>"+cgi.escape(ss)+"</pre>" except: ss='' queries = queries +"\n"+ ss # s = s+"\n"+ss sn = self.vocab.niceName(term.uri) zz = eg % (term.id,term.uri,"rdfs:Class","Class", sn, term.label, term.comment, term.status,term.status,foo,foo1+foo2+foo3+foo4+foo5, s,term.id, term.id) tl = "%s %s" % (tl, zz) # properties for term in self.vocab.properties: foo = '' foo1 = '' # domain of properties g = self.vocab.graph q = 'SELECT ?d ?l WHERE {<%s> rdfs:domain ?d . ?d rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th>Domain:</th>\n' tt = '' for (domain, label) in relations: dom = Term(domain) ss = """<span rel="rdfs:domain" href="%s"><a href="#term_%s">%s</a></span>\n""" % (domain, dom.id, label) tt = "%s %s" % (tt, ss) if tt != "": foo = "%s <td>%s</td></tr>" % (sss, tt) # range of properties q2 = 'SELECT ?d ?l WHERE {<%s> rdfs:range ?d . ?d rdfs:label ?l } ' % (term.uri) query2 = Parse(q2) relations2 = g.query(query2, initNs=bindings) sss = '<tr><th>Range:</th>\n' tt = '' for (range, label) in relations2: ran = Term(range) ss = """<span rel="rdfs:range" href="%s"<a href="#term_%s">%s</a></span>\n""" % (range, ran.id, label) tt = "%s %s" % (tt, ss) # print "D ",tt if tt != "": foo1 = "%s <td>%s</td> </tr>" % (sss, tt) # is defined by foo4 = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '\n' tt = '' for (isdefinedby) in relations: ss = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) tt = "%s %s" % (tt, ss) if tt != "": foo4 = "%s %s " % (sss, tt) # inverse functional property foo5 = '' q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#InverseFunctionalProperty> } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th colspan="2">Inverse Functional Property</th>\n' if (len(relations) > 0): ss = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#InverseFunctionalProperty"></span>""" foo5 = "%s <td> %s </td></tr>" % (sss, ss) # functonal property # inverse functional property foo6 = '' q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#FunctionalProperty> } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th colspan="2">Functional Property</th>\n' if (len(relations) > 0): ss = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#FunctionalProperty"></span>""" foo6 = "%s <td> %s </td></tr>" % (sss, ss) # end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' sn = self.vocab.niceName(term.uri) zz = eg % (term.id, term.uri,"rdf:Property","Property", sn, term.label, term.comment, term.status,term.status, foo, foo1+foo4+foo5+foo6, s,term.id, term.id) tl = "%s %s" % (tl, zz) ## ensure termlist tag is closed return(tl+"\n"+queries+"</div>\n</div>") def rdfa(self): return( "<html>rdfa here</html>") def htmlDocInfo( t, termdir='../docs' ): """Opens a file based on the term name (t) and termdir (defaults to current directory. Reads in the file, and returns a linkified version of it.""" if termdir==None: termdir=self.basedir doc = "" try: f = open("%s/%s.en" % (termdir, t), "r") doc = f.read() doc = termlink(doc) except: return "<p>No detailed documentation for this term.</p>" return doc # report what we've parsed from our various sources def report(self): s = "Report for vocabulary from " + self.vocab.filename + "\n" if self.vocab.uri != None: s += "URI: " + self.vocab.uri + "\n\n" for t in self.vocab.uterms: print "TERM as string: ",t s += t.simple_report() return s
leth/SpecGen
8a6d24b05d245d075aa739f792103c32d120064a
notes on using it for xmlns.com foaf stuff
diff --git a/foafsite-readme.txt b/foafsite-readme.txt new file mode 100644 index 0000000..1203ce7 --- /dev/null +++ b/foafsite-readme.txt @@ -0,0 +1,43 @@ +TODO before we can use it for real + +* get rid of 'validation queries' link by default +* read opts from commandline +* use same css as http://xmlns.com/foaf/spec/ +* the subclassof link --- check it works with border terms (subclasses of non foaf stuff) +* domain/range - also check border: +** fix based_near (how? what do we link to? #term_SpatialThing currently ... how?) + + + + + + + +How to use this with FOAF site: + +ie. for the real foaf spec + +1. set up subdir with relevant symlinks +2. run the script +3. compare output to what we hope for + + + +TellyClub:specgen danbri$ ./specgen5.py foaf-live/ http://xmlns.com/foaf/0.1/ foaf +ok +Printing to foaf-live/_tmp_spec.html + + + + + +_tmp_spec.html doc foaf-update.txt index.rdf style.css template.html +TellyClub:specgen danbri$ ls -l foaf-live/ +total 392 +-rw-r--r-- 1 danbri staff 177151 Sep 8 15:00 _tmp_spec.html +lrwxrwxrwx 1 danbri staff 59 Nov 14 13:23 doc -> /Users/danbri/working/foaf/trunk/xmlns.com/htdocs/foaf/doc/ +-rw-r--r-- 1 danbri staff 2115 Sep 8 15:00 foaf-update.txt +lrwxrwxrwx 1 danbri staff 69 Nov 14 13:23 index.rdf -> /Users/danbri/working/foaf/trunk/xmlns.com/htdocs/foaf/spec/index.rdf +-rw-r--r-- 1 danbri staff 1127 Sep 8 15:00 style.css +lrwxrwxrwx 1 danbri staff 72 Nov 14 13:23 template.html -> /Users/danbri/working/foaf/trunk/xmlns.com/htdocs/foaf/0.1/template.html +
leth/SpecGen
84033d24a6ef14bb7a8921bd90bc8a4b1a099165
notes on lib installer
diff --git a/README.TXT b/README.TXT index be64e8c..d7ca23c 100644 --- a/README.TXT +++ b/README.TXT @@ -1,88 +1,95 @@ This is an experimental new codebase for specgen tools. It depends utterly upon rdflib. See http://rdflib.net/2.4.0/ If you're lucky, typing this is enough: easy_install -U rdflib==2.4.0 +and if you have problems there, update easy_install etc with: + + easy_install -U setuptools + +(Last time I did all this, I got Python errors but it still works.) + + Inputs: RDF, HTML and OWL description(s) of an RDF vocabulary Output: an XHTML+RDFa specification designed for human users See libvocab.py and specgen5.py for details. --danbri To test, see run_tests.py This is quite flexible. use -h for help, or run all with ./run_tests.py When working on a specific test, it is faster to use something like: ./run_tests.py testSpecgen.testHTMLazlistExists See the src for adding more tests (simple and encouraged!), or for defining collections that can be run together. "What it does": The last FOAF spec was built using http://xmlns.com/foaf/0.1/specgen.py This reads an index.rdf, a template.html file plus a set of per-term files, eg. 'doc/homepage.en' etc., then generates the main HTML FOAF spec. Announcement: http://lists.foaf-project.org/pipermail/foaf-dev/2008-December/009415.html http://groups.google.com/group/sioc-dev/browse_thread/thread/36190062d384624d See also: http://forge.morfeo-project.org/wiki_en/index.php/SpecGen (another rewrite) http://crschmidt.net/semweb/redland/ https://lists.morfeo-project.org/pipermail/specgen-devel/ Goals: - be usable at least for (re)-generating the FOAF spec and similar - work well with multi-lingual labels - be based on SPARQL queries against RDFS/OWL vocab descriptions - evolve a Python library that supports such tasks - keep vocab-specific hackery in scripts that call the library - push display logic into CSS - use a modern, pure Python RDF library for support Status: - we load up and interpret the core RDFS/OWL - we populate Vocab, Term (Class or Property) instances - we have *no* code yet for generating HTML spec TODO: - mine the old implementations to understand what we need to know about each class and property. - decide how much of OWL we want to represent - see what rdflib itself might offer to help with all this ISSUES 1. librdf doesn't seem to like abbreviations in FILTER clauses. this worked: q= 'SELECT ?x ?l ?c ?type WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty>) } ' while this failed: q= 'PREFIX owl: <http://www.w3.org/2002/07/owl#> SELECT ?x ?l ?c ?type WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = owl:ObjectProperty) } ' (even when passing in bindings) This forces us to be verbose, ie. q= 'SELECT distinct ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty> || ?type = <http://www.w3.org/2002/07/owl#DatatypeProperty> || ?type = <http://www.w3.org/1999/02/22-rdf-syntax-ns#Property> || ?type = <http://www.w3.org/2002/07/owl#FunctionalProperty> || ?type = <http://www.w3.org/2002/07/owl#InverseFunctionalProperty>) } ' 2. Figure out the best way to do tests in Python. assert()? read diveinto... 3. TODO: work out how to do ".encode('UTF-8')" everywhere 4. Be more explicit and careful re defaulting to English, and more robust when multilingual labels are found. 5. Currently, queries find nothing in SIOC. We need to match various OWL and RDF ways of saying "this is a property", and encapsulate this in a function. And test it. SIOC should find 20<x<100 properties, etc.
leth/SpecGen
a31df6b33c2b7296a58fd9cb84758d9dcc0a8624
Fixed up testcases to use the new API; removed some hacks workarounds for the old testcases not working, and added a link to the namespace in the template as it doesn't say what it is anywhere
diff --git a/examples/foaf/template.html b/examples/foaf/template.html index 8a937af..096da4b 100644 --- a/examples/foaf/template.html +++ b/examples/foaf/template.html @@ -1,703 +1,707 @@ <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" xmlns:foaf="http://xmlns.com/foaf/0.1/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" xmlns:owl="http://www.w3.org/2002/07/owl#" xmlns:vs="http://www.w3.org/2003/06/sw-vocab-status/ns#" xmlns:wot="http://xmlns.com/wot/0.1/" > <head> <title>FOAF Vocabulary Specification</title> <link href="http://xmlns.com/xmlns-style.css" rel="stylesheet" type="text/css" /> <link href="style.css" rel="stylesheet" type="text/css" /> <link href="http://xmlns.com/foaf/spec/index.rdf" rel="alternate" type="application/rdf+xml" /> </head> <body> <h1>FOAF Vocabulary Specification 0.91<br /></h1> <h2>Namespace Document 2 November 2007 - <em>OpenID Edition</em></h2> <dl> <dt>This version:</dt> <dd><a href= "http://xmlns.com/foaf/spec/20071002.html">http://xmlns.com/foaf/spec/20071002.html</a> (<a href="20071002.rdf">rdf</a>)</dd> <dt>Latest version:</dt> <dd><a href="http://xmlns.com/foaf/spec/">http://xmlns.com/foaf/spec/</a> (<a href="index.rdf">rdf</a>)</dd> <dt>Previous version:</dt> <dd><a href="20070524.html">http://xmlns.com/foaf/spec/20070524.html</a> (<a href="20070524.rdf">rdf</a>)</dd> <dt>Authors:</dt> <dd><a href="mailto:[email protected]">Dan Brickley</a>, <a href="mailto:[email protected]">Libby Miller</a></dd> <dt>Contributors:</dt> <dd>Members of the FOAF mailing list (<a href= "http://lists.foaf-project.org/">[email protected]</a>) and the wider <a href="http://www.w3.org/2001/sw/interest/">RDF and SemWeb developer community</a>. See <a href= "#sec-ack">acknowledgements</a>.</dd> </dl> <p class="copyright">Copyright &copy; 2000-2007 Dan Brickley and Libby Miller<br /> <br /> <!-- Creative Commons License --> <a href="http://creativecommons.org/licenses/by/1.0/"><img alt= "Creative Commons License" style="border: 0; float: right; padding: 10px;" src= "somerights.gif" /></a> This work is licensed under a <a href= "http://creativecommons.org/licenses/by/1.0/">Creative Commons Attribution License</a>. This copyright applies to the <em>FOAF Vocabulary Specification</em> and accompanying documentation in RDF. Regarding underlying technology, FOAF uses W3C's <a href="http://www.w3.org/RDF/">RDF</a> technology, an open Web standard that can be freely used by anyone.</p> <hr /> <h2 id="sec-status">Abstract</h2> <p> This specification describes the FOAF language, defined as a dictionary of named properties and classes using W3C's RDF technology. </p> <div class="status"> <h2>Status of This Document</h2> <p> FOAF has been evolving gradually since its creation in mid-2000. There is now a stable core of classes and properties that will not be changed, beyond modest adjustments to their documentation to track implementation feedback and emerging best practices. New terms may be added at any time (as with a natural-language dictionary), and consequently this specification is an evolving work. The FOAF RDF namespace, by contrast, is fixed and it's identifier is not expected to <a href="#sec-evolution">change</a>. Furthermore, efforts are -underway to ensure the long-term preservation of the FOAF namespace, its xmlns.com +underway to ensure the long-term preservation of the <a href="http://xmlns.com/foaf/0.1/">FOAF namespace</a>, its xmlns.com domain name and associated documentation. </p> <p> This document is created by combining the <a href="index.rdf">RDFS/OWL</a> machine-readable FOAF ontology with a set of <a href="../doc/">per-term</a> documents. Future versions may incorporate <a href="http://svn.foaf-project.org/foaftown/foaf18n/">multilingual translations</a> of the term definitions. The RDF version of the specification is also embedded in the HTML of this document, or available directly from the namespace URI by content negotiation. </p> <p> The FOAF specification is produced as part of the <a href= "http://www.foaf-project.org/">FOAF project</a>, to provide authoritative documentation of the contents, status and purpose of the RDF/XML vocabulary and document formats known informally as 'FOAF'.</p> <p>The authors welcome comments on this document, preferably via the public FOAF developers list <a href= "mailto:[email protected]">[email protected]</a>; <a href="http://lists.foaf-project.org">public archives</a> are available. A historical backlog of known technical issues is acknowledged, and available for discussion in the <a href="http://wiki.foaf-project.org/IssueTracker">FOAF wiki</a>. Proposals for resolving these issues are welcomed, either on foaf-dev or via the wiki. Further work is also needed on the explanatory text in this specification and on the <a href="http://www.foaf-project.org/">FOAF website</a>; progress towards this will be measured in the version number of future revisions to the FOAF specification. </p> <p>This revision of the specification includes a first draft description of the new <a href="#term_openid">foaf:openid</a> property. The prose description of this property is likely to evolve, but the basic mechanism seems robust. To accompany this support for OpenID in the FOAF specification, the <a href="http://wiki.foaf-project.org/">FOAF wiki</a> has also been updated to support usage of OpenID by members of the developer community. This revision of the spec also involves a change in the DTD declared at the top of the document. This is a foundation for using inline <a href="http://en.wikipedia.org/wiki/RDFa">RDFa</a> markup in future versions. The current version however does not yet validate according to this document format; it contains RDF/XML markup describing FOAF in machine-readable form. We welcome feedback on whether to retain this markup at the expense of DTD-based validation. </p> <p> As usual, see the <a href="#sec-changes">changes</a> section for details of the changes in this version of the specification. </p> <h2 id="sec-toc">Table of Contents</h2> <ul> <li><a href="#sec-glance">FOAF at a glance</a></li> <li><a href="#sec-intro">Introduction</a></li> <li><a href="#sec-sw">The Semantic Web</a></li> <li><a href="#sec-foafsw">FOAF and the Semantic Web</a></li> <li><a href="#sec-for">What's FOAF for?</a></li> <li><a href="#sec-bg">Background</a></li> <li><a href="#sec-standards">FOAF and Standards</a></li> <li><a href="#sec-evolution">Evolution and Extension of FOAF</a></li> <li><a href="#sec-autodesc">FOAF Auto-Discovery: Publishing and Linking FOAF files</a></li> <li><a href="#sec-foafandrdf">FOAF and RDF</a></li> <li><a href="#sec-crossref">FOAF cross-reference: Listing FOAF Classes and Properties</a></li> <li><a href="#sec-ack">Acknowledgments</a></li> <li><a href="#sec-changes">Recent Changes</a></li> </ul> <h2 id="glance">FOAF at a glance</h2> <p>An a-z index of FOAF terms, by class (categories or types) and by property.</p> <div style="padding: 5px; border: solid; background-color: #ddd;"> <p>Classes: | <a href="#term_Agent">Agent</a> | <a href="#term_Document">Document</a> | <a href="#term_Group">Group</a> | <a href="#term_Image">Image</a> | <a href="#term_OnlineAccount">OnlineAccount</a> | <a href="#term_OnlineChatAccount">OnlineChatAccount</a> | <a href="#term_OnlineEcommerceAccount">OnlineEcommerceAccount</a> | <a href="#term_OnlineGamingAccount">OnlineGamingAccount</a> | <a href="#term_Organization">Organization</a> | <a href="#term_Person">Person</a> | <a href="#term_PersonalProfileDocument">PersonalProfileDocument</a> | <a href="#term_Project">Project</a> | </p> <p>Properties: | <a href="#term_accountName">accountName</a> | <a href="#term_accountServiceHomepage">accountServiceHomepage</a> | <a href="#term_aimChatID">aimChatID</a> | <a href="#term_based_near">based_near</a> | <a href="#term_birthday">birthday</a> | <a href="#term_currentProject">currentProject</a> | <a href="#term_depiction">depiction</a> | <a href="#term_depicts">depicts</a> | <a href="#term_dnaChecksum">dnaChecksum</a> | <a href="#term_family_name">family_name</a> | <a href="#term_firstName">firstName</a> | <a href="#term_fundedBy">fundedBy</a> | <a href="#term_geekcode">geekcode</a> | <a href="#term_gender">gender</a> | <a href="#term_givenname">givenname</a> | <a href="#term_holdsAccount">holdsAccount</a> | <a href="#term_homepage">homepage</a> | <a href="#term_icqChatID">icqChatID</a> | <a href="#term_img">img</a> | <a href="#term_interest">interest</a> | <a href="#term_isPrimaryTopicOf">isPrimaryTopicOf</a> | <a href="#term_jabberID">jabberID</a> | <a href="#term_knows">knows</a> | <a href="#term_logo">logo</a> | <a href="#term_made">made</a> | <a href="#term_maker">maker</a> | <a href="#term_mbox">mbox</a> | <a href="#term_mbox_sha1sum">mbox_sha1sum</a> | <a href="#term_member">member</a> | <a href="#term_membershipClass">membershipClass</a> | <a href="#term_msnChatID">msnChatID</a> | <a href="#term_myersBriggs">myersBriggs</a> | <a href="#term_name">name</a> | <a href="#term_nick">nick</a> | <a href="#term_openid">openid</a> | <a href="#term_page">page</a> | <a href="#term_pastProject">pastProject</a> | <a href="#term_phone">phone</a> | <a href="#term_plan">plan</a> | <a href="#term_primaryTopic">primaryTopic</a> | <a href="#term_publications">publications</a> | <a href="#term_schoolHomepage">schoolHomepage</a> | <a href="#term_sha1">sha1</a> | <a href="#term_surname">surname</a> | <a href="#term_theme">theme</a> | <a href="#term_thumbnail">thumbnail</a> | <a href="#term_tipjar">tipjar</a> | <a href="#term_title">title</a> | <a href="#term_topic">topic</a> | <a href="#term_topic_interest">topic_interest</a> | <a href="#term_weblog">weblog</a> | <a href="#term_workInfoHomepage">workInfoHomepage</a> | <a href="#term_workplaceHomepage">workplaceHomepage</a> | <a href="#term_yahooChatID">yahooChatID</a> | </p> </div> <p>FOAF terms, grouped in broad categories.</p> <div class="rdf-proplist"> <h3>FOAF Basics</h3> <ul> <li><a href="#term_Agent">Agent</a></li> <li><a href="#term_Person">Person</a></li> <li><a href="#term_name">name</a></li> <li><a href="#term_nick">nick</a></li> <li><a href="#term_title">title</a></li> <li><a href="#term_homepage">homepage</a></li> <li><a href="#term_mbox">mbox</a></li> <li><a href="#term_mbox_sha1sum">mbox_sha1sum</a></li> <li><a href="#term_img">img</a></li> <li><a href="#term_depiction">depiction</a> (<a href= "#term_depicts">depicts</a>)</li> <li><a href="#term_surname">surname</a></li> <li><a href="#term_family_name">family_name</a></li> <li><a href="#term_givenname">givenname</a></li> <li><a href="#term_firstName">firstName</a></li> </ul> </div> <div class="rdf-proplist"> <h3>Personal Info</h3> <ul> <li><a href="#term_weblog">weblog</a></li> <li><a href="#term_knows">knows</a></li> <li><a href="#term_interest">interest</a></li> <li><a href="#term_currentProject">currentProject</a></li> <li><a href="#term_pastProject">pastProject</a></li> <li><a href="#term_plan">plan</a></li> <li><a href="#term_based_near">based_near</a></li> <li><a href= "#term_workplaceHomepage">workplaceHomepage</a></li> <li><a href= "#term_workInfoHomepage">workInfoHomepage</a></li> <li><a href="#term_schoolHomepage">schoolHomepage</a></li> <li><a href="#term_topic_interest">topic_interest</a></li> <li><a href="#term_publications">publications</a></li> <li><a href="#term_geekcode">geekcode</a></li> <li><a href="#term_myersBriggs">myersBriggs</a></li> <li><a href="#term_dnaChecksum">dnaChecksum</a></li> </ul> </div> <div class="rdf-proplist"> <h3>Online Accounts / IM</h3> <ul> <li><a href="#term_OnlineAccount">OnlineAccount</a></li> <li><a href= "#term_OnlineChatAccount">OnlineChatAccount</a></li> <li><a href= "#term_OnlineEcommerceAccount">OnlineEcommerceAccount</a></li> <li><a href= "#term_OnlineGamingAccount">OnlineGamingAccount</a></li> <li><a href="#term_holdsAccount">holdsAccount</a></li> <li><a href= "#term_accountServiceHomepage">accountServiceHomepage</a></li> <li><a href="#term_accountName">accountName</a></li> <li><a href="#term_icqChatID">icqChatID</a></li> <li><a href="#term_msnChatID">msnChatID</a></li> <li><a href="#term_aimChatID">aimChatID</a></li> <li><a href="#term_jabberID">jabberID</a></li> <li><a href="#term_yahooChatID">yahooChatID</a></li> </ul> </div> <div style="clear: left;"></div> <div class="rdf-proplist"> <h3>Projects and Groups</h3> <ul> <li><a href="#term_Project">Project</a></li> <li><a href="#term_Organization">Organization</a></li> <li><a href="#term_Group">Group</a></li> <li><a href="#term_member">member</a></li> <li><a href= "#term_membershipClass">membershipClass</a></li> <li><a href="#term_fundedBy">fundedBy</a></li> <li><a href="#term_theme">theme</a></li> </ul> </div> <div class="rdf-proplist"> <h3>Documents and Images</h3> <ul> <li><a href="#term_Document">Document</a></li> <li><a href="#term_Image">Image</a></li> <li><a href= "#term_PersonalProfileDocument">PersonalProfileDocument</a></li> <li><a href="#term_topic">topic</a> (<a href= "#term_page">page</a>)</li> <li><a href="#term_primaryTopic">primaryTopic</a></li> <li><a href="#term_tipjar">tipjar</a></li> <li><a href="#term_sha1">sha1</a></li> <li><a href="#term_made">made</a> (<a href= "#term_maker">maker</a>)</li> <li><a href="#term_thumbnail">thumbnail</a></li> <li><a href="#term_logo">logo</a></li> </ul> </div> </div> <div style="clear: left;"></div> + <h2 id="sec-example">Namespace</h2> + + <p>The FOAF namespace is <a href="http://xmlns.com/foaf/0.1/">http://xmlns.com/foaf/0.1/</a></p> + <h2 id="sec-example">Example</h2> <p>Here is a very basic document describing a person:</p> <div class="example"> <pre> &lt;foaf:Person rdf:about="#me" xmlns:foaf="http://xmlns.com/foaf/0.1/"&gt; &lt;foaf:name&gt;Dan Brickley&lt;/foaf:name&gt; &lt;foaf:mbox_sha1sum&gt;241021fb0e6289f92815fc210f9e9137262c252e&lt;/foaf:mbox_sha1sum&gt; &lt;foaf:homepage rdf:resource="http://danbri.org/" /&gt; &lt;foaf:img rdf:resource="/images/me.jpg" /&gt; &lt;/foaf:Person&gt; </pre> </div> <p>This brief example introduces the basics of FOAF. It basically says, "there is a <a href="#term_Person">foaf:Person</a> with a <a href="#term_name">foaf:name</a> property of 'Dan Brickley' and a <a href="#term_mbox_sha1sum">foaf:mbox_sha1sum</a> property of 241021fb0e6289f92815fc210f9e9137262c252e; this person stands in a <a href="#term_homepage">foaf:homepage</a> relationship to a thing called http://danbri.org/ and a <a href= "#term_img">foaf:img</a> relationship to a thing referenced by a relative URI of /images/me.jpg</p> <div style="clear: left;"></div> <!-- ================================================================== --> <h2 id="sec-intro">1 Introduction: FOAF Basics</h2> <h3 id="sec-sw">The Semantic Web</h3> <blockquote> <p> <em> To a computer, the Web is a flat, boring world, devoid of meaning. This is a pity, as in fact documents on the Web describe real objects and imaginary concepts, and give particular relationships between them. For example, a document might describe a person. The title document to a house describes a house and also the ownership relation with a person. Adding semantics to the Web involves two things: allowing documents which have information in machine-readable forms, and allowing links to be created with relationship values. Only when we have this extra level of semantics will we be able to use computer power to help us exploit the information to a greater extent than our own reading. </em> - Tim Berners-Lee &quot;W3 future directions&quot; keynote, 1st World Wide Web Conference Geneva, May 1994 </p> </blockquote> <h3 id="sec-foafsw">FOAF and the Semantic Web</h3> <p> FOAF, like the Web itself, is a linked information system. It is built using decentralised <a href="http://www.w3.org/2001/sw/">Semantic Web</a> technology, and has been designed to allow for integration of data across a variety of applications, Web sites and services, and software systems. To achieve this, FOAF takes a liberal approach to data exchange. It does not require you to say anything at all about yourself or others, nor does it place any limits on the things you can say or the variety of Semantic Web vocabularies you may use in doing so. This current specification provides a basic "dictionary" of terms for talking about people and the things they make and do.</p> <p>FOAF was designed to be used alongside other such dictionaries ("schemas" or "ontologies"), and to beusable with the wide variety of generic tools and services that have been created for the Semantic Web. For example, the W3C work on <a href="http://www.w3.org/TR/rdf-sparql-query/">SPARQL</a> provides us with a rich query language for consulting databases of FOAF data, while the <a href="http://www.w3.org/2004/02/skos/">SKOS</a> initiative explores in more detail than FOAF the problem of describing topics, categories, "folksonomies" and subject hierarchies. Meanwhile, other W3C groups are working on improved mechanisms for encoding all kinds of RDF data (including but not limited to FOAF) within Web pages: see the work of the <a href="http://www.w3.org/2001/sw/grddl-wg/">GRDDL</a> and <a href="http://www.w3.org/TR/xhtml-rdfa-primer/">RDFa</a> efforts for more detail. The Semantic Web provides us with an <em>architecture for collaboration</em>, allowing complex technical challenges to be shared by a loosely-coordinated community of developers. </p> <p>The FOAF project is based around the use of <em>machine readable</em> Web homepages for people, groups, companies and other kinds of thing. To achieve this we use the "FOAF vocabulary" to provide a collection of basic terms that can be used in these Web pages. At the heart of the FOAF project is a set of definitions designed to serve as a dictionary of terms that can be used to express claims about the world. The initial focus of FOAF has been on the description of people, since people are the things that link together most of the other kinds of things we describe in the Web: they make documents, attend meetings, are depicted in photos, and so on.</p> <p>The FOAF Vocabulary definitions presented here are written using a computer language (RDF/OWL) that makes it easy for software to process some basic facts about the terms in the FOAF vocabulary, and consequently about the things described in FOAF documents. A FOAF document, unlike a traditional Web page, can be combined with other FOAF documents to create a unified database of information. FOAF is a <a href="http://www.w3.org/DesignIssues/LinkedData.html">Linked Data</a> system, in that it based around the idea of linking together a Web of decentralised descriptions.</p> <h3 id="sec-basicidea">The Basic Idea</h3> <p>The basic idea is pretty simple. If people publish information in the FOAF document format, machines will be able to make use of that information. If those files contain "see also" references to other such documents in the Web, we will have a machine-friendly version of today's hypertext Web. Computer programs will be able to scutter around a Web of documents designed for machines rather than humans, storing the information they find, keeping a list of "see also" pointers to other documents, checking digital signatures (for the security minded) and building Web pages and question-answering services based on the harvested documents.</p> <p>So, what is the 'FOAF document format'? FOAF files are just text documents (well, Unicode documents). They are written in XML syntax, and adopt the conventions of the Resource Description Framework (RDF). In addition, the FOAF vocabulary defines some useful constructs that can appear in FOAF files, alongside other RDF vocabularies defined elsewhere. For example, FOAF defines categories ('classes') such as <code>foaf:Person</code>, <code>foaf:Document</code>, <code>foaf:Image</code>, alongside some handy properties of those things, such as <code>foaf:name</code>, <code>foaf:mbox</code> (ie. an internet mailbox), <code>foaf:homepage</code> etc., as well as some useful kinds of relationship that hold between members of these categories. For example, one interesting relationship type is <code>foaf:depiction</code>. This relates something (eg. a <code>foaf:Person</code>) to a <code>foaf:Image</code>. The FOAF demos that feature photos and listings of 'who is in which picture' are based on software tools that parse RDF documents and make use of these properties.</p> <p>The specific contents of the FOAF vocabulary are detailed in this <a href="http://xmlns.com/foaf/0.1/">FOAF namespace document</a>. In addition to the FOAF vocabulary, one of the most interesting features of a FOAF file is that it can contain "see Also" pointers to other FOAF files. This provides a basis for automatic harvesting tools to traverse a Web of interlinked files, and learn about new people, documents, services, data...</p> <p>The remainder of this specification describes how to publish and interpret descriptions such as these on the Web, using RDF/XML for syntax (file format) and terms from FOAF. It introduces a number of categories (RDF classes such as 'Person') and properties (relationship and attribute types such as 'mbox' or 'workplaceHomepage'). Each term definition is provided in both human and machine-readable form, hyperlinked for quick reference.</p> <h2 id="sec-for">What's FOAF for?</h2> <p>For a good general introduction to FOAF, see Edd Dumbill's article, <a href= "http://www-106.ibm.com/developerworks/xml/library/x-foaf.html">XML Watch: Finding friends with XML and RDF</a> (June 2002, IBM developerWorks). Information about the use of FOAF <a href= "http://rdfweb.org/2002/01/photo/">with image metadata</a> is also available.</p> <p>The <a href= "http://rdfweb.org/2002/01/photo/">co-depiction</a> experiment shows a fun use of the vocabulary. Jim Ley's <a href= "http://www.jibbering.com/svg/AnnotateImage.html">SVG image annotation tool</a> show the use of FOAF with detailed image metadata, and provide tools for labelling image regions within a Web browser. To create a FOAF document, you can use Leigh Dodd's <a href= "http://www.ldodds.com/foaf/foaf-a-matic.html">FOAF-a-matic</a> javascript tool. To query a FOAF dataset via IRC, you can use Edd Dumbill's <a href="http://usefulinc.com/foaf/foafbot">FOAFbot</a> tool, an IRC 'community support agent'. For more information on FOAF and related projects, see the <a href= "http://rdfweb.org/foaf/">FOAF project home page</a>. </p> <h2 id="sec-bg">Background</h2> <p>FOAF is a collaborative effort amongst Semantic Web developers on the FOAF ([email protected]) mailing list. The name 'FOAF' is derived from traditional internet usage, an acronym for 'Friend of a Friend'.</p> <p>The name was chosen to reflect our concern with social networks and the Web, urban myths, trust and connections. Other uses of the name continue, notably in the documentation and investigation of Urban Legends (eg. see the <a href= "http://www.urbanlegends.com/">alt.folklore.urban archive</a> or <a href="http://www.snopes.com/">snopes.com</a>), and other FOAF stories. Our use of the name 'FOAF' for a Web vocabulary and document format is intended to complement, rather than replace, these prior uses. FOAF documents describe the characteristics and relationships amongst friends of friends, and their friends, and the stories they tell.</p> <h2 id="sec-standards">FOAF and Standards</h2> <p>It is important to understand that the FOAF <em>vocabulary</em> as specified in this document is not a standard in the sense of <a href= "http://www.iso.ch/iso/en/ISOOnline.openerpage">ISO Standardisation</a>, or that associated with <a href= "http://www.w3.org/">W3C</a> <a href= "http://www.w3.org/Consortium/Process/">Process</a>.</p> <p>FOAF depends heavily on W3C's standards work, specifically on XML, XML Namespaces, RDF, and OWL. All FOAF <em>documents</em> must be well-formed RDF/XML documents. The FOAF vocabulary, by contrast, is managed more in the style of an <a href= "http://www.opensource.org/">Open Source</a> or <a href= "http://www.gnu.org/philosophy/free-sw.html">Free Software</a> project than as an industry standardarisation effort (eg. see <a href="http://www.jabber.org/jeps/jep-0001.html">Jabber JEPs</a>).</p> <p>This specification contributes a vocabulary, "FOAF", to the Semantic Web, specifying it using W3C's <a href= "http://www.w3.org/RDF/">Resource Description Framework</a> (RDF). As such, FOAF adopts by reference both a syntax (using XML) a data model (RDF graphs) and a mathematically grounded definition for the rules that underpin the FOAF design.</p> <h2 id="sec-nsdoc">The FOAF Vocabulary Description</h2> <p>This specification serves as the FOAF "namespace document". As such it describes the FOAF vocabulary and the terms (<a href= "http://www.w3.org/RDF/">RDF</a> classes and properties) that constitute it, so that <a href= "http://www.w3.org/2001/sw/">Semantic Web</a> applications can use those terms in a variety of RDF-compatible document formats and applications.</p> <p>This document presents FOAF as a <a href= "http://www.w3.org/2001/sw/">Semantic Web</a> vocabulary or <em>Ontology</em>. The FOAF vocabulary is pretty simple, pragmatic and designed to allow simultaneous deployment and extension. FOAF is intended for widescale use, but its authors make no commitments regarding its suitability for any particular purpose.</p> <h3 id="sec-evolution">Evolution and Extension of FOAF</h3> <p>The FOAF vocabulary is identified by the namespace URI '<code>http://xmlns.com/foaf/0.1/</code>'. Revisions and extensions of FOAF are conducted through edits to this document, which by convention is accessible in the Web via the namespace URI. For practical and deployment reasons, note that <b>we do not update the namespace URI as the vocabulary matures</b>. </p> <p>The core of FOAF now is considered stable, and the version number of <em>this specification</em> reflects this stability. However, it long ago became impractical to update the namespace URI without causing huge disruption to both producers and consumers of FOAF data. We are therefore left with the digits "0.1" in our URI. This stands as a warning to all those who might embed metadata in their vocabulary identifiers. </p> <p> The evolution of FOAF is best considered in terms of the stability of individual vocabulary terms, rather than the specification as a whole. As terms stabilise in usage and documentation, they progress through the categories '<strong>unstable</strong>', '<strong>testing</strong>' and '<strong>stable</strong>'.</p><!--STATUSINFO--> <p>The properties and types defined here provide some basic useful concepts for use in FOAF descriptions. Other vocabulary (eg. the <a href="http://dublincore.org/">Dublin Core</a> metadata elements for simple bibliographic description), RSS 1.0 etc can also be mixed in with FOAF terms, as can local extensions. FOAF is designed to be extended. The <a href= "http://wiki.foaf-project.org/FoafVocab">FoafVocab</a> page in the FOAF wiki lists a number of extension vocabularies that are particularly applicable to use with FOAF.</p> <h2 id="sec-autodesc">FOAF Auto-Discovery: Publishing and Linking FOAF files</h2> <p>If you publish a FOAF self-description (eg. using <a href= "http://www.ldodds.com/foaf/foaf-a-matic.html">foaf-a-matic</a>) you can make it easier for tools to find your FOAF by putting markup in the <code>head</code> of your HTML homepage. It doesn't really matter what filename you choose for your FOAF document, although <code>foaf.rdf</code> is a common choice. The linking markup is as follows:</p> <div class="example"> <pre> &lt;link rel="meta" type="application/rdf+xml" title="FOAF" href="<em>http://example.com/~you/foaf.rdf</em>"/&gt; </pre> </div> <p>...although of course change the <em>URL</em> to point to your own FOAF document. See also: more on <a href= "http://rdfweb.org/mt/foaflog/archives/000041.html">FOAF autodiscovery</a> and services that make use of it.</p> <h2 id="sec-foafandrdf">FOAF and RDF</h2> <p>Why does FOAF use <a href= "http://www.w3.org/RDF/">RDF</a>?</p> <p>FOAF is an application of the Resource Description Framework (RDF) because the subject area we're describing -- people -- has so many competing requirements that a standalone format could not do them all justice. By using RDF, FOAF gains a powerful extensibility mechanism, allowing FOAF-based descriptions can be mixed with claims made in <em>any other RDF vocabulary</em></p> <p>People are the things that link together most of the other kinds of things we describe in the Web: they make documents, attend meetings, are depicted in photos, and so on. Consequently, there are many many things that we might want to say about people, not to mention these related objects (ie. documents, photos, meetings etc).</p> <p>FOAF as a vocabulary cannot incorporate everything we might want to talk about that is related to people, or it would be as large as a full dictionary. Instead of covering all topics within FOAF itself, we buy into a larger framework - RDF - that allows us to take advantage of work elsewhere on more specific description vocabularies (eg. for geographical / mapping data).</p> <p>RDF provides FOAF with a way to mix together different descriptive vocabularies in a consistent way. Vocabularies can be created by different communites and groups as appropriate and mixed together as required, without needing any centralised agreement on how terms from different vocabularies can be written down in XML.</p> <p>This mixing happens in two ways: firstly, RDF provides an underlying model of (typed) objects and their attributes or relationships. <code>foaf:Person</code> is an example of a type of object (a "<em>class</em>"), while <code>foaf:knows</code> and <code>foaf:name</code> are examples of a relationship and an attribute of an <code>foaf:Person</code>; in RDF we call these "<em>properties</em>". Any vocabulary described in RDF shares this basic model, which is discernable in the syntax for RDF, and which removes one level of confusion in <em>understanding</em> a given vocabulary, making it simpler to comprehend and therefore reuse a vocabulary that you have not written yourself. This is the minimal <em>self-documentation</em> that RDF gives you.</p> <p>Secondly, there are mechanisms for saying which RDF properties are connected to which classes, and how different classes are related to each other, using RDF Syntax and OWL. These can be quite general (all RDF properties by default come from an <code>rdf:Resource</code> for example) or very specific and precise (for example by using <a href= "http://www.w3.org/2001/sw/WebOnt/">OWL</a> constructs, as in the <code>foaf:Group</code> example below. This is another form of self-documentation, which allows you to connect different vocabularies together as you please. An example of this is given below where the <code>foaf:based_near</code> property has a domain and range (types of class at each end of the property) from a different namespace altogether.</p> <p>In summary then, RDF is self-documenting in ways which enable the creation and combination of vocabularies in a devolved manner. This is particularly important for a vocabulary which describes people, since people connect to many other domains of interest, which it would be impossible (as well as suboptimal) for a single group to describe adequately in non-geological time.</p> <p>RDF is usually written using XML syntax, but behaves in rather different ways to 'vanilla' XML: the same RDF can be written in many different ways in XML. This means that SAX and DOM XML parsers are not adequate to deal with RDF/XML. If you want to process the data, you will need to use one of the many RDF toolkits available, such as Jena (Java) or Redland (C). <a href= "http://lists.w3.org/Archives/Public/www-rdf-interest/">RDF Interest Group</a> members can help with issues which may arise; there is also the <a href= "http://rdfweb.org/mailman/listinfo/rdfweb-dev">[email protected]</a> mailing list which is the main list for FOAF, and two active and friendly <a href= "http://esw.w3.org/topic/InternetRelayChat">IRC</a> channels: <a href="irc://irc.freenode.net/#rdfig">#rdfig</a> and <a href= "irc://irc.freenode.net/#foaf">#foaf</a> on <a href= "http://www.freenode.net/">freenode</a>.</p> <h2 id="sec-crossref">FOAF cross-reference: Listing FOAF Classes and Properties</h2> <p>FOAF introduces the following classes and properties. View this document's source markup to see the RDF/XML version.</p> <!-- the following is the script-generated list of classes and properties --> %s %s </body> </html> diff --git a/libvocab.py b/libvocab.py index 23081f3..1189dc2 100755 --- a/libvocab.py +++ b/libvocab.py @@ -1,732 +1,729 @@ #!/usr/bin/env python # total rewrite. --danbri # Usage: # # >>> from libvocab import Vocab, Term, Class, Property # # >>> from libvocab import Vocab, Term, Class, Property # >>> v = Vocab( f='examples/foaf/index.rdf', uri='http://xmlns.com/foaf/0.1/') # >>> dna = v.lookup('http://xmlns.com/foaf/0.1/dnaChecksum') # >>> dna.label # 'DNA checksum' # >>> dna.comment # 'A checksum for the DNA of some thing. Joke.' # >>> dna.id # u'dnaChecksum' # >>> dna.uri # 'http://xmlns.com/foaf/0.1/dnaChecksum' # # # Python OO notes: # http://www.devshed.com/c/a/Python/Object-Oriented-Programming-With-Python-part-1/ # http://www.daniweb.com/code/snippet354.html # http://docs.python.org/reference/datamodel.html#specialnames # # RDFlib: # http://www.science.uva.nl/research/air/wiki/RDFlib # # http://dowhatimean.net/2006/03/spellchecking-vocabularies-with-sparql # # We define basics, Vocab, Term, Property, Class # and populate them with data from RDF schemas, OWL, translations ... and nearby html files. import rdflib from rdflib import Namespace from rdflib.Graph import Graph from rdflib.Graph import ConjunctiveGraph from rdflib.sparql.sparqlGraph import SPARQLGraph from rdflib.sparql.graphPattern import GraphPattern from rdflib.sparql.bison import Parse from rdflib.sparql import Query FOAF = Namespace('http://xmlns.com/foaf/0.1/') RDFS = Namespace('http://www.w3.org/2000/01/rdf-schema#') XFN = Namespace("http://gmpg.org/xfn/1#") RDF = Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#") OWL = Namespace('http://www.w3.org/2002/07/owl#') VS = Namespace('http://www.w3.org/2003/06/sw-vocab-status/ns#') DC = Namespace('http://purl.org/dc/elements/1.1/') DOAP = Namespace('http://usefulinc.com/ns/doap#') SIOC = Namespace('http://rdfs.org/sioc/ns#') SIOCTYPES = Namespace('http://rdfs.org/sioc/types#') SIOCSERVICES = Namespace('http://rdfs.org/sioc/services#') # # TODO: rationalise these two lists. or at least check they are same. import sys, time, re, urllib, getopt import logging import os.path import cgi import operator bindings = { u"xfn": XFN, u"rdf": RDF, u"rdfs": RDFS, u"vs": VS } #g = None def speclog(str): sys.stderr.write("LOG: "+str+"\n") # a Term has... (intrinsically and via it's RDFS/OWL description) # uri - a (primary) URI, eg. 'http://xmlns.com/foaf/0.1/workplaceHomepage' # id - a local-to-spec ID, eg. 'workplaceHomepage' # xmlns - an xmlns URI (isDefinedBy, eg. 'http://xmlns.com/foaf/0.1/') # # label - an rdfs:label # comment - an rdfs:comment # # Beyond this, properties vary. Some have vs:status. Some have owl Deprecated. # Some have OWL descriptions, and RDFS descriptions; eg. property range/domain # or class disjointness. def ns_split(uri): regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) return(rez.group(1), rez.group(2)) class Term(object): def __init__(self, uri='file://dev/null'): self.uri = str(uri) self.uri = self.uri.rstrip() # speclog("Parsing URI " + uri) a,b = ns_split(uri) self.id = b self.xmlns = a if self.id==None: speclog("Error parsing URI. "+uri) if self.xmlns==None: speclog("Error parsing URI. "+uri) # print "self.id: "+ self.id + " self.xmlns: " + self.xmlns def uri(self): try: s = self.uri except NameError: self.uri = None s = '[NOURI]' speclog('No URI for'+self) return s def id(self): print "trying id" try: s = self.id except NameError: self.id = None s = '[NOID]' speclog('No ID for'+self) return str(s) def is_external(self, vocab): print "Comparing property URI ",self.uri," with vocab uri: " + vocab.uri return(False) #def __repr__(self): # return(self.__str__) def __str__(self): try: s = self.id except NameError: self.label = None speclog('No label for '+self+' todo: take from uri regex') s = (str(self)) return(str(s)) # so we can treat this like a string def __add__(self, s): return (s+str(self)) def __radd__(self, s): return (s+str(self)) def simple_report(self): t = self s='' s += "default: \t\t"+t +"\n" s += "id: \t\t"+t.id +"\n" s += "uri: \t\t"+t.uri +"\n" s += "xmlns: \t\t"+t.xmlns +"\n" s += "label: \t\t"+t.label +"\n" s += "comment: \t\t" + t.comment +"\n" s += "status: \t\t" + t.status +"\n" s += "\n" return s def _get_status(self): try: return self._status except: return 'unknown' def _set_status(self, value): self._status = str(value) status = property(_get_status,_set_status) # a Python class representing an RDFS/OWL property. # class Property(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Property.is_property called on "+self return(True) def is_class(self): # print "Property.is_class called on "+self return(False) # A Python class representing an RDFS/OWL class # class Class(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Class.is_property called on "+self return(False) def is_class(self): # print "Class.is_class called on "+self return(True) # A python class representing (a description of) some RDF vocabulary # class Vocab(object): def __init__(self, dir, f='index.rdf', uri=None ): self.graph = rdflib.ConjunctiveGraph() self._uri = uri self.dir = dir - if not dir: - self.filename = os.path.join(dir, f) - else: - self.filename = dir + self.filename = os.path.join(dir, f) self.graph.parse(self.filename) self.terms = [] self.uterms = [] # should also load translations here? # and deal with a base-dir? ##if f != None: ## self.index() self.ns_list = { "http://www.w3.org/1999/02/22-rdf-syntax-ns#" : "rdf", "http://www.w3.org/2000/01/rdf-schema#" : "rdfs", "http://www.w3.org/2002/07/owl#" : "owl", "http://www.w3.org/2001/XMLSchema#" : "xsd", "http://rdfs.org/sioc/ns#" : "sioc", "http://xmlns.com/foaf/0.1/" : "foaf", "http://purl.org/dc/elements/1.1/" : "dc", "http://purl.org/dc/terms/" : "dct", "http://usefulinc.com/ns/doap#" : "doap", "http://www.w3.org/2003/06/sw-vocab-status/ns#" : "status", "http://purl.org/rss/1.0/modules/content/" : "content", "http://www.w3.org/2003/01/geo/wgs84_pos#" : "geo", "http://www.w3.org/2004/02/skos/core#" : "skos", "http://purl.org/NET/c4dm/event.owl#" : "event" } def addShortName(self,sn): self.ns_list[self._uri] = sn self.shortName = sn #print self.ns_list # not currently used def unique_terms(self): tmp=[] for t in list(set(self.terms)): s = str(t) if (not s in tmp): self.uterms.append(t) tmp.append(s) # TODO: python question - can we skip needing getters? and only define setters. i tried/failed. --danbri def _get_uri(self): return self._uri def _set_uri(self, value): v = str(value) # we don't want Namespace() objects and suchlike, but we can use them without whining. if ':' not in v: speclog("Warning: this doesn't look like a URI: "+v) # raise Exception("This doesn't look like a URI.") self._uri = str( value ) uri = property(_get_uri,_set_uri) def set_filename(self, filename): self.filename = filename # TODO: be explicit if/where we default to English # TODO: do we need a separate index(), versus just use __init__ ? def index(self): # speclog("Indexing description of "+str(self)) # blank down anything we learned already self.terms = [] self.properties = [] self.classes = [] tmpclasses=[] tmpproperties=[] g = self.graph query = Parse('SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a rdf:Property } ') relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: p = Property(term) # print "Made a property! "+str(p) + "using label: "#+str(label) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) query = Parse('SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type FILTER (?type = <http://www.w3.org/2002/07/owl#Class> || ?type = <http://www.w3.org/2000/01/rdf-schema#Class> ) }') relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: c = Class(term) # print "Made a class! "+str(p) + "using comment: "+comment c.label = str(label) c.comment = str(comment) self.terms.append(c) if (not str(c) in tmpclasses): self.classes.append(c) tmpclasses.append(str(c)) self.terms.sort(key=operator.attrgetter('id')) self.classes.sort(key=operator.attrgetter('id')) self.properties.sort(key=operator.attrgetter('id')) # http://www.w3.org/2003/06/sw-vocab-status/ns#" query = Parse('SELECT ?x ?vs WHERE { ?x <http://www.w3.org/2003/06/sw-vocab-status/ns#term_status> ?vs }') status = g.query(query, initNs=bindings) # print "status results: ",status.__len__() for x, vs in status: #print "STATUS: ",vs, " for ",x t = self.lookup(x) if t != None: t.status = vs # print "Set status.", t.status else: speclog("Couldn't lookup term: "+x) # Go back and see if we missed any properties defined in OWL. TODO: classes too. Or rewrite above SPARQL. addd more types for full query. q= 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty>)}' q= 'SELECT distinct ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty> || ?type = <http://www.w3.org/2002/07/owl#DatatypeProperty> || ?type = <http://www.w3.org/1999/02/22-rdf-syntax-ns#Property> || ?type = <http://www.w3.org/2002/07/owl#FunctionalProperty> || ?type = <http://www.w3.org/2002/07/owl#InverseFunctionalProperty>) } ' query = Parse(q) relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: p = Property(str(term)) got = self.lookup( str(term) ) if got==None: # print "Made an OWL property! "+str(p.uri) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) # self.terms.sort() # does this even do anything? # self.classes.sort() # self.properties.sort() # todo, use a dictionary index instead. RTFM. def lookup(self, uri): uri = str(uri) for t in self.terms: # print "Lookup: comparing '"+t.uri+"' to '"+uri+"'" # print "type of t.uri is ",t.uri.__class__ if t.uri==uri: # print "Matched." # should we str here, to be more liberal? return t else: # print "Fail." '' return None # print a raw debug summary, direct from the RDF def raw(self): g = self.graph query = Parse('SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c } ') relations = g.query(query, initNs=bindings) print "Properties and Classes (%d terms)" % len(relations) print 40*"-" for (term, label, comment) in relations: print "term %s l: %s \t\tc: %s " % (term, label, comment) print # TODO: work out how to do ".encode('UTF-8')" here # for debugging only def detect_types(self): self.properties = [] self.classes = [] for t in self.terms: # print "Doing t: "+t+" which is of type " + str(t.__class__) if t.is_property(): # print "is_property." self.properties.append(t) if t.is_class(): # print "is_class." self.classes.append(t) # CODE FROM ORIGINAL specgen: def niceName(self, uri = None ): if uri is None: return # speclog("Nicing uri "+uri) regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) if rez == None: #print "Failed to niceName. Returning the whole thing." return(uri) pref = rez.group(1) # print "...",self.ns_list.get(pref, pref),":",rez.group(2) # todo: make this work when uri doesn't match the regex --danbri # AttributeError: 'NoneType' object has no attribute 'group' return self.ns_list.get(pref, pref) + ":" + rez.group(2) # HTML stuff, should be a separate class def azlist(self): """Builds the A-Z list of terms""" c_ids = [] p_ids = [] for p in self.properties: p_ids.append(str(p.id)) for c in self.classes: c_ids.append(str(c.id)) c_ids.sort() p_ids.sort() return (c_ids, p_ids) class VocabReport(object): def __init__(self, vocab, basedir='./examples/', temploc='template.html'): self.vocab = vocab self.basedir = basedir self.temploc = temploc self._template = "no template loaded" # text.gsub(/<code>foaf:(\w+)<\/code>/){ defurl($1) } return "<code><a href=\"#term_#{term}\">foaf:#{term}</a></code>" def codelink(self, s): reg1 = re.compile(r"""<code>foaf:(\w+)<\/code>""") return(re.sub(reg1, r"""<code><a href="#term_\1">foaf:\1</a></code>""", s)) def _get_template(self): self._template = self.load_template() # should be conditional return self._template def _set_template(self, value): self._template = str(value) template = property(_get_template,_set_template) def load_template(self): filename = os.path.join(self.basedir, self.temploc) f = open(filename, "r") template = f.read() return(template) def generate(self): tpl = self.template azlist = self.az() termlist = self.termlist() # print "RDF is in ", self.vocab.filename f = open ( self.vocab.filename, "r") rdfdata = f.read() # print "GENERATING >>>>>>>> " ##havign the rdf in there is making it invalid ## tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8"), rdfdata) tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8")) return(tpl) # u = urllib.urlopen(specloc) # rdfdata = u.read() # rdfdata = re.sub(r"(<\?xml version.*\?>)", "", rdfdata) # rdfdata = re.sub(r"(<!DOCTYPE[^]]*]>)", "", rdfdata) # rdfdata.replace("""<?xml version="1.0"?>""", "") def az(self): """AZ List for html doc""" c_ids, p_ids = self.vocab.azlist() az = """<div class="azlist">""" az = """%s\n<p>Classes: |""" % az # print c_ids, p_ids for c in c_ids: # speclog("Class "+c+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(c).replace(" ", ""), c) az = """%s\n</p>""" % az az = """%s\n<p>Properties: |""" % az for p in p_ids: # speclog("Property "+p+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(p).replace(" ", ""), p) az = """%s\n</p>""" % az az = """%s\n</div>""" % az return(az) def termlist(self): """Term List for html doc""" queries = '' c_ids, p_ids = self.vocab.azlist() tl = """<div class="termlist">""" tl = """%s<h3>Classes and Properties (full detail)</h3>\n<div class='termdetails'><br />\n\n""" % tl # first classes, then properties eg = """<div class="specterm" id="term_%s" about="%s" typeof="%s"> <h3>%s: %s</h3> <em>%s</em> - %s <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#%s">%s</span></td></tr> %s %s </table> %s <p style="float: right; font-size: small;">[<a href="#term_%s">permalink</a>] [<a href="#queries_%s">validation queries</a>] [<a href="#glance">back to top</a>]</p> <br/> </div>""" # todo, push this into an api call (c_ids currently setup by az above) # classes for term in self.vocab.classes: foo = '' foo1 = '' #class in domain of g = self.vocab.graph q = 'SELECT ?d ?l WHERE {?d rdfs:domain <%s> . ?d rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th>in-domain-of:</th>\n' tt = '' for (domain, label) in relations: dom = Term(domain) ss = """<a href="#term_%s">%s</a>\n""" % (dom.id, label) tt = "%s %s" % (tt, ss) if tt != "": foo = "%s <td> %s </td></tr>" % (sss, tt) # class in range of q2 = 'SELECT ?d ?l WHERE {?d rdfs:range <%s> . ?d rdfs:label ?l } ' % (term.uri) query2 = Parse(q2) relations2 = g.query(query2, initNs=bindings) snippet = '<tr><th>in-range-of:</th>\n' tt = '' for (range, label) in relations2: ran = Term(range) ss = """<a href="#term_%s">%s</a>\n""" % (ran.id, label) tt = "%s %s" % (tt, ss) #print "R ",tt if tt != "": foo1 = "%s <td> %s</td></tr> " % (snippet, tt) # class subclassof foo2 = '' q = 'SELECT ?sc ?l WHERE {<%s> rdfs:subClassOf ?sc . ?sc rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th>subClassOf</th>\n' tt = '' for (subclass, label) in relations: sub = Term(subclass) ss = """<span rel="rdfs:subClassOf" href="%s"><a href="#term_%s">%s</a></span>\n""" % (subclass, sub.id, label) # tt = "%s %s" % (tt, ss) if tt != "": foo2 = "%s <td> %s </td></tr>" % (sss, tt) # class has subclass foo3 = '' q = 'SELECT ?sc ?l WHERE {?sc rdfs:subClassOf <%s>. ?sc rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th>has subclass</th>\n' tt = '' for (subclass, label) in relations: sub = Term(subclass) ss = """<a href="#term_%s">%s</a>\n""" % (sub.id, label) tt = "%s %s" % (tt, ss) if tt != "": foo3 = "%s <td> %s </td></tr>" % (sss, tt) # is defined by foo4 = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '\n' tt = '' for (isdefinedby) in relations: ss = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) tt = "%s %s" % (tt, ss) if tt != "": foo4 = "%s %s " % (sss, tt) # disjoint with foo5 = '' q = 'SELECT ?dj ?l WHERE { <%s> <http://www.w3.org/2002/07/owl#disjointWith> ?dj . ?dj rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th>Disjoint With:</th>\n' tt = '' for (disjointWith, label) in relations: ss = """<span rel="owl:disjointWith" href="%s"><a href="#term_%s">%s</a></span>\n""" % (disjointWith, label, label) tt = "%s %s" % (tt, ss) if tt != "": foo5 = "%s <td> %s </td></tr>" % (sss, tt) # end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' #queries filename = os.path.join(dn, term.id+".sparql") ss = '' try: f = open ( filename, "r") ss = f.read() ss = "<h4><a name=\"queries_"+term.id+"\"></a>"+term.id+" Validation Query</h4><pre>"+cgi.escape(ss)+"</pre>" except: ss='' queries = queries +"\n"+ ss # s = s+"\n"+ss sn = self.vocab.niceName(term.uri) zz = eg % (term.id,term.uri,"rdfs:Class","Class", sn, term.label, term.comment, term.status,term.status,foo,foo1+foo2+foo3+foo4+foo5, s,term.id, term.id) tl = "%s %s" % (tl, zz) # properties for term in self.vocab.properties: foo = '' foo1 = '' # domain of properties g = self.vocab.graph q = 'SELECT ?d ?l WHERE {<%s> rdfs:domain ?d . ?d rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th>Domain:</th>\n' tt = '' for (domain, label) in relations: dom = Term(domain) ss = """<span rel="rdfs:domain" href="%s"><a href="#term_%s">%s</a></span>\n""" % (domain, dom.id, label) tt = "%s %s" % (tt, ss) if tt != "": foo = "%s <td>%s</td></tr>" % (sss, tt) # range of properties q2 = 'SELECT ?d ?l WHERE {<%s> rdfs:range ?d . ?d rdfs:label ?l } ' % (term.uri) query2 = Parse(q2) relations2 = g.query(query2, initNs=bindings) sss = '<tr><th>Range:</th>\n' tt = '' for (range, label) in relations2: ran = Term(range) ss = """<span rel="rdfs:range" href="%s"<a href="#term_%s">%s</a></span>\n""" % (range, ran.id, label) tt = "%s %s" % (tt, ss) # print "D ",tt if tt != "": foo1 = "%s <td>%s</td> </tr>" % (sss, tt) # is defined by foo4 = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '\n' tt = '' for (isdefinedby) in relations: ss = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) tt = "%s %s" % (tt, ss) if tt != "": foo4 = "%s %s " % (sss, tt) # inverse functional property foo5 = '' q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#InverseFunctionalProperty> } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th colspan="2">Inverse Functional Property</th>\n' if (len(relations) > 0): ss = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#InverseFunctionalProperty"></span>""" foo5 = "%s <td> %s </td></tr>" % (sss, ss) # functonal property diff --git a/run_tests.py b/run_tests.py index 92ba2d4..e204ab1 100755 --- a/run_tests.py +++ b/run_tests.py @@ -1,455 +1,458 @@ #!/usr/bin/env python # # Tests for specgen. # # What is this, and how can you help? # # This is the test script for a rewrite of the FOAF spec generation # tool. It uses Pure python rdflib for parsing. That makes it easier to # install than the previous tools which required successful compilation # and installation of Redland and its language bindings (Ruby, Python ...). # # Everything is in public SVN. Ask danbri for an account or password reminder if # you're contributing. # # Code: svn co http://svn.foaf-project.org/foaftown/specgen/ # # Run tests (with verbose flag): # ./run_tests.py -v # # What it does: # The FOAF spec is essentially built from an index.rdf file, plus a collection of per-term *.en HTML fragments. # This filetree includes a copy of the FOAF index.rdf and markup-fragment files (see examples/foaf/ and examples/foaf/doc/). # # Code overview: # # The class Vocab represents a parsed RDF vocabulary. VocabReport represents the spec we're generating from a Vocab. # We can at least load the RDF and poke around it with SPARQL. The ideal target output can be seen by looking at the # current spec, basically we get to a "Version 1.0" when something 99% the same as the current spec can be built using this # toolset, and tested as having done so. # # Rough notes follow: # trying to test using ... # http://agiletesting.blogspot.com/2005/01/python-unit-testing-part-1-unittest.html # http://docs.python.org/library/unittest.html # TODO: convert debug print statements to appropriate testing / verbosity logger API # TODO: make frozen snapshots of some more namespace RDF files # TODO: find an idiom for conditional tests, eg. if we have xmllint handy for checking output, or rdfa ... -FOAFSNAPSHOT = 'examples/foaf/index-20081211.rdf' # a frozen copy for sanity' sake -DOAPSNAPSHOT = 'examples/doap/doap-en.rdf' # maybe we should use dated url / frozen files for all -SIOCSNAPSHOT = 'examples/sioc/sioc.rdf' +FOAFSNAPSHOTDIR = 'examples/foaf/' +FOAFSNAPSHOT = 'index-20081211.rdf' # a frozen copy for sanity' sake +DOAPSNAPSHOTDIR = 'examples/doap/' +DOAPSNAPSHOT = 'doap-en.rdf' # maybe we should use dated url / frozen files for all +SIOCSNAPSHOTDIR = 'examples/sioc/' +SIOCSNAPSHOT = 'sioc.rdf' import libvocab from libvocab import Vocab from libvocab import VocabReport from libvocab import Term from libvocab import Class from libvocab import Property from libvocab import SIOC from libvocab import OWL from libvocab import FOAF from libvocab import RDFS from libvocab import RDF from libvocab import DOAP from libvocab import XFN # used in SPARQL queries below bindings = { u"xfn": XFN, u"rdf": RDF, u"rdfs": RDFS, u"owl": OWL, u"doap": DOAP, u"sioc": SIOC, u"foaf": FOAF } import rdflib from rdflib import Namespace from rdflib.Graph import Graph from rdflib.Graph import ConjunctiveGraph from rdflib.sparql.sparqlGraph import SPARQLGraph from rdflib.sparql.graphPattern import GraphPattern from rdflib.sparql.bison import Parse from rdflib.sparql import Query import unittest class testSpecgen(unittest.TestCase): """a test class for Specgen""" def setUp(self): """set up data used in the tests. Called before each test function execution.""" def testFOAFns(self): - foaf_spec = Vocab(FOAFSNAPSHOT) + foaf_spec = Vocab(FOAFSNAPSHOTDIR,FOAFSNAPSHOT) foaf_spec.index() foaf_spec.uri = FOAF # print "FOAF should be "+FOAF self.assertEqual(str(foaf_spec.uri), 'http://xmlns.com/foaf/0.1/') def testSIOCns(self): - sioc_spec = Vocab('examples/sioc/sioc.rdf') + sioc_spec = Vocab('examples/sioc/','sioc.rdf') sioc_spec.index() sioc_spec.uri = str(SIOC) self.assertEqual(sioc_spec.uri, 'http://rdfs.org/sioc/ns#') def testDOAPWrongns(self): - doap_spec = Vocab('examples/doap/doap-en.rdf') + doap_spec = Vocab('examples/doap/','doap-en.rdf') doap_spec.index() doap_spec.uri = str(DOAP) self.assertNotEqual(doap_spec.uri, 'http://example.com/DELIBERATE_MISTAKE_HERE') def testDOAPns(self): - doap_spec = Vocab('examples/doap/doap-en.rdf') + doap_spec = Vocab('examples/doap/','doap-en.rdf') doap_spec.index() doap_spec.uri = str(DOAP) self.assertEqual(doap_spec.uri, 'http://usefulinc.com/ns/doap#') #reading list: http://tomayko.com/writings/getters-setters-fuxors def testCanUseNonStrURI(self): """If some fancy object used with a string-oriented setter, we just take the string.""" - doap_spec = Vocab('examples/doap/doap-en.rdf') + doap_spec = Vocab('examples/doap/','doap-en.rdf') print "[1]" doap_spec.index() doap_spec.uri = Namespace('http://usefulinc.com/ns/doap#') # likely a common mistake self.assertEqual(doap_spec.uri, 'http://usefulinc.com/ns/doap#') def testFOAFminprops(self): """Check we found at least 50 FOAF properties.""" - foaf_spec = Vocab('examples/foaf/index-20081211.rdf') + foaf_spec = Vocab('examples/foaf/','index-20081211.rdf') foaf_spec.index() foaf_spec.uri = str(FOAF) c = len(foaf_spec.properties) self.failUnless(c > 50 , "FOAF has more than 50 properties. count: "+str(c)) def testFOAFmaxprops(self): - foaf_spec = Vocab(dir=FOAFSNAPSHOT, uri = FOAF) + foaf_spec = Vocab(dir=FOAFSNAPSHOTDIR, f=FOAFSNAPSHOT, uri = FOAF) foaf_spec.index() c = len(foaf_spec.properties) self.failUnless(c < 100 , "FOAF has less than 100 properties. count: "+str(c)) def testSIOCmaxprops(self): """sioc max props: not more than 500 properties in SIOC""" - sioc_spec = Vocab(dir='examples/sioc/sioc.rdf') + sioc_spec = Vocab(dir='examples/sioc/',f='sioc.rdf') sioc_spec.index() sioc_spec.uri = str(SIOC) c = len(sioc_spec.properties) #print "SIOC property count: ",c self.failUnless(c < 500 , "SIOC has less than 500 properties. count was "+str(c)) # work in progress. def testDOAPusingFOAFasExternal(self): """when DOAP mentions a FOAF class, the API should let us know it is external""" - doap_spec = Vocab(dir='examples/doap/doap.rdf') + doap_spec = Vocab(dir='examples/doap/',f='doap.rdf') doap_spec.index() doap_spec.uri = str(DOAP) for t in doap_spec.classes: # print "is class "+t+" external? " # print t.is_external(doap_spec) '' # work in progress. def testFOAFusingDCasExternal(self): """FOAF using external vocabs""" - foaf_spec = Vocab(dir=FOAFSNAPSHOT) + foaf_spec = Vocab(dir=FOAFSNAPSHOTDIR, f=FOAFSNAPSHOT) foaf_spec.index() foaf_spec.uri = str(FOAF) for t in foaf_spec.terms: # print "is term "+t+" external? ", t.is_external(foaf_spec) '' def testniceName_1foafmyprop(self): """simple test of nicename for a known namespace (FOAF), unknown property""" - foaf_spec = Vocab(dir=FOAFSNAPSHOT) + foaf_spec = Vocab(dir=FOAFSNAPSHOTDIR, f=FOAFSNAPSHOT) u = 'http://xmlns.com/foaf/0.1/myprop' nn = foaf_spec.niceName(u) # print "nicename for ",u," is: ",nn self.failUnless(nn == 'foaf:myprop', "Didn't extract nicename. input is"+u+"output was"+nn) # we test behaviour for real vs fake properties, just in case... def testniceName_2foafhomepage(self): """simple test of nicename for a known namespace (FOAF), known property.""" - foaf_spec = Vocab(FOAFSNAPSHOT) + foaf_spec = Vocab(FOAFSNAPSHOTDIR,FOAFSNAPSHOT) foaf_spec.index() u = 'http://xmlns.com/foaf/0.1/homepage' nn = foaf_spec.niceName(u) # print "nicename for ",u," is: ",nn self.failUnless(nn == 'foaf:homepage', "Didn't extract nicename") def testniceName_3mystery(self): """simple test of nicename for an unknown namespace""" - foaf_spec = Vocab(FOAFSNAPSHOT) + foaf_spec = Vocab(FOAFSNAPSHOTDIR,FOAFSNAPSHOT) foaf_spec.index() u = 'http:/example.com/mysteryns/myprop' nn = foaf_spec.niceName(u) # print "nicename for ",u," is: ",nn self.failUnless(nn == 'http:/example.com/mysteryns/:myprop', "Didn't extract verbose nicename") def testniceName_3baduri(self): """niceName should return same string if passed a non-URI (but log a warning?)""" - foaf_spec = Vocab(FOAFSNAPSHOT) + foaf_spec = Vocab(FOAFSNAPSHOTDIR,FOAFSNAPSHOT) foaf_spec.index() u = 'thisisnotauri' nn = foaf_spec.niceName(u) # print "nicename for ",u," is: ",nn self.failUnless(nn == u, "niceName didn't return same string when given a non-URI") def test_set_uri_in_constructor(self): """v = Vocab( uri=something ) can be used to set the Vocab's URI. """ u = 'http://example.com/test_set_uri_in_constructor' - foaf_spec = Vocab(FOAFSNAPSHOT,uri=u) + foaf_spec = Vocab(FOAFSNAPSHOTDIR,FOAFSNAPSHOT,uri=u) foaf_spec.index() self.failUnless( foaf_spec.uri == u, "Vocab's URI was supposed to be "+u+" but was "+foaf_spec.uri) def test_set_bad_uri_in_constructor(self): """v = Vocab( uri=something ) can be used to set the Vocab's URI to a bad URI (but should warn). """ u = 'notauri' - foaf_spec = Vocab(FOAFSNAPSHOT,uri=u) + foaf_spec = Vocab(FOAFSNAPSHOTDIR,FOAFSNAPSHOT,uri=u) foaf_spec.index() self.failUnless( foaf_spec.uri == u, "Vocab's URI was supposed to be "+u+" but was "+foaf_spec.uri) def test_getset_uri(self): """getting and setting a Vocab uri property""" - foaf_spec = Vocab(FOAFSNAPSHOT,uri='http://xmlns.com/foaf/0.1/') + foaf_spec = Vocab(FOAFSNAPSHOTDIR,FOAFSNAPSHOT,uri='http://xmlns.com/foaf/0.1/') foaf_spec.index() u = 'http://foaf.tv/example#' # print "a) foaf_spec.uri is: ", foaf_spec.uri foaf_spec.uri = u # print "b) foaf_spec.uri is: ", foaf_spec.uri # print self.failUnless( foaf_spec.uri == u, "Failed to change uri.") def test_ns_split(self): from libvocab import ns_split a,b = ns_split('http://example.com/foo/bar/fee') self.failUnless( a=='http://example.com/foo/bar/') self.failUnless( b=='fee') # is this a bad idiom? use AND in a single assertion instead? def test_lookup_Person(self): """find a term given it's uri""" - foaf_spec = Vocab(dir=FOAFSNAPSHOT, uri='http://xmlns.com/foaf/0.1/') + foaf_spec = Vocab(dir=FOAFSNAPSHOTDIR,f=FOAFSNAPSHOT, uri='http://xmlns.com/foaf/0.1/') foaf_spec.index() p = foaf_spec.lookup('http://xmlns.com/foaf/0.1/Person') # print "lookup for Person: ",p self.assertNotEqual(p.uri, None, "Couldn't find person class in FOAF") def test_lookup_Wombat(self): """fail to a bogus term given it's uri""" - foaf_spec = Vocab(dir=FOAFSNAPSHOT, uri='http://xmlns.com/foaf/0.1/') + foaf_spec = Vocab(dir=FOAFSNAPSHOTDIR,f=FOAFSNAPSHOT, uri='http://xmlns.com/foaf/0.1/') foaf_spec.index() p = foaf_spec.lookup('http://xmlns.com/foaf/0.1/Wombat') # No Wombats in FOAF yet. self.assertEqual(p, None, "lookup for Wombat should return None") def test_label_for_foaf_Person(self): """check we can get the label for foaf's Person class""" - foaf_spec = Vocab(dir=FOAFSNAPSHOT, uri='http://xmlns.com/foaf/0.1/') + foaf_spec = Vocab(dir=FOAFSNAPSHOTDIR,f=FOAFSNAPSHOT, uri='http://xmlns.com/foaf/0.1/') foaf_spec.index() l = foaf_spec.lookup('http://xmlns.com/foaf/0.1/Person').label # print "Label for foaf Person is "+l self.assertEqual(l,"Person") def test_label_for_sioc_Community(self): """check we can get the label for sioc's Community class""" - sioc_spec = Vocab(dir=SIOCSNAPSHOT, uri=SIOC) + sioc_spec = Vocab(dir=SIOCSNAPSHOTDIR,f=SIOCSNAPSHOT, uri=SIOC) sioc_spec.index() l = sioc_spec.lookup(SIOC+'Community').label self.assertEqual(l,"Community") def test_label_for_foaf_workplaceHomepage(self): """check we can get the label for foaf's workplaceHomepage property""" - foaf_spec = Vocab(dir=FOAFSNAPSHOT, uri='http://xmlns.com/foaf/0.1/') + foaf_spec = Vocab(dir=FOAFSNAPSHOTDIR, f=FOAFSNAPSHOT,uri='http://xmlns.com/foaf/0.1/') foaf_spec.index() l = foaf_spec.lookup('http://xmlns.com/foaf/0.1/workplaceHomepage').label # print "Label for foaf workplaceHomepage is "+l self.assertEqual(l,"workplace homepage") def test_status_for_foaf_Person(self): """check we can get the status for foaf's Person class""" - foaf_spec = Vocab(dir=FOAFSNAPSHOT, uri='http://xmlns.com/foaf/0.1/') + foaf_spec = Vocab(dir=FOAFSNAPSHOTDIR,f=FOAFSNAPSHOT, uri='http://xmlns.com/foaf/0.1/') foaf_spec.index() s = foaf_spec.lookup('http://xmlns.com/foaf/0.1/Person').status self.assertEqual(s,"stable") # http://usefulinc.com/ns/doap#Repository def test_status_for_doap_Repository(self): """check we can get the computed 'unknown' status for doap's Repository class""" - doap_spec = Vocab(dir=DOAPSNAPSHOT, uri='http://usefulinc.com/ns/doap#') + doap_spec = Vocab(dir=DOAPSNAPSHOTDIR,f=DOAPSNAPSHOT, uri='http://usefulinc.com/ns/doap#') doap_spec.index() s = doap_spec.lookup('http://usefulinc.com/ns/doap#Repository').status self.assertEqual(s,"unknown", "if vs:term_status isn't used, we set t.status to 'unknown'") def test_reindexing_not_fattening(self): "Indexing on construction and then a couple more times shouldn't affect property count." - foaf_spec = Vocab(FOAFSNAPSHOT, uri = FOAF) + foaf_spec = Vocab(FOAFSNAPSHOTDIR,FOAFSNAPSHOT, uri = FOAF) foaf_spec.index() c = len(foaf_spec.properties) self.failUnless(c < 100 , "After indexing 3 times, foaf property count should still be < 100: "+str(c)) def test_got_sioc(self): - sioc_spec = Vocab(SIOCSNAPSHOT, uri = SIOC) + sioc_spec = Vocab(SIOCSNAPSHOTDIR,SIOCSNAPSHOT, uri = SIOC) sioc_spec.index() cr = sioc_spec.lookup('http://rdfs.org/sioc/ns#creator_of') # print("Looked up creator_of in sioc. result: "+cr) # print("Looked up creator_of comment: "+cr.comment) # print "Sioc spec with comment has size: ", len(sioc_spec.properties) def testSIOCminprops(self): """Check we found at least 20 SIOC properties (which means matching OWL properties)""" - sioc_spec = Vocab('examples/sioc/sioc.rdf') + sioc_spec = Vocab('examples/sioc/','sioc.rdf') sioc_spec.index() sioc_spec.uri = str(SIOC) c = len(sioc_spec.properties) self.failUnless(c > 20 , "SIOC has more than 20 properties. count was "+str(c)) def testSIOCminprops_v2(self): """Check we found at least 10 SIOC properties.""" - sioc_spec = Vocab(dir='examples/sioc/sioc.rdf', uri = SIOC) + sioc_spec = Vocab(dir='examples/sioc/',f='sioc.rdf', uri = SIOC) sioc_spec.index() c = len(sioc_spec.properties) self.failUnless(c > 10 , "SIOC has more than 10 properties. count was "+str(c)) def testSIOCminprops_v3(self): """Check we found at least 5 SIOC properties.""" - # sioc_spec = Vocab(dir='examples/sioc/sioc.rdf', uri = SIOC) - sioc_spec = Vocab(dir=SIOCSNAPSHOT, uri = SIOC) + # sioc_spec = Vocab(dir='examples/sioc/',f='sioc.rdf', uri = SIOC) + sioc_spec = Vocab(dir=SIOCSNAPSHOTDIR,f=SIOCSNAPSHOT, uri = SIOC) sioc_spec.index() c = len(sioc_spec.properties) self.failUnless(c > 5 , "SIOC has more than 10 properties. count was "+str(c)) def testSIOCmin_classes(self): """Check we found at least 5 SIOC classes.""" - sioc_spec = Vocab(dir=SIOCSNAPSHOT, uri = SIOC) + sioc_spec = Vocab(dir=SIOCSNAPSHOTDIR,f=SIOCSNAPSHOT, uri = SIOC) sioc_spec.index() c = len(sioc_spec.classes) self.failUnless(c > 5 , "SIOC has more than 10 classes. count was "+str(c)) def testFOAFmin_classes(self): """Check we found at least 5 FOAF classes.""" - foaf_spec = Vocab(dir=FOAFSNAPSHOT, uri = FOAF) + foaf_spec = Vocab(dir=FOAFSNAPSHOTDIR,f=FOAFSNAPSHOT, uri = FOAF) foaf_spec.index() c = len(foaf_spec.classes) self.failUnless(c > 5 , "FOAF has more than 10 classes. count was "+str(c)) def testHTMLazlistExists(self): """Check we have some kind of azlist. Note that this shouldn't really be HTML from Vocab API ultimately.""" - foaf_spec = Vocab(FOAFSNAPSHOT, uri = FOAF) + foaf_spec = Vocab(FOAFSNAPSHOTDIR, FOAFSNAPSHOT, uri = FOAF) foaf_spec.index() az = foaf_spec.azlist() # print "AZ list is ", az self.assertNotEqual (az != None, "We should have an azlist.") def testOutputHTML(self): """Check HTML output formatter does something""" - foaf_spec = Vocab(dir=FOAFSNAPSHOT, uri = FOAF) + foaf_spec = Vocab(dir=FOAFSNAPSHOTDIR,f=FOAFSNAPSHOT, uri = FOAF) foaf_spec.index() page = VocabReport(foaf_spec) az = page.az() self.failUnless(az) def testGotRDFa(self): """Check HTML output formatter rdfa method returns some text""" - foaf_spec = Vocab(dir=FOAFSNAPSHOT, uri = FOAF) + foaf_spec = Vocab(dir=FOAFSNAPSHOTDIR,f=FOAFSNAPSHOT, uri = FOAF) foaf_spec.index() page = VocabReport(foaf_spec) rdfa = page.rdfa() self.failUnless(rdfa) def testTemplateLoader(self): """Check we can load a template file.""" basedir = './examples/' temploc = 'template.html' f = open(basedir + temploc, "r") template = f.read() self.failUnless(template != None) def testTemplateLoader2(self): """Check we can load a template file thru constructors.""" - foaf_spec = Vocab(dir=FOAFSNAPSHOT, uri = FOAF) + foaf_spec = Vocab(dir=FOAFSNAPSHOTDIR,f=FOAFSNAPSHOT, uri = FOAF) foaf_spec.index() page = VocabReport(foaf_spec, basedir='./examples/', temploc='template.html') tpl = page.template # print "Page template is: ", tpl self.failUnless(tpl != None) def testTemplateLoader3(self): """Check loaded template isn't default string.""" - foaf_spec = Vocab(FOAFSNAPSHOT, uri = FOAF) + foaf_spec = Vocab(FOAFSNAPSHOTDIR,FOAFSNAPSHOT, uri = FOAF) foaf_spec.index() page = VocabReport(foaf_spec, basedir='./examples/', temploc='template.html') tpl = page.template self.assertNotEqual(tpl, "no template loaded") # TODO: check this fails appropriately: # IOError: [Errno 2] No such file or directory: './examples/nonsuchfile.html' # # def testTemplateLoader4(self): # """Check loaded template isn't default string when using bad filename.""" # foaf_spec = Vocab(FOAFSNAPSHOT, uri = FOAF) # page = VocabReport(foaf_spec, basedir='./examples/', temploc='nonsuchfile.html') # tpl = page.template # self.assertNotEqual(tpl, "no template loaded") def testGenerateReport(self): """Use the template to generate our report page.""" - foaf_spec = Vocab(dir=FOAFSNAPSHOT, uri = FOAF) + foaf_spec = Vocab(dir=FOAFSNAPSHOTDIR,f=FOAFSNAPSHOT, uri = FOAF) foaf_spec.index() page = VocabReport(foaf_spec, basedir='./examples/', temploc='template.html') tpl = page.template final = page.generate() rdfa = page.rdfa() self.assertNotEqual(final, "Nope!") def testSimpleReport(self): """Use the template to generate a simple test report in txt.""" - foaf_spec = Vocab(dir=FOAFSNAPSHOT, uri = FOAF) + foaf_spec = Vocab(dir=FOAFSNAPSHOTDIR,f=FOAFSNAPSHOT, uri = FOAF) foaf_spec.index() page = VocabReport(foaf_spec, basedir='./examples/', temploc='template.html') simple = page.report() print "Simple report: ", simple self.assertNotEqual(simple, "Nope!") def suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(testSpecgen)) return suite if __name__ == '__main__': print "Running tests..." suiteFew = unittest.TestSuite() # Add things we know should pass to a subset suite # (only skip things we have explained with a todo) # ##libby suiteFew.addTest(testSpecgen("testFOAFns")) ##libby suiteFew.addTest(testSpecgen("testSIOCns")) suiteFew.addTest(testSpecgen("testDOAPns")) # suiteFew.addTest(testSpecgen("testCanUseNonStrURI")) # todo: ensure .uri etc can't be non-str suiteFew.addTest(testSpecgen("testFOAFminprops")) # suiteFew.addTest(testSpecgen("testSIOCminprops")) # todo: improve .index() to read more OWL vocab suiteFew.addTest(testSpecgen("testSIOCmaxprops")) # run tests we expect to pass: # unittest.TextTestRunner(verbosity=2).run(suiteFew) # run tests that should eventually pass: # unittest.TextTestRunner(verbosity=2).run(suite()) # # or we can run everything: # http://agiletesting.blogspot.com/2005/01/python-unit-testing-part-1-unittest.html g = foafspec.graph #q= 'SELECT ?x ?l ?c ?type WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = owl:ObjectProperty || ?type = owl:DatatypeProperty || ?type = rdf:Property || ?type = owl:FunctionalProperty || ?type = owl:InverseFunctionalProperty) } ' #query = Parse(q) #relations = g.query(query, initNs=bindings) #for (term, label, comment) in relations: # p = Property(term) # print "property: "+str(p) + "label: "+str(label)+ " comment: "+comment if __name__ == '__main__': unittest.main()