HttpInclude [IDE Tool]

Share your advanced PureBasic knowledge/code with the community.
User avatar
HeX0R
Addict
Addict
Posts: 992
Joined: Mon Sep 20, 2004 7:12 am
Location: Hell

HttpInclude [IDE Tool]

Post by HeX0R »

A small IDE Tool to make it possible to use codes directly from the pureboards or purearea.
The codes will get stored on your hard disk for faster access.

When compiling it the first time, you will need to download also my IDE Tool Helper:
http://www.purebasic.fr/english/viewtop ... 12&t=62033
Next time the HttpInclude inside the code will work (this is a hen egg problem ;))

The tool is self installing into your IDE, so I would recommend not to compile it directly from the IDE, because then it will set the tool to "Purebasic_CompilationX.X".
Better first create an executable and then start this.

And don't forget to add HttpInclude to your custom keywords.

Examples in next thread.

Code: Select all

;*******************************************
;*
;*   Filename:    HTTP_Include.pb
;*   Version:     V1.0.1
;*   Date:        03.05.2021
;*   Author:      HeX0R
;*                http://hex0rs.coderbu.de
;*   URL:         https://www.purebasic.fr/english/viewtopic.php?f=12&t=62689
;*
;*   License:     BEER-WARE
;*                Thomas 'HeX0R' Milz wrote this file. As long as you retain this notice you
;*                can do whatever you want with this stuff. If we meet some day, and you think
;*                this stuff is worth it, you can buy me a beer in return.
;*                                                               HeX0R@coderbu.de
;*
;*   OS:          [x] Windows (> Windows XP!!)
;*                [x] Linux
;*                [?] MacOS (untested)
;*
;*   Description: With this IDE Tool you can
;*                directly include code from the internet
;*
;*
;*   Usage
;*   Just use HTTPInclude "URL" instead of IncludeFile "FILENAME"
;*   e.g.
;*   HTTPInclude "http://www.purebasic.fr/english/viewtopic.php?f=12&t=62033"
;*   you can add also special parameters to the end, e.g.:
;*   HTTPInclude "http://www.purebasic.fr/english/viewtopic.php?f=12&t=62033" ;reload ;raw
;*   Explanation:
;*   ;reload         ->    Will force the source to be reloaded (otherwise it will use the local copy on your PC (if any))
;*   ;raw            ->    Will just use the whole file, otherwise the tool expects the code is part of a forum thread (and will use regular expressions, see ;usesource below)
;*   ;load=#num      ->    load=2 will load the second code it finds in the forum thread
;*   ;usebom=        ->    You can force to read the file with a special BOM, usable: utf8, utf16, ascii
;*   ;usesource=name ->    If you don't set this, the default for the pureboards will be used (or depending on the URL, please see below)
;*                      Create more Regular expressions for different boards, please take a look into %APPDATA%\http_include\settings.prefs:
;*                      [Source_{Name}]
;*                      Name        = Name of the Regex, usually the forum name it will handle.
;*                      URL         = Regex to extract an anchor from the URL
;*                      CodeReg     = Regex to extract the code from the board
;*                      AnchorStart = This is NO Regex! But just a text to find. Anything will start from that position then
;*                      RootURL     = when set, all URLs starting with this string, will be use this Source (if not forced to use a different one via usesource=xxx)
;*                      UseRaw      = when set to 1, all regular expressions will not be used, and the raw data from the URL is directly picked up.
;*
;*
;*******************************************

Enumeration
	#File_Compiled_Source
	#File_Downloaded_Source
	#File_New_Offline_Source
	#File_Error_Log
EndEnumeration

CompilerIf Defined(DEBUG_SOURCE, #PB_Constant) = 0
	;only for debugging purposes
	#DEBUG_SOURCE = "C:\Temp\PB_EditorOutput.pb"
CompilerEndIf


InitNetwork()
EnableExplicit

;On the first run you will need this Include of course (henn/egg problem)!
;Just download it and use IncludeFile instead.
HTTPInclude "https://www.purebasic.fr/english/viewtopic.php?f=12&t=62033"


Structure _Source_
	Name.s
	RootURL.s
	URLStart.s
	URLReg.i
	AnchorStart.s
	CodeReg.i
	UseRaw.b
EndStructure

Global NewList Lines.s()
Global NewList Sources._Source_()

Procedure ErrorLog(Text.s)
	Static First

	If First = 0
		CreateFile(#File_Error_Log, GetUserDirectory(#PB_Directory_ProgramData) + "http_include/error.log")
		First = #True
	EndIf
	If IsFile(#File_Error_Log)
		WriteStringN(#File_Error_Log, FormatDate("%hh:%ii:%ss ", Date()) + Text)
	EndIf
EndProcedure

#REG_1 = "pureboard"
#REG_2 = "#p\d*"
#REG_3 = "(?<=<code>)[^<]*"
#REG_4 = ~"<div id=\"{ANCHOR}\""

Procedure SelectSource(Name.s, RootURL.s)
	Protected Result

	ForEach Sources()
		If Name
			If LCase(Name) = Sources()\Name
				Result = #True
				Break
			EndIf
		ElseIf LCase(RootURL) = Sources()\RootURL
			Result = #True
			Break
		ElseIf Sources()\Name = #REG_1
			Result = #True
			Break
		EndIf
	Next

	ProcedureReturn Result
EndProcedure

Procedure InitSources()
	Protected a$, b$

	If PreferenceGroup("Source_PureBoard") = 0
		WritePreferenceString("RootURL",     "https://www.purebasic.fr/")
		WritePreferenceString("Name",        #REG_1)
		WritePreferenceString("URL",         #REG_2)
		WritePreferenceString("CodeReg",     #REG_3)
		WritePreferenceString("AnchorStart", #REG_4)
		WritePreferenceInteger("UseRaw",     0)
	EndIf

	With Sources()
		If ExaminePreferenceGroups()
			While NextPreferenceGroup()
				a$ = PreferenceGroupName()
				If Left(LCase(a$), 6) = "source_"
					AddElement(Sources())
					\Name    = LCase(Mid(a$, 8))
					\UseRaw  = ReadPreferenceInteger("UseRaw", 0)
					\RootURL = LCase(ReadPreferenceString("RootURL", "https://www.purebasic.fr/"))
					a$       = ReadPreferenceString("URL", #REG_2)
					If a$
						\URLReg = CreateRegularExpression(#PB_Any, a$)
						If \URLReg = 0
							ErrorLog("There is an error in the URL Regex of '" + \Name + "': " + RegularExpressionError())
						EndIf
					EndIf
					\AnchorStart = ReadPreferenceString("AnchorStart", #REG_4)
					a$           = ReadPreferenceString("CodeReg", #REG_3)
					If a$
						\CodeReg = CreateRegularExpression(#PB_Any, a$, #PB_RegularExpression_DotAll)
						If \CodeReg = 0
							ErrorLog("There is an error in the Code Regex of '" + \Name + "': " + RegularExpressionError())
						EndIf
					EndIf
				EndIf
			Wend
		EndIf

		If SelectSource("", "") = 0
			AddElement(Sources())
			\Name        = "pureboard"
			\URLReg      = CreateRegularExpression(#PB_Any, #REG_2)
			\AnchorStart = #REG_4
			\CodeReg     = CreateRegularExpression(#PB_Any, #REG_3, #PB_RegularExpression_DotAll)
			\RootURL     = "https://www.purebasic.fr/"
			\UseRaw      = 0
		EndIf
	EndWith

EndProcedure

Procedure main()
	Protected SourceCode.s, BOM, URL.s, i, j, k, Pos, Reload, PathToPrefs.s, PathToIncludes.s
	Protected a$, Code.s, Changed, FileName.s, Num, Raw, SourceBOM, SourceBOMText.s, Anchor.s, Name.s

	CompilerIf #PB_Compiler_Debugger
	SourceCode = #DEBUG_SOURCE
	CompilerElse
	SourceCode = ProgramParameter(0)
	CompilerEndIf

	;First create our directorys
	PathToPrefs = GetUserDirectory(#PB_Directory_ProgramData) + "http_include/"
	If FileSize(PathToPrefs) <> -2
		CreateDirectory(PathToPrefs)
	EndIf
	;then open (or create) preferences
	If OpenPreferences(PathToPrefs + "settings.prefs") = 0
		CreatePreferences(PathToPrefs + "settings.prefs")
	EndIf

	Debug SourceCode
	InitSources()
	PreferenceGroup("main")
	;this is the path, were the includes will be stored
	PathToIncludes = ReadPreferenceString("PathToIncludes", PathToPrefs + "includes/")

	If SourceCode
		;we have a program parameter
		;let's go
		;first open the SourceCode
		If OpenFile(#File_Compiled_Source, SourceCode)
			BOM       = ReadStringFormat(#File_Compiled_Source)   ;<- save the BOM
			Changed   = #False                ;<- If we changed something, this will be true

			While Eof(#File_Compiled_Source) = 0
				;read any line and add it to our list
				AddElement(Lines())
				Lines() = ReadString(#File_Compiled_Source, BOM)
				If FindString(Trim(Trim(Lines()), #TAB$), "httpinclude", 1, #PB_String_NoCase) = 1 And CountString(Lines(), #DQUOTE$) > 1  ;<- is there a httpinclude at the beginning?
					Code      = ""
					Num       = 1
					SourceBOM = #PB_UTF8                                                   ;<- this is the BOM for the external file
					URL       = StringField(Lines(), 2, #DQUOTE$)                          ;<- get the URL of the include
					Pos       = Len(URL) + 13                                              ;<- start searching position for optional parameters (URL + 2x DQOUTE + httpinclude)
					Reload    = FindString(Lines(), ";reload",  Pos, #PB_String_NoCase)    ;<- if there is a ;reload behind it, this include will be updated
					Raw       = FindString(Lines(), ";raw",     Pos, #PB_String_NoCase)    ;<- if ;raw is an optional parameter we expect a raw code file instead of code inside a forum thread
					i         = FindString(Lines(), ";usesource=", Pos, #PB_String_NoCase)
					If i
						Name = Trim(LCase(Mid(Lines(), i + 11)))
						If SelectSource(Name, "") = 0 And SelectSource("", URL) = 0
							SelectSource("", "")
						EndIf
					ElseIf SelectSource("", URL) = 0
						SelectSource("", "")
					EndIf
					If Raw = 0
						Raw = Sources()\UseRaw
					EndIf

					i = FindString(Lines(), ";load=",   Pos, #PB_String_NoCase) ;<- with load=2 e.g. we load the second code in a thread (only useful for code inside a forum thread)
					If i
						Num = Val(Mid(Lines(), i + 6))
					EndIf
					i = FindString(Lines(), ";usebom=", Pos, #PB_String_NoCase) ;<- by default we expect the external file in UTF8 format, but maybe the site stores it different?
					If i
						SourceBOMText = Mid(Lines(), i + 8)
						If Left(LCase(SourceBOMText), 4) = "utf8"
							SourceBOM = #PB_UTF8
						ElseIf Left(LCase(SourceBOMText), 5) = "utf16"
							SourceBOM = #PB_UTF16
						ElseIf Left(LCase(SourceBOMText), 5) = "ascii"
							SourceBOM = #PB_Ascii
						EndIf
					EndIf
					If PreferenceGroup(URL) And ReadPreferenceString("file_" + Str(Num), "") And Reload = 0            ;<- check if we already have stored this include and there is no ;reload
						Lines()  = "XIncludeFile " + #DQUOTE$ + ReadPreferenceString("file_" + Str(Num), "") + #DQUOTE$  ;<- yes, o.k. just change this line and include our previously loaded (and stored) source
						Changed  = #True                                                            ;<- we changed something
					Else
						;no old include there, or user wants to update it
						;first load the include from the internet to a temporary directory
						If ReceiveHTTPFile(URL, GetTemporaryDirectory() + "http_include.tmp")
							;o.k., now open the html-file
							If ReadFile(#File_Downloaded_Source, GetTemporaryDirectory() + "http_include.tmp") = 0
								ErrorLog("Can't open downloaded file '" + GetTemporaryDirectory() + "http_include.tmp'")
							Else
								i = ReadStringFormat(#File_Downloaded_Source)
								If i <> #PB_Ascii ;if there is a BOM inside the file we overwrite the user setting
									SourceBOM = i
								EndIf
								a$ = ReadString(#File_Downloaded_Source, SourceBOM | #PB_File_IgnoreEOL) ;<- read anything in a$
								CloseFile(#File_Downloaded_Source)                                       ;<- we are finished with the tmp file, we have anything inside a$, so close it and delete it.
								DeleteFile(GetTemporaryDirectory() + "http_include.tmp")
								;now find the start of the code
								If Raw
									;we want to use the whole file as is, not much to do here
									Code = a$
								Else
									;o.k. I guess this code is inside a forum thread, so we need to find the code in it.
									;the below will only work inside pureboards, we probably have to change something for other boards.
									Dim Result$(0)
									If IsRegularExpression(Sources()\URLReg)
										k = ExtractRegularExpression(Sources()\URLReg, URL, Result$())
										If k
											Anchor = Result$(0)
											If Left(Anchor, 1) = "#"
												Anchor = Mid(Anchor, 2)
											EndIf
										EndIf
									EndIf


									If Anchor
										k = FindString(a$, ReplaceString(Sources()\AnchorStart, "{ANCHOR}", Anchor, #PB_String_NoCase), 1, #PB_String_NoCase)
										If k
											a$ = Mid(a$, k)
										EndIf
									EndIf
									If IsRegularExpression(Sources()\CodeReg)
										k = ExtractRegularExpression(Sources()\CodeReg, a$, Result$())
										If k > 0 And Num <= k
											Code = Result$(Num - 1)
											;now we have to decode a few html tags
											;maybe I didn't catch anything, need to keep an eye on this
											Code = ReplaceString(Code, "&nbsp; ", "&nbsp;")
											Code = ReplaceString(ReplaceString(Code, "<br />", #CRLF$), "&nbsp;", " ")
											Code = ReplaceString(ReplaceString(Code, "&#91;", "["), "&#93;", "]")
											Code = ReplaceString(ReplaceString(Code, "&quot;", #DQUOTE$), "&lt;", "<")
											Code = ReplaceString(ReplaceString(Code, "&gt;", ">"), "&amp;", "&")
										EndIf
									EndIf
								EndIf
								If Code

									If FileSize(PathToIncludes) <> -2
										;this seems to be the first file we want to store, so create the directory
										CreateDirectory(PathToIncludes)
									EndIf

									If Reload
										;We already had this file before and user wants it to be updated, so just take the original filename
										FileName = ReadPreferenceString("file_" + Str(Num), "")
									Else
										;search for the next unused filename
										j = 0
										While FileSize(PathToIncludes + RSet(Str(j), 6, "0") + ".pb") <> -1
											j + 1
										Wend
										FileName = PathToIncludes + RSet(Str(j), 6, "0") + ".pb"
									EndIf
									;Save our new include
									If CreateFile(#File_New_Offline_Source, FileName)
										WriteStringFormat(#File_New_Offline_Source, #PB_UTF8) ;<- for PB I usually always use UTF8 as file format
										WriteString(#File_New_Offline_Source, Code, #PB_UTF8)
										CloseFile(#File_New_Offline_Source)
										If Reload = 0
											;only write the FileName into our preference file, if there were no "reload" parameter.
											WritePreferenceString("file_" + Str(Num), FileName)
										EndIf
										;Change the line now finally
										Lines() = "XIncludeFile " + #DQUOTE$ + FileName + #DQUOTE$
										Changed = #True ;<- we changed something
									EndIf
								EndIf
							EndIf
						ElseIf Reload ;<- seems the URL couldn't get accessed, but this is just a reload, we can still use our old file
							FileName = ReadPreferenceString("file_" + Str(Num), "")
							Lines()  = "XIncludeFile " + #DQUOTE$ + FileName + #DQUOTE$
							Changed  = #True ;<- we changed something
						Else
							ErrorLog("Can't reach '" + URL + "'!")
						EndIf
					EndIf
				EndIf
			Wend
			CloseFile(#File_Compiled_Source)
			If Changed
				;something changed, so rewrite the file for the compiler
				DeleteFile(SourceCode)
				If CreateFile(#File_Compiled_Source, SourceCode)
					WriteStringFormat(#File_Compiled_Source, BOM)
					ForEach Lines()
						WriteStringN(#File_Compiled_Source, Lines(), BOM)
					Next
					CloseFile(#File_Compiled_Source)
				EndIf
			EndIf
		Else

		EndIf
		ClosePreferences()

	Else
		;no programparameter, so try to install it
		ClosePreferences()
		;See my IDE tool here: http://www.purebasic.fr/english/viewtopic.php?f=12&t=62033
		If IDETOOL::Install("HTTPIncludeA", #DQUOTE$ + "%COMPILEFILE" + #DQUOTE$, "", IDETOOL::#TRIGGER_BEFORE_COMPILING, IDETOOL::#FLAG_WAIT_FOR_TOOL | IDETOOL::#FLAG_START_HIDDEN, 0, 0, 0, 1)
			If IDETOOL::Install("HTTPIncludeB", #DQUOTE$ + "%COMPILEFILE" + #DQUOTE$, "", IDETOOL::#TRIGGER_BEFORE_EXE_CREATION, IDETOOL::#FLAG_WAIT_FOR_TOOL | IDETOOL::#FLAG_START_HIDDEN, 0, 0, 0, 1)
				OpenPreferences(PathToPrefs + "settings.prefs") ;<- open is enough, because we already created it on top of main()
				PreferenceGroup("main")
				a$ = PathRequester("Select Path where online Includes should be stored", PathToIncludes)
				If a$
					WritePreferenceString("PathToIncludes", a$)
				EndIf
				ClosePreferences()
				MessageRequester("Success!", "Successfully installed tool 'HTTPInclude'!" + #LF$ + "If your IDE is open, please restart it." + #LF$ + #LF$ + "(Remember to add HTTPInclude to your custom keywords!)")
			EndIf
		EndIf
	EndIf

	If IsFile(#File_Error_Log)
		CloseFile(#File_Error_Log)
	EndIf

EndProcedure

main()
Last edited by HeX0R on Tue May 04, 2021 12:36 pm, edited 2 times in total.
User avatar
HeX0R
Addict
Addict
Posts: 992
Joined: Mon Sep 20, 2004 7:12 am
Location: Hell

Re: HttpInclude [IDE Tool]

Post by HeX0R »

Example 1

Code: Select all

CompilerIf #PB_Compiler_OS <> #PB_OS_Windows
 CompilerError "Sorry! This example is only for Windows!"
CompilerEndIf

UseJPEGImageDecoder()

HTTPInclude "http://www.purebasic.fr/german/viewtopic.php?f=8&t=23478"

Procedure main()
 Protected wParam, *Buffer, GetFile._GETHTTP_INTERFACE_, w, h, f.f, Num
 Protected MS.s, i, j, k, *O
 
 MS = "DL#{N} ({B}Bytes loaded)"
 OpenWindow(0, 0, 0, 1200, 700, "GetHTTP Test", #PB_Window_SystemMenu | #PB_Window_TitleBar | #PB_Window_ScreenCentered)
 ImageGadget(0, 0, 0, 895, 680, 0, #PB_Image_Border)
 For i = 1 To 10
  TextGadget(i * 2 - 1, 905, 5 + 22 * i, 150, 20, ReplaceString(ReplaceString(MS, "{N}", Str(i)), "{B}", "0"))
  ButtonGadget(i * 2, 1059, 5 + 22 * i, 40, 20, "X")
 Next i
 
 CreateStatusBar(0, WindowID(0))
 AddStatusBarField(#PB_Ignore)
 
 Dim URLs.s(10)
 Dim *Pointer(10)
 URLs(0) =  "https://7wallpapers.net/wp-content/uploads/2016/05/9_Kate-Beckinsale.jpg"
 URLs(1) =  "https://images-wixmp-ed30a86b8c4ca887773594c2.wixmp.com/f/c2141608-e101-425a-987e-84d9c4dfef2d/d377vn2-00607470-5741-49e2-8967-4ef1c919f259.jpg?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1cm46YXBwOjdlMGQxODg5ODIyNjQzNzNhNWYwZDQxNWVhMGQyNmUwIiwiaXNzIjoidXJuOmFwcDo3ZTBkMTg4OTgyMjY0MzczYTVmMGQ0MTVlYTBkMjZlMCIsIm9iaiI6W1t7InBhdGgiOiJcL2ZcL2MyMTQxNjA4LWUxMDEtNDI1YS05ODdlLTg0ZDljNGRmZWYyZFwvZDM3N3ZuMi0wMDYwNzQ3MC01NzQxLTQ5ZTItODk2Ny00ZWYxYzkxOWYyNTkuanBnIn1dXSwiYXVkIjpbInVybjpzZXJ2aWNlOmZpbGUuZG93bmxvYWQiXX0.na_q9t8K4OtH3McpMxVpsvhLOZY_7kyhPFk2Yxg5DCM"
 URLs(2) =  "https://wallsdesk.com/wp-content/uploads/2016/07/Halle-Berry-for-desktop.jpg"
 URLs(3) =  "http://wallpaperspics.com/wallpapers/26/f/natalie-portman-women-actresses-celebrity-260895.jpg"
 URLs(4) =  "http://images2.fanpop.com/image/photos/8800000/Scarlett-Johansson-scarlett-johansson-8836700-1920-1200.jpg"
 URLs(5) =  "http://1.bp.blogspot.com/-L-XBLo2e-v0/Ul50CDn1bhI/AAAAAAAANbU/p8bQNQV90_k/s1600/Charlize+Theron+24+1024X768+Sexy+Wallpaper.jpg"
 URLs(6) =  "https://images4.fanpop.com/image/photos/17500000/Grace-Park-Wallpapers-grace-park-17581403-1920-1200.jpg"
 URLs(7) =  "http://wallpapers.skins.be/eva-padberg/eva-padberg-1024x768-23005.jpg"
 URLs(8) =  "http://www.wallpaperweb.org/wallpaper/babes/1600x1200/tab05vot002AlessandraAmbrosio.jpg"
 URLs(9) =  "http://www.celebs101.com/gallery/Lexa_Doig/160353/Lexa_Doig26.jpg"
 
 
 GetFile = GetHTTP_CreateInterface()
 
 For i = 0 To 9
  *Pointer(i) = GetFile\GetFileInMemory(URLs(i), "", "", #INTERNET_FLAG_RESYNCHRONIZE, WindowID(0), #WM_APP, #GETHTTP_MODE_ASYNCHRON, 256)
 Next i
 StatusBarText(0, 0, "Lade...")
 
 Repeat
  Select WaitWindowEvent(200)
   Case 0
    For i = 1 To 10
     k = GetFile\AsyncDownloadBytesLoaded(*Pointer(i - 1))
     If GetFile\IsAyncDownloadRunning(*Pointer(i - 1)) = 0
      SetGadgetText(i * 2 - 1, "DL#" + Str(i) + ": finished! (" + Str(k) + "Bytes)")
      DisableGadget(i * 2, 1)
     Else
      If k
       SetGadgetText(i * 2 - 1, ReplaceString(ReplaceString(MS, "{N}", Str(i)), "{B}", Str(k)))
      EndIf
     EndIf
    Next i
   Case #PB_Event_CloseWindow
    Break
   Case #PB_Event_Gadget
    Select EventGadget()
     Case 0
      If EventType() = #PB_EventType_LeftClick
        Num + 1
        If Num > 9
         Num = 0
        EndIf
        If GetFile\IsAyncDownloadRunning(*Pointer(Num))
         StatusBarText(0, 0, "The pic#" + Str(Num + 1) + " not yet ready!")
        Else
         *Buffer = GetFile\GetResult(*Pointer(Num))
         If *Buffer And CatchImage(0, *Buffer, MemorySize(*Buffer))
          w = ImageWidth(0)
         h = ImageHeight(0)
         If w > 895 - 4
          f = (895 - 4) / w
         EndIf
         If h > 680 - 22
          If f > ((680 - 22) / h)
           f = (680 - 22) / h
          EndIf
         EndIf
         ResizeImage(0, w * f, h * f)
         SetGadgetState(0, ImageID(0))
         StatusBarText(0, 0, "Now showing pic#" + Str(Num + 1))
        EndIf
       EndIf
      EndIf
     Default
      i = EventGadget() / 2
      If GetFile\IsAyncDownloadRunning(*Pointer(i - 1))
       GetFile\StopAsyncDownload(*Pointer(i - 1))
      EndIf
      

    EndSelect
   Case #WM_APP
    wParam  = EventwParam()
    *Buffer = GetFile\GetResult(wParam)
    If *Buffer
     If CatchImage(0, *Buffer, MemorySize(*Buffer))
      w = ImageWidth(0)
      h = ImageHeight(0)
      If w > 895 - 4
       f = (895 - 4) / w
      EndIf
      If h > 680 - 22
       If f > ((680 - 22) / h)
        f = (680 - 22) / h
       EndIf
      EndIf
      ResizeImage(0, w * f, h * f)
      SetGadgetState(0, ImageID(0))
     EndIf
    EndIf
  EndSelect
 ForEver

EndProcedure

main()
Example 2

Code: Select all

HTTPInclude "http://www.purebasic.fr/english/viewtopic.php?f=12&t=61902"

UseModule DrawingAA
  ; ******************************************************
  ; EXAMPLE
  ; Test functions to draw with anti-aliasing ( AA )
  ; ******************************************************
  If OpenWindow(0, 0, 0, 500, 500, "Test", #PB_Window_SystemMenu | #PB_Window_ScreenCentered | #PB_Window_MinimizeGadget)
   
   If CanvasGadget(0, 0, 0, 500, 500)
     StartDrawing(CanvasOutput(0))
     blackColor=RGBA(0, 0, 0, 255)
     
     ; Our fancy background
     #Carreau=25
     For n=0 To 500 Step #Carreau
      For nn=0 To 500 Step #Carreau
        If ((n + nn) / #Carreau) & %1=%1
         Box(n, nn, #Carreau, #Carreau, $FFFFFF)
        Else
         Box(n, nn, #Carreau, #Carreau, $0000FF)
        EndIf
      Next
     Next
     
     ; Drawing Circles
     DrawingModeAA(1, #PB_2DDrawing_AlphaBlend)
     CircleAA(100, 100, 70, blackColor)
     DrawingModeAA(1, #PB_2DDrawing_AlphaBlend | #PB_2DDrawing_Outlined)
     CircleAA(250, 100, 50, blackColor)
     DrawingModeAA(3)
     CircleAA(250, 100, 70, blackColor)
     
     ; Drawing Ellipses
     DrawingModeAA(2, #PB_2DDrawing_AlphaBlend)
     EllipseAA(400, 100, 30, 20, blackColor)
     DrawingModeAA(2, #PB_2DDrawing_AlphaBlend | #PB_2DDrawing_Outlined)
     EllipseAA(400, 100, 40, 60, blackColor)
     DrawingModeAA(1)
     EllipseAA(400, 100, 50, 70, blackColor)
     
     
     ; Drawing Lines
     DrawingModeAA(1);, #PB_2DDrawing_AlphaBlend)
     For n=0 To 150 Step 30
      LineAA(20, 200, 150, n, blackColor)
     Next
     For n=0 To 120 Step 30
      LineAA(20, 200, n, 150, blackColor)
     Next
     Thickness=2
     For n=0 To 150 Step 30
      DrawingModeAA(Thickness) : Thickness + 1
      LineAA(200, 200, 150, n, blackColor)
     Next
     Thickness=2
     For n=0 To 120 Step 30
      DrawingModeAA(Thickness) : Thickness + 1
      LineAA(200, 200, n, 150, blackColor)
     Next
     
     
     ; Drawing Triangles
     DrawingModeAA(1, #PB_2DDrawing_AlphaBlend)
     TriangleAA(420, 200, 480, 250, 370, 350, blackColor)
     Thickness=1
     DrawingModeAA(1, #PB_2DDrawing_AlphaBlend | #PB_2DDrawing_Outlined)
     For n=0 To 30 Step 10
      DrawingModeAA(Thickness) : Thickness + 1
      TriangleAA(490 - n, 260 + n, 390 + n, 350, 460, 400 - n, blackColor)
     Next
     StopDrawing()
   EndIf
   
   Repeat: Until WaitWindowEvent()=#PB_Event_CloseWindow
  EndIf
  End
Example 3

Code: Select all

HTTPInclude "http://www.purebasic.fr/english/viewtopic.php?f=12&t=61309" ;load=2

Define.BigInt::BigInt n1, n2, n3

BigInt::SetValue(n1, $1234567890abcdef)
BigInt::SetValue(n2, $fedcba0987654321)
BigInt::Multiply(n1, n2)
Debug BigInt::GetHex(n1)
BigInt::Divide(n1, n1, n2)
Debug BigInt::GetHex(n1)
Example 4

Code: Select all

HTTPInclude "http://www.purearea.net/pb/CodeArchiv/Gadgets/RulerGadget.pb" ;raw
Last edited by HeX0R on Mon May 03, 2021 11:01 pm, edited 1 time in total.
User avatar
Sicro
Enthusiast
Enthusiast
Posts: 538
Joined: Wed Jun 25, 2014 5:25 pm
Location: Germany
Contact:

Re: HttpInclude [IDE Tool]

Post by Sicro »

The idea is good.

But the codes from the forums or other internet sources should not
be included blindly and automatically in your own program codes.

For example, the code can work great at the beginning, but after the code author
has replaced the old code in his forum post with a new code version, it can
suddenly cause errors, which in the worst case will only become apparent very
late after the release of your final program by one of your customers.

A forum member could become angry after a dispute and insert malicious code into
his published codes. It can also be that instead of a dispute his forum account
was simply hacked by a bad guy.

The codes published on Github are more safe because all code versions are kept
and a particular code version can be accessed with a commit hash exactly. This
forces you to change the URL if you want to use a different version of the code.
This way you can be sure that the code you download is always exactly the same
code.

The forum thread is already old, but I wanted to get rid of that.
Image
Why OpenSource should have a license :: PB-CodeArchiv-Rebirth :: Pleasant-Dark (syntax color scheme) :: RegEx-Engine (compiles RegExes to NFA/DFA)
Manjaro Xfce x64 (Main system) :: Windows 10 Home (VirtualBox) :: Newest PureBasic version
User avatar
HeX0R
Addict
Addict
Posts: 992
Joined: Mon Sep 20, 2004 7:12 am
Location: Hell

Re: HttpInclude [IDE Tool]

Post by HeX0R »

The codes get locally stored after first include, it doesn't matter if it gets replaced or deleted online!
Please read first the comments in the code to really know how it works.

One big advantage is also, if you included something years ago, you still have the link to the original code in your source and can go there to see if a "refresh" might make sense, or not.
User avatar
Sicro
Enthusiast
Enthusiast
Posts: 538
Joined: Wed Jun 25, 2014 5:25 pm
Location: Germany
Contact:

Re: HttpInclude [IDE Tool]

Post by Sicro »

HeX0R wrote:The codes get locally stored after first include, it doesn't matter if it gets replaced
or deleted online!
Please read first the comments in the code to really know how it works.
Before I wrote the previous post, I not only read the comments in your code, but
also the code line by line. So I know what your code does.

The cache system is very good and reduces the problem a little bit, because the
code does not have to be re-downloaded every time the code is executed, but the
code must still be downloaded at least once and at this moment the code could
contain errors or malicious code.
HeX0R wrote:One big advantage is also, if you included something years ago, you still
have the link to the original code in your source and can go there to see
if a "refresh" might make sense, or not.
Yes, that's very good.
So you also have the forum thread URL to report bugs or suggest improvements.

What do you think about adding a code check to check if the code contains
dangerous commands? Here is an example:

Code: Select all

#DangerousCommands = "\bCreateFile\s*\(.*\)|" + ; CreateFile()
                     "\bReadFile\s*\(.*\)|" +   ; ReadFile()
                     "\b.*_\s*\(.*\)|" +        ; API_Function_()
                     "\bRunProgram\s*\(.*\)"    ; RunProgram()

RegEx_IsCodeSafe = CreateRegularExpression(#PB_Any, "(" + #DangerousCommands + ")")
If RegEx_IsCodeSafe
  
  Code$ = ~"ReadFile(\"FilePath\" ) " + #CRLF$ +
          ~"RunProgram(\"ProgramFilePath\")"
          
  If MatchRegularExpression(RegEx_IsCodeSafe, Code$)
    Debug "Code contains dangerous commands!"
    ; A window should open here and the code should be displayed, e.g. in an EditorGadget,
    ; so that the programmer can have a look at the code.
    ; There should also be two buttons to reject or accept the inclusion of the code.
  Else
    Debug "Code is safe!"
    ; Include the code
  EndIf
EndIf
Image
Why OpenSource should have a license :: PB-CodeArchiv-Rebirth :: Pleasant-Dark (syntax color scheme) :: RegEx-Engine (compiles RegExes to NFA/DFA)
Manjaro Xfce x64 (Main system) :: Windows 10 Home (VirtualBox) :: Newest PureBasic version
User avatar
HeX0R
Addict
Addict
Posts: 992
Joined: Mon Sep 20, 2004 7:12 am
Location: Hell

Re: HttpInclude [IDE Tool]

Post by HeX0R »

Sicro wrote:What do you think about adding a code check to check if the code contains dangerous commands?
There are no "dangerous" commands, you need more than a single command check to find out if something is dangerous, I will not include something like this.
In fact it was meant to be used for codes spreaded in the pure boards (although usable also with other sources), and I'm quite sure suspicious codes would be signaled quite fast here.

If you are worried about safety, then just don't use this tool.
User avatar
Sicro
Enthusiast
Enthusiast
Posts: 538
Joined: Wed Jun 25, 2014 5:25 pm
Location: Germany
Contact:

Re: HttpInclude [IDE Tool]

Post by Sicro »

HeX0R wrote:There are no "dangerous" commands, you need more than a single command
check to find out if something is dangerous, I will not include something like this.
I have described the commands as "dangerous", because someone can do
something dangerous with these commands.

It should be a simple scan and not a complex virus scanner.

Whether the code really does something dangerous, the programmer must check
manually. That's why I wrote in the code above that a window should open, which
shows the code for checking.
HeX0R wrote:In fact it was meant to be used for codes spreaded in the pure boards
(although usable also with other sources), and I'm quite sure suspicious
codes would be signaled quite fast here.
The forum threads quickly go deep into the forum. I don't know if the admins /
moderators get a notification, if someone edits his post.

A forum member will certainly report the malicious code at some point, but probably
not until the person has already suffered damage from the malicious code. Provided
the person has blindly downloaded the code and included it in the main code.
HeX0R wrote:(although usable also with other sources)
Whether these sources are also so safe...
HeX0R wrote:If you are worried about safety, then just don't use this tool.
Okay, I thought there was also the option to help to make the tool safer.
Image
Why OpenSource should have a license :: PB-CodeArchiv-Rebirth :: Pleasant-Dark (syntax color scheme) :: RegEx-Engine (compiles RegExes to NFA/DFA)
Manjaro Xfce x64 (Main system) :: Windows 10 Home (VirtualBox) :: Newest PureBasic version
User avatar
HeX0R
Addict
Addict
Posts: 992
Joined: Mon Sep 20, 2004 7:12 am
Location: Hell

Re: HttpInclude [IDE Tool]

Post by HeX0R »

Updated to be used with the new board (and made it a little more flexible also).
Mesa
Enthusiast
Enthusiast
Posts: 349
Joined: Fri Feb 24, 2012 10:19 am

Re: HttpInclude [IDE Tool]

Post by Mesa »

Just for information, the purebasic command "ReceiveHTTPFile()" doesn't work on windows XP because this command use curl without the management of ssl and windows xp 32b doesn't manage ssl, so downloads fail.

So there is a work around, in using curl.exe compiled with all static dll needed like openssl, etc.
See here: https://curl.se/windows/

Mesa.
User avatar
HeX0R
Addict
Addict
Posts: 992
Joined: Mon Sep 20, 2004 7:12 am
Location: Hell

Re: HttpInclude [IDE Tool]

Post by HeX0R »

Windows XP?
Hmm... I heard about it... when I was younger... much younger :mrgreen:

No seriously, feel free to change that for your XP, I'm only releasing the source here, I don't want to create a download packet only to support stone-old OSs.

I'll add a note to the comments, though, thanks for the info!
Post Reply