Random alert text and pop up only once - cookies

I'm try to write up code that will allow me to create a message with text that randomly displays one of three messages. In addition, this message will appear as an alert after you click a button. I now want to also program the button so it will only appear once per user. I've been able to make the random text part work, but not the one-time pop up feature. Let me know what I should do! Below is my code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Random thingy</title>
<script language type="text/javascript">
<!--
function getMessage() {
var ar = new Array(20)
ar[0] = "your assignment will be GRADED"
ar[1] = "your assignment will be UNGRADED"
ar[2] = "your assignment will be FUN"
// add as many more that you can stand but make
// sure you update the value '7' in the alert box
var now = new Date()
var sec = now.getSeconds()
alert("Your Grading Scheme:\n\n" + ar[sec % 3])
}
<!-- Begin
var expDays = 1; // number of days the cookie should last
var page = "only-popup-once.html";
var windowprops = "width=300,height=200,location=no,toolbar=no,menubar=no,scrollbars=no,resizable=yes";
function GetCookie (name) {
var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
while (i < clen) {
var j = i + alen;
if (document.cookie.substring(i, j) == arg)
return getCookieVal (j);
i = document.cookie.indexOf(" ", i) + 1;
if (i == 0) break;
}
return null;
}
function SetCookie (name, value) {
var argv = SetCookie.arguments;
var argc = SetCookie.arguments.length;
var expires = (argc > 2) ? argv[2] : null;
var path = (argc > 3) ? argv[3] : null;
var domain = (argc > 4) ? argv[4] : null;
var secure = (argc > 5) ? argv[5] : false;
document.cookie = name + "=" + escape (value) +
((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
((path == null) ? "" : ("; path=" + path)) +
((domain == null) ? "" : ("; domain=" + domain)) +
((secure == true) ? "; secure" : "");
}
function DeleteCookie (name) {
var exp = new Date();
exp.setTime (exp.getTime() - 1);
var cval = GetCookie (name);
document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();
}
var exp = new Date();
exp.setTime(exp.getTime() + (expDays*24*60*60*1000));
function amt(){
var count = GetCookie('count')
if(count == null) {
SetCookie('count','1')
return 1
}
else {
var newcount = parseInt(count) + 1;
DeleteCookie('count')
SetCookie('count',newcount,exp)
return count
}
}
function getCookieVal(offset) {
var endstr = document.cookie.indexOf (";", offset);
if (endstr == -1)
endstr = document.cookie.length;
return unescape(document.cookie.substring(offset, endstr));
}
function checkCount() {
var count = GetCookie('count');
if (count == null) {
count=1;
SetCookie('count', count, exp);
alert('MESSAGE');
}
else {
count++;
SetCookie('count', count, exp);
}
}
// End -->
</script>
</head>
<body onLoad="getMessage(); checkCount()">
<form>
<input type="button" name="again" value="Your Self-Assessment Grading Scheme. Click To Find Out." onClick="getMessage()">
</form>
</body>
</html>

Related

Finding text between tag <a> (regex with variable)

function Selection () {
if (typeof window.getSelection != "undefined") {
var sel = window.getSelection();
if (sel.rangeCount) {
var container = document.createElement("div");
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
container.appendChild(sel.getRangeAt(i).cloneContents());
}
html = container.innerHTML;
}
} else if (typeof document.selection != "undefined") {
if (document.selection.type == "Text") {
html = document.selection.createRange().htmlText;
}
}
var result = html.indexOf("href");
if (result != -1) {
window.getSelection().empty();
window.getSelection().removeAllRanges();
} else {
var textofclassText = $('.text').html();
//var patt1 = /id=\"load([\s\S]*?)+[selectedTexthtml]/g;
var result_2;
//var result_2 = textofclassText.search(patt1);
if(result_2 != "null") {
window.getSelection().empty();
window.getSelection().removeAllRanges();
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<div class="text" onmouseup="Selection()">
You
<br><a class="good" data-id="3" href="#load" id="load3">are very </a> important for us.
<br>So we're offering you
<br><a class="good" data-id="4" href="#load" id="load4"> win-win</a> option.
<br>You will get 2 refrigerators if you buy one
</div>
</body>
</html>
I need to remove selection if the selected text contains "a" tag. If I start to select link-text from left I will get only text "are very", so I need to find first match in all class ".text". I can't get how to use variable in that regex, because when I try to build string from variables it doesn't work.
var patt1 = new RegExp("id=\"load([\s\S]*?)" + html, "g");
var result = textofclassText.search(patt1);

Replacing Google Doc text with Spreadsheet Data using RegEx

I am making a merge code to take data from my spreadsheet and populate merge tags in a Google Doc. The part of the code I am unable to write correctly is the part that writes the tags back to the Google Doc. I have been able to locate the tags but the code doesn't replace them.
Here is what I've written so far.
function mergeApplication() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Merge Data");
var range = sheet.getActiveRange();
var formSheet = ss.getSheetByName("Form Responses");
var lastRow = formSheet.getLastRow();
var lastColumn = sheet.getMaxColumns();
function checkAndComplete() {
var urlColumn = lastColumn;
var checkColumn = (urlColumn - 1);
var checkRange = sheet.getRange(2, checkColumn, (lastRow - 1), 1);
var check = checkRange.getBackgrounds();
var red = "#ff0404";
var yellow = "#ffec0a";
var green = "#3bec3b";
for (var i = 0; i < check.length; i++) {
if (check[i] == green) {
continue;
} else {
var statusCell = sheet.getRange((i+2), checkColumn, 1, 1);
var urlCell = sheet.getRange((i+2), urlColumn, 1, 1);
var dataRow = sheet.getRange((i+2), 1, 1, (lastColumn - 2));
function mergeTasks() {
function docCreator() {
// var templateConditionRange = sheet.getRange((i+2), column);
// var templateConditionCheck = templateConditionRange.getValues();
var docTemplate1 = DriveApp.getFileById(id);
// var docTemplate2 = DriveApp.getFileById(id);
// var docTemplate3 = DriveApp.getFileById(id);
var folderDestination = DriveApp.getFolderById(id);
var clientName = sheet.getRange((i+2), 3).getValue();
var date = sheet.getRange((i+2), 1).getValue();
// if (templateConditionCheck[i] == "") {
var docToUse = docTemplate1;
// }
// if (templateConditionCheck[i] == "") {
// var docToUse = docTemplate2;
// }
// if (templateConditionCheck[i] == "") {
// var docToUse = docTemplate3;
// }
var docName = "Merge Tester Doc for " + clientName + " [" + date + "]";
var docCopy = docToUse.makeCopy(docName, folderDestination);
var docId = docCopy.getId();
var docURL = DriveApp.getFileById(docId).getUrl();
var docToSend = DriveApp.getFileById(docId);
var docBody = DocumentApp.openById(docId).getBody().getText();
function tagReplace() {
var taggedArray = [docBody.match(/\<{2}[\w\d\S]+\>{2}/g)];
var headerArray = [sheet.getRange(1, 1, 1, (lastColumn - 2)).getValues()];
var dataArray = [dataRow.getValues()];
var strippedArray = [];
Logger.log("The preliminary length of taggedArray is " + taggedArray.length);
Logger.log(taggedArray);
function tagStrip() {
for (var t = 0; t < taggedArray.length; t++) {
var strippedString = taggedArray[t].slice(2, -3).toString();
strippedArray.push(strippedString);
Logger.log("The current strippedArray length is " + strippedArray.length);
}
Logger.log("The final strippedArray length is " + strippedArray.length);
Logger.log("The final taggedArray length is " + taggedArray.length);
Logger.log("The final, completed strippedArray is " + strippedArray);
}
function dataMatch() {
for (var s = 0; s < strippedArray.length;) {
for (var h = 0; h < headerArray.length;) {
if (strippedArray[s] == headerArray[h]) {
docBody.replaceText(taggedArray[s].String(), dataArray[h].String());
h=0;
s++;
} else {
h++;
}
}
}
}
tagStrip;
dataMatch;
}
function emailCreator() {
var emailTag = sheet.getRange((i+2), (urlColumn - 2)).getValue();
var emailBody = HtmlService.createHtmlOutputFromFile("Email Template").getContent();
var personalizers = clientName + " [" + date + "]";
var subject = "Merge Tester Email for " + personalizers;
MailApp.sendEmail(emailTag, subject, emailBody, {
name: "Christopher Anderson",
attachments: [docToSend],
html: emailBody,
});
}
tagReplace();
statusCell.setBackground(yellow);
emailCreator();
urlCell.setValue(docURL)
}
statusCell.setBackground(red);
docCreator();
statusCell.setBackground(green);
}
mergeTasks();
}
}
}
checkAndComplete();
}
The problem section is here:
function tagReplace() {
var taggedArray = [docBody.match(/\<{2}[\w\d\S]+\>{2}/g)];
var headerArray = [sheet.getRange(1, 1, 1, (lastColumn - 2)).getValues()];
var dataArray = [dataRow.getValues()];
var strippedArray = new Array();
Logger.log("The preliminary length of taggedArray is " + taggedArray.length);
Logger.log(taggedArray);
function tagStrip() {
for (var t = 0; t < taggedArray.length; t++) {
var strippedString = taggedArray[t].slice(2, -3).toString();
strippedArray.push(strippedString);
Logger.log("The current strippedArray length is " + strippedArray.length);
}
Logger.log("The final strippedArray length is " + strippedArray.length);
Logger.log("The final taggedArray length is " + taggedArray.length);
Logger.log("The final, completed strippedArray is " + strippedArray);
}
function dataMatch() {
for (var s = 0; s < strippedArray.length;) {
for (var h = 0; h < headerArray.length;) {
if (strippedArray[s] == headerArray[h]) {
docBody.replaceText(taggedArray[s].String(), dataArray[h].String());
h=0;
s++;
} else {
h++;
}
}
}
}
tagStrip;
dataMatch;
}
It doesn't even log anything having to do with strippedArray.
It seems to be skipping over that section entirely.
Am I using the correct method of completing this task and/or is there a simpler way of doing it?
It's worth mentioning that my tags in the doc have 2 "<>" around them. That's the reason for my RegEx looking how it does.
Also, when logging the .length of taggedArray, it returns a value of 1.
You never actually call tagStrip which is supposed to work on strippedArray.
You declare it with function tagStrip(){} and later you reference the function with tagStrip; but you never actually call it. The same is happening with dataMatch.
Try calling the two functions by writing
tagStrip();
dataMatch();
If you don't include the parentheses you don't call it you just run the function Objects as statements.
Here is a portion of code I use in my add-on Simply Send, I use the same <<>> merge tags.
//copy template
var mDocDrive = doc.makeCopy(title, folder);
var mDoc = DocumentApp.openById(mDocDrive.getId());
var mDocDriveApp = DriveApp.getFileById(mDoc.getId());
var docToAttach = mDoc.getUrl();
var driveToShare = mDocDriveApp;
// replace text inside template
var body = mDoc.getBody();
body.replaceText("<<SS Title>>", title);
body.replaceText("<<timestamp>>", lastR.timestamp);
body.replaceText("<<username>>", lastR.email);
for (i in lastR.theResponses){
var cur = lastR.theResponses[i];
var name = cur.title;
name = name.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); // this will allow fields that include special characters.
var response = cur.response;
var searchPattern = "<<"+name+">>";
body.replaceText(searchPattern, response);
}
// this will replace any unused tags with nothing.
var ques = getQuestionList();
for (j in ques){
var curq = ques[j].name;
curq = curq.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
var searchPattern2 = "<<"+curq+">>";
body.replaceText(searchPattern2, "");
}
mDoc.saveAndClose();
//create pdf
if (mmDefaults.shareAs == "pdf"){
// uncomment if you want to make the pdf in the merge folder
var asPdf = mDoc.getAs('application/pdf');
asPdf.setName(mDoc.getName()+ ".pdf");
var pdf = DriveApp.createFile(asPdf);
folder.addFile(pdf);
DriveApp.removeFile(pdf);
mDocDriveApp.setTrashed(true);
var docToAttach = pdf;
driveToShare = pdf;
}

Amazon Web service - signature

I've been receiving an error from Amazon web service - InvalidParameterValue
Either Action or Operation query parameter must be present.
I believe it is most likely due to the signature being incorrect as the XML document and Header matches that of a test I did in their scratchpad.
Does anything stand out as being incorrect?
Thanks,
Clare
private static string ConstructCanonicalQueryString(SortedDictionary<string, string> sortedParameters)
{
var builder = new StringBuilder();
if (sortedParameters.Count == 0)
{
builder.Append(string.Empty);
return builder.ToString();
}
foreach (var kvp in sortedParameters)
{
builder.Append(PercentEncodeRfc3986(kvp.Key));
builder.Append("=");
builder.Append(PercentEncodeRfc3986(kvp.Value));
builder.Append("&");
}
var canonicalString = builder.ToString();
return canonicalString.Substring(0, canonicalString.Length - 1);
}
private static string PercentEncodeRfc3986(string value)
{
value = HttpUtility.UrlEncode(string.IsNullOrEmpty(value) ? string.Empty : value, Encoding.UTF8);
if (string.IsNullOrEmpty(value))
{
return string.Empty;
}
value = value.Replace("'", "%27")
.Replace("(", "%28")
.Replace(")", "%29")
.Replace("*", "%2A")
.Replace("!", "%21")
.Replace("%7e", "~")
.Replace("+", "%20")
.Replace(":", "%3A");
var sbuilder = new StringBuilder(value);
for (var i = 0; i < sbuilder.Length; i++)
{
if (sbuilder[i] != '%')
{
continue;
}
if (!char.IsLetter(sbuilder[i + 1]) && !char.IsLetter(sbuilder[i + 2]))
{
continue;
}
sbuilder[i + 1] = char.ToUpper(sbuilder[i + 1]);
sbuilder[i + 2] = char.ToUpper(sbuilder[i + 2]);
}
return sbuilder.ToString();
}
public string SignRequest(Dictionary<string, string> parametersUrl, Dictionary<string, string>
parametersSignture)
{
var secret = Encoding.UTF8.GetBytes(parametersSignture["Secret"]);
var signer = new HMACSHA256(secret);
var pc = new ParamComparer();
var sortedParameters = new SortedDictionary<string, string>(parametersUrl, pc);
var orderedParameters = ConstructCanonicalQueryString(sortedParameters);
var builder = new StringBuilder();
builder.Append(parametersSignture["RequestMethod"])
.Append(" \n")
.Append(parametersSignture["EndPoint"])
.Append("\n")
.Append("/\n")
.Append(orderedParameters);
var stringToSign = builder.ToString();
var toSign = Encoding.UTF8.GetBytes(stringToSign);
var sigBytes = signer.ComputeHash(toSign);
var signature = Convert.ToBase64String(sigBytes);
return signature.Replace("=", "%3D").Replace("/", "%2F").Replace("+", "%2B");
}
public class ParamComparer : IComparer<string>
{
public int Compare(string p1, string p2)
{
return string.CompareOrdinal(p1, p2);
}
}
The issue was that the Action wasn't included correctly into the Request

App Part issues, spPageContextInfo

I am trying to create an SharePoint hosted app that contains an app part, this app part should show what the user is following. I have used working code as an example in the app, but I don't get it to work inside of the App Part.
I get this within the app part: "Uncaught ReferenceError: _spPageContextInfo is not defined".
If anyone has a real example how to make this work inside an app part, and using social.following, please help!
This is the code in App.js:
var headline = new Array("People", "Documents", "Sites");
var ActorImg = new Array("/_layouts/15/images/person.gif", "/_layouts/15/images/lg_ICGEN.gif", "/_layouts/15/images/siteicon_16x16.png");
function doJSON(RESTuri, success, fail) {
var restUrl = _spPageContextInfo.webAbsoluteUrl + RESTuri;
var executor = new SP.RequestExecutor(_spPageContextInfo.webAbsoluteUrl);
executor.executeAsync(
{
url: restUrl,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: success,
error: fail
}
);
}
function renderSuccess(data) {
var jsonObject = JSON.parse(data.body);
var n = document.getElementById('jsonout');
n.innerHTML = data.body;
var results = jsonObject.d.Followed.results;
var str = '';
var old = -1;
var img = null;
for (j = 0; j < 5; j++) {
str += "<div class=\"container container" + j + "\">";
for (i = 0; i < results.length; i++) {
if (j != results[i].ActorType) continue;
if (old != results[i].ActorType) str += "<h1 class=\"headline" + results[i].ActorType + "\">" + headline[results[i].ActorType] + "</h1>";
img = results[i].ImageUri;
if (img == null) img = ActorImg[results[i].ActorType];
switch (results[i].ActorType) {
case 0:
// Use case: depending on ActorType if you want to use indiviual markup for every item-type
str += "<a title=\"" + results[i].Name + "\" class=\"link" + results[i].ActorType + "\" style=\"background-image:url(" + img + ")\" href=\"" + results[i].Uri + "\">" + results[i].Name + "</a>";
break;
default:
str += "<a title=\"" + results[i].Name + "\" class=\"link" + results[i].ActorType + "\" style=\"background-image:url(" + img + ")\" href=\"" + results[i].Uri + "\">" + results[i].Name + "</a>";
break;
}
old = results[i].ActorType;
}
str += "</div>";
}
n = document.getElementById('htmlout');
n.innerHTML = str + "<h1></h1>";
}
function renderFail(data, errorCode, errorMessage) {
n = document.getElementById('htmlout');
n.innerHTML = errorMessage;
}
$(document).ready(function () {
doJSON("/_api/social.following/my/followed%28types=15%29", renderSuccess, renderFail);
});
This is the div that's being used in both the app page(default.aspx) and the app part page(AppPart.aspx):
<div class="classic">
<pre id="jsonout" style="display: none;"></pre>
<div id="htmlout"></div>
</div>
Sorry guys. I solved it by just adding a reference to the sp.requestexecutor.js file, and parsed the host- and app-url from the querystring

Google Friend Connect fcauth cookie in php

this may be easy for most of you .. but not me.
I am using some "sample" Google code - as it fits my purpose so why change what works - but for the life of me I cannot access/find/get etc the FCAuth cookie after a user is logged in.
Help please - thanks in advance.
Here is my code (the Site ID is in a set variable, and all the calls work todate. just need to find/get the FCAuth cookie.
var viewer, ownerFriends, activities;
google.friendconnect.container.setParentUrl('/api/' /* location of rpc_relay.html and canvas.html */);
google.friendconnect.container.loadOpenSocialApi({
site: SITE_ID,
onload: function() { initAllData(); }});
function initAllData() {
var params = {};
params[opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS] =
[opensocial.Person.Field.ID,opensocial.Person.Field.NAME,opensocial.Person.Field.THUMBNAIL_URL,opensocial.Person.Field.PROFILE_URL];
var req = opensocial.newDataRequest();
req.add(req.newFetchPersonRequest('VIEWER', params), 'viewer');
req.add(req.newFetchPeopleRequest(
new opensocial.IdSpec({'userId' : 'OWNER', 'groupId' : 'FRIENDS'}), params),
'ownerFriends');
req.add(req.newFetchActivitiesRequest(new opensocial.IdSpec({'userId' : 'OWNER', 'groupId' : 'FRIENDS'})), 'activities');
var idspec = new opensocial.IdSpec({ 'userId' : 'VIEWER','groupId' : 'FRIENDS' });
req.add(req.newFetchPeopleRequest(idspec), 'viewer_friends');
req.send(onData);
req.send(setupData);
};
function setupData(data) {
ownerFriends = data.get('ownerFriends').getData().asArray();
var html = "";
for (var i = 0; i < ownerFriends.length && i < 8; i++) {
var person = ownerFriends[i];
html += "<a title='" + person.getField("displayName") + "' href='" + person.getField("profileUrl") + "'>";
html += "<img class='memberPhoto' src='" + person.getField("thumbnailUrl") + "' width='50px' alt='" + person.getField("displayName") + "'/>";
html += "</a> ";
};
document.getElementById('members').innerHTML = html;
viewer = data.get('viewer').getData();
if (viewer) {
document.getElementById('memberstate').innerHTML =
'<h2>' + viewer.getField("displayName") + ' welcome to the Yoga Council of Canada </h2>' ;
} else {
document.getElementById('memberstate').innerHTML =
'<h2>Join with one click</h2> After joining, you will automatically appear as a recent member.';
}
viewer = data.get('viewer').getData();
if (viewer) {
document.getElementById('profile').innerHTML =
'<img align="left" src="' + viewer.getField("thumbnailUrl") + '" style="margin-right: 20px;" >' +
'<strong>' + viewer.getField("displayName") + '</strong><br>' +
'Settings<br>' +
'Invite a friend<br>' +
'Sign out<br>';
} else {
google.friendconnect.renderSignInButton({ 'id': 'profile' });
}
};
function onData(data) {
if (!data.get("viewer_friends").hadError()) {
var site_friends = data.get("viewer_friends").getData();
var list = document.getElementById("friends-list");
list.innerHTML = "";
site_friends.each(function(friend) {
list.innerHTML += "<li>" + friend.getDisplayName() + "</li>";
});
}
};
OK, I am/was being totally thick, the cookie is automatically set as
$_COOKIE['fcauth<your appID>'];
So you can "just call it" i.e.
<?php if($_COOKIE['fcauth<your appID>']): do something endif; ?>