def format_element(bfo, only_public_records=1, addthis_id=CFG_BIBFORMAT_ADDTHIS_ID): """ Prints the AddThis box from the <http://www.addthis.com/> service. @param only_public_records: if set to 1 (the default), prints the box only if the record is public (i.e. if it belongs to the root colletion and is accessible to the world). @param addthis_id: the pubid API parameter as provided by the service (e.g. ra-4ff80aae118f4dad). This can be set at the repository level in the variable CFG_BIBFORMAT_ADDTHIS_ID in invenio(-local).conf """ if not addthis_id: return "" if int(only_public_records) and not record_public_p(bfo.recID): return "" return """\ <!-- AddThis Button BEGIN --> <div class="addthis_toolbox addthis_default_style "> <a class="addthis_button_preferred_1"></a> <a class="addthis_button_preferred_2"></a> <a class="addthis_button_preferred_3"></a> <a class="addthis_button_preferred_4"></a> <a class="addthis_button_compact"></a> <a class="addthis_counter addthis_bubble_style"></a> </div> <script type="text/javascript">var addthis_config = {"data_track_clickback":true};</script> <script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#pubid=%(addthis_id)s"></script> <!-- AddThis Button END --> """ % {'addthis_id': addthis_id}
def test_article_in_unreleased_issue(self): """webjournal - check access to unreleased article""" # Record is not public self.assertEqual(record_public_p(112), False) # Unreleased article is not visible to guest error_messages = test_web_page_content( CFG_SITE_URL + '/journal/AtlantisTimes/2009/06/News/112', expected_text=["A naturalist's voyage around the world"], unexpected_text=['Galapagos Archipelago']) if error_messages: self.fail(merge_error_messages(error_messages)) # Unreleased article is visible to editor error_messages = test_web_page_content( CFG_SITE_URL + '/journal/AtlantisTimes/2009/06/News/112', username='******', password='******', expected_text=['Galapagos Archipelago'], unexpected_text=[ 'This file is restricted', 'You are not authorized' ]) if error_messages: self.fail(merge_error_messages(error_messages))
def test_article_in_unreleased_issue(self): """webjournal - check access to unreleased article""" # Record is not public self.assertEqual(record_public_p(112), False) # Unreleased article is not visible to guest error_messages = test_web_page_content( CFG_SITE_URL + "/journal/AtlantisTimes/2009/06/News/112", expected_text=["A naturalist's voyage around the world"], unexpected_text=["Galapagos Archipelago"], ) if error_messages: self.fail(merge_error_messages(error_messages)) # Unreleased article is visible to editor error_messages = test_web_page_content( CFG_SITE_URL + "/journal/AtlantisTimes/2009/06/News/112", username="******", password="******", expected_text=["Galapagos Archipelago"], unexpected_text=["This file is restricted", "You are not authorized"], ) if error_messages: self.fail(merge_error_messages(error_messages))
def test_restricted_article_in_released_issue(self): """webjournal - check access to restricted article in released issue""" # Record is not public self.assertEqual(record_public_p(112), False) # Released article (even if restricted) is visible to guest error_messages = test_web_page_content(CFG_SITE_URL + '/journal/AtlantisTimes/2009/03/Science/111' , expected_text=["Scissor-beak"], unexpected_text=["A naturalist's voyage around the world"]) if error_messages: self.fail(merge_error_messages(error_messages))
def test_restricted_article_in_released_issue(self): """webjournal - check access to restricted article in released issue""" # Record is not public self.assertEqual(record_public_p(112), False) # Released article (even if restricted) is visible to guest error_messages = test_web_page_content( CFG_SITE_URL + '/journal/AtlantisTimes/2009/03/Science/111', expected_text=["Scissor-beak"], unexpected_text=["A naturalist's voyage around the world"]) if error_messages: self.fail(merge_error_messages(error_messages))
def detailed_record_container_top( self, recid, tabs, ln=CFG_SITE_LANG, show_similar_rec_p=True, creationdate=None, modificationdate=None, show_short_rec_p=True, citationnum=-1, referencenum=-1, discussionnum=-1, ): """Prints the box displayed in detailed records pages, with tabs at the top. Returns content as it is if the number of tabs for this record is smaller than 2 Parameters: @param recid: int - the id of the displayed record @param tabs: ** - the tabs displayed at the top of the box. @param ln: *string* - the language of the page in which the box is displayed @param show_similar_rec_p: *bool* print 'similar records' link in the box @param creationdate: *string* - the creation date of the displayed record @param modificationdate: *string* - the last modification date of the displayed record @param show_short_rec_p: *boolean* - prints a very short version of the record as reminder. @param citationnum: show (this) number of citations in the citations tab @param referencenum: show (this) number of references in the references tab @param discussionnum: show (this) number of comments/reviews in the discussion tab """ from invenio.search_engine import record_public_p # load the right message language _ = gettext_set_language(ln) # Prepare restriction flag restriction_flag = "" if not record_public_p(recid): restriction_flag = '<div class="restrictedflag"><span>%s</span></div>' % _("Restricted") # If no tabs, returns nothing (excepted if restricted) if len(tabs) <= 1: return restriction_flag # Build the tabs at the top of the page out_tabs = "" if len(tabs) > 1: first_tab = True for (label, url, selected, enabled) in tabs: addnum = "" if (citationnum > -1) and url.count("/citation") == 1: addnum = "(" + str(citationnum) + ")" if (referencenum > -1) and url.count("/references") == 1: addnum = "(" + str(referencenum) + ")" if (discussionnum > -1) and url.count("/comments") == 1: addnum = "(" + str(discussionnum) + ")" css_class = [] if selected: css_class.append("on") if first_tab: css_class.append("first") first_tab = False if not enabled: css_class.append("disabled") css_class = ' class="%s"' % " ".join(css_class) if not enabled: out_tabs += "<li%(class)s><a>%(label)s %(addnum)s</a></li>" % { "class": css_class, "label": label, "addnum": addnum, } else: out_tabs += '<li%(class)s><a href="%(url)s">%(label)s %(addnum)s </a></li>' % { "class": css_class, "url": url, "label": label, "addnum": addnum, } if out_tabs != "": out_tabs = ( """ <div class="detailedrecordtabs"> <div> <ul class="detailedrecordtabs">%s</ul> <div id="tabsSpacer" style="clear:both;height:0px"> </div></div> </div>""" % out_tabs ) # Add the clip icon and the brief record reminder if necessary record_brief = "" if show_short_rec_p: record_brief = format_record(recID=recid, of="hs", ln=ln) record_brief = """<div id="detailedrecordshortreminder"> <div id="clip"> </div> <div id="HB"> %(record_brief)s </div> </div> <div style="clear:both;height:1px"> </div> """ % { "record_brief": record_brief } # Print the content out = """ <div class="detailedrecordbox"> %(tabs)s <div class="detailedrecordboxcontent"> <div class="top-left-folded"></div> <div class="top-right-folded"></div> <div class="inside"> <!--<div style="height:0.1em;"> </div> <p class="notopgap"> </p>--> %(record_brief)s """ % { "tabs": out_tabs, "record_brief": record_brief, } out = restriction_flag + out return out
def format_element(bfo, only_public_records=1, sites="linkedin,twitter,facebook,google,delicious,sciencewise"): """ Return a snippet of JavaScript needed for displaying a bookmark toolbar @param only_public_records: if set to 1 (the default), prints the box only if the record is public (i.e. if it belongs to the root colletion and is accessible to the world). @param sites: which sites to enable (default is 'linkedin,twitter,facebook,google,delicious,sciencewise'). This should be a comma separated list of strings. Valid values are available on: <http://keith-wood.name/bookmark.html#sites> Note that 'sciencewise' is an ad-hoc service that will be displayed only in case the record has an arXiv reportnumber and will always be displayed last. """ if int(only_public_records) and not record_public_p(bfo.recID): return "" sitelist = sites.split(',') sitelist = [site.strip().lower() for site in sitelist] sciencewise = False if 'sciencewise' in sitelist: sciencewise = True sitelist.remove('sciencewise') sites_js = ", ".join("'%s'" % site for site in sitelist) title = bfo.field('245__a') description = bfo.field('520__a') sciencewise_script = "" if sciencewise: reportnumber = get_arxiv_reportnumber(bfo) sciencewise_url = "" if reportnumber: sciencewise_url = create_sciencewise_url(reportnumber) if not sciencewise_url and CFG_CERN_SITE: sciencewise_url = create_sciencewise_url(bfo.recID, cds=True) if sciencewise_url: sciencewise_script = """\ $.bookmark.addSite('sciencewise', 'ScienceWise.info', '%(siteurl)s/img/sciencewise.png', 'en', 'bookmark', '%(url)s'); $('#bookmark_sciencewise').bookmark({sites: ['sciencewise']}); """ % { 'siteurl': CFG_SITE_URL, 'url': sciencewise_url.replace("'", r"\'"), } url = '%(siteurl)s/%(record)s/%(recid)s' % \ {'recid': bfo.recID, 'record': CFG_SITE_RECORD, 'siteurl': CFG_SITE_URL} args = parse_url_string(bfo.user_info['uri']) journal_name = args["journal_name"] if journal_name and \ (journal_name in [info.get('journal_name', '') for info in get_journals_ids_and_names()]): # We are displaying a WebJournal article: URL is slightly different url = make_journal_url(bfo.user_info['uri']) return """\ <!-- JQuery Bookmark Button BEGIN --> <div id="bookmark"></div><div id="bookmark_sciencewise"></div> <style type="text/css"> #bookmark_sciencewise, #bookmark { float: left; } #bookmark_sciencewise li { padding: 2px; width: 25px} #bookmark_sciencewise ul, #bookmark ul { list-style-image: none; } </style> <script type="text/javascript" src="%(siteurl)s/js/jquery.bookmark.min.js"></script> <style type="text/css">@import "%(siteurl)s/css/jquery.bookmark.css";</style> <script type="text/javascript">// <![CDATA[ %(sciencewise)s $('#bookmark').bookmark({ sites: [%(sites_js)s], icons: '%(siteurl)s/img/bookmarks.png', url: '%(url)s', addEmail: true, title: "%(title)s", description: "%(description)s" }); // ]]> </script> <!-- JQuery Bookmark Button END --> """ % { 'siteurl': CFG_SITE_URL, 'sciencewise': sciencewise_script, 'title': escape_javascript_string(title, escape_for_html=False, escape_CDATA=True), 'description': escape_javascript_string(description, escape_for_html=False, escape_CDATA=True), 'sites_js': sites_js, 'url': url, }
def detailed_record_container_top(self, recid, tabs, ln=CFG_SITE_LANG, show_similar_rec_p=True, creationdate=None, modificationdate=None, show_short_rec_p=True, citationnum=-1, referencenum=-1, discussionnum=-1): """Prints the box displayed in detailed records pages, with tabs at the top. Returns content as it is if the number of tabs for this record is smaller than 2 Parameters: @param recid: int - the id of the displayed record @param tabs: ** - the tabs displayed at the top of the box. @param ln: *string* - the language of the page in which the box is displayed @param show_similar_rec_p: *bool* print 'similar records' link in the box @param creationdate: *string* - the creation date of the displayed record @param modificationdate: *string* - the last modification date of the displayed record @param show_short_rec_p: *boolean* - prints a very short version of the record as reminder. @param citationnum: show (this) number of citations in the citations tab @param referencenum: show (this) number of references in the references tab @param discussionnum: show (this) number of comments/reviews in the discussion tab """ from invenio.search_engine import record_public_p # load the right message language _ = gettext_set_language(ln) # Prepare restriction flag restriction_flag = '' if not record_public_p(recid): restriction_flag = '<div class="restrictedflag"><span>%s</span></div>' % _( "Restricted") # If no tabs, returns nothing (excepted if restricted) if len(tabs) <= 1: return restriction_flag # Build the tabs at the top of the page out_tabs = '' if len(tabs) > 1: first_tab = True for (label, url, selected, enabled) in tabs: addnum = "" if (citationnum > -1) and url.count("/citation") == 1: addnum = "(" + str(citationnum) + ")" if (referencenum > -1) and url.count("/references") == 1: addnum = "(" + str(referencenum) + ")" if (discussionnum > -1) and url.count("/comments") == 1: addnum = "(" + str(discussionnum) + ")" css_class = [] if selected: css_class.append('on') if first_tab: css_class.append('first') first_tab = False if not enabled: css_class.append('disabled') css_class = ' class="%s"' % ' '.join(css_class) if not enabled: out_tabs += '<li%(class)s><a>%(label)s %(addnum)s</a></li>' % \ {'class':css_class, 'label':label, 'addnum':addnum} else: out_tabs += '<li%(class)s><a href="%(url)s">%(label)s %(addnum)s </a></li>' % \ {'class':css_class, 'url':url, 'label':label, 'addnum':addnum} if out_tabs != '': out_tabs = ''' <div class="detailedrecordtabs"> <div> <ul class="detailedrecordtabs">%s</ul> <div id="tabsSpacer" style="clear:both;height:0px"> </div></div> </div>''' % out_tabs # Add the clip icon and the brief record reminder if necessary record_brief = '' if show_short_rec_p: record_brief = format_record(recID=recid, of='hs', ln=ln) record_brief = '''<div id="detailedrecordshortreminder"> <div id="clip"> </div> <div id="HB"> %(record_brief)s </div> </div> <div style="clear:both;height:1px"> </div> ''' % { 'record_brief': record_brief } # Print the content out = """ <div class="detailedrecordbox"> %(tabs)s <div class="detailedrecordboxcontent"> <div class="top-left-folded"></div> <div class="top-right-folded"></div> <div class="inside"> <!--<div style="height:0.1em;"> </div> <p class="notopgap"> </p>--> %(record_brief)s """ % { 'tabs': out_tabs, 'record_brief': record_brief } out = restriction_flag + out return out
def format_element(bfo, only_public_records=1): """ Return a small bookmark element to share record on social.cern.ch @param only_public_records: if set to 1 (the default), prints the box only if the record is public (i.e. if it belongs to the root colletion and is accessible to the world). """ if int(only_public_records) and not record_public_p(bfo.recID): return "" # Reuse bfe_title element to get the record's title title = bfe_title.format_element(bfo) url = '%(siteurl)s/%(record)s/%(recid)s' % \ {'recid': bfo.recID, 'record': CFG_SITE_RECORD, 'siteurl': CFG_SITE_URL} bookmark_template = """ <style type="text/css"> /* Some styling for the button */ a.social-button{ background: #fff; border: 1px solid #ddd; float: left; font-size: 12px; line-height: 14px; padding: 2px; text-decoration: none; } .social-button img{ float: left; margin-right: 5px; } .social-button:hover{ background: #ddd; border: 1px solid #bbb; text-decoration: none; } .social-header { margin: 0 auto; } .social-text { margin: 10px auto; } .social-remarks { margin: 5px auto; } .social-send { width: 50%%; left: 25%%; } </style> <link rel="stylesheet" href="/img/overlay.css" type="text/css" /> <script src="/js/overlay.min.js" type="text/javascript"></script> <script type="text/javascript" src="%(siteurl)s/js/SP.RequestExecutor.js"></script> <script type="text/javascript">// <![CDATA[ ///////////////////////////// SOCIAL INTEGRATION FUNCTIONS /////////////// //Taken from https://espace2013.cern.ch/webservices-help/webauthoring/AdvancedAuthoring/Pages/IntegrateSocial_API.aspx function successHandler(data){ console.log("Success"); console.log(arguments); console.log(JSON.parse(data)); } function errorHandler(){ console.log("Error"); console.log(arguments); } function postOnSocial(message){ //Write into social, first get the formDigest value that will be used on the callback 'postMessage' function executeRestCall(formDigestUrl, "POST", null, postMessage, errorHandler, message); } function postMessage(data, message){ //Get the Digest token from the RestCall var result = JSON.parse(data); var formDigest = result.d.GetContextWebInformation.FormDigestValue; var xhr = createCORSRequest("POST", myFeedManagerEndpoint + "my/Feed/Post"); xhr.onload = function () { if(this.status == 200){ // If the operation succeeds... than the feed has been updated. // Display success message in the magnific popup $('.social-header').width('110').text('Message posted !'); $('.social-text').remove(); $('.social-send').disabled = false $('.social-send').text('Close'); $('.social-remarks').remove(); // Unbind 'send' event and bind 'close' event to the button $(document).off('click', '.social-send'); $('.social-send').click( function() { $('.mfp-close').click(); }); } else { // We sent the request correctly but there has been a problem // Display error message in the magnific popup $('.social-header').width('100').text('Error !'); $('.social-text').remove(); $('.social-send').disabled = false $('.social-send').text('Close'); $('.social-remarks').text('Please reload the page and try again (make sure you are logged in on social.cern.ch)') // Unbind 'send' event and bind 'close' event to the button $(document).off('click', '.social-send'); $('.social-send').click( function() { $('.mfp-close').click(); }); } }; //Set variables on the request object xhr.withCredentials = true; xhr.setRequestHeader("X-RequestDigest", formDigest); xhr.setRequestHeader("content-type", "application/json; charset=utf-8; odata=verbose"); // Creating the data for the post // Those 6 backslashes below are to generate 2 backslashes in the REST request var data = " { 'restCreationData':{ " + " '__metadata':{ 'type':'SP.Social.SocialRestPostCreationData'}, " + " 'ID': null, " + " 'creationData':{ " + " '__metadata':{'type':'SP.Social.SocialPostCreationData' }, " + " 'ContentItems':{ " + " 'results': [ " + " { " + " '__metadata' : {'type':'SP.Social.SocialDataItem' }, " + " 'Text':'%(record_url)s'," + " 'Uri':'%(record_url)s'," + " 'ItemType':'1'" + " }, " + " { " + " '__metadata' : {'type':'SP.Social.SocialDataItem' }, " + " 'AccountName':'CERN\\\\\\\\cdssocial'," + " 'ItemType':'0'" + " } " + " ] " + " }, " + " 'ContentText': '" + message + "', " + " 'UpdateStatusText':false " + " } " + " }}"; xhr.send(data); // Uploads the message } // This function authenticate the User on Social (transparently to the User) function authenticateOnSocial(inputFunction){ var executor = new SP.RequestExecutor(requestExecutorSite); executor.executeAsync({ url: formDigestUrl, method: "GET", headers: { "Accept": "application/json; odata=verbose", "Access-Control-Allow-Origin": "*", }, dataType: "json", error: function (xhr, ajaxOptions, thrownError) { // This function will be executed always. It is not an actual 'error' situation. try{ // After the authentication completes we use the function passed in input, that will contain the calls for any other function on Social if(inputFunction !== null && inputFunction !== undefined){ inputFunction(); } }catch(e){ console.log("Error: input function parameter in the authentication function is not valid."); return; } }, }); //End of executor.executeAsync } function createCORSRequest(method, url) { var xhr = new XMLHttpRequest(); if ("withCredentials" in xhr) { // Check if the XMLHttpRequest object has a "withCredentials" property. // "withCredentials" only exists on XMLHTTPRequest2 objects. xhr.open(method, url, true); } else if (typeof XDomainRequest != "undefined") { // Otherwise, check if XDomainRequest. // XDomainRequest only exists in IE, and is IE's way of making CORS requests. xhr = new XDomainRequest(); xhr.open(method, url); } else { // Otherwise, CORS is not supported by the browser. xhr = null; } if(xhr !== null){ // if the CORS is supported... xhr.withCredentials = true; xhr.setRequestHeader("accept", "application/json; odata=verbose"); } return xhr; } function executeRestCall(url, method, data, onSucc, onError, extra) { var xhr = createCORSRequest(method, url); if (!xhr) { console.log('CORS not supported'); throw new Error('CORS not supported'); } else{ xhr.onload = function () { onSucc(xhr.responseText, extra); // passing the parameters and the results of the RESTcall to the 'onSucc' pointed function }; xhr.onerror = onError; if (data !== null && data !== undefined && data !== ''){ xhr.send(data); }else{ xhr.send(); } } } ///////////////////////////// END OF SOCIAL INTEGRATION FUNCTIONS //////// // Initial config variables for social.cern.ch // var socialUrl = "https://social-dev.cern.ch"; var socialUrl = "https://social.cern.ch"; var requestExecutorSite = socialUrl + "/_layouts/15/AppWebProxy.aspx"; var myFeedManagerEndpoint = socialUrl + "/_api/social.feed/"; var formDigestUrl = socialUrl + "/_api/contextinfo"; jQuery.support.cors = true; // Used for createCORSRequest() function createMagnificPopup() { $('.social-button').magnificPopup({ items:{ src:'<div class="social-popup overlay-white oc-content overlay-white-500">\ <h3 class="social-header">The following message will be posted:</h3>\ <textarea class="social-text">%(title)s %(record_url)s via @CDS Social</textarea>\ <div class="social-remarks"><span>Please make sure that you have an account on social.cern.ch !</span></div>\ <button type="buton" class="social-send">Post !</button>\ </div>', type: 'inline' } }); // $.click won't work, because .social-send button is created dynamically // de-attach other callbacks first $(document).off('click', '.social-send'); $(document).on('click', '.social-send', function(){ // Replace the record's url and @CDS Social with placeholders var message = $('.social-text').val() var newMessage = message.replace('%(record_url)s', '{0}') var newMessage = newMessage.replace('@CDS Social', '@{1}') // Disable the button and put a loader image inside $('.social-send').disabled = true $('.social-send').html('<img src="../img/loading.gif" style="background: none repeat scroll 0%% 0%% transparent;"/>') authenticateOnSocial(function(){ postOnSocial(newMessage); }); }); } jQuery( document ).ready(function() { // Determine if user is logged in or not based on the existence of // either 'cern-account' class or 'cern-signout' if($('.cern-account').length) { // User NOT logged in $('.social-button').click(function(){ alert('You have to be signed in to do this!'); }); } else if($('.cern-signout').length) { // User logged in $('.social-button').click(function(){ createMagnificPopup(); }); // attach the magnific popup now createMagnificPopup(); } else { $('.social-button').click(function(){ alert('There was an error, please reload the page and try again.\ If the error still occurs, please contact [email protected]'); }); } }); // ]]> </script> <a href="javascript:void(0)" class="social-button"> <img src="/img/social-logo.png"> Share on social.cern.ch </a> """ % { 'siteurl': CFG_SITE_URL, 'record_url': url, 'title': title.replace("'", "\\'") } return bookmark_template