Decode/Encode .swf file - actionscript-3

I have this .swf file: http://www.mediafire.com/download/hrr3c6c188jsgvd/upload.swf
I need to change something in this file, so I have this website http://www.showmycode.com/ decode the file and got those code:
if (!hasOwnProperty("_load05626E90")) {
_load05626E90 = true;
telltarget ("..") {
var copyright = function () {
telltarget ("..") {
geturl("http://www.google.com/search?q=PHP+Script+c-Image+Uploader+3.0", "_blank");
}
};
}
}
else {
// unexpected jump
}
var author = function () {
telltarget ("..") {
geturl("http://chiplove.biz", "_blank");
}
};
// unexpected jump
// unexpected jump
var uploadItem = function (num) {
telltarget ("..") {
var item = flash.net.FileReference(list[num]);
item.addlistener(listener2);
item.upload((((((((((("upload.php?watermark=" + watermark) + "&logo=") + logo) + "&resize=") + resize) + "&server=") + server) + "&q=") + q)+ "&account=") + account)+ "&password=") + password);
}
};
// unexpected jump
// unexpected jump
var FileChooser = function () {
telltarget ("..") {
var fileRef = new flash.net.FileReferenceList();
fileRef.addlistener(listener);
fileRef.browse(allTypes);
}
};
// unexpected jump
// unexpected jump
};
stop();
//---------------------------------------------------------------------- //Frame 1 //----------------------------------------------------------------------
this.menu = new contextmenu();
this.menu.hidebuiltinitems();
this.menu.customitems.push(new contextmenuitem("PHP Script - c-Image Uploader 3.0", copyright));
this.menu.customitems.push(new contextmenuitem("Powered by chiplove.9xpro", author));
//---------------------------------------------------------------------- //Symbol 3 Button //----------------------------------------------------------------------
on (press) {
var listener = new object();
var listener2 = new object();
var itemnum = 0;
var numfiles = 0;
delete _global.__resolve;
_global.__resolve = _global.__debugResolve;
if (list == undefined) {
var list = null;
}
var allTypes = new array();
var imageTypes = new object();
imageTypes.description = "Images (*.jpg; *.jpeg; *.jpe; *.gif; *.png;)";
imageTypes.extension = "*.jpg; *.JPG; *.jpeg; *.jpe; *.gif; *.png;";
allTypes.push(imageTypes);
listener.onselect = function (fileRefList) {
list = fileRefList.fileList; numfiles = list.length;
uploadItem(itemnum);
};
listener2.onOpen = function (file) { };
listener2.onProgress = function (file, bytesloaded, bytestotal) {
flash.external.ExternalInterface.call("loading");
};
listener2.onComplete = function (file) { };
listener2.onUploadCompleteData = function (file, data) {
var loadvars = new loadvars();
loadvars.decode(data);
flash.external.ExternalInterface.call("displaypic", file.name, loadvars.image);
itemnum = itemnum + 1;
if (itemnum < numfiles) {
uploadItem(itemnum);
}
else {
flash.external.ExternalInterface.call("responseStatus", "Done!");
}
};
flash.external.ExternalInterface.addCallBack("FileChooser", this, FileChooser);
flash.external.ExternalInterface.call("clearlist");
FileChooser();
}
I think this is Action Script code, so after make some little change I get flash builder to recompile it, however, flash builder show a lot of red underline (syntax error) in my code and can't build those code to .swf file again. I wonder if the code I got from showmycode.com is correct, or is it action script? If the code I got from showmycode.com is not correct, how can I decode, edit, then encode again that "upload.swf" file?

Related

Google maps not working IE11 (sharepoint 2010)

I have a code to show Google Maps in my list on Sharepoint 2010. Code plot list items in the map. Work great with Edge and Chrome, but on IE not.
In IE console error on this line (object doesn't support this action (error 445))
var latlng = new google.maps.LatLng(defaultLatitude,defaultLongitude);
//build map
$('#'+idOfMapDiv).css({"width":mapWidth, "height":mapHeight});
var latlng = new google.maps.LatLng(defaultLatitude,defaultLongitude);
var myOptions = {
zoom: 6,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var gmMap = new google.maps.Map(document.getElementById(idOfMapDiv), myOptions);
var gmBounds = new google.maps.LatLngBounds();
var gmGeocoder = new google.maps.Geocoder();
var jQuerySelect_GetListRowByAttributeCTXName;
if(isSharePoint2010)
{
jQuerySelect_GetListRowByAttributeCTXName = jQuerySelect_2010_GetListRowByAttributeCTXName;
}
else
{
jQuerySelect_GetListRowByAttributeCTXName = jQuerySelect_2007_GetListRowByAttributeCTXName;
}
Full code on Sharepoint:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js" type="text/javascript"></script><script src="http://maps.google.com/maps/api/js?key=MY KEY" type="text/javascript"></script><script type="text/javascript">
/* *****************************************************
AND NOW SOME VARIABLES YOU MAY WANT TO CHANGE.
***************************************************** */
var mapWidth = "1725px"; //the width of the map
var mapHeight = "400px"; //the height of the map
//if true the coordinates (latitude, longitude) will be used
//if false the addresses (street, zip, city, country) will be used
var useCoordinates = true;
//if true the map will not be shown by default
//if false the map will be shown by default
var hideMapUntilClick = false;
//if 0 absolutely no warning- and error-alerts will be written to a log-div
//if 1 the warning- and error-alerts will be written to a log-div
//if 2 the warning- and error-alerts will be alerted via javascript-alert
var showWarningAndErrorAlerts = 1;
//the internal-names of list-columns (not the display-name!)
var colLinkTitleInternalName = "ows_Nome_x0020_Instala_x00e7__x00e3_"; //will be used as the title of the geo-markers
var colLongitudeInternalName = "ows_Longitude"; //useCoordinates == true
var colLatitudeInternalName = "ows_Latitude"; //useCoordinates == true
var colStreetInternalName = "WorkAddress"; //useCoordinates == false
var colStreetDisplayName = "Endereço"; //useCoordinates == false
var colZipInternalName = "WorkZip"; //useCoordinates == false
var colCityInternalName = "WorkCity"; //useCoordinates == false
var colCountryInternalName = "WorkCountry"; //useCoordinates == false
var defaultCountryValue = "Brazil"; //the default country which will be used if no country-name will be found in the list-column
//default position (Germany: 51.165691,10.451526) > used if no markers will be set to the map
var defaultLatitude = -15.77972;
var defaultLongitude = -47.92972;
//some language-specific messages
var resxGoogleMapsLink = "Google-Map"; //the name of new menu-point in the menu-toolbar of the sharepoint-list
var resxGoogleMapsLinkTitle = "Menu: Show or hide Google-Map"; //the title which will be visible while hovering
var resxAlertsMessageText = resxGoogleMapsLink+": There are # hints!"; //the hint which will be visible if configuration warnings or errors occured.
var resxAlertsMessageTextTitle = "Click here to show or hide the hints!"; //the title which will be visible while hovering
/* *******************************************************************
NOW DO NOT CHANGE ANYTHING IF YOU ARE NOT FAMILIAR WITH JAVASCRIPT!
******************************************************************* */
var isSharePoint2010 = true;
var hasMapBeenLoadedInitially = false;
var idOfMapDiv = "divGoogleMapForSharePointList";
var idOfCustomLogDiv = "divCustomLog";
var idOfCustomLogOverview = "divCustomLogOverview";
var noOfCustomLogEntries = 0;
var noOfMaxGeocodingRequest = 10;
//the attribute-name of the column "id" > will be used for a) finding the id of a certain row and b) for building the ajax-request-url
var colID = "ID";
//now some templates for jquery-selects
var jQuerySelect_2007_GetListRowByAttributeCTXName = "table[CTXName]";
var jQuerySelect_2010_GetListRowByAttributeCTXName = "div[CTXName]";
function InitializeGoogleMapForSharePointList()
{
BuildGoogleMapCustomLogForSharePointList();
if(!DoPreCheckForInitializationOfGooglemapsForSharePointList())
{
//pre-check not successfully done > abort now!
customAlert("The Pre-Check has not been successfully! > Abort now.");
return;
}
DoSchemaCheckAndBuildGoogleMapIconForSharePointList();
}
function DoSchemaCheckAndBuildGoogleMapIconForSharePointList()
{
//get the schema-data for the list
$.get(BuildAjaxRequestUrlForSharePointListSchemaOnly(), {}, function (xml)
{
//find all necessary internal-field-names
var arrNeccessaryFields = new Array();
arrNeccessaryFields.push(colLinkTitleInternalName);
if(useCoordinates)
{
arrNeccessaryFields.push(colLatitudeInternalName);
arrNeccessaryFields.push(colLongitudeInternalName);
}
else
{
arrNeccessaryFields.push(colStreetInternalName);
arrNeccessaryFields.push(colZipInternalName);
arrNeccessaryFields.push(colCityInternalName);
arrNeccessaryFields.push(colCountryInternalName);
}
//check all neccessary internal-field-names
var foundAllNeccessaryFields = true;
for(i=0;i<arrNeccessaryFields.length;i++)
{
//getting <xml><s:Schema><s:ElementType><s:AttributeType name="[internal-field-name]">
var xmlQuery = 'xml > *:first > *:first > *[name='+arrNeccessaryFields[i]+']';
if($(xmlQuery, xml).length<1)
{
foundAllNeccessaryFields = false;
customAlert("Schema-Check failed for internal-field-name '"+arrNeccessaryFields[i]+"'. The field is not available in this list.");
}
}
//check if the neccessary fields have been found
if(foundAllNeccessaryFields)
{
BuildGoogleMapIconForSharePointList();
}
else
{
var ajaxRequestLinkTag = 'ajax-request for list-schema';
customAlert("Hint: You can get the internal names of the columns by calling the "+ajaxRequestLinkTag+" for the current sharepoint-list manually.");
customAlert("Schema-Check failed. Abort now!");
}
});
}
function DoPreCheckForInitializationOfGooglemapsForSharePointList()
{
//check if this is SharePoint2010 or not
//if it is not 2010 it is assumed that it is 2007
if(typeof(_fV4UI)!='undefined')
{
//the checked javascript-variable exists only in 2010
isSharePoint2010 = true;
}
else
{
isSharePoint2010 = false;
}
//for the first shot: support only one table
//for further version we could support more tables (table[class=ms-listviewtable].length>1)
var noOfListViews = $("table[class=ms-listviewtable]").length;
if(noOfListViews==0)
{
//no list-view exists > there is no need to show google-maps
customAlert("There is no list-view available on this site. > No need to show google-maps. > Abort now.");
return false;
}
else if(noOfListViews>1)
{
//there are more than one list-view > this is not supported at the moment
customAlert("There are more than one list-views on the site. This is not supported at the moment. > Abort now!");
return false;
}
//check if multi-lookup exists
if($("table[FieldType=LookupMulti]").length>0)
{
//If there are columns in the list-view which are of type multi-lookup the ajax-call (via owssrv.dll) will return zero results.
var multiMsg = "Multi-lookup exists! Please remove the mulit-lookup-column or use another view (otherwise the ajax-request will receive an empty result). > Abort now!";
multiMsg += "\n\nColumns which are of type multi-lookup are (the display-name will be shown):";
$("table[FieldType=LookupMulti]").each(function(){
var displayName = $(this).attr("displayName");
multiMsg += "\n- "+displayName;
});
customAlert(multiMsg);
return false;
}
//check if javascript-variable exists > we need ctx to get the id of the sharepoint-list
if(ctx==null)
{
//this javascript-variable is essential for getting the list-id and the list-view-id.
customAlert("The javascript-variable 'ctx' does not exist within the html-dom. > Abort now!");
return false;
}
//all checks passed - return true
return true;
}
function BuildGoogleMapCustomLogForSharePointList()
{
if(showWarningAndErrorAlerts!=1)
{
return;
}
var divCustomLogOverview = '<div title="'+resxAlertsMessageTextTitle+'" onclick="ToggleCustomLog();" id="'+idOfCustomLogOverview+'" style="margin: 10px; cursor: pointer; color: red; display: none;"></div>';
$("table.ms-menutoolbar").parent().append(divCustomLogOverview);
var divCustomLog = '<div id="'+idOfCustomLogDiv+'" style="margin: 10px; display: none;"></div>';
$("table.ms-menutoolbar").parent().append(divCustomLog);
}
function ToggleCustomLog()
{
//show or hide
$("#"+idOfCustomLogDiv).toggle();
}
function ToggleGoogleMapDiv()
{
//check if the map will be called for the first time
if(!hasMapBeenLoadedInitially)
{
ShowGoogleMapForSharePointList();
}
//show or hide
$("#"+idOfMapDiv).toggle();
}
function BuildGoogleMapIconForSharePointList()
{
//searching for the correct position in the menu-toolbar (ms-menutoolbar)
$("td.ms-toolbar").each(function(j){
if($(this).attr("width")=="99%")
{
//insert a new menu-item before the found placeholder
//var newMenuItem = '</internal-name-of-column><td class="ms-separator">';
var newMenuItem = '<td class="ms-separator">';
newMenuItem += '<img src="/_layouts/images/blank.gif" alt=""/>';
newMenuItem += '</td>';
newMenuItem += '<td nowrap="true" class="ms-toolbar">';
newMenuItem += '<span title="'+resxGoogleMapsLinkTitle+'">';
newMenuItem += '<div nowrap="nowrap" hoverinactive="ms-menubuttoninactivehover" hoveractive="ms-menubuttonactivehover" onmouseover="MMU_PopMenuIfShowing(this);MMU_EcbTableMouseOverOut(this, true)" class="ms-menubuttoninactivehover">';
newMenuItem += '<a onclick="javascript:ToggleGoogleMapDiv();return false;" href="#" style="cursor: pointer; white-space: nowrap;">'+resxGoogleMapsLink+'</a>';
newMenuItem += '</div>';
newMenuItem += '</span>';
newMenuItem += '</td>';
$(this).before(newMenuItem);
}
});
//adding map-canvas as div-tag to the dom
var divMapCanvas = '<div id="'+idOfMapDiv+'" style="margin: 10px; display: none;"></div>';
$("table.ms-menutoolbar").parent().before(divMapCanvas);
//check if the map should be shown as soon as possible or if it should be hidden until the user clicked the new menu-point
if(!hideMapUntilClick)
{
ToggleGoogleMapDiv();
}
}
//gets the complete list-schema and one row with all its values (not filtered by the current used view)
function BuildAjaxRequestUrlForSharePointListByID_Template()
{
if(ctx!=null)
{
//build the url of the ajax-request
return ctx.HttpRoot+'/_vti_bin/owssvr.dll?XMLDATA=1&List=' + ctx.listName + '&Query=*&FilterField1='+colID+'&FilterValue1=';
}
}
//gets the list-schema and no rows
function BuildAjaxRequestUrlForSharePointListSchemaOnly()
{
//build the url of the ajax-request
return BuildAjaxRequestUrlForSharePointListByID_Template()+'-1';
}
function ShowGoogleMapForSharePointList()
{
//build the url of the ajax-request
var urlTemplate = BuildAjaxRequestUrlForSharePointListByID_Template();
//build map
$('#'+idOfMapDiv).css({"width":mapWidth, "height":mapHeight});
var latlng = new google.maps.LatLng(defaultLatitude,defaultLongitude);
var myOptions = {
zoom: 6,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var gmMap = new google.maps.Map(document.getElementById(idOfMapDiv), myOptions);
var gmBounds = new google.maps.LatLngBounds();
var gmGeocoder = new google.maps.Geocoder();
var jQuerySelect_GetListRowByAttributeCTXName;
if(isSharePoint2010)
{
jQuerySelect_GetListRowByAttributeCTXName = jQuerySelect_2010_GetListRowByAttributeCTXName;
}
else
{
jQuerySelect_GetListRowByAttributeCTXName = jQuerySelect_2007_GetListRowByAttributeCTXName;
}
//check if the number of geocodings will exceed the max-number
if(!useCoordinates && $(jQuerySelect_GetListRowByAttributeCTXName).length > noOfMaxGeocodingRequest)
{
var linkToStatusCodes = '<a title="Statuscodes of geocoding-responses from Google-Maps" target="_blank" href="http://code.google.com/intl/de-DE/apis/maps/documentation/javascript/services.html#GeocodingStatusCodes">OVER_QUERY_LIMIT-Status</a>';
var tooManyMsg = "Hint: In the current view of the SharePoint-List there are more than "+noOfMaxGeocodingRequest+" list-entries. ";
tooManyMsg += "This will result in an "+linkToStatusCodes+" by Google-Maps (and not all markers will be shown on the map). > You have 2 options: ";
tooManyMsg += "a) Change your view to get no more than "+noOfMaxGeocodingRequest+" list-entries or ";
tooManyMsg += "b) use the coordinates (longitude, latitude) of the addresses (they will be shown on the map).";
customAlert(tooManyMsg);
}
//get each row from list-view which is shown at the moment
$(jQuerySelect_GetListRowByAttributeCTXName).each(function(j)
{
var lat, lng, gmLatLng, gmMarker, title, customUrl, street, city, country;
var idOfListItem = $(this).attr(colID);
if(isSharePoint2010)
{
var linkToListItem = '<table height="auto" width="calcWidthpx"><tr class="ms-alternating ms-itmhover"><td height="100%" class="ms-vb-title" onmouseover="OnChildItem(this)">';
linkToListItem += $(this).parent().html();
linkToListItem += '</td></tr></table><span style="font-size:72pt;"></br></span>';
}
else
{
linkToListItem = $(this).parent().html();
linkToListItem = linkToListItem.replace(/100%/g, "auto"); //exchange tag-attributes for width and height
}
//build url for the ajax-request which reads all data for a certain row (for the current list-view)
customUrl = urlTemplate+idOfListItem;
//get the data for the row
$.get(customUrl, {}, function (xml)
{
$('xml > *:last > *', xml).each(function (i)
{
//get some data from the xml-response
title = $(this).attr(colLinkTitleInternalName);
if(isSharePoint2010)
{
var titleLength= title.length+185;
linkToListItem = linkToListItem.replace('calcWidth', titleLength);
}
if(useCoordinates)
{
//getting coordinates
lat = $(this).attr(colLatitudeInternalName);
lng = $(this).attr(colLongitudeInternalName);
if(typeof(lat)!='undefined' && typeof(lng)!='undefined')
{
gmLatLng = new google.maps.LatLng(lat, lng);
msgForInfoWindow = linkToListItem; //you may add more information-text here
SetMarkerForGoogleMapForSharePointList(gmLatLng, gmMap, gmBounds, title, msgForInfoWindow);
}
else
{
customAlert(title +" has undefined lat+lng. > Do not add marker on map.");
}
}
else
{
//getting address
street = $(this).attr(colStreetInternalName);
zip = $(this).attr(colZipInternalName);
city = $(this).attr(colCityInternalName);
country = $(this).attr(colCountryInternalName);
//checking received values
if(typeof(street)=='undefined') street = ""; //optional
if(typeof(zip)=='undefined') zip = ""; //optional
if(typeof(city)=='undefined')
{
customAlert("The ajax-response got no city for '"+title+"'. > Do not add marker on map.");
return;
}
if(typeof(country)=='undefined') country = defaultCountryValue;
address = street+","+zip+","+city+","+country;
//getting coordinates
gmGeocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK)
{
if(results.length==0)
{
customAlert("Geocoding: There are no results for address '"+results[0].formatted_address+"'! Expected exactly one result. > Do not show any marker on map for this address.");
}
else if(results.length>1)
{
var msg = "Geocoding: There are too many ("+results.length+") results for given address! Expected exactly one result. > Do not show any marker on map for this address.\n\nFound addresses:\n";
for(i=0;i<results.length;i++)
{
var c = i+1;
msg += "\n"+c+": "+results[i].formatted_address;
}
customAlert(msg);
}
else
{
gmLatLng = results[0].geometry.location;
var msgForInfoWindow = linkToListItem+"<br>";
msgForInfoWindow += "<span style='font-size:0.8em;'>Koordinaten (Lat, Lon): "+gmLatLng+"<br>Adresse: "+results[0].formatted_address+"</span>";
SetMarkerForGoogleMapForSharePointList(gmLatLng, gmMap, gmBounds, title, msgForInfoWindow);
}
}
else
{
customAlert("Geocode for address '"+address+"' was not successful for the following reason: " + status);
}
});
}
});
});
});
hasMapBeenLoadedInitially = true;
}
function SetMarkerForGoogleMapForSharePointList(gmLatLng, gmMap, gmBounds, title, contentForInfoWindow)
{
var gmMarker = new google.maps.Marker({
position: gmLatLng,
map: gmMap,
title: title,
zIndex: 0
});
gmBounds.extend(gmLatLng);
gmMap.setCenter(gmBounds.getCenter());
gmMap.fitBounds(gmBounds);
if(contentForInfoWindow!=null && contentForInfoWindow!="")
{
var gmInfowindow = new google.maps.InfoWindow({
content: contentForInfoWindow
});
google.maps.event.addListener(gmMarker, 'click', function() {
gmInfowindow.open(gmMap,gmMarker);
});
}
}
function customAlert(msg)
{
if(msg==null || msg=="")
{
return;
}
else
{
var now = new Date();
msg = now.getHours()+":"+now.getMinutes()+":"+now.getSeconds()+": "+msg;
}
if(showWarningAndErrorAlerts==0)
{
//do nothing
}
else if(showWarningAndErrorAlerts==1)
{
//do log in log-div
msg = msg.replace(/\n/g, "<br/>");
msg += "<br/><br/>";
$("#"+idOfCustomLogDiv).append(msg);
noOfCustomLogEntries++;
$("#"+idOfCustomLogOverview).show();
var overviewText = resxAlertsMessageText.replace(/#/g, noOfCustomLogEntries);
$("#"+idOfCustomLogOverview).text(overviewText);
}
else if(showWarningAndErrorAlerts==2)
{
//do alert via javascript-alert
alert(msg);
}
else
{
//unsupported
}
}
//call initialization after the dom has been loaded completely > so it does not matter where this piece of javascript will be inserted in the dom
$(document).ready(InitializeGoogleMapForSharePointList);</script>
Result in Chrome e Edge:
Screenshot
Just to put an answer to this question, adding the meta tag of <meta http-equiv="X-UA-Compatible" content="IE=8"> would solve the issue.

Simple autocomplete with Ace Editor in AS3?

I'm working in XML and I'd like to provide autocomplete suggestions for the attributes for specific node types using AS3.
For example, if the user is has a cursor in the following node:
<s:Button label="Hello World"/>
I'd like autocomplete to show "width, height, x, y".
I'm trying to get the node name and namespace and then give the editor a list of attributes that should appear in autocomplete.
I found similar questions but those are using a service call and a few that are out dated. I may delete this question if it is a duplicate.
Ace Editor for AS3 here.
In my case, for AS3, it is a combination of items:
ace.setCompleters(null); // I'm removing existing autocomplete
ace.addCompleter(codeCompleter); // adding my own
public var autoCompleteErrorMessage:String = "Nothing available";
public function codeCompleter(editor:Object, session:Object, position:Object, prefix:String, callback:Function):void {
var row:int = position.row;
var column:int = position.column;
/*
if (prefix.length === 0) {
callback(null, []);
return;
}
*/
//var myList:Array = {value: "message", caption: "Caption to user", meta: "Type shown", score: "I don't know"};
var testing:Boolean = false;
if (testing) {
callback(autoCompleteErrorMessage, [{value:"addedToStage"},{value:"added"},{value:"adding"}]);
}
else {
callback(autoCompleteErrorMessage, attributes);
}
}
protected function cursorChangeHandler(event:Event):void {
var qname:QName = getQNameFromCursorPosition(ace.row, ace.column);
if (qname==null) {
if (attributes.length) {
attributes = [];
}
return;
}
if (qname) {
attributes = getSuggestionListFromObject(classObject);
autoCompleteErrorMessage = null;
lastSelectedQName = qname;
}
}
public static var XML_TAG_NAME:String = "meta.tag.tag-name.xml";
public static var XML_TAG_OPEN:String = "meta.tag.punctuation.tag-open.xml";
public static var XML_TAG_CLOSE:String = "meta.tag.punctuation.tag-close.xml";
public static var XML_ATTRIBUTE_NAME:String = "entity.other.attribute-name.xml";
public function getQNameFromCursorPosition(row:int, column:int):QName {
var token:Object;
var line:String;
var type:String;
var value:String;
var found:Boolean;
var qname:QName;
for (; row > -1; row--) {
line = ace.getLine(row);
column = line.length;
for (; column>-1; column--) {
token = ace.getTokenAt(row, column);
type = token ? token.type : "";
if (type==XML_TAG_NAME) {
value = token.value;
found = true;
}
}
if (found) break;
}
if (found) {
qname = new QName("", value);
}
return qname;
}
The getQNameFromCursorPosition() method is fragile and I'm looking into a new method using the jumpToMatching() method.

GmailApp.search doesn't filter the labels

I try to send the all attachments to my Google Drive account but I have problem with the search of GmailApp.search.
I have a Camera in my home that sends an email every 5 minutes with the same Subject and each message has an attached file that's name is the day-time.jpg
First I think in search by label and then of the process, I put a new label to mark and don't repeat the message, but I always receive all the message.
I tried to test many ways and always received the message that has label:processed.
function () {
//All message of the camera have the label GoogleDrive
var threads = GmailApp.search("has:attachment -label:processed label:GoogleDrive", 0, 5);
var folder = getFolder(driveFolder);
for (var x=0; x<threads.length; x++) {
var message = threads[x].getMessages();
for(var y=0; y<message.length; y++) {
var desc = message[y].getSubject() + " #" + message[y].getId();
var att = message[y].getAttachments();
for (var z=0; z<att.length; z++) {
try {
if (check) {
var name = att[z].getName();
if (name.indexOf(".") != -1) {
var extn = name.substr(name.lastIndexOf(".")+1).toLowerCase();
if (valid.indexOf(extn) != -1) {
file = folder.createFile(att[z]);
file.setDescription(desc);
} else {
Logger.log("Skipping " + name);
}
}
} else {
file = folder.createFile(att[z]);
file.setDescription(desc);
}
}
catch (e) {
Logger.log(e.toString());
}
}
}
threads[x].addLabel(moveToLabel); //this variable is processed label
}
}
Regards
I have this function. I use the ctrlq.org code as base, only I put the principal function.
Now I copy all the script
function createFilter(label, archiveLabel) {
var filter = "has:attachment -label:" + archiveLabel + " label:" + label;
return filter;
}
function help() {
var html = HtmlService.createHtmlOutputFromFile('help')
.setTitle("Google Scripts Support")
.setWidth(400)
.setHeight(260);
var ss = SpreadsheetApp.getActive();
ss.show(html);
}
function premium() {
var html = HtmlService.createHtmlOutput('Upgrade to the premium edition of Send to Google Drive and unlock new features. You can also opt for one-on-one support via email, Skype or Google Hangouts.')
.setTitle("Send to Google Drive Premium")
.setWidth(240)
.setHeight(100);
var ss = SpreadsheetApp.getActive();
ss.show(html);
}
function sendToGoogleDrive() {
var sheet = SpreadsheetApp.getActiveSheet();
var gmailLabels = sheet.getRange("D4:D4").getValue();
var driveFolder = sheet.getRange("D5:D5").getValue();
var archiveLabel = sheet.getRange("D6:D6").getValue();
var filetypes = sheet.getRange("D7:D7").getValue();
var valid = filetypes.replace(/\s/g,"").toLowerCase().split(",");
var check = true;
if ( (valid.indexOf("all") != -1) || (valid.length == 1 && valid[0] == "")) {
check = false;
}
var moveToLabel = getGmailLabel(archiveLabel);
var filter = createFilter(gmailLabels, archiveLabel);
var threads = GmailApp.search(filter, 0, 5);
var folder = getFolder(driveFolder);
sheet.getRange("D9:D9").setValue(sheet.getRange("D9:D9").getValue() + ", [th(" + threads.length + ")");
for (var x=0; x<threads.length; x++) {
var message = threads[x].getMessages();
sheet.getRange("D9:D9").setValue(sheet.getRange("D9:D9").getValue() + ", ms(" + message.length + ")");
for(var y=0; y<message.length; y++) {
var desc = message[y].getSubject() + " #" + message[y].getId();
var att = message[y].getAttachments();
//sheet.getRange("D9:D9").setValue(sheet.getRange("D9:D9").getValue() + ", at(" + att.length + ")");
for (var z=0; z<att.length; z++) {
try {
if (check) {
var name = att[z].getName();
if (name.indexOf(".") != -1) {
var extn = name.substr(name.lastIndexOf(".")+1).toLowerCase();
if (valid.indexOf(extn) != -1) {
file = folder.createFile(att[z]);
file.setDescription(desc);
} else {
Logger.log("Skipping " + name);
}
}
} else {
file = folder.createFile(att[z]);
file.setDescription(desc);
}
}
catch (e) {
Logger.log(e.toString());
}
}
}
threads[x].moveToTrash();
threads[x].addLabel(moveToLabel);
}
sheet.getRange("D9:D9").setValue(sheet.getRange("D9:D9").getValue() + "]");
}
function configure() {
reset(true);
ScriptApp.newTrigger("sendToGoogleDrive").timeBased().everyMinutes(5).create();
Browser.msgBox("Initialized", "The program is now running. You can close this sheet", Browser.Buttons.OK);
}
function init() {
return;
}
function onOpen() {
var menu = [
{name: "Help and Support »",functionName: "help"},
null,
{ name: "Step 1: Authorize", functionName: "init" },
{ name: "Step 2: Run Program", functionName: "configure" },
null,
{ name: "Uninstall (Stop)", functionName: "reset" },
null,
{name: "Upgrade to Premium »",functionName: "premium"},
null
];
SpreadsheetApp.getActiveSpreadsheet()
.addMenu("Gmail Attachments", menu);
}
function getFolder(parent) {
var parentFolder, searchFolder = DriveApp.getFoldersByName(parent);
if (searchFolder.hasNext()) {
parentFolder = searchFolder.next();
} else {
parentFolder = DriveApp.createFolder(parent);
}
return parentFolder;
}
function getGmailLabel(name) {
var label = GmailApp.getUserLabelByName(name);
if ( ! label ) {
label = GmailApp.createLabel(name);
}
return label;
}
function reset(e) {
var triggers = ScriptApp.getProjectTriggers();
for (var i = 0; i < triggers.length; i++) {
ScriptApp.deleteTrigger(triggers[i]);
}
if (!e) {
Browser.msgBox("Script Stopped", "You can start the script anytime later!", Browser.Buttons.OK);
}
}
My inbox have these mails:
1
The problem is then I run the script the mail has a new label (now I send to Trash too), but in the next run the GmailApp.Search, find the mail that have processed label.
I copy the configuration sheet
2
It looks like you have not defined moveToLabel and hence the same set of Gmail threads are getting processed in each loop.
Add this line before the for loop.
var moveToLabel = GmailApp.getUserLabelByName("processed");
if ( ! moveToLabel ) {
moveToLabel = GmailApp.createLabel(processed);
}
You can get the full snippet at ctrlq.org.

broken image after writing Base64 image using FileWriter

I want to add some text over image taken from device camera using cordova camera plugin.
For that i used canvas and draw text over the image and saved using FileWriter.writer() method, but while i checked image in gallery, image is shown as broken and, in proprties resolution is -1x-1.
while i debug, before calling write() i am able see base64 image and when i clicked,image is opened in new tab.
Please find my code and please provide your comments.
var gImageURI = '';
var gFileSystem = {};
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, errorHandler);
function getPhoto(source, type) {
navigator.camera.getPicture(function (imageURI) { onPhotoURISuccess(imageURI, type) }, onFail, {
quality: 35,
destinationType: navigator.camera.DestinationType.FILE_URI,
saveToPhotoAlbum: false,
sourceType: source,
allowEdit: false,
targetWidth: 600,
targetHeight: 800
});
}
// Called when a photo is successfully retrieved
function onPhotoURISuccess(imageURI, type) {
if(type=="camera")
canvasimage(imageURI);
}
// Called if something bad happens.
function onFail(message) {
console.log('Failed because: ' + message);
}
// sets the filesystem to the global var gFileSystem
function gotFS(fileSystem) {
gFileSystem = fileSystem;
}
// send the full URI of the moved image to the updateImageSrc() method which does some DOM manipulation
function movedImageSuccess(fileEntry, type) {
debugger;
updateImageSrc(fileEntry.fullPath, type);
}
// simple error handler
function errorHandler(e) {
var msg = '';
switch (e.code) {
case FileError.QUOTA_EXCEEDED_ERR:
msg = 'QUOTA_EXCEEDED_ERR';
break;
case FileError.NOT_FOUND_ERR:
msg = 'NOT_FOUND_ERR';
break;
case FileError.SECURITY_ERR:
msg = 'SECURITY_ERR';
break;
case FileError.INVALID_MODIFICATION_ERR:
msg = 'INVALID_MODIFICATION_ERR';
break;
case FileError.INVALID_STATE_ERR:
msg = 'INVALID_STATE_ERR';
break;
default:
msg = e.code;
break;
};
console.log('Error: ' + msg);
}
function btnCameraClick() {
$("#divAttachments").show();
$("#divLandmarks").hide();
getPhoto(navigator.camera.PictureSourceType.CAMERA, 'camera');
}
function updateImageSrc(filepath, type) {
try {
var filenamewithextensn = filepath.substring(filepath.lastIndexOf('/') + 1);
var strfilename = filenamewithextensn.split('.');
var filename = strfilename[0];
var tag = filepath.substring(filepath.lastIndexOf('/') + 1);
// alert('File Path after moving : ' + filepath);
// alert('tag :' + tag);
var fullpath = gFileSystem.root.toURL() + tag;
// alert('full path to dataabase '+fullpath);
var query = "";
if (type == "camera") {
//query= insert query
}
}
catch (err) {
ErrorMessageDB("something");
}
}
function canvasimage(src) {
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
var imgdata = new Image;
imgdata.onload = function () {
canvas.width = this.width;
canvas.height = this.height;
ctx.drawImage(this, 0, 0);
ctx.font = "11pt Verdana";
ctx.fillStyle = "black";
ctx.fillText("19-11-2014", 22, 42);
ctx.fillStyle = "white";
ctx.fillText("19-11-2014", 20, 40);
var dataURL = canvas.toDataURL();
//alert(dataURL);
//dataURL=dataURL.substring(dataURL.indexOf("base64\,") + 7);
gotfilesystem(dataURL);
}
imgdata.src = src;
//var index = dataURL.indexOf(',');
//return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
// return dataURL;
}
function gotfilesystem(dataURL) {
var d = new Date();
var s = d.getDate().toString() + d.getMonth().toString() + d.getMinutes().toString() + d.getSeconds().toString()
var fname="thumbnail_" + s + ".png";
gFileSystem.root.getFile(fname, { create: true, exclusive: false },
function(entry) {
gotfileentrysuccess(entry, dataURL);
}, function() {
});
}
function gotfileentrysuccess(entry, dataURL) {
entry.createWriter( function(fileWriter) {gotFileWriter(fileWriter,dataURL,entry)});
}
function gotFileWriter(writer, dataURL,entry) {
writer.onwriteend = function(evt) {
movedImageSuccess(entry, 'camera');
};
writer.write(dataURL);
}
You need to create a Blob using your base64 string then pass the Blob to the FileWriter.writer() method.
There is a nice example of how to do this here:
Convert Data URI to File then append to FormData

jquery cookie code error

I tried to create a cookie for the link but it showed me errors like this....how to fix it...
Uncaught ReferenceError: createCookie is not defined
i am providing my code in fiidle
http://jsfiddle.net/SSMX4/82/ cookie not working
my jquery code is below
// locale selector actions
$('#region-picker').click(function(){
if ($("#locale-select").is(":visible")) return closeSelector('slide');
var foot_height = $('#footer').innerHeight();
var foot_height_css = foot_height-1;
var select_position = '-=' + (Number(700)+18);
console.log("hallo"+select_position);
var $selector = $('#locale-select');
$('#locale_pop').fadeOut();
$selector.css({top:foot_height_css});
$selector.fadeIn(function(){
$(this).addClass('open');
$(this).animate({top:select_position}, 1000);
});
});
$('#select-tab').click(function(e){
e.stopPropagation()
closeSelector('slide');
});
// don't hide when clicked within the box
$('#locale-select').click(function(e){
e.stopPropagation();
});
$(document).click(function(){
if ($('#locale-select').hasClass('open')) {
closeSelector('disappear');
}
});
$('.locale-link').click(function(){
//var $clicked = $(this); //"$(this)" and "this" is the clicked span
$(".locale-select-lable").html($(this).html());
//search for "marginXXXXX"
var flags = $(this).attr("class").match(/(margin\w+)\s/g);
//create new class; add matching value if found
var flagClass = "tk-museo-sans locale-select-lable" + (flags.length ? " " + flags[0] : "");
//set new class definition
$(".locale-select-lable").attr("class", flagClass);
closeSelector('disappear');
//if ($("#locale-select").is(":visible")) return closeSelector('slide');
/*
// var desired_locale = $(this).attr('rel');
// createCookie('desired-locale',desired_locale,360);
// createCookie('buy_flow_locale',desired_locale,360);
//closeSelector('disappear');
*/
}); /* CORRECTED */
$('#locale_pop a.close').click(function(){
var show_blip_count = readCookie('show_blip_count');
if (!show_blip_count) {
createCookie('show_blip_count',3,360);
}
else if (show_blip_count < 3 ) {
eraseCookie('show_blip_count');
createCookie('show_blip_count',3,360);
}
$('#locale_pop').slideUp();
return false;
});
function closeSelector(hide_type){
var foot_height = $('#footer').innerHeight();
var select_position = '+=' + (Number(400)+20);
if (hide_type == 'slide') {
$('#locale-select').animate({top:select_position}, 1000, function(){
$(this).removeClass('open');
$(this).fadeOut()
});
}
else if (hide_type == 'disappear'){
$('#locale-select').fadeOut('fast');
$('#locale-select').removeClass('open');
}
}
$('.locale-link').click(function(){
var desired_locale = $(this).attr('rel');
console.log("cookie....." + desired_locale);
createCookie('desired-locale',desired_locale,360);
createCookie('buy_flow_locale',desired_locale,360);
closeSelector('disappear');
})
$('#locale_pop a.close').click(function(){
var show_blip_count = readCookie('show_blip_count');
if (!show_blip_count) {
createCookie('show_blip_count',3,360);
}
else if (show_blip_count < 3 ) {
eraseCookie('show_blip_count');
createCookie('show_blip_count',3,360);
}
$('#locale_pop').slideUp();
return false;
});
​
I did not find your declaration of the function "createCookie". It seems you copied the code and forgot to copy the function.
Btw: "xxx is not defined" always means the variable/function does not exist ..