def cell_call(self, row, col, **kwargs): entity = self.cw_rset.get_entity(row, col) root = entity.cw_adapt_to('ITree').root() self.w(u'<a href="%s">%s %s</a> ' % ( xml_escape(root.absolute_url()), xml_escape(root.dc_type()), xml_escape(cut(root.dc_title(), 40))))
def search_link(self, rset): """ Method that generates a the url of the CWSearch form we want to save. """ # Construct the form path # > get rql as url parameter path = u'rql={0}'.format(self._cw.url_quote(rset.printable_rql())) # > get the vid of the view if self._cw.form.get("vid"): path += u'&vid={0}'.format(self._cw.url_quote(self._cw.form["vid"])) # > say its a view path = u'view?' + path # Define the form default tile title = self._cw._("--unique title--") # Create the url to the CWSearch form cls = self._cw.vreg["etypes"].etype_class("CWSearch") add_url = cls.cw_create_url(self._cw, path=path, title=title) base_url = cls.cw_create_url(self._cw, title=title) link = (u'<a class="btn btn-primary" cubicweb:target="{0}" ' 'id="facetBkLink" href="{1}">'.format(xml_escape(base_url), xml_escape(add_url))) # Create the button button = u'<div class="btn-toolbar">' button += u'<div class="btn-group-vertical btn-block">' button += link button += u'<span class="glyphicon glyphicon-save"> {0}</span>'.format( self._cw._("Save search")) button += u'</a></div></div><br />' return self.linkbox_template.format(button)
def entity_call(self, entity): """element as an item for an xml feed""" entity.complete() scan = entity.reverse_has_data[0] self.w(u'<dataResource xsi:type="dimensionedBinaryDataResource_t">\n') self.w(u'<uri offset="0" size="262144">%s</uri>\n' % xml_escape(scan.full_filepath)) ##self.w(u'<elementType>int32</elementType>') ##self.w(u'<byteOrder>msbfirst</byteOrder>') self.w(u'<elementType>float32</elementType>') self.w(u'<compression>%s</compression>' % xml_escape(scan.format)) if entity.shape_x: self.w(u'<dimension label="x">\n') self.w(u'<size>%s</size>' % entity.shape_x) self.w(u'<spacing>%s</spacing>' % entity.voxel_res_x) # XXX harc-coded ? self.w(u'<direction>1 0 0</direction>\n') self.w(u'<units>mm</units>\n') self.w(u'</dimension>\n') if entity.shape_y: self.w(u'<dimension label="y">\n') self.w(u'<size>%s</size>' % entity.shape_y) self.w(u'<spacing>%s</spacing>' % entity.voxel_res_y) # XXX harc-coded ? self.w(u'<direction>0 1 0</direction>\n') self.w(u'<units>mm</units>\n') self.w(u'</dimension>\n') if entity.shape_z: self.w(u'<dimension label="y">\n') self.w(u'<size>%s</size>' % entity.shape_z) self.w(u'<spacing>%s</spacing>' % entity.voxel_res_z) # XXX harc-coded ? self.w(u'<direction>0 0 1</direction>\n') self.w(u'<units>mm</units>\n') self.w(u'</dimension>\n') self.w(u'</dataResource>\n')
def dict_to_html(w, dict): # XHTML doesn't allow emtpy <ul> nodes if dict: w(u'<dl>') for key in sorted(dict): w(u'<dt>%s</dt><dd>%s</dd>' % ( xml_escape(str(key)), xml_escape(repr(dict[key])))) w(u'</dl>')
def prevnext_div(self, w, type, cssclass, url, title, content): csscls = {'prev':'previous', 'next':'next'} w(u'<li class="%s">' % csscls[type]) w(u'<a href="%s" title="%s">%s</a>' % (xml_escape(url), xml_escape(title), content)) w(u'</li>') self._cw.html_headers.add_raw('<link rel="%s" href="%s" />' % ( type, xml_escape(url)))
def entity_call(self, entity): """element as an item for an xml feed""" entity.complete() subject = entity.reverse_concerned_by[0] # XXX studyID/visitID -> Assessment self.w(u'<visit ID="%(id)s" projectID="%(p)s" subjectID="%(s)s"/>\n' % {'id':xml_escape(entity.identifier), 'p': xml_escape(subject.related_studies[0].name), 's': xml_escape(subject.identifier)})
def call(self, rset=None, **kwargs): rset = rset or self.cw_rset w = self.w w(u'<div>') for entity in rset.entities(): w(u'<h2>%s</h2>' % xml_escape(entity.title)) if entity.synopsis: w(u'<blockquote><p>%s</p></blockquote>' % xml_escape(entity.synopsis)) if entity.content: w(entity.content) w(u'</div>')
def entity_call(self, entity): """element as an item for an xml feed""" entity.complete() assessment = entity.reverse_generates[0] if entity.reverse_generates else None # XXX studyID/visitID -> Assessment self.w(u'<acquisition ID="%(id)s" projectID="%(p)s" subjectID="%(s)s" ' 'visitID="%(a)s" studyID="%(a)s" episodeID="%(la)s"/>\n' % {'id': xml_escape(entity.identifier), 'p': xml_escape(entity.related_study[0].name), 's': xml_escape(entity.concerns[0].identifier), 'a': xml_escape(assessment.identifier) if assessment else None, 'la': xml_escape(entity.type)})
def call(self, **kwargs): super(CardDoesNotExistView, self).call(**kwargs) etype = self._cw.vreg['etypes'].etype_class('Card') ctx = {'url': etype.cw_create_url(self._cw, wikiid=self._cw.form['wikiid']), 'message': xml_escape(self._cw._('This card does not exist yet.')), 'invite': xml_escape(self._cw._('Create it?')), 'notice': '', } if not self._cw.vreg.schema['Card'].has_perm(self._cw, 'add'): ctx['notice'] = xml_escape(self._cw._(' (You may need to log in first.)')) self.w(u'<div class="section">%(message)s ' u'<a href="%(url)s">%(invite)s</a>%(notice)s</div>' % ctx)
def cell_call(self, row, col, **kwargs): self._cw.add_js('cubicweb.ajax.js') self._cw.add_css('cubes.comment.css') entity = self.cw_rset.get_entity(row, col) actions = self._cw.vreg['actions'] # DOM id of the whole comment's content cdivid = 'comment%sDiv' % entity.eid self.w(u'<div id="%s">' % cdivid) self.w(u'<div class="commentInfo">') self.w(self._cw.format_date(entity.creation_date)) self.w(u' %s' % self._cw.format_time(entity.creation_date)) if entity.creator: authorlink = entity.creator.view('oneline') self.w(u', %s <span class="author">%s</span> \n' % (self._cw._('written by'), authorlink,)) replyaction = actions.select_or_none('reply_comment', self._cw, rset=self.cw_rset, row=row) if replyaction is not None: url = self._cw.ajax_replace_url('comment%sHolder' % entity.eid, eid=entity.eid, vid='addcommentform') self.w(u' | <span class="replyto"><a href="%s">%s</a></span>' % (xml_escape(url), self._cw._(replyaction.title))) editaction = actions.select_or_none('edit_comment', self._cw, rset=self.cw_rset, row=row) if editaction is not None: # split(':', 1)[1] to remove javascript: formjs = self._cw.ajax_replace_url( cdivid, 'append', eid=entity.eid, vid='editcommentform').split(':', 1)[1] url = "javascript: jQuery('#%s div').hide(); %s" % (cdivid, formjs) self.w(u' | <span class="replyto"><a href="%s">%s</a></span>' % (xml_escape(url), self._cw._(editaction.title))) deleteaction = actions.select_or_none('delete_comment', self._cw, rset=self.cw_rset, row=row) if deleteaction is not None: root = entity.cw_adapt_to('ITree').root() url = self._cw.ajax_replace_url( 'comment%s' % entity.eid, eid=entity.eid, vid='deleteconf', __redirectpath=root.rest_path()) self.w(u' | <span class="replyto"><a href="%s">%s</a></span>' % (xml_escape(url), self._cw._(deleteaction.title))) self.w(u'</div>\n') # close comment's info div self.w(u'<div class="commentBody">%s</div>\n' % entity.printable_value('content')) # holder for reply form self.w(u'<div id="comment%sHolder" class="replyComment"></div>' % entity.eid) self.w(u'</div>\n') # close comment's content div
def startup_views(self): views = [v for v in self._cw.vreg['views'].possible_views(self._cw, None) if v.category == 'startupview' and v.__regid__ not in self.skip_startup_views] if not views: return html = [] w = html.append w(u'<ul>') for v in sorted(views, key=lambda x: self._cw._(x.title)): w('<li><a href="%s">%s</a></li>' % ( xml_escape(v.url()), xml_escape(self._cw._(v.title).capitalize()))) w(u'</ul>') self.w(self.box_html % {'title' : self._cw._('Startup views'), 'content': u'\n'.join(html)})
def _open(self): req = self._cw self.w(u'<?xml version="1.0" encoding="%s"?>\n' % req.encoding) self.w( u'<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">\n' ) self.w(u' <channel>\n') self.w(u' <title>%s RSS Feed</title>\n' % xml_escape(self.page_title())) self.w(u' <description>%s</description>\n' % xml_escape(req.form.get('vtitle', ''))) params = req.form.copy() params.pop('vid', None) self.w(u' <link>%s</link>\n' % xml_escape(self._cw.build_url(**params)))
def entity_call(self, entity): """element as an item for an xml feed""" entity.complete() # XXX studyID/visitID -> Assessment self.w(u'<xcede:step ID="%(id)s" name="%(la)s" minOccurences="1" maxOccurences="1" required="true">' % {'id':xml_escape(entity.identifier), 'la': xml_escape(entity.name)}) # Questions/answers rset = self._cw.execute('Any Q, QI, QP, QT, QTY, QPA ORDERBY QP ASC ' 'WHERE QQ is Questionnaire, QQ eid %(e)s, ' 'Q questionnaire QQ, Q identifier QI, Q position QP, Q text QT, ' 'Q type QTY, Q possible_answers QPA', {'e': entity.eid}) self.w(u'<xcede:items>') self.wview('xcede-item', rset) self.w(u'</xcede:items>') self.w(u'</xcede:step>')
def call(self): w = self.w rset, descr = self.cw_rset, self.cw_rset.description eschema = self._cw.vreg.schema.eschema labels = self.columns_labels(tr=False) w(u'<?xml version="1.0" encoding="%s"?>\n' % self._cw.encoding) w(u'<%s query="%s">\n' % (self.xml_root, xml_escape(rset.printable_rql()))) for rowindex, row in enumerate(self.cw_rset): w(u' <row>\n') for colindex, val in enumerate(row): etype = descr[rowindex][colindex] tag = labels[colindex] attrs = {} if '(' in tag: attrs['expr'] = tag tag = 'funccall' if val is not None and not eschema(etype).final: attrs['eid'] = val # csvrow.append(val) # val is eid in that case val = self._cw.view('textincontext', rset, row=rowindex, col=colindex) else: val = self._cw.view('final', rset, row=rowindex, col=colindex, format='text/plain') w(simple_sgml_tag(tag, val, **attrs)) w(u'\n </row>\n') w(u'</%s>\n' % self.xml_root)
def template_header(self, content_type, view=None, page_title='', additional_headers=()): page_title = page_title or view.page_title() additional_headers = additional_headers or view.html_headers() whead = self.whead self.write_doctype() whead(u'<meta http-equiv="content-type" content="%s; charset=%s"/>\n' % (content_type, self._cw.encoding)) whead(u'\n'.join(additional_headers) + u'\n') self.wview('htmlheader', rset=self.cw_rset) w = self.w whead(u'<title>%s</title>\n' % xml_escape(page_title)) w(u'<body>\n') w(u'<div id="page">') w(u'<table width="100%" border="0" id="mainLayout"><tr>\n') w(u'<td id="navColumnLeft">\n') self.topleft_header() boxes = list(self._cw.vreg['ctxcomponents'].poss_visible_objects( self._cw, rset=self.cw_rset, view=view, context='left')) if boxes: w(u'<div class="navboxes">\n') for box in boxes: box.render(w=w) self.w(u'</div>\n') w(u'</td>') w(u'<td id="contentColumn" rowspan="2">')
def display_form(self, entity): """ Generate the html code. """ # Get the json form json_data = json.load(entity.data) # Get the associated CWUpload entity # cwupload = entity.reverse_result_form[0] # Display a title self.w(u'<div class="page-header">') self.w(u'<h2>{0}</h2>'.format(xml_escape(entity.dc_title()))) self.w(u'</div>') self.w(u'<table class="upload-table">') # Display the form for label, attribute in json_data.iteritems(): self.w(u'<tr><td><b>{0}</b></td><td>{1}</td></tr>'.format( self._cw._(label), attribute)) # Link to the upload entity # self.w(u'<tr><td><b>{0}</b></td><td>{1}</td></tr>'.format( # self._cw._("Related upload"), cwupload.view("outofcontext"))) self.w(u'</table>')
def alternates(self): urlgetter = self._cw.vreg['components'].select_or_none( 'rss_feed_url', self._cw, rset=self.cw_rset) if urlgetter is not None: self.whead( u'<link rel="alternate" type="application/rss+xml" title="RSS feed" href="%s"/>\n' % xml_escape(urlgetter.feed_url()))
def call(self, view): self.set_request_content_type() self.template_header(self.content_type, view) w = self.w w(u'<div class="row-fluid">') w(u'<div class="span12" id="pageContent">') vtitle = self._cw.form.get('vtitle') if vtitle: w(u'<div class="vtitle">%s</div>\n' % xml_escape(vtitle)) # display entity type restriction component etypefilter = self._cw.vreg['components'].select_or_none( 'etypenavigation', self._cw, rset=self.cw_rset) if etypefilter and etypefilter.cw_propval('visible'): etypefilter.render(w=w) nav_html = UStringIO() if view and not view.handle_pagination: view.paginate(w=nav_html.write) w(nav_html.getvalue()) w(u'<div id="contentmain">\n') view.render(w=w) w(u'</div>\n') # closes id=contentmain w(nav_html.getvalue()) w(u'</div>\n' # closes id=pageContent u'</div>\n') # closes row-fluid self.template_footer(view)
def cell_call(self, row, col): w = self.w req = self._cw if req.ie_browser(): req.add_js('excanvas.js') req.add_js('jquery.sparkline.js') entity = self.cw_rset.get_entity(row, col) plot_type = "type : 'bar', barWidth : 5" if entity.is_constant: data = [entity.first] * 10 else: data = entity.array if len(data) > self._switch_to_line_threshold: data = self._resample(data, self._switch_to_line_threshold) plot_type = "type : 'line'" elif len(data) > self._downsample_threshold: data = self._resample(data, self._downsample_threshold) req.html_headers.add_onload(self.onload % { 'target': entity.eid, 'plot_type': plot_type }) content = u'<!-- %s -->' % xml_escape(u', '.join( unicode(elt) for elt in data)) w( tags.span(content, id='sparklinefor%s' % entity.eid, escapecontent=False))
def call(self, width=None, height=None): req = self._cw w = self.w if req.ie_browser(): req.add_js('excanvas.js') req.add_js(('jquery.flot.js', 'jquery.flot.selection.js', 'cubes.timeseries.js')) width = width or req.form.get('width', 700) height = height or req.form.get('height', 400) figid = u'figure%s' % req.varmaker.next() w( t.div(u'', id='main%s' % figid, style='width: %spx; height: %spx;' % (width, height))) w( t.div(u'', id='overview%s' % figid, style='width: %spx; height: %spx;' % (width, height / 3))) w(t.button(req._('Zoom reset'), id='reset', klass='validateButton')) plotdata = ("{label: '%s', data: %s}" % (xml_escape(ts.dc_title()), self.dump_plot(ts)) for ts in self.cw_rset.entities()) req.html_headers.add_onload(self.onload % { 'figid': figid, 'plotdata': ','.join(plotdata) })
def cell_call(self, row, col, **kwargs): entity = self.cw_rset.get_entity(row, col) th_sep = entity.thousands_separator if not th_sep: th_sep = self.noseparator else: th_sep = udata.name(th_sep) self.w( xml_escape( self._cw._( 'separators: decimal = %s, thousands = %s, csv = %s')) % (t.span(xml_escape(udata.name(entity.decimal_separator)), klass='highlight'), t.span(xml_escape(th_sep), klass='highlight'), t.span(xml_escape(udata.name(entity.csv_separator)), klass='highlight')))
def call(self, view=None): req = self._cw if hasattr(view, 'filter_box_context_info'): rset = view.filter_box_context_info()[0] else: rset = self.cw_rset # display multilines query as one line rql = rset is not None and rset.printable_rql() or req.form.get('rql', '') rql = rql.replace(u"\n", u" ") rql_suggestion_comp = self._cw.vreg['components'].select_or_none('rql.suggestions', self._cw) if rql_suggestion_comp is not None: # enable autocomplete feature only if the rql # suggestions builder is available self._cw.add_css('jquery.ui.css') self._cw.add_js(('cubicweb.ajax.js', 'jquery.ui.js')) self._cw.add_onload('$("#rql").autocomplete({source: "%s"});' % (req.build_url('json', fname='rql_suggest'))) self.w(u'''<div id="rqlinput" class="%s"><form action="%s"><fieldset> <input type="text" id="rql" name="rql" value="%s" title="%s" accesskey="q" class="searchField" /> ''' % (not self.cw_propval('visible') and 'hidden' or '', req.build_url('view'), xml_escape(rql), req._('full text or RQL query'))) if req.search_state[0] != 'normal': self.w(u'<input type="hidden" name="__mode" value="%s"/>' % ':'.join(req.search_state[1])) self.w(u'</fieldset></form></div>')
def cell_call(self, row, col, **kwargs): entity = self.cw_rset.complete_entity(row, col) self.w(entity.view('incontext')) searched = self.cw_rset.searched_text() if searched is None: return searched = searched.lower() highlighted = '<b>%s</b>' % searched for attr in entity.e_schema.indexable_attributes(): try: value = xml_escape( entity.printable_value(attr, format='text/plain').lower()) except TransformError as ex: continue except Exception: continue if searched in value: contexts = [] for ctx in value.split(searched): if len(ctx) > 30: contexts.append(u'...' + ctx[-30:]) else: contexts.append(ctx) value = u'\n' + highlighted.join(contexts) self.w(value.replace('\n', '<br/>'))
def cell_call(self, row, col): entity = self.cw_rset.get_entity(row, col) self.w(u'<div class="thumbnail row">') self.w(u'<div class="col-md-2">') self.w(u'<a href="#"><img alt="" src="%s"></a>' % entity.image_url) self.w(u'</div>') self.w(u'<div class="col-md-8">') self.w(u'<a href="%s">%s</a>' % (entity.absolute_url(), xml_escape(entity.dc_title()))) self.w(u'<div class="row">') self.w(u'%s <em>%s</em>' % (self._cw._('Type'), entity.type)) self.w(u' - ') self.w(u'%s <em>%s</em>' % (self._cw._('Format'), entity.format)) self.w(u'</div>') self.w(u'</div>') self.w(u'<div class="col-md-2">') self.w(u'''<button class="btn btn-danger" type="button" style="margin-top:8px" onclick="$('#info-%s').toggle()">%s</button>''' % (entity.eid, self._cw._('See more'))) self.w(u'</div>') self.w(u'<div class="col-md-10 well pull-right" id="info-%s" style="display:none">' % entity.eid) self.w(u'<dl class="dl-horizontal">') self.add_additional_infos(entity) if entity.description: self.w('<dt>%s</dt><dd>%s</dd>' % (self._cw._('Description'), entity.description)) if entity.has_data : data = entity.has_data[0] data.view('scan-data-view', w=self.w) self.w(u'</dl>') demo = self._cw.vreg.config.get('demo-site', False) if not demo: self.w(u'<a href="%s"><button class="btn btn-sm btn-primary" type="button">%s</button></a>' % (self._cw.build_url(vid='data-zip', rql='Any X WHERE X eid %s' % entity.eid), self._cw._('Download as a Zip file'))) self.w(u'</div>') self.w(u'</div>')
def call(self, **kwargs): self.w(u'<h2>%s</h2>' % self._cw._("Registry's content")) keys = sorted(self._cw.vreg) url = xml_escape(self._cw.url()) self.w(u'<p>%s</p>\n' % ' - '.join('<a href="%s#%s">%s</a>' % (url, key, key) for key in keys)) for key in keys: if key in ('boxes', 'contentnavigation'): # those are bw compat registries continue self.w(u'<h3 id="%s">%s</h3>' % (key, key)) if self._cw.vreg[key]: values = sorted(self._cw.vreg[key].iteritems()) self.wview('pyvaltable', pyvalue=[(key, xml_escape(repr(val))) for key, val in values]) else: self.w(u'<p>Empty</p>\n')
def publish(self, rset=None): job_id = self._cw.form['condor_job_id'] schedd_name = self._cw.form['condor_schedd_name'] errcode, output = remove(self._cw.vreg.config, schedd_name, job_id) raise Redirect( self._cw.build_url(vid='condor_jobs', __message=xml_escape(output.strip())))
def get_total(self, entity): """ Gives the table that contains the total. entity: Entity. Any entity of class Refund. Returns: Flowable (very likely a Table). """ _ = entity._cw._ lin_data = [] s = "<b>%s</b>" % xml_escape(_(u"To refund (EUR)")) lin_data.append(Paragraph(s, style_table_data)) s = u"<b>%s</b>" % format_number(entity.total, 2) lin_data.append(Paragraph(s, style_table_data_num)) # Builds the total table tot_table = Table([lin_data], [3.25 * cm, 2.75 * cm]) tot_table.setStyle( TableStyle([ ('ALIGN', (0, 0), (-1, -1), 'LEFT'), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('LEFTPADDING', (0, 0), (-1, -1), 0.2 * cm), ('RIGHTPADDING', (0, 0), (-1, -1), 0.2 * cm), ('TOPPADDING', (0, 0), (-1, -1), 0.2 * cm), ('BOTTOMPADDING', (0, 0), (-1, -1), 0.2 * cm), ('BOX', (0, 0), (-1, -1), 0.05 * cm, black), ('INNERGRID', (0, 0), (-1, -1), 0.02 * cm, black), ])) return tot_table
def _render_fields(self, fields, w, form): if form.parent_form is not None: entity = form.edited_entity values = form.form_previous_values qeid = eid_param('eid', entity.eid) cbsetstate = "setCheckboxesState('eid', %s, 'checked')" % \ xml_escape(json_dumps(entity.eid)) w(u'<tr class="%s">' % (entity.cw_row % 2 and u'even' or u'odd')) # XXX turn this into a widget used on the eid field w(u'<td>%s</td>' % checkbox('eid', entity.eid, checked=qeid in values)) for field in fields: error = form.field_error(field) if error: w(u'<td class="error">') self.render_error(w, error) else: w(u'<td>') if isinstance(field.widget, (fwdgs.Select, fwdgs.CheckBox, fwdgs.Radio)): field.widget.attrs['onchange'] = cbsetstate elif isinstance(field.widget, fwdgs.Input): field.widget.attrs['onkeypress'] = cbsetstate # XXX else w(u'<div>%s</div>' % field.render(form, self)) w(u'</td>\n') w(u'</tr>') else: self._main_display_fields = fields
def mk_action(self, title, url, escape=True, **kwargs): """factory function to create dummy actions compatible with the .format_actions method """ if escape: title = xml_escape(title) return self.box_action(self._action(title, url, **kwargs))
def wrap_object_form(self, group, oid, label, form): w = self.w w(u'<div class="component">') w(u'''<div class="componentLink"><a href="javascript:$.noop();" onclick="javascript:toggleVisibility('field_%(oid)s_%(group)s')" class="componentTitle">%(label)s</a>''' % { 'label': label, 'oid': oid, 'group': group }) w(u''' (<div class="openlink"><a href="javascript:$.noop();" onclick="javascript:openFieldset('fieldset_%(group)s')">%(label)s</a></div>)''' % { 'label': self._cw._('open all'), 'group': group }) w(u'</div>') docmsgid = '%s_%s_description' % (group, oid) doc = self._cw._(docmsgid) if doc != docmsgid: w(u'<div class="helper">%s</div>' % xml_escape(doc).capitalize()) w(u'</div>') w(u'<fieldset id="field_%(oid)s_%(group)s" class="%(group)s preferences hidden">' % { 'oid': oid, 'group': group }) w(form) w(u'</fieldset>')
def visit_system_message(self, node): backref_text = '' if len(node['backrefs']): backrefs = node['backrefs'] if len(backrefs) == 1: backref_text = '; <em>backlink</em>' else: i = 1 backlinks = [] for backref in backrefs: backlinks.append(str(i)) i += 1 backref_text = ('; <em>backlinks: %s</em>' % ', '.join(backlinks)) if node.hasattr('line'): line = ', line %s' % node['line'] else: line = '' a_start = a_end = '' error = u'System Message: %s%s/%s%s (%s %s)%s</p>\n' % ( a_start, node['type'], node['level'], a_end, self.encode(node['source']), line, backref_text) self.body.append( u'<div class="system-message"><b>ReST / HTML errors:</b>%s</div>' % xml_escape(error))
def build_unrelated_select_div(self, entity, rschema, role, is_cell=False, hidden=True): options = [] divid = 'div%s_%s_%s' % (rschema.type, role, entity.eid) selectid = 'select%s_%s_%s' % (rschema.type, role, entity.eid) if rschema.symmetric or role == 'subject': targettypes = rschema.objects(entity.e_schema) etypes = '/'.join( sorted(etype.display_name(self._cw) for etype in targettypes)) else: targettypes = rschema.subjects(entity.e_schema) etypes = '/'.join( sorted(etype.display_name(self._cw) for etype in targettypes)) etypes = uilib.cut( etypes, self._cw.property_value('navigation.short-line-size')) options.append('<option>%s %s</option>' % (self._cw._('select a'), etypes)) options += self._get_select_options(entity, rschema, role) options += self._get_search_options(entity, rschema, role, targettypes) relname, role = self._cw.form.get('relation').rsplit('_', 1) return u"""\ <div class="%s" id="%s"> <select id="%s" onchange="javascript: addPendingInsert(this.options[this.selectedIndex], %s, %s, '%s');"> %s </select> </div> """ % (hidden and 'hidden' or '', divid, selectid, xml_escape(json_dumps(entity.eid)), is_cell and 'true' or 'null', relname, '\n'.join(options))
def condor_status_section(self): w = self.w _ = self._cw._ with (h2(w)): w(_('Condor Status')) errcode, output = status(self._cw.vreg.config) with (pre(w)): w(xml_escape(output))
def template_header(self, content_type, view=None, page_title='', additional_headers=()): self._cw.html_headers.define_var('BASE_URL', self._cw.base_url()) self._cw.html_headers.define_var('DATA_URL', self._cw.datadir_url) w = self.whead # explictly close the <base> tag to avoid IE 6 bugs while browsing DOM w(u'<base href="%s"></base>' % xml_escape(self._cw.base_url())) w(u'<meta http-equiv="content-type" content="%s; charset=%s"/>\n' % (content_type, self._cw.encoding)) w(NOINDEX) w(NOFOLLOW) w(u'\n'.join(additional_headers) + u'\n') self.wview('htmlheader', rset=self.cw_rset) w(u'<title>%s</title>\n' % xml_escape(page_title))
def add_etype_button(req, etype, csscls='addButton right', **urlkwargs): vreg = req.vreg eschema = vreg.schema.eschema(etype) if eschema.has_perm(req, 'add'): url = vreg['etypes'].etype_class(etype).cw_create_url(req, **urlkwargs) return u'<a href="%s" class="%s">%s</a>' % (xml_escape(url), csscls, req.__('New %s' % etype)) return u''
def entity_call(self, entity, **kwargs): if entity.reverse_primary_email: self.w(u'<b>') if entity.alias: alias = entity.alias elif entity.reverse_use_email: alias = entity.reverse_use_email[0].dc_title() else: alias = None if alias: mailto = "mailto:%s <%s>" % (alias, entity.display_address()) else: mailto = "mailto:%s" % entity.display_address() self.w(u'<a href="%s">%s</a>' % (xml_escape(mailto), xml_escape(entity.display_address()))) if entity.reverse_primary_email: self.w(u'</b>')
def condor_queue_section(self): w = self.w _ = self._cw._ with (h2(w)): w(_('Condor Queue')) errcode, output = queue(self._cw.vreg.config) with (pre(w)): w(xml_escape(output))
def toggleable_relation_link(eid, nodeid, label='x'): """return javascript snippet to delete/undelete a relation between two entities """ js = u"javascript: togglePendingDelete('%s', %s);" % ( nodeid, xml_escape(json_dumps(eid))) return u'[<a class="handle" href="%s" id="handle%s">%s</a>]' % (js, nodeid, label)
def do_paginate(view, rset=None, w=None, show_all_option=True, page_size=None): """write pages index in w stream (default to view.w) and then limit the result set (default to view.rset) to the currently displayed page if we're not explicitly told to display everything (by setting __force_display in req.form) """ req = view._cw if rset is None: rset = view.cw_rset if w is None: w = view.w nav = req.vreg['components'].select_or_none('navigation', req, rset=rset, page_size=page_size, view=view) if nav: if w is None: w = view.w if req.form.get('__force_display'): # allow to come back to the paginated view params = dict(req.form) basepath = req.relative_path(includeparams=False) del params['__force_display'] url = nav.page_url(basepath, params) w(u'<div class="displayAllLink btn btn-small">' u'<a href="%s">%s</a></div>\n' % (xml_escape(url), req._('back to pagination (%s results)') % nav.page_size)) else: # get boundaries before component rendering start, stop = nav.page_boundaries() nav.render(w=w) params = dict(req.form) nav.clean_params(params) # make a link to see them all if show_all_option: basepath = req.relative_path(includeparams=False) params['__force_display'] = 1 params['__fromnavigation'] = 1 url = nav.page_url(basepath, params) w(u'<div class="displayAllLink btn btn-small">' u'<a href="%s">%s</a></div>\n' % (xml_escape(url), req._('show %s results') % len(rset))) rset.limit(offset=start, limit=stop - start, inplace=True)
def cell_call(self, row, col): entity = self.cw_rset.get_entity(row, col) rschema = self._cw.vreg.schema.rschema(entity.rtype.name) rdef = rschema.rdefs[(entity.stype.name, entity.otype.name)] constraints = [ xml_escape(str(c)) for c in getattr(rdef, 'constraints') ] self.w(u'<br/>'.join(constraints))
def call(self, id, klass, title=True, showmessage=True, showonload=True): w = self.w if not (showmessage or self._cw.message): showmessage = False stitle = ' ' if title: stitle = self._cw.property_value('ui.site-title') if stitle: stitle = xml_escape(stitle) config = self._cw.vreg.config if config['auth-mode'] != 'http': self.login_form(id, "loginModal", stitle, showmessage, showonload) # Cookie authentication if self._cw.https and config.anonymous_user()[0]: path = xml_escape(config['base-url'] + self._cw.relative_path()) w(u'<div class="loginMessage alert"><a href="%s">%s</a></div>\n' % (path, self._cw._('No account? Try public access at %s') % path))
def entity_call(self, entity): """element as an item for an xml feed""" entity.complete() source = entity.cw_source[0].name self.w(u'<%s eid="%s" cwuri="%s" cwsource="%s">\n' % (entity.cw_etype, entity.eid, xml_escape( entity.cwuri), xml_escape(source))) for rschema, attrschema in sorted( entity.e_schema.attribute_definitions()): attr = rschema.type if attr in ('eid', 'cwuri'): continue else: try: value = entity.cw_attr_cache[attr] except KeyError: # Bytes continue if value is None: self.w(u' <%s/>\n' % attr) else: if attrschema in SERIALIZERS: value = SERIALIZERS[attrschema](value) self.w(u' <%s>%s</%s>\n' % (attr, value, attr)) for relstr in self._cw.list_form_param('relation'): try: rtype, role = relstr.split('-') except ValueError: self.error('badly formated relation name %r', relstr) continue if role == 'subject': getrschema = entity.e_schema.subjrels elif role == 'object': getrschema = entity.e_schema.objrels else: self.error('badly formated relation name %r', relstr) continue if rtype not in getrschema: self.error('unexisting relation %r', relstr) continue self.w(u' <%s role="%s">\n' % (rtype, role)) self.wview('xmlrelateditem', entity.related(rtype, role, safe=True), 'null') self.w(u' </%s>\n' % rtype) self.w(u'</%s>\n' % (entity.e_schema))
def entity_call(self, entity): self._cw.add_js('cubicweb.edition.js') self._cw.add_css('cubicweb.acl.css') w = self.w _ = self._cw._ w(u'<h1><span class="etype">%s</span> <a href="%s">%s</a></h1>' % (entity.dc_type().capitalize(), xml_escape( entity.absolute_url()), xml_escape(entity.dc_title()))) # first show permissions defined by the schema self.w('<h2>%s</h2>' % _('Schema\'s permissions definitions')) self.permissions_table(entity.e_schema) self.w('<h2>%s</h2>' % _('Manage security')) # ownership information if self._cw.vreg.schema.rschema('owned_by').has_perm( self._cw, 'add', fromeid=entity.eid): self.owned_by_edit_form(entity) else: self.owned_by_information(entity)
def render_body(self, w): if self._cw.form.pop('__fromsearchbox', None): rql = self._cw.form.get('rql', '') else: rql = '' w(self.formdef % {'action': self._cw.build_url('view'), 'value': xml_escape(rql), 'id': self.cw_extra_kwargs.get('domid', 'tsearch') })
def cell_call(self, row, col): entity = self.cw_rset.get_entity(row, col) self.w(u'<div class="row">') self.w(u'<div class="col-md-2"></div>') self.w(u'<div class="col-md-8">') self.w(u'<h4><a href="%s">%s</a></h4>' % tuple(map(xml_escape, (entity.absolute_url(), entity.dc_title())))) self.w(u'%s :<em>%s</em>' % (xml_escape(self._cw._('subject')), entity.reverse_related_therapies[0].view('incontext'))) if entity.start_date: self.w(u' - %s :<em>%s</em>' % (xml_escape(self._cw._('start_date')), entity.start_date)) if entity.stop_date: self.w(u' - %s :<em>%s</em>' % (xml_escape(self._cw._('stop_date')), entity.stop_date)) if entity.therapy_for: self.w(u' - %s :<em>%s</em>' % (xml_escape(self._cw._('therapy_for')), entity.therapy_for[0].view('incontext'))) self.w(u'</div>') self.w(u'</div>')
def render(self, w): if self._cw.form.pop('__fromsearchbox', None): rql = self._cw.form.get('rql', '') else: rql = '' w(self.formdef % {'action': self._cw.build_url('view'), 'tabindex1': self._cw.next_tabindex(), 'value': xml_escape(rql), 'tabindex2': self._cw.next_tabindex()})
def bookmark_link(self, rset): req = self._cw bk_path = u'rql=%s' % req.url_quote(rset.printable_rql()) if req.form.get('vid'): bk_path += u'&vid=%s' % req.url_quote(req.form['vid']) bk_path = u'view?' + bk_path bk_title = req._('my custom search') linkto = u'bookmarked_by:%s:subject' % req.user.eid bkcls = req.vreg['etypes'].etype_class('Bookmark') bk_add_url = bkcls.cw_create_url(req, path=bk_path, title=bk_title, __linkto=linkto) bk_base_url = bkcls.cw_create_url(req, title=bk_title, __linkto=linkto) bk_link = u'<a cubicweb:target="%s" id="facetBkLink" href="%s">%s</a>' % ( xml_escape(bk_base_url), xml_escape(bk_add_url), req._('bookmark this search')) return self.bk_linkbox_template % bk_link
def format_link_content(self, startstr, stopstr): """Return text for a page link, where `startstr` and `stopstr` are the text for the lower/upper boundaries of the page. By default text are stripped down to :attr:`nb_chars` characters. """ text = u'%s - %s' % (startstr.lower()[:self.nb_chars], stopstr.lower()[:self.nb_chars]) return xml_escape(text)
def render_body(self, w): # Don't display search box title, just display the search box body if self._cw.form.pop('__fromsearchbox', None): rql = self._cw.form.get('rql', '') else: rql = '' w(self.formdef % {'action': self._cw.build_url('view'), 'tabindex1': self._cw.next_tabindex(), 'value': xml_escape(rql), 'searchlabel': self._cw._('Search')})
def cell_call(self, row, col): entity = self.cw_rset.complete_entity(row, col) ithumb = entity.cw_adapt_to('IThumbnail') if ithumb is not None: icon = xml_escape(ithumb.thumbnail_url()) else: icon = self._cw.uiprops['FILE_ICON'] title = xml_escape(entity.dc_title()) # .currently_displayed is None if we went directly to cell_call, # eg view called only for that entity, in which case we want # it to be considered as selected. if self.currently_displayed is None or entity.eid == self.currently_displayed: self.w(u'<a href="javascript:displayImg(%(eid)s)" title="%(title)s"><img id="img%(eid)s" ' u'class="selectedimg" alt="%(title)s" src="%(icon)s"/></a>' % {'eid':entity.eid, 'title':title,'icon':icon}) else: self.w(u'<a href="javascript:displayImg(%(eid)s)" title="%(title)s"><img id="img%(eid)s" ' 'alt="%(title)s" src="%(icon)s"/></a>' % {'eid':entity.eid, 'title':title,'icon':icon})
def do_paginate(view, rset=None, w=None, show_all_option=True, page_size=None): """write pages index in w stream (default to view.w) and then limit the result set (default to view.rset) to the currently displayed page if we're not explicitly told to display everything (by setting __force_display in req.form) """ req = view._cw if rset is None: rset = view.cw_rset if w is None: w = view.w nav = req.vreg['components'].select_or_none( 'navigation', req, rset=rset, page_size=page_size, view=view) if nav: if w is None: w = view.w if req.form.get('__force_display'): # allow to come back to the paginated view params = dict(req.form) basepath = req.relative_path(includeparams=False) del params['__force_display'] url = nav.page_url(basepath, params) w(u'<div class="displayAllLink">' u'<a href="%s">%s</a></div>\n' % (xml_escape(url), req._('back to pagination (%s results)') % nav.page_size)) else: # get boundaries before component rendering start, stop = nav.page_boundaries() nav.render(w=w) params = dict(req.form) nav.clean_params(params) # make a link to see them all if show_all_option: basepath = req.relative_path(includeparams=False) params['__force_display'] = 1 params['__fromnavigation'] = 1 url = nav.page_url(basepath, params) w(u'<div class="displayAllLink">' u'<a href="%s">%s</a></div>\n' % (xml_escape(url), req._('show %s results') % len(rset))) rset.limit(offset=start, limit=stop-start, inplace=True)
def render_content(self, w, **kwargs): entity = self.cw_rset.get_entity(0, 0) rset = self.get_values_rset() jsbind = self.add_jsbind(w) if rset: w(self._cw.view('jqplot-2col', tab_id='pill', rset=rset, jsbind=jsbind, title=xml_escape(entity.dc_title()), displayactions=True, actions=('print',), legend={'show': False}, width='100%')) else: w(u'<div>%s</div>' % self._cw._('No values available'))
def entity_call(self, entity): """element as an item for an xml feed""" entity.complete() assessment = entity.reverse_generates[0] if entity.reverse_generates else None questionnaire = entity.instance_of[0] # XXX studyID/visitID -> Assessment self.w(u'<xcede:data xsi:type="xcede:assessment_t" subjectID="%s">\n' % xml_escape(entity.concerns[0].identifier)) self.w(u'<xcede:name>%s</xcede:name>\n' % xml_escape(questionnaire.name)) self.w(u'<xcede:dataInstance validated="%s">\n' % entity.valid) if questionnaire.note: self.w(u'<xcede:assessmentInfo><xcede:description>%s</xcede:description></xcede:assessmentInfo>' % xml_escape(questionnaire.note)) rset = self._cw.execute('Any AV, QI, QP ORDERBY QP ASC WHERE A is Answer, A question Q, ' 'Q position QP, Q identifier QI, A value AV, A questionnaire_run QR, QR eid %(e)s', {'e': entity.eid}) for value, qid, qp in rset: self.w(u'<xcede:assessmentItem ID="%s"><xcede:value>%s</xcede:value></xcede:assessmentItem>\n' % (xml_escape(qid), value)) self.w(u'</xcede:dataInstance>\n') self.w(u'</xcede:data>\n')
def call(self, **kwargs): self.warning('[0.5.0] bootstrap.views.primary.BSRelatedView: move me in CW 3.18.0') if 'dispctrl' in self.cw_extra_kwargs: if 'limit' in self.cw_extra_kwargs['dispctrl']: limit = self.cw_extra_kwargs['dispctrl']['limit'] else: limit = self._cw.property_value('navigation.related-limit') list_limit = self.cw_extra_kwargs['dispctrl'].get('use_list_limit', 5) subvid = self.cw_extra_kwargs['dispctrl'].get('subvid', 'incontext') else: limit = list_limit = None subvid = 'incontext' if limit is None or self.cw_rset.rowcount <= limit: if self.cw_rset.rowcount == 1: self.wview(subvid, self.cw_rset, row=0) elif list_limit is None or 1 < self.cw_rset.rowcount <= list_limit: self.wview('csv', self.cw_rset, subvid=subvid) else: # bs customization begins self.wview('list', self.cw_rset, subvid=subvid, klass='list-unstyled') # bs customization ends # else show links to display related entities else: rql = self.cw_rset.printable_rql() rset = self.cw_rset.limit(limit) # remove extra entity if list_limit is None: self.wview('csv', rset, subvid=subvid) self.w(u'<a href="%s" class="see-all">%s</a>' % ( xml_escape(self._cw.build_url(rql=rql, vid='list', subvid=subvid)), self._cw._('see them all'))) else: self.w(u'<div>') # bs customization begins self.wview('list', rset, subvid=subvid, klass='list-unstyled') # bs customization ends self.w(u'<a href="%s" class="see-all">%s</a>' % ( xml_escape(self._cw.build_url(rql=rql, vid='list', subvid=subvid)), self._cw._('see them all'))) self.w(u'</div>')
def display_header(self, entity): w = self.w w(u'<div class="well">') w(u'<div class="page-header">') w(u'<h2>%s</h2>' % xml_escape(entity.dc_title())) w(u'</div>') w(u'<dl class="dl-horizontal">') for label, attribute in self.iterate_attributes(entity): if attribute: w(u'<dt>%s</dt><dd>%s</dd>' % (self._cw._(label), attribute)) w(u'</dl>') # Additional header self.display_additional_header(entity) # Data self.display_data_table(entity) w(u'</div>')
def render(self, w, **kwargs): if 'ctx-entity-tabs' in self._cw.vreg: tabs = list(self._cw.vreg['ctx-entity-tabs'].possible_objects(self._cw, rset=self.cw_rset)) else: tabs = [] if tabs: w(u'<ul class="nav nav-pills" id="entity-tab">') # Main info w(u'<li class="active"><a href="#entity-mainview" data-toggle="pill" ' 'class="bnt btn-warning">%s</a></li>' % xml_escape(self._cw._('Main info'))) # Other tabs for tab in tabs: w(u'<li><a href="#%s" data-toggle="pill" class="bnt btn-warning">%s</a></li>' % (tab.__regid__, tab.get_title())) w(u'</ul>')
def cell_call(self, row, col): entity = self.cw_rset.complete_entity(row, col) self.w(u'<item>\n') self.w(u'<guid isPermaLink="true">%s</guid>\n' % xml_escape(entity.absolute_url())) self.render_title_link(entity) root = entity.cw_adapt_to('ITree').root() description = entity.dc_description(format='text/html') + \ self._cw._(u'about') + \ u' <a href=%s>%s</a>' % (root.absolute_url(), root.dc_title()) self._marker('description', description) self._marker('dc:date', entity.dc_date(self.date_format)) self.render_entity_creator(entity) self.w(u'</item>\n') self.wview('rssitem', entity.related('comments', 'object'), 'null')
def entity_call(self, entity): """element as an item for an xml feed""" entity.complete() self.w(u'<project ID="%s">\n' % xml_escape(entity.name)) self.w(u'<projectInfo>\n') self.w(u'<subjectGroupList>\n') groups = {} rset = self._cw.execute('Any GI, SIS WHERE S related_groups G, S related_studies SI, ' 'SI eid %(e)s, G identifier GI, S identifier SIS', {'e': entity.eid}) for gi, si in rset: groups.setdefault(gi, []).append(si) for gi, sis in groups.iteritems(): self.w(u'<subjectGroup ID="%s">\n' % gi) for si in sis: self.w(u'<subjectID>%s</subjectID>\n' % si) self.w(u'</subjectGroup>\n') self.w(u'</subjectGroupList>\n') self.w(u'</projectInfo>\n') self.w(u'</project>\n')
def render(self, form, field=None, renderer=None): label = form._cw._(self.label) attrs = self.attrs.copy() if self.cwaction: assert self.onclick is None attrs['onclick'] = "postForm('__action_%s', \'%s\', \'%s\')" % ( self.cwaction, self.label, form.domid) elif self.onclick: attrs['onclick'] = self.onclick if self.name: attrs['name'] = self.name if self.setdomid: attrs['id'] = self.name if self.settabindex and not 'tabindex' in attrs: attrs['tabindex'] = form._cw.next_tabindex() if self.icon: img = u'<i class="%s"> </i>' % self.icon else: img = u'' return tags.button(img + xml_escape(label), escapecontent=False, value=label, type=self.type, **attrs)