text
stringlengths
1
2.83M
id
stringlengths
16
152
metadata
dict
__index_level_0__
int64
0
949
--- title: SendDeathMessageToPlayer description: Adds a death to the 'killfeed' on the right-hand side of the screen for a single player. tags: ["player"] --- ## คำอธิบาย Adds a death to the 'killfeed' on the right-hand side of the screen for a single player. | Name | Description | | -------- | --------------------------------------------------------------------------------------------------------------------------- | | playerid | The ID of the player to send the death message to. | | killer | The ID of the killer (can be INVALID_PLAYER_ID). | | killee | The ID of the player that died. | | weapon | The reason (not always a weapon) for the victim's death. Special icons can also be used (ICON_CONNECT and ICON_DISCONNECT). | ## ส่งคืน 1: The function was executed successfully. 0: The function failed to execute. ## ตัวอย่าง ```c public OnPlayerDeath(playerid, killerid, WEAPON:reason) { // Sends a death message to "playerid" shows that "killerid" killed "playerid" for "reason" SendDeathMessageToPlayer(playerid, killerid, playerid, reason); return 1; } ``` ## ฟังก์ชั่นที่เกี่ยวข้องกัน - SendDeathMessage: Add a kill to the death list. - OnPlayerDeath: Called when a player dies.
openmultiplayer/web/docs/translations/th/scripting/functions/SendDeathMessageToPlayer.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/SendDeathMessageToPlayer.md", "repo_id": "openmultiplayer", "token_count": 784 }
460
--- title: SetObjectMaterialText description: Replace the texture of an object with text. tags: [] --- ## คำอธิบาย Replace the texture of an object with text. | Name | Description | | ------------- | --------------------------------------------------------------------------------------------- | | objectid | The ID of the object to replace the texture of with text. | | text | The text to show on the object. (MAX 2048 characters) | | materialindex | The object's material index to replace with text. | | materialsize | The [size](/docs/scripting/resources/materialtextsizes) of the material. | | fontface | The font to use. | | fontsize | The size of the text (MAX 255). | | bold | Bold text. Set to 1 for bold, 0 for not. | | fontcolor | The color of the text, in ARGB format. | | backcolor | The background color, in ARGB format. | | textalignment | The [alignment](/docs/scripting/resources/materialtextalignment) of the text (default: left). | ## ส่งคืน 1: The function was executed successfully. 0: The function failed to execute. ## ตัวอย่าง ```c if (strcmp("/text", cmdtext, true) == 0) { new objectid = CreateObject(19353, 0, 0, 10, 0.0, 0.0, 90.0); //create the object SetObjectMaterialText(objectid, "SA-MP {FFFFFF}0.3{008500}e {FF8200}RC7", 0, OBJECT_MATERIAL_SIZE_256x128, "Arial", 28, 0, 0xFFFF8200, 0xFF000000, OBJECT_MATERIAL_TEXT_ALIGN_CENTER); // write "SA-MP 0.3e RC7" on the object, with orange font color and black background return 1; } ``` ## บันทึก :::tip Color embedding can be used for multiple colors in the text. ::: :::warning You MUST use ARGB color format, not RGBA like used in client messages etc. ::: ## ฟังก์ชั่นที่เกี่ยวข้องกัน - SetPlayerObjectMaterialText: Replace the texture of a player object with text. - SetObjectMaterial: Replace the texture of an object with the texture from another model in the game. - Ultimate Creator by Nexius - SetObjectMaterialText Editor by RIDE2DAY - Fusez's Map Editor by RedFusion
openmultiplayer/web/docs/translations/th/scripting/functions/SetObjectMaterialText.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/SetObjectMaterialText.md", "repo_id": "openmultiplayer", "token_count": 1281 }
461
--- title: SetPlayerColor description: Set the colour of a player's nametag and marker (radar blip). tags: ["player"] --- ## คำอธิบาย Set the colour of a player's nametag and marker (radar blip). | Name | Description | | -------- | ---------------------------------------- | | playerid | The ID of the player whose color to set. | | color | The color to set. Supports alpha values. | ## ส่งคืน This function does not return any specific values. ## ตัวอย่าง ```c // Red, using hexadecimal notation: SetPlayerColor(playerid, 0xFF0000FF); //Red, using decimal notation: SetPlayerColor(playerid, 4278190335); ``` ## บันทึก :::tip This function will change player's color for everyone, even if player's color was changed with SetPlayerMarkerForPlayer for any other player. If used under OnPlayerConnect, the affecting player will not see the color in the TAB menu. ::: ## ฟังก์ชั่นที่เกี่ยวข้องกัน - SetPlayerMarkerForPlayer: Set a player's marker. - GetPlayerColor: Check the color of a player. - ChangeVehicleColor: Set the color of a vehicle.
openmultiplayer/web/docs/translations/th/scripting/functions/SetPlayerColor.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/SetPlayerColor.md", "repo_id": "openmultiplayer", "token_count": 435 }
462
--- title: SetPlayerPosFindZ description: This sets the players position then adjusts the players z-coordinate to the nearest solid ground under the position. tags: ["player"] --- ## คำอธิบาย This sets the players position then adjusts the players z-coordinate to the nearest solid ground under the position. | Name | Description | | -------- | -------------------------------------------- | | playerid | The ID of the player to set the position of. | | Float:x | The X coordinate to position the player at. | | Float:y | The X coordinate to position the player at. | | Float:z | The Z coordinate to position the player at. | ## ส่งคืน 1: The function executed successfully. 0: The function failed to execute. This means the player specified does not exist. ## ตัวอย่าง ```c SetPlayerPosFindZ(playerid, 1234.5, 1234.5, 1000.0); ``` ## บันทึก :::warning This function does not work if the new coordinates are far away from where the player currently is. The Z height will be 0, which will likely put them underground. It is highly recommended that the MapAndreas plugin be used instead. ::: ## ฟังก์ชั่นที่เกี่ยวข้องกัน - SetPlayerPos: Set a player's position. - OnPlayerClickMap: Called when a player sets a waypoint/target on the pause menu map.
openmultiplayer/web/docs/translations/th/scripting/functions/SetPlayerPosFindZ.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/SetPlayerPosFindZ.md", "repo_id": "openmultiplayer", "token_count": 469 }
463
--- title: SetSVarString description: Set a string server variable. tags: [] --- :::warning This function was added in SA-MP 0.3.7 R2 and will not work in earlier versions! ::: ## คำอธิบาย Set a string server variable. | Name | Description | | -------------- | -------------------------------- | | varname[] | The name of the server variable. | | string_value[] | The string to be set. | ## ส่งคืน 1: The function executed successfully. 0: The function failed to execute. The variable name is null or over 40 characters. ## ตัวอย่าง ```c // set "Version" SetSVarString("Version", "0.3.7"); // will print version that server has new string[5 + 1]; GetSVarString("Version", string, sizeof(string)); printf("Version: %s", string); ``` ## ฟังก์ชั่นที่เกี่ยวข้องกัน - SetSVarInt: Set an integer for a server variable. - GetSVarInt: Get a player server as an integer. - GetSVarString: Get the previously set string from a server variable. - SetSVarFloat: Set a float for a server variable. - GetSVarFloat: Get the previously set float from a server variable. - DeleteSVar: Delete a server variable.
openmultiplayer/web/docs/translations/th/scripting/functions/SetSVarString.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/SetSVarString.md", "repo_id": "openmultiplayer", "token_count": 454 }
464
--- title: SetVehicleZAngle description: Set the Z rotation (yaw) of a vehicle. tags: ["vehicle"] --- ## คำอธิบาย Set the Z rotation (yaw) of a vehicle. | Name | Description | | ------------- | --------------------------------------------- | | vehicleid | The ID of the vehicle to set the rotation of. | | Float:z_angle | The Z angle to set. | ## ส่งคืน 1: The function executed successfully. 0: The function failed to execute. The vehicle specified does not exist. ## ตัวอย่าง ```c public OnPlayerCommandText(playerid, cmdtext[]) { if (strcmp(cmdtext, "/flip", true) == 0) { new currentveh; new Float:angle; currentveh = GetPlayerVehicleID(playerid); GetVehicleZAngle(currentveh, angle); SetVehicleZAngle(currentveh, angle); SendClientMessage(playerid, 0xFFFFFFFF, "Your vehicle has been flipped."); return 1; } return 0; } ``` ## บันทึก :::tip A vehicle's X and Y (pitch and roll) rotation will be reset when this function is used. The X and Y rotations can not be set. This function does not work on unoccupied vehicles (It is believed to be a GTA limitation). ::: ## ฟังก์ชั่นที่เกี่ยวข้องกัน - GetVehicleZAngle: Check the current angle of a vehicle. - SetVehiclePos: Set the position of a vehicle.
openmultiplayer/web/docs/translations/th/scripting/functions/SetVehicleZAngle.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/SetVehicleZAngle.md", "repo_id": "openmultiplayer", "token_count": 605 }
465
--- title: TextDrawBackgroundColor description: Adjusts the text draw area background color (the outline/shadow - NOT the box. tags: ["textdraw"] --- ## คำอธิบาย Adjusts the text draw area background color (the outline/shadow - NOT the box. For box color, see TextDrawBoxColor). | Name | Description | | ----- | ----------------------------------------------------- | | text | The ID of the textdraw to set the background color of | | color | The color that the textdraw should be set to. | ## ส่งคืน This function does not return any specific values. ## ตัวอย่าง ```c new Text:MyTextdraw; public OnGameModeInit() { MyTextdraw= TextDrawCreate(320.0, 425.0, "This is an example textdraw"); TextDrawUseBox(MyTextdraw, 1); TextDrawBackgroundColor(MyTextdraw, 0xFFFFFFFF); // Set the background color of MyTextdraw to white return 1; } ``` ## บันทึก :::tip If TextDrawSetOutline is used with size > 0, the outline color will match the color used in TextDrawBackgroundColor. Changing the value of color seems to alter the color used in TextDrawColor ::: :::tip If you want to change the background colour of a textdraw that is already shown, you don't have to recreate it. Simply use TextDrawShowForPlayer/TextDrawShowForAll after modifying the textdraw and the change will be visible. ::: ## ฟังก์ชั่นที่เกี่ยวข้องกัน - [TextDrawCreate](../functions/TextDrawCreate.md): Create a textdraw. - [TextDrawDestroy](../functions/TextDrawDestroy.md): Destroy a textdraw. - [TextDrawColor](../functions/TextDrawColor.md): Set the color of the text in a textdraw. - [TextDrawBoxColor](../functions/TextDrawBoxColor.md): Set the color of the box in a textdraw. - [TextDrawAlignment](../functions/TextDrawAlignment.md): Set the alignment of a textdraw. - [TextDrawFont](../functions/TextDrawFont.md): Set the font of a textdraw. - [TextDrawLetterSize](../functions/TextDrawLetterSize.md): Set the letter size of the text in a textdraw. - [TextDrawTextSize](../functions/TextDrawTextSize.md): Set the size of a textdraw box. - [TextDrawSetOutline](../functions/TextDrawSetOutline.md): Choose whether the text has an outline. - [TextDrawSetShadow](../functions/TextDrawSetShadow.md): Toggle shadows on a textdraw. - [TextDrawSetProportional](../functions/TextDrawSetProportional.md): Scale the text spacing in a textdraw to a proportional ratio. - [TextDrawUseBox](../functions/TextDrawUseBox.md): Toggle if the textdraw has a box or not. - [TextDrawSetString](../functions/TextDrawSetString.md): Set the text in an existing textdraw. - [TextDrawShowForPlayer](../functions/TextDrawShowForPlayer.md): Show a textdraw for a certain player. - [TextDrawHideForPlayer](../functions/TextDrawHideForPlayer.md): Hide a textdraw for a certain player. - [TextDrawShowForAll](../functions/TextDrawShowForAll.md): Show a textdraw for all players. - [TextDrawHideForAll](../functions/TextDrawHideForAll.md): Hide a textdraw for all players.
openmultiplayer/web/docs/translations/th/scripting/functions/TextDrawBackgroundColor.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/TextDrawBackgroundColor.md", "repo_id": "openmultiplayer", "token_count": 1008 }
466
--- title: TextDrawSetString description: Changes the text on a textdraw. tags: ["textdraw"] --- ## คำอธิบาย Changes the text on a textdraw. | Name | Description | | -------- | ------------------------------- | | text | The TextDraw to change | | string[] | The new string for the TextDraw | ## ส่งคืน This function does not return any specific values. ## ตัวอย่าง ```c new Text:himessage; public OnGameModeInit() { himessage = TextDrawCreate(1.0, 5.6, "Hi, how are you?"); return 1; } public OnPlayerConnect(playerid) { new newtext[41], name[MAX_PLAYER_NAME]; GetPlayerName(playerid, name, MAX_PLAYER_NAME); format(newtext, sizeof(newtext), "Hi %s, how are you?", name); TextDrawSetString(himessage, newtext); TextDrawShowForPlayer(playerid, himessage); return 1; } ``` ## บันทึก :::warning There are limits to the length of textdraw strings - see here for more info. ::: ## ฟังก์ชั่นที่เกี่ยวข้องกัน - [TextDrawCreate](../functions/TextDrawCreate.md): Create a textdraw. - [TextDrawDestroy](../functions/TextDrawDestroy.md): Destroy a textdraw. - [TextDrawColor](../functions/TextDrawColor.md): Set the color of the text in a textdraw. - [TextDrawBoxColor](../functions/TextDrawBoxColor.md): Set the color of the box in a textdraw. - [TextDrawBackgroundColor](../functions/TextDrawBackgroundColor.md): Set the background color of a textdraw. - [TextDrawAlignment](../functions/TextDrawAlignment.md): Set the alignment of a textdraw. - [TextDrawFont](../functions/TextDrawFont.md): Set the font of a textdraw. - [TextDrawLetterSize](../functions/TextDrawLetterSize.md): Set the letter size of the text in a textdraw. - [TextDrawTextSize](../functions/TextDrawTextSize.md): Set the size of a textdraw box. - [TextDrawSetOutline](../functions/TextDrawSetOutline.md): Choose whether the text has an outline. - [TextDrawSetShadow](../functions/TextDrawSetShadow.md): Toggle shadows on a textdraw. - [TextDrawSetProportional](../functions/TextDrawSetProportional.md): Scale the text spacing in a textdraw to a proportional ratio. - [TextDrawUseBox](../functions/TextDrawUseBox.md): Toggle if the textdraw has a box or not. - [TextDrawShowForPlayer](../functions/TextDrawShowForPlayer.md): Show a textdraw for a certain player. - [TextDrawHideForPlayer](../functions/TextDrawHideForPlayer.md): Hide a textdraw for a certain player. - [TextDrawShowForAll](../functions/TextDrawShowForAll.md): Show a textdraw for all players. - [TextDrawHideForAll](../functions/TextDrawHideForAll.md): Hide a textdraw for all players.
openmultiplayer/web/docs/translations/th/scripting/functions/TextDrawSetString.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/TextDrawSetString.md", "repo_id": "openmultiplayer", "token_count": 936 }
467
--- title: floatadd description: Adds two floats together. tags: [] --- :::warning This function starts with lowercase letter. ::: ## คำอธิบาย Adds two floats together. This function is redundant as the standard operator (+) does the same thing. | Name | Description | | ------------- | ------------- | | Float:Number1 | First float. | | Float:Number2 | Second float. | ## ส่งคืน The sum of the two given floats. ## ตัวอย่าง ```c public OnGameModeInit() { new Float:Number1 = 2, Float:Number2 = 3; //Declares two floats, Number1 (2) and Number2 (3) new Float:Sum; Sum = floatadd(Number1, Number2); //Saves the Sum(=2+3 = 5) of Number1 and Number2 in the float "Sum" return 1; } ``` ## ฟังก์ชั่นที่เกี่ยวข้องกัน - [Floatsub](../functions/Floatsub): Subtracts two floats. - [Floatmul](../functions/Floatmul): Multiplies two floats. - [Floatdiv](../functions/Floatdiv): Divides a float by another.
openmultiplayer/web/docs/translations/th/scripting/functions/floatadd.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/floatadd.md", "repo_id": "openmultiplayer", "token_count": 412 }
468
--- title: format description: Formats a string to include variables and other strings inside it. tags: [] --- :::warning This function starts with lowercase letter. ::: ## คำอธิบาย Formats a string to include variables and other strings inside it. | Name | Description | | -------------- | ----------------------------------------- | | output[] | The string to output the result to | | len | The maximum length output can contain | | format[] | The format string | | {Float,\_}:... | Indefinite number of arguments of any tag | ## ส่งคืน This function does not return any specific values. ## ตัวอย่าง ```c new result[128]; new number = 42; format(result,sizeof(result), "The number is %i.",number); //-> The number is 42. new string[]= "simple message"; format(result,sizeof(result), "This is a %s containing the number %i.", string, number); // This is a simple message containing the number 42. new string[64]; format(string,sizeof(string),"Your score is: %d",GetPlayerScore(playerid)); SendClientMessage(playerid,0xFFFFFFAA,string); new hour, minute, second, string[32]; gettime(hour, minute, second); format(string, sizeof(string), "The time is %02d:%02d:%02d.", hour, minute, second); // will output something like 09:45:02 SendClientMessage(playerid, -1, string); new string[35]; format(string,sizeof(string),"43%s of my shirts are black.","%%"); SendClientMessage(playerid,0xFFFFFAA,string); ``` ## บันทึก :::warning This function doesn't support packed strings. ::: ## ฟังก์ชั่นที่เกี่ยวข้องกัน - [print](../functions/print): Print a basic message to the server logs and console. - [printf](../functions/printf): Print a formatted message into the server logs and console.
openmultiplayer/web/docs/translations/th/scripting/functions/format.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/format.md", "repo_id": "openmultiplayer", "token_count": 689 }
469
--- title: memcpy description: Copy bytes from one location to another. tags: [] --- :::warning This function starts with lowercase letter. ::: ## คำอธิบาย Copy bytes from one location to another. | Name | Description | | --------------------- | ------------------------------------------------------------------------------------- | | dest[] | An array into which the bytes from source are copied in. | | const source[] | The source array. | | index | The start index in bytes in the destination array where the data should be copied to. | | numbytes | The number of bytes (not cells) to copy. | | maxlength=sizeof dest | The maximum number of cells that fit in the destination buffer. | ## ส่งคืน True on success, false on failure. ## ตัวอย่าง ```c //Concatenate two strings with memcpy new destination[64] = "This is "; new source[] = "a string in a 32 Bit Array"; memcpy(destination, source, strlen(destination) * 4, sizeof source * 4, sizeof destination); print(destination); //Output: This is a string in a 32 Bit Array ``` ## ฟังก์ชั่นที่เกี่ยวข้องกัน - [strcmp](../functions/strcmp.md): Compare two strings to see if they are the same. - [strfind](../functions/strfind.md): Search for a substring in a string. - [strdel](../functions/strdel.md): Delete part/all of a string. - [strins](../functions/strins.md): Put a string into another string. - [strlen](../functions/strlen.md): Check the length of a string. - [strmid](../functions/strmid.md): Extract characters from a string. - [strpack](../functions/strpack.md): Pack a string into a destination. - [strval](../functions/strval.md): Find the value of a string. - [strcat](../functions/strcat.md): Concatenate two strings.
openmultiplayer/web/docs/translations/th/scripting/functions/memcpy.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/memcpy.md", "repo_id": "openmultiplayer", "token_count": 883 }
470
--- title: strmid description: Extract a range of characters from a string. tags: [] --- :::warning This function starts with lowercase letter. ::: ## คำอธิบาย Extract a range of characters from a string. | Name | Description | | --------------------- | -------------------------------------------------------------------- | | dest[] | The string to store the extracted characters in. | | const source[] | The string from which to extract characters. | | start | The position of the first character. | | end | The position of the last character. | | maxlength=sizeof dest | The length of the destination. (Will be the size of dest by default) | ## ส่งคืน The number of characters stored in dest[] ## ตัวอย่าง ```c strmid(string, "Extract 'HELLO' without the !!!!: HELLO!!!!", 34, 39); //string contains "HELLO" ``` ## ฟังก์ชั่นที่เกี่ยวข้องกัน - strcmp: Compare two strings to check if they are the same. - strfind: Search for a string in another string. - strtok: Get the next 'token' (word/parameter) in a string. - strdel: Delete part of a string. - strins: Insert text into a string. - strlen: Get the length of a string. - strpack: Pack a string into a destination string. - strval: Convert a string into an integer. - strcat: Concatenate two strings into a destination reference.
openmultiplayer/web/docs/translations/th/scripting/functions/strmid.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/strmid.md", "repo_id": "openmultiplayer", "token_count": 680 }
471
--- title: "Scripting: Tags" description: A guide for Tags, a type-like feature of the Pawn language providing safety features for working with values of different intent. --- ## Introduction A tag is a prefix to a variable which tells the compiler to treat the variable specially under certain circumstances. For example you can use tags to define where a variable can and can't be used, or a special way to add two variables together. There are two types of tag - strong tags (starting with a capital letter) and weak tags (starting with a lower case letter), for the most part they're the same however under certain circumstances weak tags can be converted to tagless silently by the compiler, i.e. you won't get a warning, most of the time with weak tags, and all the time with strong tags, implicitly changing the tag will result in a warning to tell you data is likely being used wrong. A very simple example is the following: ```c new File:myfile = fopen("file.txt", io_read); myFile += 4; ``` The `fopen` function will return a value with a tag of type `File:`, there is no problem on that line as the return value is being stored to a variable also with a tag of `File:` (note the cases are the same too). However on the next line the value `4` is added to the file handle. `4` has no tag (it is actually tag type `_:` but variables, values and functions with no tag are automatically set to that and you don't need to worry about it normally) and myFile has a tag of `File:`, obviously nothing and something can't possibly be the same so the compiler will issue a warning, this is good as a handle to a file is meaningless in terms of it's actual value and so modifying it will merely destroy the handle and mean the file can't be closed as there is no longer a valid handle to pass and close the file with. ### Strong tags As mentioned above a strong tag is any tag starting with a capital letter. Examples of these in SA:MP include: ```c Float: File: Text: ``` These cannot be mixed with other variable types and will always issue a warning when you try to do so: ```c new Float:myFloat, File:myFile, myBlank; myFile = fopen("file.txt", io_read); // File: = File:, no warning myFloat = myFile; // Float: = File:, "tag mismatch" warning myFloat = 4; // Float: = _: (none), "tag mismatch" warning myBlank = myFloat; // _: (none) = Float:, "tag mismatch" warning ``` ### Weak tags A weak tag behaves mostly the same as a strong tag however the compiler will not issue a warning when the destination is tagless and the source is a weak tag. For example compare the following strong and weak tag codes, the first with the strong tag will give a warning, the second with the weak tag will not: ```c new Strong:myStrong, weak:myWeak, myNone; myNone = myStrong; // Warning myNone = myWeak; // No warning ``` However the reverse is not true: ```c myWeak = myNone; // Warning ``` This is also true with functions, calling a function with a tagless parameter, passing a weak tagged variable will not give a warning: ```c new weak:myWeak; MyFunction(myWeak); MyFunction(myVar) { ... } ``` But calling a function with a tagged parameter (weak or strong), passing an untagged parameter will give a warning. Examples of weak tags in SA:MP are less well known as such though are often used and include: ```c bool: filemode: floatround_method: ``` ## Use ### Declaring Declaring a variable with a tag is very simple, just write the tag, there's no need to define a tag in advance in any way however this is possible and does have it's uses as will become apparent later: ```c new Mytag:myVariable; ``` Declaring a variable with one of the existing tags will allow you to use that variable with the functions and operators already written for that tag type. ### Functions Creating a function to take or return a tag is very simple, just prefix the relevant part with the desired tag type, for example: ```c Float:GetValue(File:fHnd, const name[]) { ... } ``` That function takes the handle to a file and returns a float value (presumably a value read from the file and corresponding to the value name passed in `name[]`). This function would most likely use the `floatstr` function, which also returns a Float: (as you can tell by looking at the status bar of pawno when you click on the function in the right hand function list), after taking a string. The implementation of this function is not important but it will convert the string to an IEEE float value, which is then stored as a cell (it's actually strictly stored as an integer which just happens to have an identical bit pattern to the relevant IEEE number as PAWN is typeless, but that's what tags are partially there to combat). ### Operators Operators such as `+`, `==`, `>` etc can be overloaded for different tags, i.e. doing `+` on two Float:s does something different to doing it on two non-tagged variables. This is especially useful in the case of float variables as as mentioned they are not really floats they are integers with a very specific bit pattern, if the operators were not overloaded the operations would simply be performed on the integers which would give gibberish if the answer were interpreted as a float again. For this reason the Float: tag has overloaded versions of most of the operators to call special functions to do the maths in the server instead of in pawn. An operator is exactly like a normal function but instead of a function name you use "operator(**symbol**)" where (**symbol**) is the operator you want to overwrite. The valid operators are: ```c + - = ++ -- == * / != > < >= <= ! % ``` Things like `\`, `*`, `=` etc are done automatically. Things like `&` etc can't be overloaded. You can also overload an operator multiple times with different combinations of tag. For example: ```c stock Float:operator=(Mytag:oper) { return float(_:oper); } ``` If you add that to your code and do: ```c new Float:myFloat, Mytag:myTag; myFloat = myTag; ``` You will no longer get a compiler warning as you would have before because the `=` operator for the case `Float: = Mytag:` is now handled so the compiler knows exactly what to do. ### Overwriting In the overloading example above the functional line was: ```c return float(_:oper); ``` This is an example of tag overwriting, the `_:` in front of oper means the compiler basically ignores the fact that oper has a tag type of Mytag: and treats it as tag type `_:` (i.e. no tag type). The function `float()` tags a normal number so must be passed one. In that example it is assumed that `Mytag` stores an ordinary integer but overwriting must be dealt with very carefully, for example the following will give very odd results: ```c new Float:f1, Float:f2 = 4.0; f1 = float(_:f2); ``` Sense would dictate that `f1` would end up as `4.0`, however it won't. As mentioned f2 stores a representation of `4.0`, not just `4` as an integer would, this means the actual value of the variable as an integer is a very odd number. Thus if you tell the compiler to treat the variable as an integer it will simply take the bit pattern in the variable as the value, it won't convert the float to an integer, so you will get an almost random number (it's not actually random as there's a pattern to IEEE floating points but it will be nothing like `4.0`).
openmultiplayer/web/docs/translations/th/scripting/language/Tags.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/language/Tags.md", "repo_id": "openmultiplayer", "token_count": 1976 }
472
--- title: Door States description: Information about byte size and its corresponding door state bits. --- :::note To be used with [GetVehicleDamageStatus](../functions/GetVehicleDamageStatus) and [UpdateVehicleDamageStatus](../functions/UpdateVehicleDamageStatus). ::: ## Which bit stores what? The damage of each door (note that the hood and the trunk are also doors) will be saved in 1 byte (which is 8 bits). You can only change the state of one bit for every door at each time - so you have to call the function twice if you want to damage and open the door. - The **first bit** stores whether the door is **opened (bit 1)** or **not (bit 0)** (the door will still lock (and change the first bit to 0) if closed - its just open). - The **second bit** stores whether the door is **damaged (bit 1)** or **not (bit 0)** (If you want a damaged door to turn normal you have to remove and re-attach it undamaged). - The **third bit** stores whether the door is **removed (bit 1)** or **attached (bit 0)**. - The rest of the bits are empty. It seems like there is no bit which stores if the door will lock or not. Notice that you count the bits from behind - so the first is the rightmost bit ## Which byte stores what? - The **first byte** stores the state of the **hood**. - The **second byte** stores the state of the **trunk**. - The **third byte** stores the state of the **drivers door**. - The **fourth byte** stores the state of the **co-drivers door**. The states of the 2 rear doors cannot be handled by [GetVehicleDamageStatus](../functions/GetVehicleDamageStatus "GetVehicleDamageStatus") and [UpdateVehicleDamageStatus](../functions/UpdateVehicleDamageStatus "UpdateVehicleDamageStatus"). Notice that I count the bytes from behind - so the first is the rightmost byte ## Example The following code tells that the hood is removed, the front left door damaged, the front right door opened and the trunk is damaged and opened: `00000001 00000010 00000011 00000100` However SA-MP returns a decimal number so you have to convert it to a binary number first to get a result like above. What SA-MP would return you in this case is this: `16909060` ## Info table **First byte (hood):** ``` 0 (000) 1 (001) 2 (010) 3 (011) 4 (100) 5 (101) 6 (110) 7 (111) °--° °\[\]° °~~° °{}° ° ° ° ° ° ° ° ° | | | | | | | | | | | | | | | | °--° °--° °--° °--° °--° °--° °--° °--° ``` **Second byte (trunk):** ``` 0 (000) 1 (001) 2 (010) 3 (011) 4 (100) 5 (101) 6 (110) 7 (111) °--° °--° °--° °--° °--° °--° °--° °--° | | | | | | | | | | | | | | | | °--° °\[\]° °--° °{}° ° ° ° ° ° ° ° ° ``` **Third byte (drivers door):** ``` 0 (000) 1 (001) 2 (010) 3 (011) 4 (100) 5 (101) 6 (110) 7 (111) °--° °--° °--° °--° °--° °--° °--° °--° | | -- | § | ww | | | | | °--° °--° °--° °--° °--° °--° °--° °--° ``` **Fourth byte (co-drivers door):** ``` 0 (000) 1 (001) 2 (010) 3 (011) 4 (100) 5 (101) 6 (110) 7 (111) °--° °--° °--° °--° °--° °--° °--° °--° | | | -- | § | ww | | | | °--° °--° °--° °--° °--° °--° °--° °--° ``` _Legend:_ ``` Static Doors Hood / Trunk ° - Light | - healthy, closed -- - healthy, closed -- - healthy, opened \[\] - healthy, opened § - damaged, closed ~~ - damaged, closed ww - damaged, opened {} - damaged, opened - missing - missing ``` ## Wrapper Usefull little snippet to avoid working with the bits and bytes too much; ```c enum Door { DOOR\_HOOD, DOOR\_TRUNK, DOOR\_DRIVER DOOR\_PASSENGER } enum DoorState(<<= 1) { IS\_OPENED = 1, IS\_DAMAGED, IS\_REMOVED }   stock GetDoorState(doorStates, Door:door, DoorState:doorState) return (doorStates >>> (8 \* door)) & doorState; ``` ## Example usage ```c new panels, doors, lights, tires; GetVehicleDamageStatus(vehicleid, panels, doors, lights, tires);     // simple if (GetDoorState(doors, DOOR\_DRIVER, IS\_DAMAGED)) { [SendClientMessage](./functions/SendClientMessage)(playerid, \-1, "The driver door of your vehicle is damaged!"); }   // or even combined if (GetDoorState(doors, DOOR\_HOOD, IS\_OPENED | IS\_DAMAGED)) { [SendClientMessage](./functions/SendClientMessage)(playerid, \-1, "The hood of your vehicle is both opened and damaged!"); } ```
openmultiplayer/web/docs/translations/th/scripting/resources/doorstates.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/resources/doorstates.md", "repo_id": "openmultiplayer", "token_count": 2122 }
473
--- title: Text Alignments --- To be used with [SetObjectMaterialText](../functions/SetObjectMaterialText). ```c OBJECT_MATERIAL_TEXT_ALIGN_LEFT 0 OBJECT_MATERIAL_TEXT_ALIGN_CENTER 1 OBJECT_MATERIAL_TEXT_ALIGN_RIGHT 2 ```
openmultiplayer/web/docs/translations/th/scripting/resources/textalignments.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/resources/textalignments.md", "repo_id": "openmultiplayer", "token_count": 91 }
474
--- title: OnEnterExitModShop description: Bu callback, bir oyuncu modifiye garajlarından birine giriş veya çıkış yaptığında tetiklenir. tags: [] --- ## Açıklama Bu callback, bir oyuncu modifiye garajlarından birine giriş veya çıkış yaptığında tetiklenir. | Name | Description | | ---------- | ---------------------------------------------------------------------------- | | playerid | Modifiye garajına giriş/çıkış yapan oyuncunun ID'si. | | enterexit | Giriş yaptıysa 1, çıkış yaptıysa 2 değerini alır. | | interiorid | Girilen modifiye garajının interior ID'si. (eğer çıkıyorsa 0 değerini alır.) | ## Çalışınca Vereceği Sonuçlar Her zaman öncelikle filterscriptler içerisinde çağrılır. ## Örnekler ``` public OnEnterExitModShop(playerid, enterexit, interiorid) { if (enterexit == 0) // Eğer enterexit değeri 0'a eşit ise, modifiye garajından çıkış yaptığı anlamına gelir. { SendClientMessage(playerid, COLOR_WHITE, "Nice car! You have been taxed $100."); GivePlayerMoney(playerid, -100); } return 1; } ``` ## Notlar :::warning Bilinen Hata(lar): Oyuncular aynı modifiye garajına girdiğinde sıkışabilirler/çarpışırlar. ::: ## Bağlantılı Fonksiyonlar - [AddVehicleComponent](../functions/AddVehicleComponent.md): Araca bir parça eklemeye yarar.
openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnEnterExitModShop.md/0
{ "file_path": "openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnEnterExitModShop.md", "repo_id": "openmultiplayer", "token_count": 683 }
475
--- title: OnPlayerEditObject description: Bu callback bir oyuncu obje düzenlemeyi bitirdiğinde çağırılır (EditObject/EditPlayerObject). tags: ["player"] --- ## Açıklama Bu callback bir oyuncu obje düzenlemeyi bitirdiğinde çağırılır (EditObject/EditPlayerObject). | İsim | Açıklama | |------------------------|---------------------------------------------------------------------------| | playerid | Düzenlemeyi yapan oyuncunun ID'si. | | playerobject | Genel bir obje ise 0 olur, oyuncu objesi ise 1 olur. | | objectid | Düzenlenen objenin ID'si. | | EDIT_RESPONSE:response | Verilen cevabın tipi. [tıkla](../resources/objecteditionresponsetypes.md) | | Float:fX | Düzenlenen objenin X yönündeki koordinatı. | | Float:fY | Düzenlenen objenin Y yönündeki koordinatı. | | Float:fZ | Düzenlenen objenin Z yönündeki koordinatı. | | Float:fRotX | Güzenlenen objenin X yönündeki rotasyonu. | | Float:fRotY | Güzenlenen objenin Y yönündeki rotasyonu. | | Float:fRotZ | Güzenlenen objenin Z yönündeki rotasyonu. | ## Çalışınca Vereceği Sonuçlar 1 - Diğer scriptlerin bu callbacke ulaşmasını engeller. 0 - Bu script bittikten sonra callback diğer scriptlerde işlenir. Her zaman ilk olarak filterscriptlerde çağırılır. ## Örnekler ```c public OnPlayerEditObject(playerid, playerobject, objectid, EDIT_RESPONSE:response, Float:fX, Float:fY, Float:fZ, Float:fRotX, Float:fRotY, Float:fRotZ) { new Float: oldX, Float: oldY, Float: oldZ, Float: oldRotX, Float: oldRotY, Float: oldRotZ; GetObjectPos(objectid, oldX, oldY, oldZ); GetObjectRot(objectid, oldRotX, oldRotY, oldRotZ); if (!playerobject) // Eğer bu global bir obje ise, pozisyonunu diğer oyuncular içinde eşzamanlar. { if (!IsValidObject(objectid)) { return 1; } SetObjectPos(objectid, fX, fY, fZ); SetObjectRot(objectid, fRotX, fRotY, fRotZ); } switch (response) { case EDIT_RESPONSE_FINAL: { // Oyuncu save butonuna tıkladı. // Pozisyonu ve/veya rotasyonu güncellenen objenin kayıt edilmesi için kodlar yazabilirsiniz. } case EDIT_RESPONSE_CANCEL: { // Oyuncu düzenleme işlemini iptal ettiği için objeyi eski pozisyonuna ve/veya rotasyonuna geri getirir. if (!playerobject) // Obje bir oyuncu objesi değil ise. { SetObjectPos(objectid, oldX, oldY, oldZ); SetObjectRot(objectid, oldRotX, oldRotY, oldRotZ); } else { SetPlayerObjectPos(playerid, objectid, oldX, oldY, oldZ); SetPlayerObjectRot(playerid, objectid, oldRotX, oldRotY, oldRotZ); } } } return 1; } ``` ## Notlar :::warning EDIT_RESPONSE_UPDATE kullanırken, devam etmekte olan bir düzenlemeyi bırakırken bu callbacking çağırılmayacağının ve EDIT_RESPONSE_UPDATE'in son güncellemesinin nesnelerin mevcut konumunun senkronizasyonundan çıkmasına neden olacağını unutmayın. ::: ## Bağlantılı Fonksiyonlar - [EditObject](../functions/EditObject.md): Edit an object. - [CreateObject](../functions/CreateObject.md): Create an object. - [DestroyObject](../functions/DestroyObject.md): Destroy an object. - [MoveObject](../functions/MoveObject.md): Move an object.
openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnPlayerEditObject.md/0
{ "file_path": "openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnPlayerEditObject.md", "repo_id": "openmultiplayer", "token_count": 2055 }
476
--- title: OnPlayerRequestDownload description: Fonksiyon, bir oyuncu özel model indirmeleri istediğinde çağrılır. tags: ["player"] --- <VersionWarnTR name='callback' version='SA-MP 0.3.DL R1' /> ## Açıklama Fonksiyon, bir oyuncu özel model indirmeleri istediğinde çağrılır. | Parametre | Açıklama | | --------- | -------------------------------------------------------- | | playerid | Model indirmesi isteyen oyuncunun ID'si. | | type | İsteğin türü (aşağıya bakın). | | crc | Özel model dosyasının CRC sağlama toplamı. | ## Çalışınca Vereceği Sonuçlar 0 - İndirme isteği reddedildi. 1 - İndirme isteği kabul edildi. ## Örnekler ```c #define DOWNLOAD_REQUEST_EMPTY (0) #define DOWNLOAD_REQUEST_MODEL_FILE (1) #define DOWNLOAD_REQUEST_TEXTURE_FILE (2) new baseurl[] = "https://files.sa-mp.com/server"; public OnPlayerRequestDownload(playerid, type, crc) { new fullurl[256+1]; new dlfilename[64+1]; new foundfilename=0; if (!IsPlayerConnected(playerid)) return 0; if (type == DOWNLOAD_REQUEST_TEXTURE_FILE) { foundfilename = FindTextureFileNameFromCRC(crc,dlfilename,64); } else if (type == DOWNLOAD_REQUEST_MODEL_FILE) { foundfilename = FindModelFileNameFromCRC(crc,dlfilename,64); } if (foundfilename) { format(fullurl,256,"%s/%s",baseurl,dlfilename); RedirectDownload(playerid,fullurl); } return 0; } ``` ## Bağlantılı Fonksiyonlar - [OnPlayerFinishedDownloading](OnPlayerFinishedDownloading): Fonksiyon, oyuncu özel model dosyalarını indirdiğinde çağrılır.
openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnPlayerRequestDownload.md/0
{ "file_path": "openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnPlayerRequestDownload.md", "repo_id": "openmultiplayer", "token_count": 799 }
477
--- title: OnVehicleDamageStatusUpdate description: Bu fonksiyon, aracın kapıları, farları, lastikleri veya panelleri gibi araç elemanları hasar aldığında çağrılır. tags: ["vehicle"] --- :::tip Araç hasar değerlerinin ne işe yaradığını görmek için bkz. [here](../resources/damagestatus). ::: ## Açıklama Bu fonksiyon, aracın kapıları, farları, lastikleri veya panelleri gibi araç elemanları hasar aldığında çağrılır. | Parametre | Açıklama | | --------- | ------------------------------------------------------------------------------------------------------- | | vehicleid | Hasar durumu değiştirilen aracın ID'si. | | playerid | Hasar durumundaki değişikliği senkronize eden oyuncunun ID'si (arabaya hasar veren veya tamir ettiren). | ## Çalışınca Vereceği Sonuçlar 1 - Diğer filterscript komutlarının çağrıyı almasını önleyecektir. 0 - Çağrının sonraki filterscript komutuna aktarılacağını belirtir. Filterscript komutlarında her zaman ilk olarak çağrılır. ## Örnekler ```c public OnVehicleDamageStatusUpdate(vehicleid, playerid) { // Araç bileşenlerini kontrol edin. new panels, doors, lights, tires; GetVehicleDamageStatus(vehicleid, panels, doors, lights, tires); // Lastikleri 0'a ayarlayın, yani hiçbiri patlamaz. tires = 0; // Patlamamış lastiklerle aracın hasar durumunu güncelleyin UpdateVehicleDamageStatus(vehicleid, panels, doors, lights, tires); return 1; } ``` ## Notlar :::tip Bu fonksiyon, aracın sağlık değerini içermez. ::: ## Bağlantılı Fonksiyonlar - [GetVehicleDamageStatus](../functions/GetVehicleDamageStatus): Her araç elamanı için araç hasar durumunu ayrı ayrı alma. - [UpdateVehicleDamageStatus](../functions/UpdateVehicleDamageStatus): Aracın hasar değerini düzenleme.
openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnVehicleDamageStatusUpdate.md/0
{ "file_path": "openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnVehicleDamageStatusUpdate.md", "repo_id": "openmultiplayer", "token_count": 909 }
478
--- title: AddStaticPickup description: Bu işlev oyuna "statik" bir toplama ekler. tags: [] --- ## Açıklama Bu işlev oyuna "statik" bir toplama ekler. Bu manyetikler, komut dosyası yazmadan çalışabilme özelliği ile silah, sağlık, zırh vb. destekler (silah / sağlık / zırh otomatik olarak verilecektir). | İsim | Açıklama | | ----------------------------------- | ------------------------------------------------------------------------------------------------------ | | [model](../resources/pickupids.md) | pickup modeli. | | [type](../resources/pickuptypes.md) | Kaldırma mekanizması tipi. Toplayıcının pickup'a nasıl tepki vereceğini belirler. | | Float:X | pickup mekanizmasını oluşturmak için X koordinatı. | | Float:Y | pickup mekanizmasını oluşturmak için Y koordinatı. | | Float:Z | pickup mekanizmasını oluşturmak için Z koordinatı. | | virtualworld | Toplanma sağlayacak sanal dünya kimliği. Dünyalarda teslim alma özelliğini göstermek için -1 kullanın. | ## Çalışınca Vereceği Sonuçlar 1 kaldırma mekanizması başarıyla oluşturuldu. 0 oluşturulamadı. ## Örnekler ```c public OnGameModeInit() { // Create a pickup for armor AddStaticPickup(1242, 2, 1503.3359, 1432.3585, 10.1191, 0); // Zırhın hemen yanında, sağlık için bir pickup oluşturun. AddStaticPickup(1240, 2, 1506.3359, 1432.3585, 10.1191, 0); return 1; } ``` ## Notlar :::tip Bu işlev, OnPlayerPickUpPickup gibi kullanabileceğiniz bir pickup kimliği getirmez. Kimlik atamak istiyorsanız CreatePickup'ı kullanın. ::: ## Bağlantılı Fonksiyonlar - [CreatePickup](CreatePickup.md): Pickup oluşturun. - [DestroyPickup](DestroyPickup.md): Pickup yok edin. - [OnPlayerPickUpPickup](../callbacks/OnPlayerPickUpPickup.md): Oyuncu bir pickup aldığında çağrılır.
openmultiplayer/web/docs/translations/tr/scripting/functions/AddStaticPickup.md/0
{ "file_path": "openmultiplayer/web/docs/translations/tr/scripting/functions/AddStaticPickup.md", "repo_id": "openmultiplayer", "token_count": 1264 }
479
--- title: AttachTrailerToVehicle description: Bir aracı bir başka araca römork olarak bağlama. tags: ["vehicle"] --- ## Açıklama Bir aracı bir başka araca römork olarak bağlama. | Parametre | Açıklama | | --------- | ------------------------------------------------- | | trailerid | Römork işlevi görecek aracın ID'si. | | vehicleid | Römorku çekecek olan aracın ID'si. | ## Çalışınca Vereceği Sonuçlar Bu fonksiyon römork işlevi görecek olan araç yaratılmamış/geçersiz olsa bile her zaman 1 olarak döner. ## Örnekler ```c new vehicleId = CreateVehicle(...); new trailerId = CreateVehicle(...); AttachTrailerToVehicle(trailerId, vehicleId); ``` ## Notlar :::warning Bu fonksiyon, araçlar eğer oyuncunun görüş açısındaysa işe yarar. ((bknz. [IsVehicleStreamedIn](IsVehicleStreamedIn)). ::: ## Bağlantılı Fonksiyonlar - [DetachTrailerFromVehicle](DetachTrailerFromVehicle): Bağlı olan araçları birbirinden ayırma. - [IsTrailerAttachedToVehicle](IsTrailerAttachedToVehicle): Aracın belirtilen araca bağlı olup olmadığını kontrol etme. - [GetVehicleTrailer](GetVehicleTrailer): Aracın hangi aracı çektiğini kontrol edin.
openmultiplayer/web/docs/translations/tr/scripting/functions/AttachTrailerToVehicle.md/0
{ "file_path": "openmultiplayer/web/docs/translations/tr/scripting/functions/AttachTrailerToVehicle.md", "repo_id": "openmultiplayer", "token_count": 568 }
480
--- title: CreateObject description: Obje oluşturma. tags: [] --- ## Açıklama Oyun dünyası üzerinde obje oluşturma. | Parametre | Açıklama | | ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | modelid | Oluşturulacak objenin modeli. | | Float:X | Oluşturulacak objenin X koordinatı. | | Float:Y | Oluşturulacak objenin Y koordinatı. | | Float:Z | Oluşturulacak objenin Z koordinatı. | | Float:rX | Oluşturulacak objenin X rotasyonu. | | Float:rY | Oluşturulacak objenin Y rotasyonu. | | Float:rZ | Oluşturulacak objenin Z rotasyonu. | | Float:DrawDistance | (opsiyonel) Objenin görüş mesafesi. 0.0, objenin varsayılan mesafelerinde oluşturulmasına neden olur. | ## Örnekler ```c public OnGameModeInit() { CreateObject(2587, 2001.195679, 1547.113892, 14.283400, 0.0, 0.0, 96.0); // Obje, varsayılan görüş mesafesinde oluşturulacaktır. CreateObject(2587, 2001.195679, 1547.113892, 14.283400, 0.0, 0.0, 96.0, 300.0); // Obje, 300.0 görüş mesafesinde oluşturulacaktır. return 1; } ``` ## Notlar :::tip Obje sınırı 1000(MAX_OBJECTS)'dir. Sınırın aşılması için streamer kullanılabilir. ::: ## Bağlantılı Fonksiyonlar - [DestroyObject](DestroyObject): Obje silme. - [IsValidObject](IsValidObject): Objenin oluşturulup oluşturulmadığını kontrol etme. - [MoveObject](MoveObject): Objeyi hareket ettirme. - [StopObject](StopObject): Hareket eden objeyi durdurma. - [SetObjectPos](SetObjectPos): Objenin pozisyonunu ayarlama. - [SetObjectRot](SetObjectRot): Objenin rotasyonunu ayarlama. - [GetObjectPos](GetObjectPos): Objenin pozisyonunu kontrol etme. - [GetObjectRot](GetObjectRot): Objenin rotasyonunu kontrol etme. - [AttachObjectToPlayer](AttachObjectToPlayer): Objeyi oyuncuya bağlama. - [SetObjectMaterialText](SetObjectMaterialText): Obje dokusunu metinle değiştirme. - [SetObjectMaterial](SetObjectMaterial): Objenin dokusunu değiştirme. - [CreatePlayerObject](CreatePlayerObject): Oyuncuya özel obje oluşturma. - [DestroyPlayerObject](DestroyPlayerObject): Oyuncuya özel objeyi silme. - [IsValidPlayerObject](IsValidPlayerObject): Oyuncuya özel objenin oluşturulup oluşturulmadığını kontrol etme. - [MovePlayerObject](MovePlayerObject): Oyuncuya özel objeyi hareket ettirme. - [StopPlayerObject](StopPlayerObject): Haraket eden oyuncuya özel objeyi durdurma. - [SetPlayerObjectPos](SetPlayerObjectPos): Oyuncuya özel objenin pozisyonunu ayarlama. - [SetPlayerObjectRot](SetPlayerObjectRot): Oyuncuya özel objenin rotasyonunu ayarlama. - [GetPlayerObjectPos](GetPlayerObjectPos): Oyuncuya özel objenin pozisyonunu kontrol etme. - [GetPlayerObjectRot](GetPlayerObjectRot): Oyuncuya özel objenin rotasyonunu kontrol etme. - [AttachPlayerObjectToPlayer](AttachPlayerObjectToPlayer): Oyuncuya özel objeyi oyuncuya bağlama. - [SetPlayerObjectMaterialText](SetPlayerObjectMaterialText): Oyuncuya özel objenin dokusunu metinle değiştirme. - [SetPlayerObjectMaterial](SetPlayerObjectMaterial): Oyuncuya özel objenin dokusunu değiştirme.
openmultiplayer/web/docs/translations/tr/scripting/functions/CreateObject.md/0
{ "file_path": "openmultiplayer/web/docs/translations/tr/scripting/functions/CreateObject.md", "repo_id": "openmultiplayer", "token_count": 2377 }
481
--- title: "Anahtar Kelimeler: Operatörler" --- ## `char` `char`, bir paketlenmiş dize içinde verilen karakter sayısını tutmak için gereken hücre sayısını döndürür. Yani belirli bir bayi sayısını tutmak için gereken 4 bayilik hücre sayısını. Örneğin: ```c 4 char ``` 1 döndürür. ```c 3 char ``` 1 döndürür (bir değişkenin 3/4'ünü alamazsınız). ```c 256 char ``` 64 döndürür (256'yı 4'e bölerseniz). Bu genellikle değişken bildirimlerinde kullanılır. ```c new someVar[40 char]; ``` 10 hücrelik bir dizi yapacaktır. Paketlenmiş diziler hakkında daha fazla bilgi için pawn-lang.pdf'ye başvurun. ## `defined` Bir sembolün var olup olmadığını kontrol eder. Genellikle #if ifadelerinde kullanılır: ```c new someVar = 5; #if defined someVar printf("%d", someVar); #else #error The variable 'someVar' isn't defined #endif ``` Genellikle bir tanımın tanımlanıp tanımlanmadığını kontrol etmek ve buna göre kod üretmek için kullanılır: ```c #define FILTERSCRIPT #if defined FILTERSCRIPT public OnFilterScriptInit() { return 1; } #else public OnGameModeInit() { return 1; } #endif ``` ## `sizeof` Bir dizinin ELEMANLAR cinsinden boyutunu döndürür: ```c new someVar[10]; printf("%d", sizeof (someVar)); ``` Çıkış: ```c 10 ``` Ve: ```c new someVar[2][10]; printf("%d %d", sizeof (someVar), sizeof (someVar[])); ``` Şunu verir: ```c 2 10 ``` ## `state` Bu tekrar PAWN otanom koduyla ilgilidir ve bu nedenle burada ele alınmaz. ## `tagof` Bu, bir değişkenin etiketini temsil eden bir sayı döndürür: ```c new someVar, Float:someFloat; printf("%d %d", tagof (someVar), tagof (someFloat)); ``` Şunu verir: ```c -./,),(-*,( -1073741820 ``` Bu hafif bir hata olsa da temelde şunu ifade eder: ```c 0x80000000 0xC0000004 ``` Örneğin, bir değişkenin bir float (etiket 'Float:') olup olmadığını kontrol etmek için: ```c new Float: fValue = 6.9; new tag = tagof (fValue); if (tag == tagof (Float:)) { print("float"); } else { print("not a float"); } ```
openmultiplayer/web/docs/translations/tr/scripting/language/Operators.md/0
{ "file_path": "openmultiplayer/web/docs/translations/tr/scripting/language/Operators.md", "repo_id": "openmultiplayer", "token_count": 1012 }
482
--- title: open.mp fonksiyonları description: Yeni fonksiyonlar ve callbackler. --- Bu sayfa open.mp'ye eklenen tüm fonksiyonları ve callbackleri içerir ## Oyuncu | İsim | |---------------------------------------------------------------------------------------------------------| | [TogglePlayerWidescreen](../scripting/functions/TogglePlayerWidescreen) | | [IsPlayerWidescreenToggled](../scripting/functions/IsPlayerWidescreenToggled) | | [SetPlayerGravity](../scripting/functions/SetPlayerGravity) | | [GetPlayerGravity](../scripting/functions/GetPlayerGravity) | | [ClearPlayerWorldBounds](../scripting/functions/ClearPlayerWorldBounds) | | [GetPlayerRotationQuat](../scripting/functions/GetPlayerRotationQuat) | | [GetPlayerSpectateID](../scripting/functions/GetPlayerSpectateID) | | [GetPlayerSpectateType](../scripting/functions/GetPlayerSpectateType) | | [GetPlayerSurfingOffsets](../scripting/functions/GetPlayerSurfingOffsets) | | [GetPlayerWorldBounds](../scripting/functions/GetPlayerWorldBounds) | | [GetPlayerZAim](../scripting/functions/GetPlayerZAim) | | [IsPlayerSpawned](../scripting/functions/IsPlayerSpawned) | | [GetPlayerHydraReactorAngle](../scripting/functions/GetPlayerHydraReactorAngle) | | [GetPlayerLandingGearState](../scripting/functions/GetPlayerLandingGearState) | | [GetPlayerLastSyncedTrailerID](../scripting/functions/GetPlayerLastSyncedTrailerID) | | [GetPlayerSirenState](../scripting/functions/GetPlayerSirenState) | | [GetPlayerTrainSpeed](../scripting/functions/GetPlayerTrainSpeed) | | [IsPlayerInModShop](../scripting/functions/IsPlayerInModShop) | | [GetPlayerDialogData](../scripting/functions/GetPlayerDialogData) | | [GetPlayerDialogID](../scripting/functions/GetPlayerDialogID) | | [HidePlayerDialog](../scripting/functions/HidePlayerDialog) | | [GetPlayerWeather](../scripting/functions/GetPlayerWeather) | | [GetPlayerSkillLevel](../scripting/functions/GetPlayerSkillLevel) | | [GetPlayerRawIp](../scripting/functions/GetPlayerRawIp) | | [GetPlayerAttachedObject](../scripting/functions/GetPlayerAttachedObject) | | [GetSpawnInfo](../scripting/functions/GetSpawnInfo) | | [GetPlayerBuildingsRemoved](../scripting/functions/GetPlayerBuildingsRemoved) | | [RemovePlayerWeapon](../scripting/functions/RemovePlayerWeapon) | | [AllowPlayerWeapons](../scripting/functions/AllowPlayerWeapons) | | [IsPlayerControllable](../scripting/functions/IsPlayerControllable) | | [IsPlayerCameraTargetEnabled](../scripting/functions/IsPlayerCameraTargetEnabled) | | [TogglePlayerGhostMode](../scripting/functions/TogglePlayerGhostMode) | | [GetPlayerGhostMode](../scripting/functions/GetPlayerGhostMode) | | [GetPlayerAnimationFlags](../scripting/functions/GetPlayerAnimationFlags) | | [IsPlayerUsingOfficialClient](../scripting/functions/IsPlayerUsingOfficialClient) | | [IsPlayerInDriveByMode](../scripting/functions/IsPlayerInDriveByMode) | | [IsPlayerCuffed](../scripting/functions/IsPlayerCuffed) | | [SetPlayerAdmin](../scripting/functions/SetPlayerAdmin) | | [GetPlayers](../scripting/functions/GetPlayers) | ## Obje | İsim | |---------------------------------------------------------------------------------------------------------| | [SetObjectNoCameraCollision](../scripting/functions/SetObjectNoCameraCollision) | | [SetPlayerObjectNoCameraCollision](../scripting/functions/SetPlayerObjectNoCameraCollision) | | [AttachPlayerObjectToObject](../scripting/functions/AttachPlayerObjectToObject) | | [BeginObjectEditing](../scripting/functions/BeginObjectEditing) | | [BeginObjectSelecting](../scripting/functions/BeginObjectSelecting) | | [BeginPlayerObjectEditing](../scripting/functions/BeginPlayerObjectEditing) | | [EndObjectEditing](../scripting/functions/EndObjectEditing) | | [GetObjectAttachedData](../scripting/functions/GetObjectAttachedData) | | [GetObjectAttachedOffset](../scripting/functions/GetObjectAttachedOffset) | | [GetObjectDrawDistance](../scripting/functions/GetObjectDrawDistance) | | [GetObjectMaterial](../scripting/functions/GetObjectMaterial) | | [GetObjectMaterialText](../scripting/functions/GetObjectMaterialText) | | [GetObjectMoveSpeed](../scripting/functions/GetObjectMoveSpeed) | | [GetObjectMovingTargetPos](../scripting/functions/GetObjectMovingTargetPos) | | [GetObjectMovingTargetRot](../scripting/functions/GetObjectMovingTargetRot) | | [GetObjectSyncRotation](../scripting/functions/GetObjectSyncRotation) | | [GetObjectType](../scripting/functions/GetObjectType) | | [GetPlayerCameraTargetPlayerObject](../scripting/functions/GetPlayerCameraTargetPlayerObject) | | [GetPlayerObjectAttachedData](../scripting/functions/GetPlayerObjectAttachedData) | | [GetPlayerObjectAttachedOffset](../scripting/functions/GetPlayerObjectAttachedOffset) | | [GetPlayerObjectDrawDistance](../scripting/functions/GetPlayerObjectDrawDistance) | | [GetPlayerObjectMaterial](../scripting/functions/GetPlayerObjectMaterial) | | [GetPlayerObjectMaterialText](../scripting/functions/GetPlayerObjectMaterialText) | | [GetPlayerObjectMoveSpeed](../scripting/functions/GetPlayerObjectMoveSpeed) | | [GetPlayerObjectMovingTargetPos](../scripting/functions/GetPlayerObjectMovingTargetPos) | | [GetPlayerObjectMovingTargetRot](../scripting/functions/GetPlayerObjectMovingTargetRot) | | [GetPlayerObjectSyncRotation](../scripting/functions/GetPlayerObjectSyncRotation) | | [GetPlayerSurfingPlayerObjectID](../scripting/functions/GetPlayerSurfingPlayerObjectID) | | [HasObjectCameraCollision](../scripting/functions/HasObjectCameraCollision) | | [HasPlayerObjectCameraCollision](../scripting/functions/HasPlayerObjectCameraCollision) | | [IsObjectHiddenForPlayer](../scripting/functions/IsObjectHiddenForPlayer) | | [IsObjectMaterialSlotUsed](../scripting/functions/IsObjectMaterialSlotUsed) | | [IsPlayerObjectMaterialSlotUsed](../scripting/functions/IsPlayerObjectMaterialSlotUsed) | | [SetObjectMoveSpeed](../scripting/functions/SetObjectMoveSpeed) | | [SetObjectsDefaultCameraCollision](../scripting/functions/SetObjectsDefaultCameraCollision) | | [SetPlayerObjectMoveSpeed](../scripting/functions/SetPlayerObjectMoveSpeed) | | [HideObjectForPlayer](../scripting/functions/HideObjectForPlayer) | | [ShowObjectForPlayer](../scripting/functions/ShowObjectForPlayer) | ## Pickup | İsim | |---------------------------------------------------------------------------------------------------------| | [CreatePlayerPickup](../scripting/functions/CreatePlayerPickup) | | [DestroyPlayerPickup](../scripting/functions/DestroyPlayerPickup) | | [GetPickupModel](../scripting/functions/GetPickupModel) | | [GetPickupPos](../scripting/functions/GetPickupPos) | | [GetPickupType](../scripting/functions/GetPickupType) | | [GetPickupVirtualWorld](../scripting/functions/GetPickupVirtualWorld) | | [GetPlayerPickupModel](../scripting/functions/GetPlayerPickupModel) | | [GetPlayerPickupPos](../scripting/functions/GetPlayerPickupPos) | | [GetPlayerPickupType](../scripting/functions/GetPlayerPickupType) | | [GetPlayerPickupVirtualWorld](../scripting/functions/GetPlayerPickupVirtualWorld) | | [IsPickupHiddenForPlayer](../scripting/functions/IsPickupHiddenForPlayer) | | [IsPickupStreamedIn](../scripting/functions/IsPickupStreamedIn) | | [IsPlayerPickupStreamedIn](../scripting/functions/IsPlayerPickupStreamedIn) | | [IsValidPickup](../scripting/functions/IsValidPickup) | | [IsValidPlayerPickup](../scripting/functions/IsValidPlayerPickup) | | [SetPickupForPlayer](../scripting/functions/SetPickupForPlayer) | | [SetPickupModel](../scripting/functions/SetPickupModel) | | [SetPickupPos](../scripting/functions/SetPickupPos) | | [SetPickupType](../scripting/functions/SetPickupType) | | [SetPickupVirtualWorld](../scripting/functions/SetPickupVirtualWorld) | | [SetPlayerPickupModel](../scripting/functions/SetPlayerPickupModel) | | [SetPlayerPickupPos](../scripting/functions/SetPlayerPickupPos) | | [SetPlayerPickupType](../scripting/functions/SetPlayerPickupType) | | [SetPlayerPickupVirtualWorld](../scripting/functions/SetPlayerPickupVirtualWorld) | | [HidePickupForPlayer](../scripting/functions/HidePickupForPlayer) | | [ShowPickupForPlayer](../scripting/functions/ShowPickupForPlayer) | | [OnPickupStreamIn](../scripting/callbacks/OnPickupStreamIn) | | [OnPickupStreamOut](../scripting/callbacks/OnPickupStreamOut) | | [OnPlayerPickUpPlayerPickup](../scripting/callbacks/OnPlayerPickUpPlayerPickup) | | [OnPlayerPickupStreamIn](../scripting/callbacks/OnPlayerPickupStreamIn) | | [OnPlayerPickupStreamOut](../scripting/callbacks/OnPlayerPickupStreamOut) | ## Araç | İsim | |---------------------------------------------------------------------------------------------------------| | [ChangeVehicleColours](../scripting/functions/ChangeVehicleColours) | | [GetPlayerLastSyncedVehicleID](../scripting/functions/GetPlayerLastSyncedVehicleID) | | [GetRandomVehicleColourPair](../scripting/functions/GetRandomVehicleColourPair) | | [GetVehicleCab](../scripting/functions/GetVehicleCab) | | [GetVehicleTower](../scripting/functions/GetVehicleTower) | | [GetVehicleColours](../scripting/functions/GetVehicleColours) | | [GetVehicleHydraReactorAngle](../scripting/functions/GetVehicleHydraReactorAngle) | | [GetVehicleInterior](../scripting/functions/GetVehicleInterior) | | [GetVehicleLandingGearState](../scripting/functions/GetVehicleLandingGearState) | | [GetVehicleDriver](../scripting/functions/GetVehicleDriver) | | [GetVehicleLastDriver](../scripting/functions/GetVehicleLastDriver) | | [GetVehicleMatrix](../scripting/functions/GetVehicleMatrix) | | [GetVehicleModelCount](../scripting/functions/GetVehicleModelCount) | | [GetVehicleModelsUsed](../scripting/functions/GetVehicleModelsUsed) | | [GetVehicleNumberPlate](../scripting/functions/GetVehicleNumberPlate) | | [GetVehicleOccupiedTick](../scripting/functions/GetVehicleOccupiedTick) | | [GetVehiclePaintjob](../scripting/functions/GetVehiclePaintjob) | | [GetVehicleRespawnDelay](../scripting/functions/GetVehicleRespawnDelay) | | [GetVehicleRespawnTick](../scripting/functions/GetVehicleRespawnTick) | | [GetVehicleSirenState](../scripting/functions/GetVehicleSirenState) | | [GetVehicleSpawnInfo](../scripting/functions/GetVehicleSpawnInfo) | | [GetVehicleTrainSpeed](../scripting/functions/GetVehicleTrainSpeed) | | [SetVehicleBeenOccupied](../scripting/functions/SetVehicleBeenOccupied) | | [HasVehicleBeenOccupied](../scripting/functions/HasVehicleBeenOccupied) | | [IsVehicleOccupied](../scripting/functions/IsVehicleOccupied) | | [HideVehicle](../scripting/functions/HideVehicle) | | [ShowVehicle](../scripting/functions/ShowVehicle) | | [IsVehicleHidden](../scripting/functions/IsVehicleHidden) | | [SetVehicleDead](../scripting/functions/SetVehicleDead) | | [IsVehicleDead](../scripting/functions/IsVehicleDead) | | [IsVehicleSirenEnabled](../scripting/functions/IsVehicleSirenEnabled) | | [SetVehicleOccupiedTick](../scripting/functions/SetVehicleOccupiedTick) | | [SetVehicleParamsSirenState](../scripting/functions/SetVehicleParamsSirenState) | | [SetVehicleRespawnDelay](../scripting/functions/SetVehicleRespawnDelay) | | [SetVehicleRespawnTick](../scripting/functions/SetVehicleRespawnTick) | | [SetVehicleSpawnInfo](../scripting/functions/SetVehicleSpawnInfo) | | [ToggleVehicleSirenEnabled](../scripting/functions/ToggleVehicleSirenEnabled) | | [VehicleColourIndexToColour](../scripting/functions/VehicleColourIndexToColour) | | [GetVehicles](../scripting/functions/GetVehicles) | ## TextDraw | İsim | |---------------------------------------------------------------------------------------------------------| | [TextDrawColour](../scripting/functions/TextDrawColour) | | [TextDrawBoxColour](../scripting/functions/TextDrawBoxColour) | | [TextDrawBackgroundColour](../scripting/functions/TextDrawBackgroundColour) | | [TextDrawGetAlignment](../scripting/functions/TextDrawGetAlignment) | | [TextDrawGetBackgroundColor](../scripting/functions/TextDrawGetBackgroundColor) | | [TextDrawGetBackgroundColour](../scripting/functions/TextDrawGetBackgroundColour) | | [TextDrawGetBoxColor](../scripting/functions/TextDrawGetBoxColor) | | [TextDrawGetBoxColour](../scripting/functions/TextDrawGetBoxColour) | | [TextDrawGetColor](../scripting/functions/TextDrawGetColor) | | [TextDrawGetColour](../scripting/functions/TextDrawGetColour) | | [TextDrawGetFont](../scripting/functions/TextDrawGetFont) | | [TextDrawGetLetterSize](../scripting/functions/TextDrawGetLetterSize) | | [TextDrawGetOutline](../scripting/functions/TextDrawGetOutline) | | [TextDrawGetPos](../scripting/functions/TextDrawGetPos) | | [TextDrawGetPreviewModel](../scripting/functions/TextDrawGetPreviewModel) | | [TextDrawGetPreviewRot](../scripting/functions/TextDrawGetPreviewRot) | | [TextDrawGetPreviewVehicleColours](../scripting/functions/TextDrawGetPreviewVehicleColours) | | [TextDrawGetShadow](../scripting/functions/TextDrawGetShadow) | | [TextDrawGetString](../scripting/functions/TextDrawGetString) | | [TextDrawGetTextSize](../scripting/functions/TextDrawGetTextSize) | | [TextDrawIsBox](../scripting/functions/TextDrawIsBox) | | [TextDrawIsProportional](../scripting/functions/TextDrawIsProportional) | | [TextDrawIsSelectable](../scripting/functions/TextDrawIsSelectable) | | [TextDrawSetPos](../scripting/functions/TextDrawSetPos) | | [TextDrawSetPreviewVehicleColours](../scripting/functions/TextDrawSetPreviewVehicleColours) | | [TextDrawSetStringForPlayer](../scripting/functions/TextDrawSetStringForPlayer) | | [IsValidTextDraw](../scripting/functions/IsValidTextDraw) | | [IsTextDrawVisibleForPlayer](../scripting/functions/IsTextDrawVisibleForPlayer) | | [PlayerTextDrawBackgroundColour](../scripting/functions/PlayerTextDrawBackgroundColour) | | [PlayerTextDrawBoxColour](../scripting/functions/PlayerTextDrawBoxColour) | | [PlayerTextDrawColour](../scripting/functions/PlayerTextDrawColour) | | [PlayerTextDrawGetAlignment](../scripting/functions/PlayerTextDrawGetAlignment) | | [PlayerTextDrawGetBackgroundCol](../scripting/functions/PlayerTextDrawGetBackgroundCol) | | [PlayerTextDrawGetBackgroundColour](../scripting/functions/PlayerTextDrawGetBackgroundColour) | | [PlayerTextDrawGetBoxColor](../scripting/functions/PlayerTextDrawGetBoxColor) | | [PlayerTextDrawGetBoxColour](../scripting/functions/PlayerTextDrawGetBoxColour) | | [PlayerTextDrawGetColor](../scripting/functions/PlayerTextDrawGetColor) | | [PlayerTextDrawGetColour](../scripting/functions/PlayerTextDrawGetColour) | | [PlayerTextDrawGetFont](../scripting/functions/PlayerTextDrawGetFont) | | [PlayerTextDrawGetLetterSize](../scripting/functions/PlayerTextDrawGetLetterSize) | | [PlayerTextDrawGetOutline](../scripting/functions/PlayerTextDrawGetOutline) | | [PlayerTextDrawGetPos](../scripting/functions/PlayerTextDrawGetPos) | | [PlayerTextDrawGetPreviewModel](../scripting/functions/PlayerTextDrawGetPreviewModel) | | [PlayerTextDrawGetPreviewRot](../scripting/functions/PlayerTextDrawGetPreviewRot) | | [PlayerTextDrawGetPreviewVehicleColours](../scripting/functions/PlayerTextDrawGetPreviewVehicleColours) | | [PlayerTextDrawGetShadow](../scripting/functions/PlayerTextDrawGetShadow) | | [PlayerTextDrawGetString](../scripting/functions/PlayerTextDrawGetString) | | [PlayerTextDrawGetTextSize](../scripting/functions/PlayerTextDrawGetTextSize) | | [PlayerTextDrawIsBox](../scripting/functions/PlayerTextDrawIsBox) | | [PlayerTextDrawIsProportional](../scripting/functions/PlayerTextDrawIsProportional) | | [PlayerTextDrawIsSelectable](../scripting/functions/PlayerTextDrawIsSelectable) | | [PlayerTextDrawSetPos](../scripting/functions/PlayerTextDrawSetPos) | | [PlayerTextDrawSetPreviewVehicleColours](../scripting/functions/PlayerTextDrawSetPreviewVehicleColours) | | [IsValidPlayerTextDraw](../scripting/functions/IsValidPlayerTextDraw) | | [IsPlayerTextDrawVisible](../scripting/functions/IsPlayerTextDrawVisible) | ## GameText | İsim | |---------------------------------------------------------------------------------------------------------| | [GetGameText](../scripting/functions/GetGameText) | | [HasGameText](../scripting/functions/HasGameText) | | [HideGameTextForAll](../scripting/functions/HideGameTextForAll) | | [HideGameTextForPlayer](../scripting/functions/HideGameTextForPlayer) | ## GangZone | İsim | |---------------------------------------------------------------------------------------------------------| | [IsValidGangZone](../scripting/functions/IsValidGangZone) | | [IsPlayerInGangZone](../scripting/functions/IsPlayerInGangZone) | | [IsGangZoneVisibleForPlayer](../scripting/functions/IsGangZoneVisibleForPlayer) | | [GangZoneGetColourForPlayer](../scripting/functions/GangZoneGetColourForPlayer) | | [GangZoneGetFlashColourForPlayer](../scripting/functions/GangZoneGetFlashColourForPlayer) | | [IsGangZoneFlashingForPlayer](../scripting/functions/IsGangZoneFlashingForPlayer) | | [GangZoneGetPos](../scripting/functions/GangZoneGetPos) | | [UseGangZoneCheck](../scripting/functions/UseGangZoneCheck) | | [CreatePlayerGangZone](../scripting/functions/CreatePlayerGangZone) | | [PlayerGangZoneDestroy](../scripting/functions/PlayerGangZoneDestroy) | | [PlayerGangZoneShow](../scripting/functions/PlayerGangZoneShow) | | [PlayerGangZoneHide](../scripting/functions/PlayerGangZoneHide) | | [PlayerGangZoneFlash](../scripting/functions/PlayerGangZoneFlash) | | [PlayerGangZoneStopFlash](../scripting/functions/PlayerGangZoneStopFlash) | | [PlayerGangZoneGetColour](../scripting/functions/PlayerGangZoneGetColour) | | [PlayerGangZoneGetFlashColour](../scripting/functions/PlayerGangZoneGetFlashColour) | | [PlayerGangZoneGetPos](../scripting/functions/PlayerGangZoneGetPos) | | [IsValidPlayerGangZone](../scripting/functions/IsValidPlayerGangZone) | | [IsPlayerInPlayerGangZone](../scripting/functions/IsPlayerInPlayerGangZone) | | [IsPlayerGangZoneVisible](../scripting/functions/IsPlayerGangZoneVisible) | | [IsPlayerGangZoneFlashing](../scripting/functions/IsPlayerGangZoneFlashing) | | [UsePlayerGangZoneCheck](../scripting/functions/UsePlayerGangZoneCheck) | | [OnPlayerEnterGangZone](../scripting/callbacks/OnPlayerEnterGangZone) | | [OnPlayerLeaveGangZone](../scripting/callbacks/OnPlayerLeaveGangZone) | | [OnPlayerEnterPlayerGangZone](../scripting/callbacks/OnPlayerEnterPlayerGangZone) | | [OnPlayerLeavePlayerGangZone](../scripting/callbacks/OnPlayerLeavePlayerGangZone) | | [OnPlayerClickGangZone](../scripting/callbacks/OnPlayerClickGangZone) | | [OnPlayerClickPlayerGangZone](../scripting/callbacks/OnPlayerClickPlayerGangZone) | ## Checkpoint | İsim | |---------------------------------------------------------------------------------------------------------| | [IsPlayerCheckpointActive](../scripting/functions/IsPlayerCheckpointActive) | | [GetPlayerCheckpoint](../scripting/functions/GetPlayerCheckpoint) | | [IsPlayerRaceCheckpointActive](../scripting/functions/IsPlayerRaceCheckpointActive) | | [GetPlayerRaceCheckpoint](../scripting/functions/GetPlayerRaceCheckpoint) | ## Aktör | İsim | |---------------------------------------------------------------------------------------------------------| | [SetActorSkin](../scripting/functions/SetActorSkin) | | [GetActorSkin](../scripting/functions/GetActorSkin) | | [GetActorAnimation](../scripting/functions/GetActorAnimation) | | [GetActorSpawnInfo](../scripting/functions/GetActorSpawnInfo) | | [GetActors](../scripting/functions/GetActors) | ## 3D TextLabel | İsim | |---------------------------------------------------------------------------------------------------------| | [Is3DTextLabelStreamedIn](../scripting/functions/Is3DTextLabelStreamedIn) | | [Get3DTextLabelText](../scripting/functions/Get3DTextLabelText) | | [Get3DTextLabelColor](../scripting/functions/Get3DTextLabelColor) | | [Get3DTextLabelColour](../scripting/functions/Get3DTextLabelColour) | | [Get3DTextLabelPos](../scripting/functions/Get3DTextLabelPos) | | [Set3DTextLabelDrawDistance](../scripting/functions/Set3DTextLabelDrawDistance) | | [Get3DTextLabelDrawDistance](../scripting/functions/Get3DTextLabelDrawDistance) | | [Get3DTextLabelLOS](../scripting/functions/Get3DTextLabelLOS) | | [Set3DTextLabelLOS](../scripting/functions/Set3DTextLabelLOS) | | [Get3DTextLabelVirtualWorld](../scripting/functions/Get3DTextLabelVirtualWorld) | | [Set3DTextLabelVirtualWorld](../scripting/functions/Set3DTextLabelVirtualWorld) | | [Get3DTextLabelAttachedData](../scripting/functions/Get3DTextLabelAttachedData) | | [IsValid3DTextLabel](../scripting/functions/IsValid3DTextLabel) | | [IsValidPlayer3DTextLabel](../scripting/functions/IsValidPlayer3DTextLabel) | | [GetPlayer3DTextLabelText](../scripting/functions/GetPlayer3DTextLabelText) | | [GetPlayer3DTextLabelColor](../scripting/functions/GetPlayer3DTextLabelColor) | | [GetPlayer3DTextLabelColour](../scripting/functions/GetPlayer3DTextLabelColour) | | [GetPlayer3DTextLabelPos](../scripting/functions/GetPlayer3DTextLabelPos) | | [SetPlayer3DTextLabelDrawDistance](../scripting/functions/SetPlayer3DTextLabelDrawDistance) | | [GetPlayer3DTextLabelDrawDistance](../scripting/functions/GetPlayer3DTextLabelDrawDistance) | | [GetPlayer3DTextLabelLOS](../scripting/functions/GetPlayer3DTextLabelLOS) | | [GetPlayer3DTextLabelVirtualWorld](../scripting/functions/GetPlayer3DTextLabelVirtualWorld) | | [SetPlayer3DTextLabelVirtualWorld](../scripting/functions/SetPlayer3DTextLabelVirtualWorld) | | [GetPlayer3DTextLabelAttached](../scripting/functions/GetPlayer3DTextLabelAttached) | | [GetPlayer3DTextLabelAttachedData](../scripting/functions/GetPlayer3DTextLabelAttachedData) | ## Class | İsim | |---------------------------------------------------------------------------------------------------------| | [GetAvailableClasses](../scripting/functions/GetAvailableClasses) | | [EditPlayerClass](../scripting/functions/EditPlayerClass) | | [GetPlayerClass](../scripting/functions/GetPlayerClass) | ## Menu | İsim | |---------------------------------------------------------------------------------------------------------| | [GetMenuItem](../scripting/functions/GetMenuItem) | | [GetMenuItems](../scripting/functions/GetMenuItems) | | [GetMenuColumns](../scripting/functions/GetMenuColumns) | | [GetMenuColumnHeader](../scripting/functions/GetMenuColumnHeader) | | [GetMenuPos](../scripting/functions/GetMenuPos) | | [GetMenuColumnWidth](../scripting/functions/GetMenuColumnWidth) | | [IsMenuDisabled](../scripting/functions/IsMenuDisabled) | | [IsMenuRowDisabled](../scripting/functions/IsMenuRowDisabled) | ## Veri tabanı | İsim | |---------------------------------------------------------------------------------------------------------| | [DB_ExecuteQuery](../scripting/functions/DB_ExecuteQuery) | | [DB_FreeResultSet](../scripting/functions/DB_FreeResultSet) | | [DB_GetDatabaseConnectionCount](../scripting/functions/DB_GetDatabaseConnectionCount) | | [DB_GetDatabaseResultSetCount](../scripting/functions/DB_GetDatabaseResultSetCount) | | [DB_GetFieldCount](../scripting/functions/DB_GetFieldCount) | | [DB_GetFieldFloat](../scripting/functions/DB_GetFieldFloat) | | [DB_GetFieldFloatByName](../scripting/functions/DB_GetFieldFloatByName) | | [DB_GetFieldInt](../scripting/functions/DB_GetFieldInt) | | [DB_GetFieldIntByName](../scripting/functions/DB_GetFieldIntByName) | | [DB_GetFieldName](../scripting/functions/DB_GetFieldName) | | [DB_GetFieldString](../scripting/functions/DB_GetFieldString) | | [DB_GetFieldStringByName](../scripting/functions/DB_GetFieldStringByName) | | [DB_GetLegacyDBResult](../scripting/functions/DB_GetLegacyDBResult) | | [DB_GetMemHandle](../scripting/functions/DB_GetMemHandle) | | [DB_GetRowCount](../scripting/functions/DB_GetRowCount) | | [DB_SelectNextRow](../scripting/functions/DB_SelectNextRow) | ## Core | İsim | |---------------------------------------------------------------------------------------------------------| | [SetModeRestartTime](../scripting/functions/SetModeRestartTime) | | [GetModeRestartTime](../scripting/functions/GetModeRestartTime) | | [IsAdminTeleportAllowed](../scripting/functions/IsAdminTeleportAllowed) | | [AreAllAnimationsEnabled](../scripting/functions/AreAllAnimationsEnabled) | | [EnableAllAnimations](../scripting/functions/EnableAllAnimations) | | [IsValidAnimationLibrary](../scripting/functions/IsValidAnimationLibrary) | | [ArePlayerWeaponsAllowed](../scripting/functions/ArePlayerWeaponsAllowed) | | [AreInteriorWeaponsAllowed](../scripting/functions/AreInteriorWeaponsAllowed) | | [GetWeaponSlot](../scripting/functions/GetWeaponSlot) | | [GetWeather](../scripting/functions/GetWeather) | | [GetWorldTime](../scripting/functions/GetWorldTime) | | [ToggleChatTextReplacement](../scripting/functions/ToggleChatTextReplacement) | | [ChatTextReplacementToggled](../scripting/functions/ChatTextReplacementToggled) | | [AllowNickNameCharacter](../scripting/functions/AllowNickNameCharacter) | | [IsValidNickName](../scripting/functions/IsValidNickName) | | [ClearBanList](../scripting/functions/ClearBanList) | | [IsBanned](../scripting/functions/IsBanned) | ## Sunucu Kuralı | İsim | |---------------------------------------------------------------------------------------------------------| | [AddServerRule](../scripting/functions/AddServerRule) | | [RemoveServerRule](../scripting/functions/RemoveServerRule) | | [IsValidServerRule](../scripting/functions/IsValidServerRule) | | [SetServerRule](../scripting/functions/SetServerRule) | | [SetServerRuleFlags](../scripting/functions/SetServerRuleFlags) | | [GetServerRuleFlags](../scripting/functions/GetServerRuleFlags) | ## Zamanlayıcı | İsim | |---------------------------------------------------------------------------------------------------------| | [IsValidTimer](../scripting/functions/IsValidTimer) | | [IsRepeatingTimer](../scripting/functions/IsRepeatingTimer) | | [GetTimerInterval](../scripting/functions/GetTimerInterval) | | [GetTimerRemaining](../scripting/functions/GetTimerRemaining) | | [CountRunningTimers](../scripting/functions/CountRunningTimers) | | [GetRunningTimers](../scripting/functions/GetRunningTimers) | ## Özel Model | İsim | |---------------------------------------------------------------------------------------------------------| | [IsValidCustomModel](../scripting/functions/IsValidCustomModel) | | [GetCustomModelPath](../scripting/functions/GetCustomModelPath) |
openmultiplayer/web/docs/translations/tr/server/omp-functions.md/0
{ "file_path": "openmultiplayer/web/docs/translations/tr/server/omp-functions.md", "repo_id": "openmultiplayer", "token_count": 21071 }
483
--- title: OnFilterScriptInit description: 初始化(加载完成)过滤脚本(filterscript)时,将调用此回调函数。 tags: [] --- ## 描述 初始化(加载完成)过滤脚本(filterscript)时,将调用此回调函数。 ## 案例 ```c public OnFilterScriptInit() { print("\n--------------------------------------"); print("已加载过滤脚本。"); print("--------------------------------------\n"); return 1; } ``` ## 相关回调
openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnFilterScriptInit.md/0
{ "file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnFilterScriptInit.md", "repo_id": "openmultiplayer", "token_count": 234 }
484
--- title: OnPlayerCommandText description: 当玩家在客户端聊天框中输入指令时,这个回调函数被调用。 tags: ["player"] --- ## 描述 当玩家在客户端聊天框中输入指令时,这个回调函数被调用。 | 参数名 | 描述 | | --------- | ------------------------ | | playerid | 输入指令的玩家的 ID。 | | cmdtext[] | 输入的指令(包括正斜杠)。 | ## 返回值 它在过滤脚本中总是先被调用,所以返回 1 会阻止其他脚本看到它。 ## 案例 ```c public OnPlayerCommandText(playerid, cmdtext[]) { if (!strcmp(cmdtext, "/help", true)) { SendClientMessage(playerid, -1, "服务器: 这是/help指令!"); return 1; // 返回1将通知服务器该指令已被处理。 // OnPlayerCommandText不会在其他脚本中被调用。 } return 0; // 返回0将通知服务器该脚本还没有处理该指令。 // OnPlayerCommandText将在其他脚本中被调用,直到其中一个返回1。 // 如果最终没有任何脚本返回1,'SERVER: Unknown Command'(服务器: 未知指令)消息将显示给玩家。 } ``` ## 要点 <TipNPCCallbacksCN /> ## 相关函数 - [SendRconCommand](../functions/SendRconCommand): 通过脚本发送 RCON 指令。
openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnPlayerCommandText.md/0
{ "file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnPlayerCommandText.md", "repo_id": "openmultiplayer", "token_count": 796 }
485
--- title: OnPlayerLeaveCheckpoint description: 当玩家离开SetPlayerCheckpoint函数为其设置的检查点时,会调用此回调。 tags: ["player", "checkpoint"] --- ## 描述 当玩家离开 SetPlayerCheckpoint 函数为其设置的检查点时,会调用此回调。 一次只能设置一个检查点。 | 参数名 | 描述 | | -------- | ----------------------- | | playerid | 离开检查点的玩家的 ID。 | ## 返回值 它在过滤脚本中总是先被调用。 ## 案例 ```c public OnPlayerLeaveCheckpoint(playerid) { printf("玩家 %i 离开了一个检查点!", playerid); return 1; } ``` ## 要点 <TipNPCCallbacksCN /> ## 相关函数 - [SetPlayerCheckpoint](../functions/SetPlayerCheckpoint): 为玩家创建一个检查点。 - [DisablePlayerCheckpoint](../functions/DisablePlayerCheckpoint): 禁用玩家的当前检查点。 - [IsPlayerInCheckpoint](../functions/IsPlayerInCheckpoint): 检查玩家是否在检查站。 - [SetPlayerRaceCheckpoint](../functions/SetPlayerRaceCheckpoint): 为玩家创建一个比赛检查点。 - [DisablePlayerRaceCheckpoint](../functions/DisablePlayerRaceCheckpoint): 禁用玩家当前的比赛检查点。 - [IsPlayerInRaceCheckpoint](../functions/IsPlayerInRaceCheckpoint): 检查某位玩家是否在比赛检查点。
openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnPlayerLeaveCheckpoint.md/0
{ "file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnPlayerLeaveCheckpoint.md", "repo_id": "openmultiplayer", "token_count": 696 }
486
--- title: OnPlayerWeaponShot description: 当玩家使用武器射击时,这个回调函数被调用。 tags: ["player"] --- ## 描述 该回调函数在玩家使用武器射击时调用。仅适用于有子弹的武器。仅对乘客提供支持(不对司机提供支持,并且不适用 sea sparrow (水上飞机)/hunter shots (阿帕奇直升机))。 | 参数名 | 描述 | | -------- | ------------------------------------------------------------------------------- | | playerid | 用武器射击的玩家的 ID。 | | WEAPON:weaponid | 该玩家使用的[武器](../resources/weaponids)的 ID。 | | BULLET_HIT_TYPE:hittype | 射击击中的物体[类型](../resources/bullethittypes)(无、玩家、车辆或(玩家)物体)。 | | hitid | 被击中的玩家、车辆或物体的 ID。 | | Float:fX | 玩家所击中的 X 轴坐标。 | | Float:fY | 玩家所击中的 Y 轴坐标。 | | Float:fZ | 玩家所击中的 Z 轴坐标。 | ## 返回值 0 - 防止子弹造成伤害。 1 - 允许子弹造成伤害。 它在过滤脚本中总是先被调用,所以返回 0 会阻止其他脚本看到它。 ## 案例 ```c public OnPlayerWeaponShot(playerid, WEAPON:weaponid, BULLET_HIT_TYPE:hittype, hitid, Float:fX, Float:fY, Float:fZ) { new szString[144]; format(szString, sizeof(szString), "武器 %i 开火了。击中物体类型: %i 被击中的ID: %i 坐标: %f, %f, %f", weaponid, hittype, hitid, fX, fY, fZ); SendClientMessage(playerid, -1, szString); return 1; } ``` ## 要点 :::tip 这个回调函数只在启用延迟补偿时被调用。 如果 hittype(物体类型) 是: - BULLET_HIT_TYPE_NONE:fX, fY 和 fZ 参数是法线坐标,如果没有击中任何物体(例如子弹无法到达的远的物体),坐标将为 0.0; - 其他类型:fX,fY 和 fZ 是相对于 Hitid 的偏移量。 ::: :::tip [GetPlayerLastShotVectors](../functions/GetPlayerLastShotVectors) 函数可以在这个回调中用于获得更详细的子弹向量信息。 ::: :::warning 已知 Bug(s): 当你作为驾驶员在车中射击或者你在瞄准后(在空中射击)时不会被调用。 如果你射击的是一名驾驶着一辆车的玩家,那么 hittype 值为 BULLET_HIT_TYPE_VEHICLE,并带有正确的 hitid(即击中的玩家的车辆 id),而不是 BULLET_HIT_TYPE_PLAYER(击中的玩家)。 SA-MP 0.3.7 版本中修正了部分问题:当用户恶意发送假武器数据时,其他的玩家客户端会冻结或崩溃。要解决这一问题,请检查参数中的 weaponid 武器 ID 是否能够真正发射子弹。 ::: ## 相关函数 - [GetPlayerLastShotVectors](../functions/GetPlayerLastShotVectors): 获取玩家最后一枪的向量信息。
openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnPlayerWeaponShot.md/0
{ "file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnPlayerWeaponShot.md", "repo_id": "openmultiplayer", "token_count": 1998 }
487
--- title: AddMenuItem description: 向指定菜单中添加菜单项。 tags: ["menu"] --- ## 描述 向指定菜单中添加菜单项。 | 参数名 | 说明 | | ------- | ----------------------- | | menuid | 要添加菜单项的菜单 ID。 | | column | 要添加菜单项到哪列。 | | title[] | 菜单项的标题。 | ## 返回值 添加后该项的行索引。 ## 案例 ```c new Menu:gExampleMenu; public OnGameModeInit() { gExampleMenu = CreateMenu("你的菜单", 2, 200.0, 100.0, 150.0, 150.0); AddMenuItem(gExampleMenu, 0, "菜单项 1"); AddMenuItem(gExampleMenu, 0, "菜单项 2"); return 1; } ``` ## 要点 :::tip 传递无效菜单 ID 时崩溃。 每个菜单只能有 12 个选项(第 13 个到列名标题的右边(彩色),第 14 个及以上根本不显示)。 只能使用 2 列(0 和 1)。 每个菜单项只能添加 8 种颜色编码 (`~r~`, `~g~`等)。 菜单项的最大长度是 31 个符号。 ::: ## 相关函数 - [CreateMenu](CreateMenu): 创建一个菜单。 - [SetMenuColumnHeader](SetMenuColumnHeader): 设置菜单中某一列的标题。 - [DestroyMenu](DestroyMenu): 销毁一个菜单。 - [OnPlayerSelectedMenuRow](../callbacks/OnPlayerSelectedMenuRow): 当玩家在菜单中选择了一个菜单项时调用。 - [OnPlayerExitedMenu](../callbacks/OnPlayerExitedMenu): 当玩家退出菜单时调用。
openmultiplayer/web/docs/translations/zh-cn/scripting/functions/AddMenuItem.md/0
{ "file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/functions/AddMenuItem.md", "repo_id": "openmultiplayer", "token_count": 826 }
488
--- title: AttachCameraToObject description: 您可以使用此函数将玩家视角附加到物体上。 tags: [] --- ## 描述 您可以使用此函数将玩家视角附加到物体上。 | 参数名 | 说明 | | -------- | --------------------------- | | playerid | 将视角附加到物体上的玩家 ID | | objectid | 将视角附加到的物体 ID | ## 返回值 该函数不返回任何特定的值。 ## 案例 ```c public OnPlayerCommandText(playerid, cmdtext[]) { if (!strcmp(cmdtext, "/attach", false)) { new objectId = CreateObject(1245, 0.0, 0.0, 3.0, 0.0, 0.0, 0.0); AttachCameraToObject(playerid, objectId); SendClientMessage(playerid, 0xFFFFFFAA, "你的视角现在附加到物体上了。"); return 1; } return 0; } ``` ## 要点 :::tip 在试图将玩家的视角附加到物体之前,必须先创建物体。 ::: ## 相关函数 - [AttachCameraToPlayerObject](AttachCameraToPlayerObject): 将玩家的视角附加在玩家物体上。
openmultiplayer/web/docs/translations/zh-cn/scripting/functions/AttachCameraToObject.md/0
{ "file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/functions/AttachCameraToObject.md", "repo_id": "openmultiplayer", "token_count": 594 }
489
--- title: GetPlayerCameraZoom description: 检索指定玩家的游戏视角缩放级别。 tags: ["player", "camera"] --- ## 描述 检索指定玩家的游戏视角缩放级别。 | 参数名 | 说明 | | -------- | ------------------------------- | | playerid | 要获取视角缩放级别的玩家的 ID。 | ## 返回值 以浮点数形式返回玩家的视角缩放级别(数码相机, 狙击瞄准镜等等)。 ## 案例 ```c new szString[144]; format(szString, sizeof(szString), "你的视角缩放级别是: %f", GetPlayerCameraZoom(playerid)); SendClientMessage(playerid, -1, szString); ``` ## 要点 :::tip 这将检索游戏视角(包括狙击瞄准镜)的缩放级别,而不只是作为武器类的数码相机的变焦级别。 ::: ## 相关函数 - [GetPlayerCameraAspectRatio](GetPlayerCameraAspectRation): 获取玩家视角的纵横比。 - [GetPlayerCameraPos](GetPlayerCameraPos): 找出玩家的视角在哪里。 - [GetPlayerCameraFrontVector](GetPlayerCameraFrontVector): 获取玩家视角的前向量。
openmultiplayer/web/docs/translations/zh-cn/scripting/functions/GetPlayerCameraZoom.md/0
{ "file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/functions/GetPlayerCameraZoom.md", "repo_id": "openmultiplayer", "token_count": 631 }
490
--- title: floatsin description: 从特定角度求正弦值。 tags: ["math", "floating-point"] --- <LowercaseNote /> ## 描述 从给定角度求正弦值。输入的角度可以是弧度、角度或分数。 | 参数名 | 说明 | | ----------- | ------------------------------------------------------------- | | Float:value | 求正弦的角度。 | | anglemode | 要使用的[角度模式](../resources/anglemodes),取决于输入的值。 | ## 返回值 输入值的正弦值。 ## 案例 ```c GetPosInFrontOfPlayer(playerid, Float:distance, &Float:x, &Float:y, &Float:z) { if (GetPlayerPos(playerid, x, y, z)) // 如果玩家未连接,则此函数返回0 { new Float:z_angle; GetPlayerFacingAngle(playerid, z_angle); x += distance * floatsin(-z_angle, degrees); // GTA中的角度是逆时针方向的,所以我们需要反转检索到的角度 y += distance * floatcos(-z_angle, degrees); return 1; // 成功时返回1,通过引用返回实际坐标 } return 0; // 如果玩家没有连接,返回0 } ``` ## 要点 :::warning GTA/SA-MP 在大多数情况下使用角度来表示弧度,例如[GetPlayerFacingAngle](GetPlayerFacingAngle)。因此,你很可能想要使用“角度”模式,而不是弧度。还要注意 GTA 中的角度是逆时针的;270° 为东,90° 为西。南仍然是 180°,北仍然是 0°/360°。 ::: ## 相关函数 - [floattan](floattan): 从特定角度求正切值。 - [floatcos](floatcos): 从特定角度求余弦值。
openmultiplayer/web/docs/translations/zh-cn/scripting/functions/floatsin.md/0
{ "file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/functions/floatsin.md", "repo_id": "openmultiplayer", "token_count": 977 }
491
--- title: Menu Guide --- A short tutorial that explains how to use the menu system of the game. This menu system is different to SA-MP dialogs and better reflects the traditional UI of the original game. ## Menus in SA-MP Menus look very complicated and difficult to script for the most players, although it isn't. Here I will show you how to create a simple menu. At the end we will have created a teleport menu. ## First menu steps First we have to create a menu. The prefix before is `Menu:` this makes the variable the correct [tag](../scripting/language/Tags). There are different types for different uses such as `Float:` `bool:` `Text3D:` etc. Write the following code near the top of your script: ```c new Menu:teleportmenu; ``` Okay, we created the variable to store the menu. Now we have to create the menu and assign the variable we created to the menu. Type this into `OnGameModeInit`: ```c teleportmenu = CreateMenu("Teleportmenu", 2, 200.0, 100.0, 150.0, 150.0); ``` Now a bit of an explanation about the [CreateMenu](../scripting/functions/CreateMenu) arguments. **Parameters:** | Parameter | Specifies | | --------------- | ---------------------------------------------------------------- | | title | The heading of the menu | | columns | The number here defines how much columns are used (2 is maximum) | | Float:x | The heigth position of the menu on screen (left to right) | | Float:y | The width position of the menu on screen (up and down) | | Float:col1width | The width of the first column | | Float:col2width | The width of the second column | ## Add some menu items Ok, now we've got the Menu, but we need some items, under which you can choose in the menu. You add them underneath the `CreateMenu` that we made earlier. ```c AddMenuItem(teleportmenu, 0, "LS"); AddMenuItem(teleportmenu, 0, "LS"); AddMenuItem(teleportmenu, 0, "SF"); AddMenuItem(teleportmenu, 0, "SF"); AddMenuItem(teleportmenu, 0, "LV"); AddMenuItem(teleportmenu, 0, "LV");   AddMenuItem(teleportmenu, 1, "Grove Street"); AddMenuItem(teleportmenu, 1, "Starfish Tower"); AddMenuItem(teleportmenu, 1, "Wheel Arch Angels"); AddMenuItem(teleportmenu, 1, "Jizzys"); AddMenuItem(teleportmenu, 1, "4 Dragons"); AddMenuItem(teleportmenu, 1, "Come-a-Lot"); ``` The explanation for [AddMenuItem](../scripting/functions/AddMenuItem): | menuid | The menuid of the menu where the item shall be displayed | | ------ | -------------------------------------------------------- | | column | The column in which the item shall be shown | | text | The text of the item | ## Creating the effects for the items Okay, now that we have created a full menu with items what should happen when you choose an item? In our example we want to make a teleportmenu, so we should get teleported to the position we choose. When a player selects an item on a menu the script calls the callback [OnPlayerSelectedMenuRow](../scripting/callbacks/OnPlayerSelectedMenuRow). The best way to do it is to do it with a switch, this is like several if statements to check if a variable is worth certain values. But first we only want these effects for the menu we want so we need to create a variable that holds what menu the player is looking at, this is done with `GetPlayerMenu`: ```c new Menu:CurrentMenu = GetPlayerMenu(playerid); ``` Now, when somebody selects something on the menu, their menuid will be saved in `CurrentMenu`. Now we have to check that the menu they selected on is the menu we want: ```c public OnPlayerSelectedMenuRow(playerid, row) { new Menu:CurrentMenu = GetPlayerMenu(playerid); if (CurrentMenu == teleportmenu) { //stuff } return 1; } ``` Now in between these brackets is where the `switch` is, this checks what item the player selected or `row` this can be done with `if` statements checking what `row` it is, but the `switch` is a much simpler way of writing it. ```c if(CurrentMenu == teleportmenu) { switch(row) { case 0: //Grove Street { SetPlayerPos(playerid, 2493.9133, -1682.3986, 13.3382); SetPlayerInterior(playerid, 0); SendClientMessage(playerid, 0xFFFFFFFF, "Welcome to Grove Street"); } case 1: //Starfish Tower { SetPlayerPos(playerid, 1541.2833, -1362.4741, 329.6457); SetPlayerInterior(playerid, 0); SendClientMessage(playerid, 0xFFFFFFFF, "Welcome to the top of Starfish Tower"); } case 2: //Wheel Arch Angels { SetPlayerPos(playerid, -2705.5503, 206.1621, 4.1797); SetPlayerInterior(playerid, 0); SendClientMessage(playerid, 0xFFFFFFFF, "Welcome to the Wheel Arch Angels tuning-shop"); } case 3: //Jizzys { SetPlayerPos(playerid, -2617.5156, 1390.6353, 7.1105); SetPlayerInterior(playerid, 0); SendClientMessage(playerid, 0xFFFFFFFF, "Welcome to Jizzy's Nightclub!"); } case 4: //4Dragons { SetPlayerPos(playerid, 2028.5538, 1008.3543, 10.8203); SetPlayerInterior(playerid, 0); SendClientMessage(playerid, 0xFFFFFFFF, "Welcome to the Four Dragons Casino"); } case 5: //Come-a-Lot { SetPlayerPos(playerid, 2169.1838, 1122.5426, 12.6107); SetPlayerInterior(playerid, 0); SendClientMessage(playerid, 0xFFFFFFFF, "Welcome to the Come-a-Lot casino!"); } } } ``` ## Last steps Now we need a command to show the menu. This is the easiest step. Just a comparison with `strcmp` and a `ShowMenuForPlayer`. This is done in `OnPlayerCommandText`. Or, if you have a command processor already, use that instead to call `ShowMenuForPlayer`. ```c if(strcmp(cmdtext, "/teleport", true) == 0) { ShowMenuForPlayer(teleportmenu,playerid); return 1; } ``` Really easy, wasn't it? ## Last words Okay, after you read this AND understood it, try your own menu. As you could see, it isn't that difficult, but will impress the players on your server all the more. And you can script really cool effects with this. It's also very cool for general stores or supermarkets for the things you can buy. Then you can subtract some money as effect and the price is shown in another column in the menu. But now, work on your own. You can also add [TogglePlayerControllable](../scripting/functions/TogglePlayerControllable) with `false` after `ShowPlayerMenu` and [TogglePlayerControllable](../scripting/functions/TogglePlayerControllable) with `true` at end of `OnPlayerSelectedMenuRow` so that player may not move while they are browsing menus. I hope you learned something from this tutorial. If you have any questions, ask in the forums/discord.
openmultiplayer/web/docs/tutorials/MenuGuide.md/0
{ "file_path": "openmultiplayer/web/docs/tutorials/MenuGuide.md", "repo_id": "openmultiplayer", "token_count": 2501 }
492
# اوبن ملتي بلاير هو عباره عن مود ملتي بلاير تحت الانشاء للعبه <em>جراند ثفت أوتو: سان أندرياس</em> و سوف تتوافق مع مود الملتي بلاير الحالي <em>سان اندريس ملتي بلاير</em> هذا يعني ان <strong>مستخدمين سامب و اصحاب السرفرات و الاسكربتات يمكنهم اللعب علي اوبن ام بي بدون مشاكل</strong> و سوف يتوافر بعض التحسينات و التصحيلات بدون اي تغيرات اذا تريد ان تعرف موعد الاصدار او تريد المساعده فعليك الذهاب الي [هذا الرابط](https://forum.open.mp/showthread.php?tid=99) لمعرفة معلومات اكثر. اذا # [اسئله و اجوبه](/faq)
openmultiplayer/web/frontend/content/ar/index.mdx/0
{ "file_path": "openmultiplayer/web/frontend/content/ar/index.mdx", "repo_id": "openmultiplayer", "token_count": 451 }
493
--- title: Vehicle Sync date: "2019-11-09T11:33:00" author: Southclaws --- A quick post demonstrating the evolution of vehicle sync. <video autoPlay loop width="100%" controls> <source src="https://assets.open.mp/assets/images/videos/vehicle_sync_01.mp4" type="video/mp4" /> Sorry, your browser doesn't support embedded videos. </video> <video autoPlay loop width="100%" controls> <source src="https://assets.open.mp/assets/images/videos/vehicle_sync_02.mp4" type="video/mp4" /> Sorry, your browser doesn't support embedded videos. </video> <video autoPlay loop width="100%" controls> <source src="https://assets.open.mp/assets/images/videos/vehicle_sync_03.mp4" type="video/mp4" /> Sorry, your browser doesn't support embedded videos. </video>
openmultiplayer/web/frontend/content/en/blog/vehicle-sync.mdx/0
{ "file_path": "openmultiplayer/web/frontend/content/en/blog/vehicle-sync.mdx", "repo_id": "openmultiplayer", "token_count": 244 }
494
# Open Multiplayer Egy közelgő módosítás a _Grand Theft Auto: San Andreas_ nevű játékhoz ami teljesen kompatibilis lesz a már jól ismert _San Andreas Multiplayer_ móddal. <br /> Ez azt jelenti hogy a **már létező SA:MP kliens és minden SA:MP script működni fog az open.mp-vel** és ezen túlmenően sok hiba rögzítésre, és javításra kerül ami azt eredményezi hogy nem lesz szükség megoldásokat keresni alapvető problémákra. Ha kíváncsi vagy mikor lesz elérhető a projekt, vagy szeretnél közreműködni, kérlek látogasd meg <a href="https://forum.open.mp/showthread.php?tid=99">ezt a fórum témát</a> további információért. # [GYIK](/faq)
openmultiplayer/web/frontend/content/hu/index.mdx/0
{ "file_path": "openmultiplayer/web/frontend/content/hu/index.mdx", "repo_id": "openmultiplayer", "token_count": 322 }
495
<h1>Ofte stilte spørsmål</h1> <hr /> <h2>Hva er open.mp?</h2> open.mp (Open Multiplayer, OMP) er en erstatning til SA:MP, igangsatt som en respons til den uønskede mengden problemer med oppdateringer og styring av SA:MP. Den første utgivelsen vil være en ren erstatning bare til serveren. Eksisterende SA:MP-klienter vil fortsatt kunne koble til serverene. På lengre sikt så vil en ny open.mp klient bli tilgjengelig, som vil bidra til at flere og bedre oppdateringer er velkomne. <hr /> <h2>Er dette en fork?</h2> Nei. Dette er en helt restrukturert code fra scratch, som utnytter seg av tiår med kompetanse og kjennskap. Det har vært forsøkt å forke SA:MP før, men vi tror at disse prosjektene ikke har gjort det riktig: <ol> <li> De har vært basert på lekket kode. Utviklerne av disse har ikke hatt rettigheter til koden, og har derfor alltid vært bakpå både rettslig og moralsk. Vi nekter å benytte oss av slik kode. Det vil direkte påvirke hvor kjapt det går å utvikle, men vil være den helt riktige veien på sikt. </li> <li> De har forsøkt å lage for mye nytt på en gang. Enten så har de erstattet hele kode-strukturen, eller fjernet ting for å legge til nye, eller bare endre på ting som ikke er kompatibelt. Dette forhindrer store, eksisterende servere og spillere fra å flytte over, siden det ville ha ment de måtte endre på noe av (hvis ikke alt av) koden deres - som er svært uheldig. Vi ønsker selvfølgelig å gjøre endringer og tweake ting over tid, men førsteprioritet er å kunne støtte eksisterende servere, som tillater de å bruke vår kode uten at de må endre på deres. </li> </ol> <hr /> <h2>Hvorfor gjør dere dette?</h2> Uten hell så har det vært prøvd flere ganger å få utviklingen til å gå fremover på SA:MP. Det i form av nye ideèr, masing og tilbud om å hjelpe til fra Beta-laget; støttet av et stort samfunn som har bedt om noe nytt; så har det ikke vært noen som helts fremgang. Det tenkes at dette er på grunn av at eier ikke har sett intresse av å ta hand om modden lengre, som forøvrig ikke er problemet, men det har ikke vært noe forsøk på å la andre ta over. Istedet for å la modden leve videre så har eier åpenbart tenkt å la alt dø sammen med han. Noen sier de tror det er fordi eier tjener gode penger på siden, men det er ingen bevis på at dette stemmer. Selv om det har vært svært stor interesse og et sammensveiset samfunn, han trodde det bare var et par år igjen for SA-MP, og medlemmene i samfunnet som hadde jobbet så enormt hardt for alt sammen, ikke fortjene en fortsettelse. <br /> Vi er ikke enige. <hr /> <h2>Siden det er en "åpen" Multiplayer, vil det være åpen-kildekode?</h2> Ja, dette er planen. Nå først så vil vi fokusere på å være synlige i form av at vi faktisk jobber med koden (som allerede vil være en forbedring) og vi vil etterhvert åpne opp kildekoden, så snart ting er satt i stein. <hr /> <h2>Hvordan kan jeg hjelpe?</h2> Hold utkikk på forumet vårt. Vi har en tråd om akkurat dette, og vi vil holde den oppdatert så snart det kommer mer. Siden prosjektet var avslørt litt snarere enn planlagt, så har vi kommet langt på vei mot en første-utgivelse, men det betyr ikke at mer hjelp er satt stor pris på. Takk på forhånd for at du bidrar og tror på prosjektet: <br /> <a href="https://forum.open.mp/showthread.php?tid=99"> <u>"Hvordan hjelpe"-tråden</u> </a> <hr /> <h2>Hva er burgershot.gg?</h2> burgershot.gg er et spilleforum, og ikke mer. En stor del folk er medlem av begge deler, og noen OMP oppdateringer og utviklingsdetaljer er postet der, men burgershot og OMP er to individuelle prosjekter. Burgershot er ikke OMP forumet, og OMP er ikke en del av burgershot. Så snart en full open.mp side er oppe, så kan de ansees som individuelle fora (Akkurat som da SA:MP var hostet på GTAforums, helt til SA:MP fikk sin egen side). <hr /> <h2>Hva er OpenMP?</h2> Det er et "Open Multi-Processing" prosjekt som heter "OpenMP", vi er "open.mp". To totalt forskjellige ting.
openmultiplayer/web/frontend/content/no/faq.mdx/0
{ "file_path": "openmultiplayer/web/frontend/content/no/faq.mdx", "repo_id": "openmultiplayer", "token_count": 1690 }
496
# Open Multiplayer Предстојећи мултиплејер мод за _Grand Theft Auto: San Andreas_ који ће бити скроз компактан са постојећим мултиплејер модом _San Andreas Multiplayer._ <br /> То значи да ће **постојећи SA:MP клијенти и све SA:MP скрипте радити на open.mp** и, као шлаг на торту, многе грешке биће сређене унутар серверског софтвера, без потребе за заобилазним решењима. Ако се питате када је планирано јавно издање или како да допринесеш пројекту, погледајте [овај чланак на форуму](https://forum.open.mp/showthread.php?tid=99) за више информација. # [Често постављана питања](/faq)
openmultiplayer/web/frontend/content/sr/index.mdx/0
{ "file_path": "openmultiplayer/web/frontend/content/sr/index.mdx", "repo_id": "openmultiplayer", "token_count": 530 }
497
--- title: Timers module date: "2019-05-22T03:15:00" author: Y_Less --- Це короткий огляд одного з вдосконалених нами модулів для таймерів у open.mp: ```pawn native SetTimer(const func[], msInterval, bool:repeat) = SetTimerEx; native SetTimerEx(const func[], msInterval, bool:repeat, const params[], GLOBAL_TAG_TYPES:...); native KillTimer(timer) = Timer_Kill; // CreateTimer native Timer:Timer_Create(const func[], usDelay, usInterval, repeatCount, const params[] = "", GLOBAL_TAG_TYPES:...); // KillTimer native bool:Timer_Kill(Timer:timer); // Return time till next call. native Timer_GetTimeRemaining(Timer:timer); // Get number of calls left to make (0 for unlimited). native Timer_GetCallsRemaining(Timer:timer); // Get `repeatCount` parameter. native Timer_GetTotalCalls(Timer:timer); // Get `usInterval` parameter. native Timer_GetInterval(Timer:timer); // Reset time remaining till next call to `usInterval`. native bool:Timer_Restart(Timer:timer); ``` Перші два призначені лише для зворотної сумісності, решта — це вдосконалений API: ```pawn native Timer:Timer_Create(const func[], usDelay, usInterval, repeatCount, const params[] = "", GLOBAL_TAG_TYPES:...); ``` - `func` - Досить очевидно з назви. - `usDelay` - Знову очевидно, це затримка перед викликом (у мікросекундах). - `usInterval` - На що скинути `usDelay` після першого виклику. Отже, якщо ви хочете, щоб таймер працював щогодини, але зараз було 8:47, виклик буде `Timer_Create("OnTheHour", 780 SECONDS, 3600 SECONDS, 0);` - `repeatCount` - На відміну від старих функцій, які є лише "один раз" або "назавжди", замість цього для виклику функції потрібна кількість разів. "раз" буде "1", "500" зупиниться після 500 дзвінків, і (назад від старого API) "0" означає "постійно". - `GLOBAL_TAG_TYPES` - Подібне до `{Float, ...}`, але з більшою кількістю параметрів.
openmultiplayer/web/frontend/content/uk/blog/timers.mdx/0
{ "file_path": "openmultiplayer/web/frontend/content/uk/blog/timers.mdx", "repo_id": "openmultiplayer", "token_count": 1142 }
498
--- title: 载具同步 date: "2019-11-09T11:33:00" author: Southclaws --- 这是一篇演示载具同步的演变的快讯。 <video autoPlay loop width="100%" controls> <source src="https://assets.open.mp/assets/images/videos/vehicle_sync_01.mp4" type="video/mp4" /> 抱歉,您的浏览器不支持嵌入式视频。 </video> <video autoPlay loop width="100%" controls> <source src="https://assets.open.mp/assets/images/videos/vehicle_sync_02.mp4" type="video/mp4" /> 抱歉,您的浏览器不支持嵌入式视频。 </video> <video autoPlay loop width="100%" controls> <source src="https://assets.open.mp/assets/images/videos/vehicle_sync_03.mp4" type="video/mp4" /> 抱歉,您的浏览器不支持嵌入式视频。 </video>
openmultiplayer/web/frontend/content/zh-cn/blog/vehicle-sync.mdx/0
{ "file_path": "openmultiplayer/web/frontend/content/zh-cn/blog/vehicle-sync.mdx", "repo_id": "openmultiplayer", "token_count": 366 }
499
<?xml version="1.0" encoding="utf-8"?> <browserconfig> <msapplication> <tile> <square70x70logo src="/static/mstile-70x70.png"/> <square150x150logo src="/static/mstile-150x150.png"/> <square310x310logo src="/static/mstile-310x310.png"/> <wide310x150logo src="/static/mstile-310x150.png"/> <TileColor>#da532c</TileColor> </tile> </msapplication> </browserconfig>
openmultiplayer/web/frontend/public/images/assets/browserconfig.xml/0
{ "file_path": "openmultiplayer/web/frontend/public/images/assets/browserconfig.xml", "repo_id": "openmultiplayer", "token_count": 221 }
500
import Link from "next/link"; import { useRouter } from "next/router"; import { flow, map, sortBy } from "lodash/fp"; import { last } from "lodash"; import { useState } from "react"; export type SidebarCategory = { type: string; path: string; label: string; items: SidebarItem[]; }; export type SidebarItem = SidebarCategory | string; export type SidebarTree = { Sidebar: SidebarItem[]; }; // makes the path into a nicely readable string const nicenPath = (s: string) => last(s.split("/")); type Props = { title: string; path: string; current: string; tree: SidebarItem[]; open?: boolean; }; export const DocsSidebar = () => { const [visible, setVisible] = useState(false); const { asPath } = useRouter(); return ( <nav className="br-ns bb b--black-30 pa2 b--black-30 truncate w4-ns w4-m w5-l flex-auto"> <div className="tr pa2 dn-ns"> <label htmlFor="sidebar">{visible ? "Hide" : "Show"} Menu</label> <input className="dn" type="checkbox" name="sidebar" id="sidebar" checked={visible} onChange={(e) => setVisible(e.target.checked)} /> </div> {/* In desktop mode, always display, regardless of `visible` */} <div className={visible ? `db-ns` : `db-ns dn`}> <DocsSidebarNode title="Contents" path="/docs" current={asPath} tree={((process.env.tree as unknown) as SidebarTree).Sidebar} open={true} /> </div> <style jsx global>{` nav details { user-select: none; } nav details > summary { border-radius: 0.25em; line-height: 1.1em; margin: 0em; font-size: 1.1em; font-weight: 600; cursor: pointer; padding: 0.25rem; } nav details > summary::marker, nav details > summary::-webkit-details-marker { color: var(--ifm-color-gray-700); } nav details a, nav details a:visited { text-decoration: none; padding: 0 0.2em 0 0.2em; color: var(--ifm-color-gray-700); } nav details a:hover { color: var(--ifm-color-primary-darkest); border-radius: 0.25em; } nav details > ul { list-style-type: none; margin: 0; padding-left: 0.5em; } nav details > ul > li { padding: 0.25em; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } nav details > ul > li > a { margin-left: 1em; line-height: 1.5em; } `}</style> </nav> ); }; const DocsSidebarNode = ({ title, path, current, tree, open }: Props) => ( <> <details open={open}> <summary> <Link href={path}> <a>{title}</a> </Link> </summary> <ul> {flow( sortBy((v: SidebarItem) => typeof v === "string"), map((v: SidebarItem) => typeof v === "string" ? ( <li key={v}> <Link href={`/${v}`}> <a>{nicenPath(v)}</a> </Link> </li> ) : ( <li key={v.label}> <DocsSidebarNode title={v.label} path={v.path} current={current} tree={v.items} open={current.includes(v.path)} /> </li> ) ) )(tree)} </ul> </details> </> );
openmultiplayer/web/frontend/src/components/Sidebar.tsx/0
{ "file_path": "openmultiplayer/web/frontend/src/components/Sidebar.tsx", "repo_id": "openmultiplayer", "token_count": 1901 }
501
import { useRouter } from "next/router"; import { FC } from "react"; import { apiSWR } from "src/fetcher/fetcher"; import { APIError } from "src/types/_generated_Error"; import { User, UserSchema } from "src/types/_generated_User"; import useSWR from "swr"; import ErrorBanner from "../ErrorBanner"; import Measured from "../generic/Measured"; import LoadingBanner from "../LoadingBanner"; import MemberProfile from "./MemberProfile"; type Props = { user?: User; }; const MemberView: FC<Props> = ({ user }) => { const { query } = useRouter(); const { data, error } = useSWR<User, APIError>( `/users/${query["id"]}`, apiSWR({ schema: UserSchema }), { fallbackData: user } ); if (error) { return <ErrorBanner {...error} />; } if (!data) { return <LoadingBanner />; } return ( <Measured> <MemberProfile user={data} /> </Measured> ); }; export default MemberView;
openmultiplayer/web/frontend/src/components/member/MemberView.tsx/0
{ "file_path": "openmultiplayer/web/frontend/src/components/member/MemberView.tsx", "repo_id": "openmultiplayer", "token_count": 328 }
502
import Admonition from "../../../Admonition"; export default function TipNpcCallback() { return ( <Admonition type="tip"> <p>Ovaj callback također može pozvati NPC.</p> </Admonition> ); }
openmultiplayer/web/frontend/src/components/templates/translations/bs/npc-callbacks-tip.tsx/0
{ "file_path": "openmultiplayer/web/frontend/src/components/templates/translations/bs/npc-callbacks-tip.tsx", "repo_id": "openmultiplayer", "token_count": 84 }
503
import Admonition from "../../../Admonition"; export default function WarningVersion({ version, name = "函数", }: { version: string; name: string; }) { return ( <Admonition type="warning"> <p> 这个{name}是在{version}中添加的,在以前的版本中不起作用! </p> </Admonition> ); }
openmultiplayer/web/frontend/src/components/templates/translations/zh-cn/version-warning.tsx/0
{ "file_path": "openmultiplayer/web/frontend/src/components/templates/translations/zh-cn/version-warning.tsx", "repo_id": "openmultiplayer", "token_count": 153 }
504
import { FC } from "react"; import { GetServerSideProps } from "next"; import { apiSSP } from "src/fetcher/fetcher"; import { APIError } from "src/types/_generated_Error"; import ErrorBanner from "src/components/ErrorBanner"; type Props = { data: { version: string }; error: APIError; }; const Page: FC<Props> = ({ data: { version }, error }) => { if (error) { return <ErrorBanner {...error} />; } return ( <section className="center measure-wide"> <h1>{`About`}</h1> <h2>API Version</h2> <p>{version}</p> </section> ); }; export const getServerSideProps: GetServerSideProps = async (ctx) => ({ props: await apiSSP<Props>("/version", ctx), }); export default Page;
openmultiplayer/web/frontend/src/pages/about.tsx/0
{ "file_path": "openmultiplayer/web/frontend/src/pages/about.tsx", "repo_id": "openmultiplayer", "token_count": 272 }
505
import { AddIcon } from "@chakra-ui/icons"; import { Box, Button, Center, Checkbox, Flex, FormControl, FormHelperText, FormLabel, Heading, Input, Modal, ModalBody, ModalCloseButton, ModalContent, ModalHeader, ModalOverlay, Select, Text, useDisclosure, } from "@chakra-ui/react"; import Fuse from "fuse.js"; import { filter, flow, map, reverse, sortBy, sum } from "lodash/fp"; import { NextSeo } from "next-seo"; import NProgress from "nprogress"; import { FormEvent, useState } from "react"; import { toast } from "react-nextjs-toast"; import ErrorBanner from "src/components/ErrorBanner"; import { CardList } from "src/components/generic/CardList"; import ServerRow from "src/components/listing/ServerRow"; import LoadingBanner from "src/components/LoadingBanner"; import { API_ADDRESS } from "src/config"; import { All, Essential } from "src/types/_generated_Server"; import useSWR from "swr"; const API_SERVERS = `${API_ADDRESS}/servers/`; const getServers = async (): Promise<Array<Essential>> => { const r: Response = await fetch(API_SERVERS); const servers: Array<Essential> = await r.json(); return servers; }; type Stats = { players: number; servers: number; }; const getStats = (servers: Array<Essential>): Stats => ({ players: flow( map((s: Essential) => s.pc), // get just the player count (pc) sum // sum all player counts )(servers), servers: servers.length, }); type SortBy = "relevance" | "pc"; type Query = { search?: string; showEmpty: boolean; showPartnersOnly: boolean; showOmpOnly: boolean; sort: SortBy; }; const dataToList = (data: Essential[], q: Query) => { const fuse = new Fuse(data, { threshold: 0.2, shouldSort: true, includeScore: true, ignoreLocation: true, keys: ["ip", "hn", "gm"], }); const items = q.search ? map((r: Fuse.FuseResult<Essential>) => r.item)(fuse.search(q.search)) : data; return flow( filter((s: Essential) => (!q.showEmpty ? s.pc > 0 : true)), filter((s: Essential) => (q.showPartnersOnly ? s.pr === true : true)), filter((s: Essential) => (q.showOmpOnly ? s.omp === true : true)), q.sort != "relevance" ? sortBy(q.sort) : sortBy(""), reverse, map((s: Essential) => <ServerRow key={s.ip} server={s} />) )(items); }; const Stats = ({ stats: { players, servers } }: { stats: Stats }) => { return ( <Center> <Text my={4}> <strong>{players}</strong> players on <strong>{servers}</strong> servers with an average of <strong>{(players / servers).toFixed(1)}</strong>{" "} players per server. </Text> </Center> ); }; const AddServer = ({ onAdd }: { onAdd: (server: All) => void }) => { const [value, setValue] = useState(""); const handleSubmit = async (e: FormEvent<HTMLFormElement>) => { NProgress.start(); e.preventDefault(); const response = await fetch(API_SERVERS, { method: "POST", mode: "cors", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ ip: value }), }); NProgress.inc(); if (response.status === 200) { const server = (await response.json()) as All; onAdd(server); toast.notify( `${server.core.hn} is added to our pending list. If it's not available after maximum 48 hours, you can contact us on Discord!`, { title: "Server Submitted!", } ); } else { const error = (await response.json()) as { error: string }; toast.notify(`Status ${response.statusText}: ${error?.error}`, { title: "Submission failed!", type: "error", }); } NProgress.done(); }; return ( <form action={API_SERVERS} target="_self" method="post" onSubmit={handleSubmit} > <Flex gridGap={2} width="100%"> <Input type="text" name="address" placeholder="IP/Domain" value={value} onChange={(e) => setValue(e.target.value)} /> <Button colorScheme="blue" mr={3} type="submit"> Add </Button> </Flex> </form> ); }; const List = ({ data, onAdd, }: { data: Array<Essential>; onAdd: (server: All) => void; }) => { const [search, setSearch] = useState(""); const [showEmpty, setShowEmpty] = useState(true); const [showPartnersOnly, setShowPartnersOnly] = useState(false); const [showOmpOnly, setShowOmpOnly] = useState(false); const [sort, setSort] = useState("relevance"); const { isOpen, onOpen, onClose } = useDisclosure(); return ( <> <form action=""> <Flex gridGap={2} flexDir={{ base: "column", md: "row" }}> <Select flexShrink={2} placeholder="Sort by" name="sortBy" id="sortBy" value={sort} onChange={(e) => setSort(e.target.value)} > <option value="relevance">Relevance</option> <option value="pc">Players</option> </Select> <Input flexGrow={2} type="text" placeholder="Search by IP or Name" name="search" id="search" value={search} onChange={(e) => { setSearch(e.target.value); }} /> <Button flexGrow={1} px="3em" onClick={onOpen} rightIcon={<AddIcon boxSize="0.8em" />} > Add server </Button> <Modal isOpen={isOpen} onClose={onClose} blockScrollOnMount={false}> <ModalOverlay /> <ModalContent top={10}> <ModalHeader>Add a server</ModalHeader> <ModalCloseButton /> <ModalBody> <FormControl mb={4}> <FormLabel>IP or Domain</FormLabel> <AddServer onAdd={(server: All) => { onAdd(server); onClose(); }} /> <FormHelperText> IP must be in format <strong>ip:port</strong> </FormHelperText> </FormControl> </ModalBody> </ModalContent> </Modal> </Flex> <Flex marginTop={2} gridGap={2} flexDir={{ base: "column", md: "row" }}> <Checkbox isChecked={showEmpty} onChange={(e) => setShowEmpty(e.target.checked)} > Show empty servers </Checkbox> <Checkbox isChecked={showOmpOnly} onChange={(e) => setShowOmpOnly(e.target.checked)} > Show only open.mp servers </Checkbox> <Checkbox isChecked={showPartnersOnly} onChange={(e) => setShowPartnersOnly(e.target.checked)} > Show only partners </Checkbox> </Flex> </form> <Stats stats={getStats(data)} /> <CardList> {dataToList(data, { search, showEmpty, showPartnersOnly, showOmpOnly, sort: sort as SortBy, })} </CardList> </> ); }; const Page = () => { const { data, error, mutate } = useSWR<Array<Essential>, TypeError>( API_SERVERS, getServers ); if (error) { return <ErrorBanner {...error} />; } if (!data) { return <LoadingBanner />; } return ( <Box as="section" maxWidth="50em" margin="auto" padding="1em 2em"> <NextSeo title="SA-MP Servers Index" description="Live indexing and data for all SA-MP servers." /> <Heading mb={"1em"}>Servers</Heading> <List data={data} onAdd={(server: All) => mutate([...data!, server.core], false)} /> </Box> ); }; export default Page;
openmultiplayer/web/frontend/src/pages/servers/index.tsx/0
{ "file_path": "openmultiplayer/web/frontend/src/pages/servers/index.tsx", "repo_id": "openmultiplayer", "token_count": 3676 }
506
import * as z from "zod" export const EssentialSchema = z.object({ ip: z.string(), hn: z.string(), pc: z.number(), pm: z.number(), gm: z.string(), la: z.string(), pa: z.boolean(), vn: z.string(), omp: z.boolean(), pr: z.boolean(), }) export type Essential = z.infer<typeof EssentialSchema> export const AllSchema = z.object({ ip: z.string(), dm: z.string().nullable(), core: EssentialSchema, ru: z.map(z.string(), z.string()).optional(), description: z.string().nullable(), banner: z.string().nullable(), active: z.boolean(), lastUpdated: z.string(), }) export type All = z.infer<typeof AllSchema>
openmultiplayer/web/frontend/src/types/_generated_Server.ts/0
{ "file_path": "openmultiplayer/web/frontend/src/types/_generated_Server.ts", "repo_id": "openmultiplayer", "token_count": 244 }
507
package ratelimiter import ( "net/http" "time" "github.com/sethvargo/go-limiter/httplimit" "github.com/sethvargo/go-limiter/memorystore" ) func WithRateLimit(perinterval uint64, interval time.Duration) func(next http.Handler) http.Handler { store, err := memorystore.New(&memorystore.Config{ Tokens: perinterval, Interval: interval, }) if err != nil { panic(err) } mw, err := httplimit.NewMiddleware(store, httplimit.IPKeyFunc("CF-Connecting-IP", "X-Forwarded-For", "X-Real-IP")) if err != nil { panic(err) } return mw.Handle }
openmultiplayer/web/internal/web/ratelimiter/ratelimit.go/0
{ "file_path": "openmultiplayer/web/internal/web/ratelimiter/ratelimit.go", "repo_id": "openmultiplayer", "token_count": 225 }
508
/* Warnings: - You are about to drop the column `lastActive` on the `User` table. All the data in the column will be lost. */ -- AlterTable ALTER TABLE "Server" ADD COLUMN "lastActive" TIMESTAMP(3); -- AlterTable ALTER TABLE "User" DROP COLUMN "lastActive";
openmultiplayer/web/prisma/migrations/20231022181746_move_lastactive_field_from_user_to_server/migration.sql/0
{ "file_path": "openmultiplayer/web/prisma/migrations/20231022181746_move_lastactive_field_from_user_to_server/migration.sql", "repo_id": "openmultiplayer", "token_count": 91 }
509
FROM node:12.22.3 # Install Google Chrome RUN wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - RUN sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list' RUN apt-get update && apt-get install -y google-chrome-stable
overleaf/web/Dockerfile.frontend/0
{ "file_path": "overleaf/web/Dockerfile.frontend", "repo_id": "overleaf", "token_count": 121 }
510
const _ = require('lodash') const SessionManager = { getSessionUser(session) { const sessionUser = _.get(session, ['user']) const sessionPassportUser = _.get(session, ['passport', 'user']) return sessionUser || sessionPassportUser || null }, setInSessionUser(session, props) { const sessionUser = SessionManager.getSessionUser(session) if (!sessionUser) { return } for (const key in props) { const value = props[key] sessionUser[key] = value } return null }, isUserLoggedIn(session) { const userId = SessionManager.getLoggedInUserId(session) return ![null, undefined, false].includes(userId) }, getLoggedInUserId(session) { const user = SessionManager.getSessionUser(session) if (user) { return user._id } else { return null } }, getLoggedInUserV1Id(session) { const user = SessionManager.getSessionUser(session) if (user != null && user.v1_id != null) { return user.v1_id } else { return null } }, } module.exports = SessionManager
overleaf/web/app/src/Features/Authentication/SessionManager.js/0
{ "file_path": "overleaf/web/app/src/Features/Authentication/SessionManager.js", "repo_id": "overleaf", "token_count": 407 }
511
/* eslint-disable camelcase, node/handle-callback-err, max-len, no-unused-vars, */ // TODO: This file was created by bulk-decaffeinate. // Fix any style issues and re-enable lint. /* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ let CollaboratorsInviteController const OError = require('@overleaf/o-error') const ProjectGetter = require('../Project/ProjectGetter') const LimitationsManager = require('../Subscription/LimitationsManager') const UserGetter = require('../User/UserGetter') const CollaboratorsGetter = require('./CollaboratorsGetter') const CollaboratorsInviteHandler = require('./CollaboratorsInviteHandler') const logger = require('logger-sharelatex') const Settings = require('@overleaf/settings') const EmailHelper = require('../Helpers/EmailHelper') const EditorRealTimeController = require('../Editor/EditorRealTimeController') const AnalyticsManager = require('../Analytics/AnalyticsManager') const SessionManager = require('../Authentication/SessionManager') const rateLimiter = require('../../infrastructure/RateLimiter') module.exports = CollaboratorsInviteController = { getAllInvites(req, res, next) { const projectId = req.params.Project_id logger.log({ projectId }, 'getting all active invites for project') return CollaboratorsInviteHandler.getAllInvites( projectId, function (err, invites) { if (err != null) { OError.tag(err, 'error getting invites for project', { projectId, }) return next(err) } return res.json({ invites }) } ) }, _checkShouldInviteEmail(email, callback) { if (callback == null) { callback = function (err, shouldAllowInvite) {} } if (Settings.restrictInvitesToExistingAccounts === true) { logger.log({ email }, 'checking if user exists with this email') return UserGetter.getUserByAnyEmail( email, { _id: 1 }, function (err, user) { if (err != null) { return callback(err) } const userExists = user != null && (user != null ? user._id : undefined) != null return callback(null, userExists) } ) } else { return callback(null, true) } }, _checkRateLimit(user_id, callback) { if (callback == null) { callback = function (error) {} } return LimitationsManager.allowedNumberOfCollaboratorsForUser( user_id, function (err, collabLimit) { if (collabLimit == null) { collabLimit = 1 } if (err != null) { return callback(err) } if (collabLimit === -1) { collabLimit = 20 } collabLimit = collabLimit * 10 const opts = { endpointName: 'invite-to-project-by-user-id', timeInterval: 60 * 30, subjectName: user_id, throttle: collabLimit, } return rateLimiter.addCount(opts, callback) } ) }, inviteToProject(req, res, next) { const projectId = req.params.Project_id let { email } = req.body const sendingUser = SessionManager.getSessionUser(req.session) const sendingUserId = sendingUser._id if (email === sendingUser.email) { logger.log( { projectId, email, sendingUserId }, 'cannot invite yourself to project' ) return res.json({ invite: null, error: 'cannot_invite_self' }) } logger.log({ projectId, email, sendingUserId }, 'inviting to project') return LimitationsManager.canAddXCollaborators( projectId, 1, (error, allowed) => { let privileges if (error != null) { return next(error) } if (!allowed) { logger.log( { projectId, email, sendingUserId }, 'not allowed to invite more users to project' ) return res.json({ invite: null }) } ;({ email, privileges } = req.body) email = EmailHelper.parseEmail(email) if (email == null || email === '') { logger.log( { projectId, email, sendingUserId }, 'invalid email address' ) return res.status(400).send({ errorReason: 'invalid_email' }) } return CollaboratorsInviteController._checkRateLimit( sendingUserId, function (error, underRateLimit) { if (error != null) { return next(error) } if (!underRateLimit) { return res.sendStatus(429) } return CollaboratorsInviteController._checkShouldInviteEmail( email, function (err, shouldAllowInvite) { if (err != null) { OError.tag( err, 'error checking if we can invite this email address', { email, projectId, sendingUserId, } ) return next(err) } if (!shouldAllowInvite) { logger.log( { email, projectId, sendingUserId }, 'not allowed to send an invite to this email address' ) return res.json({ invite: null, error: 'cannot_invite_non_user', }) } return CollaboratorsInviteHandler.inviteToProject( projectId, sendingUser, email, privileges, function (err, invite) { if (err != null) { OError.tag(err, 'error creating project invite', { projectId, email, sendingUserId, }) return next(err) } logger.log( { projectId, email, sendingUserId }, 'invite created' ) EditorRealTimeController.emitToRoom( projectId, 'project:membership:changed', { invites: true } ) return res.json({ invite }) } ) } ) } ) } ) }, revokeInvite(req, res, next) { const projectId = req.params.Project_id const inviteId = req.params.invite_id logger.log({ projectId, inviteId }, 'revoking invite') return CollaboratorsInviteHandler.revokeInvite( projectId, inviteId, function (err) { if (err != null) { OError.tag(err, 'error revoking invite', { projectId, inviteId, }) return next(err) } EditorRealTimeController.emitToRoom( projectId, 'project:membership:changed', { invites: true } ) return res.sendStatus(201) } ) }, resendInvite(req, res, next) { const projectId = req.params.Project_id const inviteId = req.params.invite_id logger.log({ projectId, inviteId }, 'resending invite') const sendingUser = SessionManager.getSessionUser(req.session) return CollaboratorsInviteController._checkRateLimit( sendingUser._id, function (error, underRateLimit) { if (error != null) { return next(error) } if (!underRateLimit) { return res.sendStatus(429) } return CollaboratorsInviteHandler.resendInvite( projectId, sendingUser, inviteId, function (err) { if (err != null) { OError.tag(err, 'error resending invite', { projectId, inviteId, }) return next(err) } return res.sendStatus(201) } ) } ) }, viewInvite(req, res, next) { const projectId = req.params.Project_id const { token } = req.params const _renderInvalidPage = function () { logger.log( { projectId, token }, 'invite not valid, rendering not-valid page' ) return res.render('project/invite/not-valid', { title: 'Invalid Invite' }) } // check if the user is already a member of the project const currentUser = SessionManager.getSessionUser(req.session) return CollaboratorsGetter.isUserInvitedMemberOfProject( currentUser._id, projectId, function (err, isMember) { if (err != null) { OError.tag(err, 'error checking if user is member of project', { projectId, }) return next(err) } if (isMember) { logger.log( { projectId, userId: currentUser._id }, 'user is already a member of this project, redirecting' ) return res.redirect(`/project/${projectId}`) } // get the invite return CollaboratorsInviteHandler.getInviteByToken( projectId, token, function (err, invite) { if (err != null) { OError.tag(err, 'error getting invite by token', { projectId, token, }) return next(err) } // check if invite is gone, or otherwise non-existent if (invite == null) { logger.log({ projectId, token }, 'no invite found for this token') return _renderInvalidPage() } // check the user who sent the invite exists return UserGetter.getUser( { _id: invite.sendingUserId }, { email: 1, first_name: 1, last_name: 1 }, function (err, owner) { if (err != null) { OError.tag(err, 'error getting project owner', { projectId, }) return next(err) } if (owner == null) { logger.log({ projectId }, 'no project owner found') return _renderInvalidPage() } // fetch the project name return ProjectGetter.getProject( projectId, {}, function (err, project) { if (err != null) { OError.tag(err, 'error getting project', { projectId, }) return next(err) } if (project == null) { logger.log({ projectId }, 'no project found') return _renderInvalidPage() } // finally render the invite return res.render('project/invite/show', { invite, project, owner, title: 'Project Invite', }) } ) } ) } ) } ) }, acceptInvite(req, res, next) { const projectId = req.params.Project_id const { token } = req.params const currentUser = SessionManager.getSessionUser(req.session) logger.log( { projectId, userId: currentUser._id, token }, 'got request to accept invite' ) return CollaboratorsInviteHandler.acceptInvite( projectId, token, currentUser, function (err) { if (err != null) { OError.tag(err, 'error accepting invite by token', { projectId, token, }) return next(err) } EditorRealTimeController.emitToRoom( projectId, 'project:membership:changed', { invites: true, members: true } ) AnalyticsManager.recordEvent(currentUser._id, 'project-invite-accept', { projectId, userId: currentUser._id, }) if (req.xhr) { return res.sendStatus(204) // Done async via project page notification } else { return res.redirect(`/project/${projectId}`) } } ) }, }
overleaf/web/app/src/Features/Collaborators/CollaboratorsInviteController.js/0
{ "file_path": "overleaf/web/app/src/Features/Collaborators/CollaboratorsInviteController.js", "repo_id": "overleaf", "token_count": 6295 }
512
const request = require('request').defaults({ timeout: 30 * 100 }) const OError = require('@overleaf/o-error') const settings = require('@overleaf/settings') const _ = require('underscore') const async = require('async') const logger = require('logger-sharelatex') const metrics = require('@overleaf/metrics') const { promisify } = require('util') module.exports = { flushProjectToMongo, flushMultipleProjectsToMongo, flushProjectToMongoAndDelete, flushDocToMongo, deleteDoc, getDocument, setDocument, getProjectDocsIfMatch, clearProjectState, acceptChanges, deleteThread, resyncProjectHistory, updateProjectStructure, promises: { flushProjectToMongo: promisify(flushProjectToMongo), flushMultipleProjectsToMongo: promisify(flushMultipleProjectsToMongo), flushProjectToMongoAndDelete: promisify(flushProjectToMongoAndDelete), flushDocToMongo: promisify(flushDocToMongo), deleteDoc: promisify(deleteDoc), getDocument: promisify(getDocument), setDocument: promisify(setDocument), getProjectDocsIfMatch: promisify(getProjectDocsIfMatch), clearProjectState: promisify(clearProjectState), acceptChanges: promisify(acceptChanges), deleteThread: promisify(deleteThread), resyncProjectHistory: promisify(resyncProjectHistory), updateProjectStructure: promisify(updateProjectStructure), }, } function flushProjectToMongo(projectId, callback) { _makeRequest( { path: `/project/${projectId}/flush`, method: 'POST', }, projectId, 'flushing.mongo.project', callback ) } function flushMultipleProjectsToMongo(projectIds, callback) { const jobs = projectIds.map(projectId => callback => { flushProjectToMongo(projectId, callback) }) async.series(jobs, callback) } function flushProjectToMongoAndDelete(projectId, callback) { _makeRequest( { path: `/project/${projectId}`, method: 'DELETE', }, projectId, 'flushing.mongo.project', callback ) } function flushDocToMongo(projectId, docId, callback) { _makeRequest( { path: `/project/${projectId}/doc/${docId}/flush`, method: 'POST', }, projectId, 'flushing.mongo.doc', callback ) } function deleteDoc(projectId, docId, callback) { _makeRequest( { path: `/project/${projectId}/doc/${docId}`, method: 'DELETE', }, projectId, 'delete.mongo.doc', callback ) } function getDocument(projectId, docId, fromVersion, callback) { _makeRequest( { path: `/project/${projectId}/doc/${docId}?fromVersion=${fromVersion}`, json: true, }, projectId, 'get-document', function (error, doc) { if (error) { return callback(error) } callback(null, doc.lines, doc.version, doc.ranges, doc.ops) } ) } function setDocument(projectId, docId, userId, docLines, source, callback) { _makeRequest( { path: `/project/${projectId}/doc/${docId}`, method: 'POST', json: { lines: docLines, source, user_id: userId, }, }, projectId, 'set-document', callback ) } function getProjectDocsIfMatch(projectId, projectStateHash, callback) { // If the project state hasn't changed, we can get all the latest // docs from redis via the docupdater. Otherwise we will need to // fall back to getting them from mongo. const timer = new metrics.Timer('get-project-docs') const url = `${settings.apis.documentupdater.url}/project/${projectId}/get_and_flush_if_old?state=${projectStateHash}` request.post(url, function (error, res, body) { timer.done() if (error) { OError.tag(error, 'error getting project docs from doc updater', { url, projectId, }) return callback(error) } if (res.statusCode === 409) { // HTTP response code "409 Conflict" // Docupdater has checked the projectStateHash and found that // it has changed. This means that the docs currently in redis // aren't the only change to the project and the full set of // docs/files should be retreived from docstore/filestore // instead. callback() } else if (res.statusCode >= 200 && res.statusCode < 300) { let docs try { docs = JSON.parse(body) } catch (error1) { return callback(OError.tag(error1)) } callback(null, docs) } else { callback( new OError( `doc updater returned a non-success status code: ${res.statusCode}`, { projectId, url, } ) ) } }) } function clearProjectState(projectId, callback) { _makeRequest( { path: `/project/${projectId}/clearState`, method: 'POST', }, projectId, 'clear-project-state', callback ) } function acceptChanges(projectId, docId, changeIds, callback) { _makeRequest( { path: `/project/${projectId}/doc/${docId}/change/accept`, json: { change_ids: changeIds }, method: 'POST', }, projectId, 'accept-changes', callback ) } function deleteThread(projectId, docId, threadId, callback) { _makeRequest( { path: `/project/${projectId}/doc/${docId}/comment/${threadId}`, method: 'DELETE', }, projectId, 'delete-thread', callback ) } function resyncProjectHistory( projectId, projectHistoryId, docs, files, callback ) { _makeRequest( { path: `/project/${projectId}/history/resync`, json: { docs, files, projectHistoryId }, method: 'POST', }, projectId, 'resync-project-history', callback ) } function updateProjectStructure( projectId, projectHistoryId, userId, changes, callback ) { if ( settings.apis.project_history == null || !settings.apis.project_history.sendProjectStructureOps ) { return callback() } const { deletes: docDeletes, adds: docAdds, renames: docRenames, } = _getUpdates('doc', changes.oldDocs, changes.newDocs) const { deletes: fileDeletes, adds: fileAdds, renames: fileRenames, } = _getUpdates('file', changes.oldFiles, changes.newFiles) const updates = [].concat( docDeletes, fileDeletes, docAdds, fileAdds, docRenames, fileRenames ) const projectVersion = changes && changes.newProject && changes.newProject.version if (updates.length < 1) { return callback() } if (projectVersion == null) { logger.warn( { projectId, changes, projectVersion }, 'did not receive project version in changes' ) return callback(new Error('did not receive project version in changes')) } _makeRequest( { path: `/project/${projectId}`, json: { updates, userId, version: projectVersion, projectHistoryId, }, method: 'POST', }, projectId, 'update-project-structure', callback ) } function _makeRequest(options, projectId, metricsKey, callback) { const timer = new metrics.Timer(metricsKey) request( { url: `${settings.apis.documentupdater.url}${options.path}`, json: options.json, method: options.method || 'GET', }, function (error, res, body) { timer.done() if (error) { logger.warn( { error, projectId }, 'error making request to document updater' ) callback(error) } else if (res.statusCode >= 200 && res.statusCode < 300) { callback(null, body) } else { error = new Error( `document updater returned a failure status code: ${res.statusCode}` ) logger.warn( { error, projectId }, `document updater returned failure status code: ${res.statusCode}` ) callback(error) } } ) } function _getUpdates(entityType, oldEntities, newEntities) { if (!oldEntities) { oldEntities = [] } if (!newEntities) { newEntities = [] } const deletes = [] const adds = [] const renames = [] const oldEntitiesHash = _.indexBy(oldEntities, entity => entity[entityType]._id.toString() ) const newEntitiesHash = _.indexBy(newEntities, entity => entity[entityType]._id.toString() ) // Send deletes before adds (and renames) to keep a 1:1 mapping between // paths and ids // // When a file is replaced, we first delete the old file and then add the // new file. If the 'add' operation is sent to project history before the // 'delete' then we would have two files with the same path at that point // in time. for (const id in oldEntitiesHash) { const oldEntity = oldEntitiesHash[id] const newEntity = newEntitiesHash[id] if (newEntity == null) { // entity deleted deletes.push({ type: `rename-${entityType}`, id, pathname: oldEntity.path, newPathname: '', }) } } for (const id in newEntitiesHash) { const newEntity = newEntitiesHash[id] const oldEntity = oldEntitiesHash[id] if (oldEntity == null) { // entity added adds.push({ type: `add-${entityType}`, id, pathname: newEntity.path, docLines: newEntity.docLines, url: newEntity.url, hash: newEntity.file != null ? newEntity.file.hash : undefined, }) } else if (newEntity.path !== oldEntity.path) { // entity renamed renames.push({ type: `rename-${entityType}`, id, pathname: oldEntity.path, newPathname: newEntity.path, }) } } return { deletes, adds, renames } }
overleaf/web/app/src/Features/DocumentUpdater/DocumentUpdaterHandler.js/0
{ "file_path": "overleaf/web/app/src/Features/DocumentUpdater/DocumentUpdaterHandler.js", "repo_id": "overleaf", "token_count": 3868 }
513
const _ = require('underscore') const settings = require('@overleaf/settings') module.exports = _.template(`\ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en" style="Margin: 0; background: #E4E8EE !important; margin: 0; min-height: 100%; padding: 0;"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="viewport" content="width=device-width"> <style>.button td { border-radius: 9999px; } .force-overleaf-style a, .force-overleaf-style a[href] { color: #138A07 !important; text-decoration: none !important; -moz-hyphens: none; -ms-hyphens: none; -webkit-hyphens: none; hyphens: none; } .force-overleaf-style a:visited, .force-overleaf-style a[href]:visited { color: #138A07; } .force-overleaf-style a:hover, .force-overleaf-style a[href]:hover { color: #3d7935; } .force-overleaf-style a:active, .force-overleaf-style a[href]:active { color: #3d7935; } </style> <style>@media only screen { html { min-height: 100%; background: #f6f6f6; } } @media only screen and (max-width: 596px) { .small-float-center { margin: 0 auto !important; float: none !important; text-align: center !important; } .small-text-center { text-align: center !important; } .small-text-left { text-align: left !important; } .small-text-right { text-align: right !important; } } @media only screen and (max-width: 596px) { .hide-for-large { display: block !important; width: auto !important; overflow: visible !important; max-height: none !important; font-size: inherit !important; line-height: inherit !important; } } @media only screen and (max-width: 596px) { table.body table.container .hide-for-large, table.body table.container .row.hide-for-large { display: table !important; width: 100% !important; } } @media only screen and (max-width: 596px) { table.body table.container .callout-inner.hide-for-large { display: table-cell !important; width: 100% !important; } } @media only screen and (max-width: 596px) { table.body table.container .show-for-large { display: none !important; width: 0; mso-hide: all; overflow: hidden; } } @media only screen and (max-width: 596px) { table.body img { width: auto; height: auto; } table.body center { min-width: 0 !important; } table.body .container { width: 95% !important; } table.body .columns, table.body .column { height: auto !important; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; padding-left: 16px !important; padding-right: 16px !important; } table.body .columns .column, table.body .columns .columns, table.body .column .column, table.body .column .columns { padding-left: 0 !important; padding-right: 0 !important; } table.body .collapse .columns, table.body .collapse .column { padding-left: 0 !important; padding-right: 0 !important; } td.small-1, th.small-1 { display: inline-block !important; width: 8.33333% !important; } td.small-2, th.small-2 { display: inline-block !important; width: 16.66667% !important; } td.small-3, th.small-3 { display: inline-block !important; width: 25% !important; } td.small-4, th.small-4 { display: inline-block !important; width: 33.33333% !important; } td.small-5, th.small-5 { display: inline-block !important; width: 41.66667% !important; } td.small-6, th.small-6 { display: inline-block !important; width: 50% !important; } td.small-7, th.small-7 { display: inline-block !important; width: 58.33333% !important; } td.small-8, th.small-8 { display: inline-block !important; width: 66.66667% !important; } td.small-9, th.small-9 { display: inline-block !important; width: 75% !important; } td.small-10, th.small-10 { display: inline-block !important; width: 83.33333% !important; } td.small-11, th.small-11 { display: inline-block !important; width: 91.66667% !important; } td.small-12, th.small-12 { display: inline-block !important; width: 100% !important; } .columns td.small-12, .column td.small-12, .columns th.small-12, .column th.small-12 { display: block !important; width: 100% !important; } table.body td.small-offset-1, table.body th.small-offset-1 { margin-left: 8.33333% !important; Margin-left: 8.33333% !important; } table.body td.small-offset-2, table.body th.small-offset-2 { margin-left: 16.66667% !important; Margin-left: 16.66667% !important; } table.body td.small-offset-3, table.body th.small-offset-3 { margin-left: 25% !important; Margin-left: 25% !important; } table.body td.small-offset-4, table.body th.small-offset-4 { margin-left: 33.33333% !important; Margin-left: 33.33333% !important; } table.body td.small-offset-5, table.body th.small-offset-5 { margin-left: 41.66667% !important; Margin-left: 41.66667% !important; } table.body td.small-offset-6, table.body th.small-offset-6 { margin-left: 50% !important; Margin-left: 50% !important; } table.body td.small-offset-7, table.body th.small-offset-7 { margin-left: 58.33333% !important; Margin-left: 58.33333% !important; } table.body td.small-offset-8, table.body th.small-offset-8 { margin-left: 66.66667% !important; Margin-left: 66.66667% !important; } table.body td.small-offset-9, table.body th.small-offset-9 { margin-left: 75% !important; Margin-left: 75% !important; } table.body td.small-offset-10, table.body th.small-offset-10 { margin-left: 83.33333% !important; Margin-left: 83.33333% !important; } table.body td.small-offset-11, table.body th.small-offset-11 { margin-left: 91.66667% !important; Margin-left: 91.66667% !important; } table.body table.columns td.expander, table.body table.columns th.expander { display: none !important; } table.body .right-text-pad, table.body .text-pad-right { padding-left: 10px !important; } table.body .left-text-pad, table.body .text-pad-left { padding-right: 10px !important; } table.menu { width: 100% !important; } table.menu td, table.menu th { width: auto !important; display: inline-block !important; } table.menu.vertical td, table.menu.vertical th, table.menu.small-vertical td, table.menu.small-vertical th { display: block !important; } table.menu[align="center"] { width: auto !important; } table.button.small-expand, table.button.small-expanded { width: 100% !important; } table.button.small-expand table, table.button.small-expanded table { width: 100%; } table.button.small-expand table a, table.button.small-expanded table a { text-align: center !important; width: 100% !important; padding-left: 0 !important; padding-right: 0 !important; } table.button.small-expand center, table.button.small-expanded center { min-width: 0; } }</style> </head> <body leftmargin="0" topmargin="0" marginwidth="0" marginheight="0" bgcolor="#F6F6F6" style="-moz-box-sizing: border-box; -ms-text-size-adjust: 100%; -webkit-box-sizing: border-box; -webkit-text-size-adjust: 100%; Margin: 0; box-sizing: border-box; color: #5D6879; font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: normal; line-height: 1.3; margin: 0; min-width: 100%; padding: 0; text-align: left; width: 100% !important;"> <!-- <span class="preheader"></span> --> <table class="body" border="0" cellspacing="0" cellpadding="0" width="100%" height="100%" style="Margin: 0; background: #E4E8EE; border-collapse: collapse; border-spacing: 0; color: #5D6879; font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: normal; height: 100%; line-height: 1.3; margin: 0; padding: 0; text-align: left; vertical-align: top; width: 100%;"> <tr style="padding: 0; text-align: left; vertical-align: top;"> <td class="body-cell" align="center" valign="top" bgcolor="#F6F6F6" style="-moz-hyphens: auto; -webkit-hyphens: auto; Margin: 0; background: #E4E8EE !important; border-collapse: collapse !important; color: #5D6879; font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: normal; hyphens: auto; line-height: 1.3; margin: 0; padding: 0; padding-bottom: 20px; text-align: left; vertical-align: top; word-wrap: break-word;"> <center data-parsed="" style="min-width: 580px; width: 100%;"> <table align="center" class="wrapper header float-center" style="Margin: 0 auto; background: #1E2530; border-bottom: none; border-collapse: collapse; border-spacing: 0; float: none; margin: 0 auto; padding: 0; text-align: center; vertical-align: top; width: 100%;"><tr style="padding: 0; text-align: left; vertical-align: top;"><td class="wrapper-inner" style="-moz-hyphens: auto; -webkit-hyphens: auto; Margin: 0; border-collapse: collapse !important; color: #5D6879; font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: normal; hyphens: auto; line-height: 1.3; margin: 0; padding: 20px; text-align: left; vertical-align: top; word-wrap: break-word;"> <table align="center" class="container" style="Margin: 0 auto; background: transparent; border-collapse: collapse; border-spacing: 0; margin: 0 auto; padding: 0; text-align: inherit; vertical-align: top; width: 580px;"><tbody><tr style="padding: 0; text-align: left; vertical-align: top;"><td style="-moz-hyphens: auto; -webkit-hyphens: auto; Margin: 0; border-collapse: collapse !important; color: #5D6879; font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: normal; hyphens: auto; line-height: 1.3; margin: 0; padding: 0; text-align: left; vertical-align: top; word-wrap: break-word;"> <table class="row collapse" style="border-collapse: collapse; border-spacing: 0; display: table; padding: 0; position: relative; text-align: left; vertical-align: top; width: 100%;"><tbody><tr style="padding: 0; text-align: left; vertical-align: top;"> <th class="small-12 large-12 columns first last" style="Margin: 0 auto; color: #5D6879; font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: normal; line-height: 1.3; margin: 0 auto; padding: 0; padding-bottom: 0; padding-left: 0; padding-right: 0; text-align: left; width: 588px;"><table style="border-collapse: collapse; border-spacing: 0; padding: 0; text-align: left; vertical-align: top; width: 100%;"><tr style="padding: 0; text-align: left; vertical-align: top;"><th style="Margin: 0; color: #5D6879; font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: normal; line-height: 1.3; margin: 0; padding: 0; text-align: left;"> <h1 style="Margin: 0; Margin-bottom: px; color: #FFFFFF; font-family: Georgia, serif; font-size: 30px; font-weight: normal; line-height: 1.3; margin: 0; margin-bottom: px; padding: 0; text-align: left; word-wrap: normal;"> ${settings.appName} </h1> </th> <th class="expander" style="Margin: 0; color: #5D6879; font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: normal; line-height: 1.3; margin: 0; padding: 0 !important; text-align: left; visibility: hidden; width: 0;"></th></tr></table></th> </tr></tbody></table> </td></tr></tbody></table> </td></tr></table> <table class="spacer float-center" style="Margin: 0 auto; border-collapse: collapse; border-spacing: 0; float: none; margin: 0 auto; padding: 0; text-align: center; vertical-align: top; width: 100%;"><tbody><tr style="padding: 0; text-align: left; vertical-align: top;"><td height="20px" style="-moz-hyphens: auto; -webkit-hyphens: auto; Margin: 0; border-collapse: collapse !important; color: #5D6879; font-family: Helvetica, Arial, sans-serif; font-size: 20px; font-weight: normal; hyphens: auto; line-height: 20px; margin: 0; mso-line-height-rule: exactly; padding: 0; text-align: left; vertical-align: top; word-wrap: break-word;">&#xA0;</td></tr></tbody></table> <table align="center" class="container main float-center" style="Margin: 0 auto; Margin-top: 10px; background: #FFFFFF; border-collapse: collapse; border-spacing: 0; float: none; margin: 0 auto; margin-top: 10px; padding: 0; text-align: center; vertical-align: top; width: 580px;"><tbody><tr style="padding: 0; text-align: left; vertical-align: top;"><td style="-moz-hyphens: auto; -webkit-hyphens: auto; Margin: 0; border-collapse: collapse !important; color: #5D6879; font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: normal; hyphens: auto; line-height: 1.3; margin: 0; padding: 0; text-align: left; vertical-align: top; word-wrap: break-word;"> <table class="spacer" style="border-collapse: collapse; border-spacing: 0; padding: 0; text-align: left; vertical-align: top; width: 100%;"><tbody><tr style="padding: 0; text-align: left; vertical-align: top;"><td height="20px" style="-moz-hyphens: auto; -webkit-hyphens: auto; Margin: 0; border-collapse: collapse !important; color: #5D6879; font-family: Helvetica, Arial, sans-serif; font-size: 20px; font-weight: normal; hyphens: auto; line-height: 20px; margin: 0; mso-line-height-rule: exactly; padding: 0; text-align: left; vertical-align: top; word-wrap: break-word;">&#xA0;</td></tr></tbody></table> <%= body %> <table class="wrapper secondary" align="center" style="background: #E4E8EE; border-collapse: collapse; border-spacing: 0; padding: 0; text-align: left; vertical-align: top; width: 100%;"><tr style="padding: 0; text-align: left; vertical-align: top;"><td class="wrapper-inner" style="-moz-hyphens: auto; -webkit-hyphens: auto; Margin: 0; border-collapse: collapse !important; color: #5D6879; font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: normal; hyphens: auto; line-height: 1.3; margin: 0; padding: 0; text-align: left; vertical-align: top; word-wrap: break-word;"> <table class="spacer" style="border-collapse: collapse; border-spacing: 0; padding: 0; text-align: left; vertical-align: top; width: 100%;"><tbody><tr style="padding: 0; text-align: left; vertical-align: top;"><td height="10px" style="-moz-hyphens: auto; -webkit-hyphens: auto; Margin: 0; border-collapse: collapse !important; color: #5D6879; font-family: Helvetica, Arial, sans-serif; font-size: 10px; font-weight: normal; hyphens: auto; line-height: 10px; margin: 0; mso-line-height-rule: exactly; padding: 0; text-align: left; vertical-align: top; word-wrap: break-word;">&#xA0;</td></tr></tbody></table> <p style="Margin: 0; Margin-bottom: 10px; color: #5D6879; font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: normal; line-height: 1.3; margin: 0; margin-bottom: 10px; padding: 0; text-align: left;"><small style="color: #5D6879; font-size: 80%;"> ${ settings.email && settings.email.template && settings.email.template.customFooter ? `${settings.email.template.customFooter}<br>` : '' }${settings.appName} &bull; <a href="${ settings.siteUrl }" style="Margin: 0; color: #0F7A06; font-family: Helvetica, Arial, sans-serif; font-weight: normal; line-height: 1.3; margin: 0; padding: 0; text-align: left; text-decoration: none;">${ settings.siteUrl }</a> </small></p> </td></tr></table> </td></tr></tbody></table> </center> </td> </tr> </table> <!-- prevent Gmail on iOS font size manipulation --> <div style="display:none; white-space:nowrap; font:15px courier; line-height:0;"> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div> </body> </html>\ `)
overleaf/web/app/src/Features/Email/Layouts/BaseWithHeaderEmailLayout.js/0
{ "file_path": "overleaf/web/app/src/Features/Email/Layouts/BaseWithHeaderEmailLayout.js", "repo_id": "overleaf", "token_count": 6194 }
514
const { ObjectId } = require('mongodb') const Settings = require('@overleaf/settings') const EXISTING_UI = { newLogsUI: false, subvariant: null } const NEW_UI_WITH_POPUP = { newLogsUI: true, subvariant: 'new-logs-ui-with-popup', } const NEW_UI_WITHOUT_POPUP = { newLogsUI: true, subvariant: 'new-logs-ui-without-popup', } function _getVariantForPercentile(percentile) { // The current percentages are: // - 33% New UI with pop-up (originally, 5%) // - 33% New UI without pop-up (originally, 5%) // - 34% Existing UI // To ensure group stability, the implementation below respects the original partitions // for the new UI variants: [0, 5[ and [5,10[. // Two new partitions are added: [10, 38[ and [38, 66[. These represent an extra 28p.p. // which, with to the original 5%, add up to 33%. if (percentile < 5) { // This partition represents the "New UI with pop-up" group in the original roll-out (5%) return NEW_UI_WITH_POPUP } else if (percentile >= 5 && percentile < 10) { // This partition represents the "New UI without pop-up" group in the original roll-out (5%) return NEW_UI_WITHOUT_POPUP } else if (percentile >= 10 && percentile < 38) { // This partition represents an extra 28% of users getting the "New UI with pop-up" return NEW_UI_WITH_POPUP } else if (percentile >= 38 && percentile < 66) { // This partition represents an extra 28% of users getting the "New UI without pop-up" return NEW_UI_WITHOUT_POPUP } else { return EXISTING_UI } } function getNewLogsUIVariantForUser(user) { const { _id: userId, alphaProgram: isAlphaUser } = user const isSaaS = Boolean(Settings.overleaf) if (!userId || !isSaaS) { return EXISTING_UI } const userIdAsPercentile = (ObjectId(userId).getTimestamp() / 1000) % 100 if (isAlphaUser) { return NEW_UI_WITH_POPUP } else { return _getVariantForPercentile(userIdAsPercentile) } } module.exports = { getNewLogsUIVariantForUser, }
overleaf/web/app/src/Features/Helpers/NewLogsUI.js/0
{ "file_path": "overleaf/web/app/src/Features/Helpers/NewLogsUI.js", "repo_id": "overleaf", "token_count": 708 }
515
const { BackwardCompatibleError } = require('../Errors/Errors.js') class UrlFetchFailedError extends BackwardCompatibleError {} class InvalidUrlError extends BackwardCompatibleError {} class CompileFailedError extends BackwardCompatibleError {} class OutputFileFetchFailedError extends BackwardCompatibleError {} class AccessDeniedError extends BackwardCompatibleError {} class BadEntityTypeError extends BackwardCompatibleError {} class BadDataError extends BackwardCompatibleError {} class ProjectNotFoundError extends BackwardCompatibleError {} class V1ProjectNotFoundError extends BackwardCompatibleError {} class SourceFileNotFoundError extends BackwardCompatibleError {} class NotOriginalImporterError extends BackwardCompatibleError {} class FeatureNotAvailableError extends BackwardCompatibleError {} class RemoteServiceError extends BackwardCompatibleError {} class FileCannotRefreshError extends BackwardCompatibleError {} module.exports = { CompileFailedError, UrlFetchFailedError, InvalidUrlError, OutputFileFetchFailedError, AccessDeniedError, BadEntityTypeError, BadDataError, ProjectNotFoundError, V1ProjectNotFoundError, SourceFileNotFoundError, NotOriginalImporterError, FeatureNotAvailableError, RemoteServiceError, FileCannotRefreshError, }
overleaf/web/app/src/Features/LinkedFiles/LinkedFilesErrors.js/0
{ "file_path": "overleaf/web/app/src/Features/LinkedFiles/LinkedFilesErrors.js", "repo_id": "overleaf", "token_count": 344 }
516
// TODO: This file was created by bulk-decaffeinate. // Sanity-check the conversion and remove this comment. const _ = require('underscore') module.exports = { areSame(lines1, lines2) { if (!Array.isArray(lines1) || !Array.isArray(lines2)) { return false } return _.isEqual(lines1, lines2) }, }
overleaf/web/app/src/Features/Project/DocLinesComparitor.js/0
{ "file_path": "overleaf/web/app/src/Features/Project/DocLinesComparitor.js", "repo_id": "overleaf", "token_count": 118 }
517
/* eslint-disable camelcase, node/handle-callback-err, max-len, no-unused-vars, */ // TODO: This file was created by bulk-decaffeinate. // Fix any style issues and re-enable lint. /* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * DS103: Rewrite code to no longer use __guard__ * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ const { Project } = require('../../models/Project') const ProjectDetailsHandler = require('./ProjectDetailsHandler') const logger = require('logger-sharelatex') const settings = require('@overleaf/settings') const HistoryManager = require('../History/HistoryManager') const ProjectEntityUpdateHandler = require('./ProjectEntityUpdateHandler') const { promisifyAll } = require('../../util/promises') const ProjectHistoryHandler = { setHistoryId(project_id, history_id, callback) { // reject invalid history ids if (callback == null) { callback = function (err) {} } if (!history_id || typeof history_id !== 'number') { return callback(new Error('invalid history id')) } // use $exists:false to prevent overwriting any existing history id, atomically return Project.updateOne( { _id: project_id, 'overleaf.history.id': { $exists: false } }, { 'overleaf.history.id': history_id }, function (err, result) { if (err != null) { return callback(err) } if ((result != null ? result.n : undefined) === 0) { return callback(new Error('history exists')) } return callback() } ) }, getHistoryId(project_id, callback) { if (callback == null) { callback = function (err, result) {} } return ProjectDetailsHandler.getDetails( project_id, function (err, project) { if (err != null) { return callback(err) } // n.b. getDetails returns an error if the project doesn't exist return callback( null, __guard__( __guard__( project != null ? project.overleaf : undefined, x1 => x1.history ), x => x.id ) ) } ) }, upgradeHistory(project_id, callback) { // project must have an overleaf.history.id before allowing display of new history if (callback == null) { callback = function (err, result) {} } return Project.updateOne( { _id: project_id, 'overleaf.history.id': { $exists: true } }, { 'overleaf.history.display': true, 'overleaf.history.upgradedAt': new Date(), }, function (err, result) { if (err != null) { return callback(err) } // return an error if overleaf.history.id wasn't present if ((result != null ? result.n : undefined) === 0) { return callback(new Error('history not upgraded')) } return callback() } ) }, downgradeHistory(project_id, callback) { if (callback == null) { callback = function (err, result) {} } return Project.updateOne( { _id: project_id, 'overleaf.history.upgradedAt': { $exists: true } }, { 'overleaf.history.display': false, $unset: { 'overleaf.history.upgradedAt': 1 }, }, function (err, result) { if (err != null) { return callback(err) } if ((result != null ? result.n : undefined) === 0) { return callback(new Error('history not downgraded')) } return callback() } ) }, ensureHistoryExistsForProject(project_id, callback) { // We can only set a history id for a project that doesn't have one. The // history id is cached in the project history service, and changing an // existing value corrupts the history, leaving it in an irrecoverable // state. Setting a history id when one wasn't present before is ok, // because undefined history ids aren't cached. if (callback == null) { callback = function (err) {} } return ProjectHistoryHandler.getHistoryId( project_id, function (err, history_id) { if (err != null) { return callback(err) } if (history_id != null) { return callback() } // history already exists, success return HistoryManager.initializeProject(function (err, history) { if (err != null) { return callback(err) } if (!(history != null ? history.overleaf_id : undefined)) { return callback(new Error('failed to initialize history id')) } return ProjectHistoryHandler.setHistoryId( project_id, history.overleaf_id, function (err) { if (err != null) { return callback(err) } return ProjectEntityUpdateHandler.resyncProjectHistory( project_id, function (err) { if (err != null) { return callback(err) } return HistoryManager.flushProject(project_id, callback) } ) } ) }) } ) }, } function __guard__(value, transform) { return typeof value !== 'undefined' && value !== null ? transform(value) : undefined } ProjectHistoryHandler.promises = promisifyAll(ProjectHistoryHandler) module.exports = ProjectHistoryHandler
overleaf/web/app/src/Features/Project/ProjectHistoryHandler.js/0
{ "file_path": "overleaf/web/app/src/Features/Project/ProjectHistoryHandler.js", "repo_id": "overleaf", "token_count": 2302 }
518
const crypto = require('crypto') const { db } = require('../../infrastructure/mongodb') const Errors = require('../Errors/Errors') const { promisifyAll } = require('../../util/promises') const ONE_HOUR_IN_S = 60 * 60 const OneTimeTokenHandler = { getNewToken(use, data, options, callback) { // options is optional if (!options) { options = {} } if (!callback) { callback = function (error, data) {} } if (typeof options === 'function') { callback = options options = {} } const expiresIn = options.expiresIn || ONE_HOUR_IN_S const createdAt = new Date() const expiresAt = new Date(createdAt.getTime() + expiresIn * 1000) const token = crypto.randomBytes(32).toString('hex') db.tokens.insertOne( { use, token, data, createdAt, expiresAt, }, function (error) { if (error) { return callback(error) } callback(null, token) } ) }, getValueFromTokenAndExpire(use, token, callback) { if (!callback) { callback = function (error, data) {} } const now = new Date() db.tokens.findOneAndUpdate( { use, token, expiresAt: { $gt: now }, usedAt: { $exists: false }, }, { $set: { usedAt: now, }, }, function (error, result) { if (error) { return callback(error) } const token = result.value if (!token) { return callback(new Errors.NotFoundError('no token found')) } callback(null, token.data) } ) }, } OneTimeTokenHandler.promises = promisifyAll(OneTimeTokenHandler) module.exports = OneTimeTokenHandler
overleaf/web/app/src/Features/Security/OneTimeTokenHandler.js/0
{ "file_path": "overleaf/web/app/src/Features/Security/OneTimeTokenHandler.js", "repo_id": "overleaf", "token_count": 789 }
519
const OError = require('@overleaf/o-error') const logger = require('logger-sharelatex') const ProjectGetter = require('../Project/ProjectGetter') const UserGetter = require('../User/UserGetter') const SubscriptionLocator = require('./SubscriptionLocator') const Settings = require('@overleaf/settings') const CollaboratorsGetter = require('../Collaborators/CollaboratorsGetter') const CollaboratorsInvitesHandler = require('../Collaborators/CollaboratorsInviteHandler') const V1SubscriptionManager = require('./V1SubscriptionManager') const { V1ConnectionError } = require('../Errors/Errors') const { promisifyAll } = require('../../util/promises') const LimitationsManager = { allowedNumberOfCollaboratorsInProject(projectId, callback) { ProjectGetter.getProject( projectId, { owner_ref: true }, (error, project) => { if (error) { return callback(error) } this.allowedNumberOfCollaboratorsForUser(project.owner_ref, callback) } ) }, allowedNumberOfCollaboratorsForUser(userId, callback) { UserGetter.getUser(userId, { features: 1 }, function (error, user) { if (error) { return callback(error) } if (user.features && user.features.collaborators) { callback(null, user.features.collaborators) } else { callback(null, Settings.defaultFeatures.collaborators) } }) }, canAddXCollaborators(projectId, numberOfNewCollaborators, callback) { if (!callback) { callback = function (error, allowed) {} } this.allowedNumberOfCollaboratorsInProject( projectId, (error, allowedNumber) => { if (error) { return callback(error) } CollaboratorsGetter.getInvitedCollaboratorCount( projectId, (error, currentNumber) => { if (error) { return callback(error) } CollaboratorsInvitesHandler.getInviteCount( projectId, (error, inviteCount) => { if (error) { return callback(error) } if ( currentNumber + inviteCount + numberOfNewCollaborators <= allowedNumber || allowedNumber < 0 ) { callback(null, true) } else { callback(null, false) } } ) } ) } ) }, hasPaidSubscription(user, callback) { if (!callback) { callback = function (err, hasSubscriptionOrIsMember) {} } this.userHasV2Subscription(user, (err, hasSubscription, subscription) => { if (err) { return callback(err) } this.userIsMemberOfGroupSubscription(user, (err, isMember) => { if (err) { return callback(err) } this.userHasV1Subscription(user, (err, hasV1Subscription) => { if (err) { return callback( new V1ConnectionError( 'error getting subscription from v1' ).withCause(err) ) } callback( err, isMember || hasSubscription || hasV1Subscription, subscription ) }) }) }) }, // alias for backward-compatibility with modules. Use `haspaidsubscription` instead userHasSubscriptionOrIsGroupMember(user, callback) { this.hasPaidSubscription(user, callback) }, userHasV2Subscription(user, callback) { if (!callback) { callback = function (err, hasSubscription, subscription) {} } SubscriptionLocator.getUsersSubscription( user._id, function (err, subscription) { if (err) { return callback(err) } let hasValidSubscription = false if (subscription) { if ( subscription.recurlySubscription_id || subscription.customAccount ) { hasValidSubscription = true } } callback(err, hasValidSubscription, subscription) } ) }, userHasV1OrV2Subscription(user, callback) { if (!callback) { callback = function (err, hasSubscription) {} } this.userHasV2Subscription(user, (err, hasV2Subscription) => { if (err) { return callback(err) } if (hasV2Subscription) { return callback(null, true) } this.userHasV1Subscription(user, (err, hasV1Subscription) => { if (err) { return callback(err) } if (hasV1Subscription) { return callback(null, true) } callback(null, false) }) }) }, userIsMemberOfGroupSubscription(user, callback) { if (!callback) { callback = function (error, isMember, subscriptions) {} } SubscriptionLocator.getMemberSubscriptions( user._id, function (err, subscriptions) { if (!subscriptions) { subscriptions = [] } if (err) { return callback(err) } callback(err, subscriptions.length > 0, subscriptions) } ) }, userHasV1Subscription(user, callback) { if (!callback) { callback = function (error, hasV1Subscription) {} } V1SubscriptionManager.getSubscriptionsFromV1( user._id, function (err, v1Subscription) { callback( err, !!(v1Subscription ? v1Subscription.has_subscription : undefined) ) } ) }, teamHasReachedMemberLimit(subscription) { const currentTotal = (subscription.member_ids || []).length + (subscription.teamInvites || []).length + (subscription.invited_emails || []).length return currentTotal >= subscription.membersLimit }, hasGroupMembersLimitReached(subscriptionId, callback) { if (!callback) { callback = function (err, limitReached, subscription) {} } SubscriptionLocator.getSubscription( subscriptionId, function (err, subscription) { if (err) { OError.tag(err, 'error getting subscription', { subscriptionId, }) return callback(err) } if (!subscription) { logger.warn({ subscriptionId }, 'no subscription found') return callback(new Error('no subscription found')) } const limitReached = LimitationsManager.teamHasReachedMemberLimit( subscription ) callback(err, limitReached, subscription) } ) }, } LimitationsManager.promises = promisifyAll(LimitationsManager, { multiResult: { userHasV2Subscription: ['hasSubscription', 'subscription'], userIsMemberOfGroupSubscription: ['isMember', 'subscriptions'], hasGroupMembersLimitReached: ['limitReached', 'subscription'], }, }) module.exports = LimitationsManager
overleaf/web/app/src/Features/Subscription/LimitationsManager.js/0
{ "file_path": "overleaf/web/app/src/Features/Subscription/LimitationsManager.js", "repo_id": "overleaf", "token_count": 3003 }
520
let TeamInvitesHandler const logger = require('logger-sharelatex') const crypto = require('crypto') const async = require('async') const settings = require('@overleaf/settings') const { ObjectId } = require('mongodb') const { Subscription } = require('../../models/Subscription') const UserGetter = require('../User/UserGetter') const SubscriptionLocator = require('./SubscriptionLocator') const SubscriptionUpdater = require('./SubscriptionUpdater') const LimitationsManager = require('./LimitationsManager') const EmailHandler = require('../Email/EmailHandler') const EmailHelper = require('../Helpers/EmailHelper') const Errors = require('../Errors/Errors') module.exports = TeamInvitesHandler = { getInvite(token, callback) { return Subscription.findOne( { 'teamInvites.token': token }, function (err, subscription) { if (err) { return callback(err) } if (!subscription) { return callback(new Errors.NotFoundError('team not found')) } const invite = subscription.teamInvites.find(i => i.token === token) callback(null, invite, subscription) } ) }, createInvite(teamManagerId, subscription, email, callback) { email = EmailHelper.parseEmail(email) if (!email) { return callback(new Error('invalid email')) } return UserGetter.getUser(teamManagerId, function (error, teamManager) { if (error) { return callback(error) } removeLegacyInvite(subscription.id, email, function (error) { if (error) { return callback(error) } createInvite(subscription, email, teamManager, callback) }) }) }, importInvite(subscription, inviterName, email, token, sentAt, callback) { checkIfInviteIsPossible( subscription, email, function (error, possible, reason) { if (error) { return callback(error) } if (!possible) { return callback(reason) } subscription.teamInvites.push({ email, inviterName, token, sentAt, }) subscription.save(callback) } ) }, acceptInvite(token, userId, callback) { TeamInvitesHandler.getInvite(token, function (err, invite, subscription) { if (err) { return callback(err) } if (!invite) { return callback(new Errors.NotFoundError('invite not found')) } SubscriptionUpdater.addUserToGroup( subscription._id, userId, function (err) { if (err) { return callback(err) } removeInviteFromTeam(subscription.id, invite.email, callback) } ) }) }, revokeInvite(teamManagerId, subscription, email, callback) { email = EmailHelper.parseEmail(email) if (!email) { return callback(new Error('invalid email')) } removeInviteFromTeam(subscription.id, email, callback) }, // Legacy method to allow a user to receive a confirmation email if their // email is in Subscription.invited_emails when they join. We'll remove this // after a short while. createTeamInvitesForLegacyInvitedEmail(email, callback) { SubscriptionLocator.getGroupsWithEmailInvite(email, function (err, teams) { if (err) { return callback(err) } async.map( teams, (team, cb) => TeamInvitesHandler.createInvite(team.admin_id, team, email, cb), callback ) }) }, } var createInvite = function (subscription, email, inviter, callback) { checkIfInviteIsPossible( subscription, email, function (error, possible, reason) { if (error) { return callback(error) } if (!possible) { return callback(reason) } // don't send invites when inviting self; add user directly to the group const isInvitingSelf = inviter.emails.some( emailData => emailData.email === email ) if (isInvitingSelf) { return SubscriptionUpdater.addUserToGroup( subscription._id, inviter._id, err => { if (err) { return callback(err) } // legacy: remove any invite that might have been created in the past removeInviteFromTeam(subscription._id, email, error => { const inviteUserData = { email: inviter.email, first_name: inviter.first_name, last_name: inviter.last_name, invite: false, } callback(error, inviteUserData) }) } ) } const inviterName = getInviterName(inviter) let invite = subscription.teamInvites.find( invite => invite.email === email ) if (invite) { invite.sentAt = new Date() } else { invite = { email, inviterName, token: crypto.randomBytes(32).toString('hex'), sentAt: new Date(), } subscription.teamInvites.push(invite) } subscription.save(function (error) { if (error) { return callback(error) } const opts = { to: email, inviter, acceptInviteUrl: `${settings.siteUrl}/subscription/invites/${invite.token}/`, appName: settings.appName, } EmailHandler.sendEmail('verifyEmailToJoinTeam', opts, error => { Object.assign(invite, { invite: true }) callback(error, invite) }) }) } ) } var removeInviteFromTeam = function (subscriptionId, email, callback) { const searchConditions = { _id: new ObjectId(subscriptionId.toString()) } const removeInvite = { $pull: { teamInvites: { email } } } async.series( [ cb => Subscription.updateOne(searchConditions, removeInvite, cb), cb => removeLegacyInvite(subscriptionId, email, cb), ], callback ) } var removeLegacyInvite = (subscriptionId, email, callback) => Subscription.updateOne( { _id: new ObjectId(subscriptionId.toString()), }, { $pull: { invited_emails: email, }, }, callback ) var checkIfInviteIsPossible = function (subscription, email, callback) { if (!subscription.groupPlan) { logger.log( { subscriptionId: subscription.id }, 'can not add members to a subscription that is not in a group plan' ) return callback(null, false, { wrongPlan: true }) } if (LimitationsManager.teamHasReachedMemberLimit(subscription)) { logger.log( { subscriptionId: subscription.id }, 'team has reached member limit' ) return callback(null, false, { limitReached: true }) } UserGetter.getUserByAnyEmail(email, function (error, existingUser) { if (error) { return callback(error) } if (!existingUser) { return callback(null, true) } const existingMember = subscription.member_ids.find( memberId => memberId.toString() === existingUser._id.toString() ) if (existingMember) { logger.log( { subscriptionId: subscription.id, email }, 'user already in team' ) callback(null, false, { alreadyInTeam: true }) } else { callback(null, true) } }) } var getInviterName = function (inviter) { let inviterName if (inviter.first_name && inviter.last_name) { inviterName = `${inviter.first_name} ${inviter.last_name} (${inviter.email})` } else { inviterName = inviter.email } return inviterName }
overleaf/web/app/src/Features/Subscription/TeamInvitesHandler.js/0
{ "file_path": "overleaf/web/app/src/Features/Subscription/TeamInvitesHandler.js", "repo_id": "overleaf", "token_count": 3178 }
521
const { ObjectId } = require('mongodb') const _ = require('lodash') const { callbackify } = require('util') const logger = require('logger-sharelatex') const metrics = require('@overleaf/metrics') const path = require('path') const request = require('request-promise-native') const settings = require('@overleaf/settings') const CollaboratorsGetter = require('../Collaborators/CollaboratorsGetter') .promises const UserGetter = require('../User/UserGetter.js').promises const tpdsUrl = _.get(settings, ['apis', 'thirdPartyDataStore', 'url']) async function addDoc(options) { metrics.inc('tpds.add-doc') options.streamOrigin = settings.apis.docstore.pubUrl + path.join( `/project/${options.project_id}`, `/doc/${options.doc_id}`, '/raw' ) return addEntity(options) } async function addEntity(options) { const projectUserIds = await getProjectUsersIds(options.project_id) for (const userId of projectUserIds) { const job = { method: 'post', headers: { sl_entity_rev: options.rev, sl_project_id: options.project_id, sl_all_user_ids: JSON.stringify([userId]), sl_project_owner_user_id: projectUserIds[0], }, uri: buildTpdsUrl(userId, options.project_name, options.path), title: 'addFile', streamOrigin: options.streamOrigin, } await enqueue(userId, 'pipeStreamFrom', job) } } async function addFile(options) { metrics.inc('tpds.add-file') options.streamOrigin = settings.apis.filestore.url + path.join(`/project/${options.project_id}`, `/file/${options.file_id}`) return addEntity(options) } function buildMovePaths(options) { if (options.newProjectName) { return { startPath: path.join('/', options.project_name, '/'), endPath: path.join('/', options.newProjectName, '/'), } } else { return { startPath: path.join('/', options.project_name, '/', options.startPath), endPath: path.join('/', options.project_name, '/', options.endPath), } } } function buildTpdsUrl(userId, projectName, filePath) { const projectPath = encodeURIComponent(path.join(projectName, '/', filePath)) return `${tpdsUrl}/user/${userId}/entity/${projectPath}` } async function deleteEntity(options) { metrics.inc('tpds.delete-entity') const projectUserIds = await getProjectUsersIds(options.project_id) for (const userId of projectUserIds) { const job = { method: 'delete', headers: { sl_project_id: options.project_id, sl_all_user_ids: JSON.stringify([userId]), sl_project_owner_user_id: projectUserIds[0], }, uri: buildTpdsUrl(userId, options.project_name, options.path), title: 'deleteEntity', sl_all_user_ids: JSON.stringify([userId]), } await enqueue(userId, 'standardHttpRequest', job) } } async function deleteProject(options) { // deletion only applies to project archiver const projectArchiverUrl = _.get(settings, [ 'apis', 'project_archiver', 'url', ]) // silently do nothing if project archiver url is not in settings if (!projectArchiverUrl) { return } metrics.inc('tpds.delete-project') // send the request directly to project archiver, bypassing third-party-datastore try { const response = await request({ uri: `${settings.apis.project_archiver.url}/project/${options.project_id}`, method: 'delete', }) return response } catch (err) { logger.error( { err, project_id: options.project_id }, 'error deleting project in third party datastore (project_archiver)' ) } } async function enqueue(group, method, job) { const tpdsWorkerUrl = _.get(settings, ['apis', 'tpdsworker', 'url']) // silently do nothing if worker url is not in settings if (!tpdsWorkerUrl) { return } try { const response = await request({ uri: `${tpdsWorkerUrl}/enqueue/web_to_tpds_http_requests`, json: { group, job, method }, method: 'post', timeout: 5 * 1000, }) return response } catch (err) { // log error and continue logger.error({ err, group, job, method }, 'error enqueueing tpdsworker job') } } async function getProjectUsersIds(projectId) { // get list of all user ids with access to project. project owner // will always be the first entry in the list. const [ ownerUserId, ...invitedUserIds ] = await CollaboratorsGetter.getInvitedMemberIds(projectId) // if there are no invited users, always return the owner if (!invitedUserIds.length) { return [ownerUserId] } // filter invited users to only return those with dropbox linked const dropboxUsers = await UserGetter.getUsers( { _id: { $in: invitedUserIds.map(id => ObjectId(id)) }, 'dropbox.access_token.uid': { $ne: null }, }, { _id: 1, } ) const dropboxUserIds = dropboxUsers.map(user => user._id) return [ownerUserId, ...dropboxUserIds] } async function moveEntity(options) { metrics.inc('tpds.move-entity') const projectUserIds = await getProjectUsersIds(options.project_id) const { endPath, startPath } = buildMovePaths(options) for (const userId of projectUserIds) { const job = { method: 'put', title: 'moveEntity', uri: `${tpdsUrl}/user/${userId}/entity`, headers: { sl_project_id: options.project_id, sl_entity_rev: options.rev, sl_all_user_ids: JSON.stringify([userId]), sl_project_owner_user_id: projectUserIds[0], }, json: { user_id: userId, endPath, startPath, }, } await enqueue(userId, 'standardHttpRequest', job) } } async function pollDropboxForUser(userId) { metrics.inc('tpds.poll-dropbox') const job = { method: 'post', uri: `${tpdsUrl}/user/poll`, json: { user_ids: [userId], }, } return enqueue(`poll-dropbox:${userId}`, 'standardHttpRequest', job) } const TpdsUpdateSender = { addDoc: callbackify(addDoc), addEntity: callbackify(addEntity), addFile: callbackify(addFile), deleteEntity: callbackify(deleteEntity), deleteProject: callbackify(deleteProject), enqueue: callbackify(enqueue), moveEntity: callbackify(moveEntity), pollDropboxForUser: callbackify(pollDropboxForUser), promises: { addDoc, addEntity, addFile, deleteEntity, deleteProject, enqueue, moveEntity, pollDropboxForUser, }, } module.exports = TpdsUpdateSender
overleaf/web/app/src/Features/ThirdPartyDataStore/TpdsUpdateSender.js/0
{ "file_path": "overleaf/web/app/src/Features/ThirdPartyDataStore/TpdsUpdateSender.js", "repo_id": "overleaf", "token_count": 2485 }
522
const logger = require('logger-sharelatex') const util = require('util') const { AffiliationError } = require('../Errors/Errors') const Features = require('../../infrastructure/Features') const { User } = require('../../models/User') const UserDeleter = require('./UserDeleter') const UserGetter = require('./UserGetter') const UserUpdater = require('./UserUpdater') const Analytics = require('../Analytics/AnalyticsManager') const UserOnboardingEmailQueueManager = require('./UserOnboardingEmailManager') const UserPostRegistrationAnalyticsManager = require('./UserPostRegistrationAnalyticsManager') const OError = require('@overleaf/o-error') async function _addAffiliation(user, affiliationOptions) { try { await UserUpdater.promises.addAffiliationForNewUser( user._id, user.email, affiliationOptions ) } catch (error) { throw new AffiliationError('add affiliation failed').withCause(error) } try { user = await UserGetter.promises.getUser(user._id) } catch (error) { logger.error( OError.tag(error, 'could not get fresh user data', { userId: user._id, email: user.email, }) ) } return user } async function createNewUser(attributes, options = {}) { let user = new User() if (attributes.first_name == null || attributes.first_name === '') { attributes.first_name = attributes.email.split('@')[0] } Object.assign(user, attributes) user.ace.syntaxValidation = true if (user.featureSwitches != null) { user.featureSwitches.pdfng = true } const reversedHostname = user.email.split('@')[1].split('').reverse().join('') const emailData = { email: user.email, createdAt: new Date(), reversedHostname, } if (Features.hasFeature('affiliations')) { emailData.affiliationUnchecked = true } if ( attributes.samlIdentifiers && attributes.samlIdentifiers[0] && attributes.samlIdentifiers[0].providerId ) { emailData.samlProviderId = attributes.samlIdentifiers[0].providerId } user.emails = [emailData] user = await user.save() if (Features.hasFeature('affiliations')) { try { user = await _addAffiliation(user, options.affiliationOptions || {}) } catch (error) { if (options.requireAffiliation) { await UserDeleter.promises.deleteMongoUser(user._id) throw OError.tag(error) } else { logger.error(OError.tag(error)) } } } Analytics.recordEvent(user._id, 'user-registered') Analytics.setUserProperty(user._id, 'created-at', new Date()) if (Features.hasFeature('saas')) { try { await UserOnboardingEmailQueueManager.scheduleOnboardingEmail(user) await UserPostRegistrationAnalyticsManager.schedulePostRegistrationAnalytics( user ) } catch (error) { logger.error( OError.tag(error, 'Failed to schedule sending of onboarding email', { userId: user._id, }) ) } } return user } const UserCreator = { createNewUser: util.callbackify(createNewUser), promises: { createNewUser: createNewUser, }, } module.exports = UserCreator
overleaf/web/app/src/Features/User/UserCreator.js/0
{ "file_path": "overleaf/web/app/src/Features/User/UserCreator.js", "repo_id": "overleaf", "token_count": 1131 }
523
/* eslint-disable max-len, */ // TODO: This file was created by bulk-decaffeinate. // Fix any style issues and re-enable lint. /* * decaffeinate suggestions: * DS101: Remove unnecessary use of Array.from * DS102: Remove unnecessary code created because of implicit returns * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ const SessionManager = require('../Authentication/SessionManager') const UserMembershipHandler = require('./UserMembershipHandler') const Errors = require('../Errors/Errors') const EmailHelper = require('../Helpers/EmailHelper') const CSVParser = require('json2csv').Parser module.exports = { index(req, res, next) { const { entity, entityConfig } = req return entity.fetchV1Data(function (error, entity) { if (error != null) { return next(error) } return UserMembershipHandler.getUsers( entity, entityConfig, function (error, users) { let entityName if (error != null) { return next(error) } const entityPrimaryKey = entity[ entityConfig.fields.primaryKey ].toString() if (entityConfig.fields.name) { entityName = entity[entityConfig.fields.name] } return res.render('user_membership/index', { name: entityName, users, groupSize: entityConfig.hasMembersLimit ? entity.membersLimit : undefined, translations: entityConfig.translations, paths: entityConfig.pathsFor(entityPrimaryKey), }) } ) }) }, add(req, res, next) { const { entity, entityConfig } = req const email = EmailHelper.parseEmail(req.body.email) if (email == null) { return res.status(400).json({ error: { code: 'invalid_email', message: req.i18n.translate('invalid_email'), }, }) } if (entityConfig.readOnly) { return next(new Errors.NotFoundError('Cannot add users to entity')) } return UserMembershipHandler.addUser( entity, entityConfig, email, function (error, user) { if (error != null ? error.alreadyAdded : undefined) { return res.status(400).json({ error: { code: 'user_already_added', message: req.i18n.translate('user_already_added'), }, }) } if (error != null ? error.userNotFound : undefined) { return res.status(404).json({ error: { code: 'user_not_found', message: req.i18n.translate('user_not_found'), }, }) } if (error != null) { return next(error) } return res.json({ user }) } ) }, remove(req, res, next) { const { entity, entityConfig } = req const { userId } = req.params if (entityConfig.readOnly) { return next(new Errors.NotFoundError('Cannot remove users from entity')) } const loggedInUserId = SessionManager.getLoggedInUserId(req.session) if (loggedInUserId === userId) { return res.status(400).json({ error: { code: 'managers_cannot_remove_self', message: req.i18n.translate('managers_cannot_remove_self'), }, }) } return UserMembershipHandler.removeUser( entity, entityConfig, userId, function (error, user) { if (error != null ? error.isAdmin : undefined) { return res.status(400).json({ error: { code: 'managers_cannot_remove_admin', message: req.i18n.translate('managers_cannot_remove_admin'), }, }) } if (error != null) { return next(error) } return res.sendStatus(200) } ) }, exportCsv(req, res, next) { const { entity, entityConfig } = req const fields = ['email', 'last_logged_in_at'] return UserMembershipHandler.getUsers( entity, entityConfig, function (error, users) { if (error != null) { return next(error) } const csvParser = new CSVParser({ fields }) res.header('Content-Disposition', 'attachment; filename=Group.csv') res.contentType('text/csv') return res.send(csvParser.parse(users)) } ) }, new(req, res, next) { return res.render('user_membership/new', { entityName: req.params.name, entityId: req.params.id, }) }, create(req, res, next) { const entityId = req.params.id const entityConfig = req.entityConfig return UserMembershipHandler.createEntity( entityId, entityConfig, function (error, entity) { if (error != null) { return next(error) } return res.redirect(entityConfig.pathsFor(entityId).index) } ) }, }
overleaf/web/app/src/Features/UserMembership/UserMembershipController.js/0
{ "file_path": "overleaf/web/app/src/Features/UserMembership/UserMembershipController.js", "repo_id": "overleaf", "token_count": 2227 }
524
const { callbackify, promisify } = require('util') const JWT = require('jsonwebtoken') const Settings = require('@overleaf/settings') const jwtSign = promisify(JWT.sign) async function sign(payload, options = {}) { const key = Settings.jwt.key const algorithm = Settings.jwt.algorithm if (!key || !algorithm) { throw new Error('missing JWT configuration') } const token = await jwtSign(payload, key, { ...options, algorithm }) return token } module.exports = { sign: callbackify(sign), promises: { sign, }, }
overleaf/web/app/src/infrastructure/JsonWebToken.js/0
{ "file_path": "overleaf/web/app/src/infrastructure/JsonWebToken.js", "repo_id": "overleaf", "token_count": 179 }
525
const Settings = require('@overleaf/settings') const OError = require('@overleaf/o-error') const botUserAgents = [ 'kube-probe', 'GoogleStackdriverMonitoring', 'GoogleHC', 'Googlebot', 'bingbot', 'facebookexternal', ].map(agent => { return agent.toLowerCase() }) // SessionAutostartMiddleware provides a mechanism to force certain routes not // to get an automatic session where they don't have one already. This allows us // to work around issues where we might overwrite a user's login cookie with one // that is hidden by a `SameSite` setting. // // When registering a route with disableSessionAutostartForRoute, a callback // should be provided that handles the case that a session is not available. // This will be called as a standard middleware with (req, res, next) - calling // next will continue and sett up a session as normal, otherwise the app can // perform a different operation as usual class SessionAutostartMiddleware { constructor() { this.middleware = this.middleware.bind(this) this._cookieName = Settings.cookieName this._noAutostartCallbacks = new Map() } static applyInitialMiddleware(router) { const middleware = new SessionAutostartMiddleware() router.sessionAutostartMiddleware = middleware router.use(middleware.middleware) } disableSessionAutostartForRoute(route, method, callback) { if (typeof callback !== 'function') { throw new Error('callback not provided when disabling session autostart') } if (!this._noAutostartCallbacks[route]) { this._noAutostartCallbacks[route] = new Map() } this._noAutostartCallbacks[route][method] = callback } applyDefaultPostGatewayForRoute(route) { this.disableSessionAutostartForRoute( route, 'POST', SessionAutostartMiddleware.genericPostGatewayMiddleware ) } autostartCallbackForRequest(req) { return ( this._noAutostartCallbacks[req.path] && this._noAutostartCallbacks[req.path][req.method] ) } reqIsBot(req) { const agent = (req.headers['user-agent'] || '').toLowerCase() const foundMatch = botUserAgents.find(botAgent => { return agent.includes(botAgent) }) if (foundMatch) { return true } else { return false } } middleware(req, _res, next) { if (!req.signedCookies[this._cookieName]) { const callback = this.autostartCallbackForRequest(req) if (callback) { req.session = { noSessionCallback: callback, } } else if (this.reqIsBot(req)) { req.session = { noSessionCallback: (_req, _res, next) => { next() }, } } } next() } static invokeCallbackMiddleware(req, res, next) { if (req.session.noSessionCallback) { return req.session.noSessionCallback(req, res, next) } next() } static genericPostGatewayMiddleware(req, res, next) { if (req.method !== 'POST') { return next( new OError('post gateway invoked for non-POST request', { path: req.path, method: req.method, }) ) } if (req.body.viaGateway) { return next() } res.render('general/post-gateway', { form_data: req.body }) } } module.exports = SessionAutostartMiddleware
overleaf/web/app/src/infrastructure/SessionAutostartMiddleware.js/0
{ "file_path": "overleaf/web/app/src/infrastructure/SessionAutostartMiddleware.js", "repo_id": "overleaf", "token_count": 1206 }
526
const mongoose = require('../infrastructure/Mongoose') const { Schema } = mongoose const { ObjectId } = Schema const OauthAccessTokenSchema = new Schema( { accessToken: String, accessTokenExpiresAt: Date, oauthApplication_id: { type: ObjectId, ref: 'OauthApplication' }, refreshToken: String, refreshTokenExpiresAt: Date, scope: String, user_id: { type: ObjectId, ref: 'User' }, }, { collection: 'oauthAccessTokens', } ) exports.OauthAccessToken = mongoose.model( 'OauthAccessToken', OauthAccessTokenSchema ) exports.OauthAccessTokenSchema = OauthAccessTokenSchema
overleaf/web/app/src/models/OauthAccessToken.js/0
{ "file_path": "overleaf/web/app/src/models/OauthAccessToken.js", "repo_id": "overleaf", "token_count": 222 }
527
const { promisify, callbackify } = require('util') const pLimit = require('p-limit') module.exports = { promisify, promisifyAll, promisifyMultiResult, callbackify, callbackifyMultiResult, expressify, promiseMapWithLimit, } /** * Promisify all functions in a module. * * This is meant to be used only when all functions in the module are async * callback-style functions. * * It's very much tailored to our current module structure. In particular, it * binds `this` to the module when calling the function in order not to break * modules that call sibling functions using `this`. * * This will not magically fix all modules. Special cases should be promisified * manually. * * The second argument is a bag of options: * * - without: an array of function names that shouldn't be promisified * * - multiResult: an object whose keys are function names and values are lists * of parameter names. This is meant for functions that invoke their callbacks * with more than one result in separate parameters. The promisifed function * will return these results as a single object, with each result keyed under * the corresponding parameter name. */ function promisifyAll(module, opts = {}) { const { without = [], multiResult = {} } = opts const promises = {} for (const propName of Object.getOwnPropertyNames(module)) { if (without.includes(propName)) { continue } const propValue = module[propName] if (typeof propValue !== 'function') { continue } if (multiResult[propName] != null) { promises[propName] = promisifyMultiResult( propValue, multiResult[propName] ).bind(module) } else { promises[propName] = promisify(propValue).bind(module) } } return promises } /** * Promisify a function that returns multiple results via additional callback * parameters. * * The promisified function returns the results in a single object whose keys * are the names given in the array `resultNames`. * * Example: * * function f(callback) { * return callback(null, 1, 2, 3) * } * * const g = promisifyMultiResult(f, ['a', 'b', 'c']) * * const result = await g() // returns {a: 1, b: 2, c: 3} */ function promisifyMultiResult(fn, resultNames) { function promisified(...args) { return new Promise((resolve, reject) => { try { fn(...args, (err, ...results) => { if (err != null) { return reject(err) } const promiseResult = {} for (let i = 0; i < resultNames.length; i++) { promiseResult[resultNames[i]] = results[i] } resolve(promiseResult) }) } catch (err) { reject(err) } }) } return promisified } /** * Reverse the effect of `promisifyMultiResult`. * * This is meant for providing a temporary backward compatible callback * interface while we migrate to promises. */ function callbackifyMultiResult(fn, resultNames) { function callbackified(...args) { const [callback] = args.splice(-1) fn(...args) .then(result => { const cbResults = resultNames.map(resultName => result[resultName]) callback(null, ...cbResults) }) .catch(err => { callback(err) }) } return callbackified } /** * Transform an async function into an Express middleware * * Any error will be passed to the error middlewares via `next()` */ function expressify(fn) { return (req, res, next) => { fn(req, res, next).catch(next) } } /** * Map values in `array` with the async function `fn` * * Limit the number of unresolved promises to `concurrency`. */ function promiseMapWithLimit(concurrency, array, fn) { const limit = pLimit(concurrency) return Promise.all(array.map(x => limit(() => fn(x)))) }
overleaf/web/app/src/util/promises.js/0
{ "file_path": "overleaf/web/app/src/util/promises.js", "repo_id": "overleaf", "token_count": 1321 }
528
extends ../layout block content main.content.content-alt#main-content .container.beta-opt-in-wrapper .row .col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2 .card .page-header.text-centered h1 | #{translate("sharelatex_beta_program")} .beta-opt-in .container-fluid .row .col-md-12 if user.betaProgram p #{translate("beta_program_already_participating")}. p #{translate("thank_you_for_being_part_of_our_beta_program")}. else p #{translate("beta_program_benefits")} p #[strong How it works:] ul li #{translate("beta_program_badge_description")}&nbsp;#[span(aria-label=translate("beta_feature_badge") role="img").beta-badge] li #{translate("you_will_be_able_to_contact_us_any_time_to_share_your_feedback")}. li #{translate("we_may_also_contact_you_from_time_to_time_by_email_with_a_survey")}. li #{translate("you_can_opt_in_and_out_of_the_program_at_any_time_on_this_page")}. .row.text-centered .col-md-12 if user.betaProgram form(id="beta-program-opt-out", method="post", action="/beta/opt-out", novalidate) input(type="hidden", name="_csrf", value=csrfToken) .form-group a( href="https://forms.gle/CFEsmvZQTAwHCd3X9" target="_blank" rel="noopener noreferrer" ).btn.btn-primary.btn-lg #{translate("give_feedback")} .form-group button.btn.btn-info.btn-sm( type="submit" ) span #{translate("beta_program_opt_out_action")} .form-group a(href="/project").btn.btn-link.btn-sm #{translate("back_to_your_projects")} else form(id="beta-program-opt-in", method="post", action="/beta/opt-in", novalidate) input(type="hidden", name="_csrf", value=csrfToken) .form-group button.btn.btn-primary( type="submit" ) span #{translate("beta_program_opt_in_action")} .form-group a(href="/project").btn.btn-link.btn-sm #{translate("back_to_your_projects")}
overleaf/web/app/views/beta_program/opt_in.pug/0
{ "file_path": "overleaf/web/app/views/beta_program/opt_in.pug", "repo_id": "overleaf", "token_count": 1228 }
529
.ui-layout-center( ng-controller="ReviewPanelController", ng-class="{\ 'rp-unsupported': editor.showRichText,\ 'rp-state-current-file': (reviewPanel.subView === SubViews.CUR_FILE),\ 'rp-state-current-file-expanded': (reviewPanel.subView === SubViews.CUR_FILE && ui.reviewPanelOpen),\ 'rp-state-current-file-mini': (reviewPanel.subView === SubViews.CUR_FILE && !ui.reviewPanelOpen),\ 'rp-state-overview': (reviewPanel.subView === SubViews.OVERVIEW),\ 'rp-size-mini': ui.miniReviewPanelVisible,\ 'rp-size-expanded': ui.reviewPanelOpen,\ 'rp-layout-left': reviewPanel.layoutToLeft,\ 'rp-loading-threads': reviewPanel.loadingThreads,\ }" ) .loading-panel( ng-show="(!editor.sharejs_doc || editor.opening) && !editor.error_state", style=showRichText ? "top: 32px" : "", ) span(ng-show="editor.open_doc_id") i.fa.fa-spin.fa-refresh | &nbsp;&nbsp;#{translate("loading")}… span(ng-show="!editor.open_doc_id") i.fa.fa-arrow-left | &nbsp;&nbsp;#{translate("open_a_file_on_the_left")} if moduleIncludesAvailable('editor:main') != moduleIncludes('editor:main', locals) else .toolbar.toolbar-editor .multi-selection-ongoing( ng-show="multiSelectedCount > 0" ) .multi-selection-message h4 {{ multiSelectedCount }} #{translate('files_selected')} include ./source-editor if !isRestrictedTokenMember include ./review-panel
overleaf/web/app/views/project/editor/editor-no-symbol-palette.pug/0
{ "file_path": "overleaf/web/app/views/project/editor/editor-no-symbol-palette.pug", "repo_id": "overleaf", "token_count": 592 }
530
script(type='text/ng-template', id='newFileModalTemplate') .modal-header h3 Add Files .modal-body.modal-new-file(ng-show="file_count < 2000") table tr td.modal-new-file--list ul.list-unstyled li(ng-class="type == 'doc' ? 'active' : null") a(href, ng-click="type = 'doc'") i.fa.fa-fw.fa-file | | New File li(ng-class="type == 'upload' ? 'active' : null") a(href, ng-click="type = 'upload'") i.fa.fa-fw.fa-upload | | Upload li(ng-class="type == 'project' ? 'active' : null") a(href, ng-click="type = 'project'") i.fa.fa-fw.fa-folder-open | | From Another Project if hasFeature('link-url') li(ng-class="type == 'url' ? 'active' : null") a(href, ng-click="type = 'url'") i.fa.fa-fw.fa-globe | | From External URL != moduleIncludes("newFileModal:selector", locals) td(class="modal-new-file--body modal-new-file--body-{{type}}") div(ng-if="type == 'doc'", ng-controller="NewDocModalController") form(novalidate, name="newDocForm") label(for="name") File Name input.form-control( type="text", placeholder="File Name", required, ng-model="inputs.name", on-enter="create()", select-name-on="open", valid-file, name="name" ) div.alert.alert-danger.row-spaced-small(ng-if="error") div(ng-switch="error") span(ng-switch-when="already exists") #{translate("file_already_exists")} span(ng-switch-default) {{error}} div.alert.alert-danger.row-spaced-small(ng-show="newDocForm.name.$error.validFile && newDocForm.name.$viewValue.length") | #{translate('files_cannot_include_invalid_characters')} div(ng-if="type == 'upload'", ng-controller="UploadFileModalController") .alert.alert-warning.small(ng-if="tooManyFiles") #{translate("maximum_files_uploaded_together", {max:"{{max_files}}"})} .alert.alert-warning.small(ng-if="rateLimitHit") #{translate("too_many_files_uploaded_throttled_short_period")} .alert.alert-warning.small(ng-if="notLoggedIn") #{translate("session_expired_redirecting_to_login", {seconds:"{{secondsToRedirect}}"})} .alert.alert-warning.small(ng-if="conflicts.length > 0") p.text-center | The following files already exist in this project: ul.text-center.list-unstyled.row-spaced-small li(ng-repeat="conflict in conflicts track by $index"): strong {{ conflict }} p.text-center.row-spaced-small | Do you want to overwrite them? p.text-center a(href, ng-click="doUpload()").btn.btn-primary Overwrite | &nbsp; a(href, ng-click="cancel()").btn.btn-default Cancel div( fine-upload endpoint="/project/{{ project_id }}/upload" template-id="qq-file-uploader-template" multiple="true" auto-upload="false" on-complete-callback="onComplete" on-upload-callback="onUpload" on-validate-batch="onValidateBatch" on-error-callback="onError" on-submit-callback="onSubmit" on-cancel-callback="onCancel" control="control" params="{'folder_id': parent_folder_id}" ) div(ng-if="type == 'project'", ng-controller="ProjectLinkedFileModalController") div form .form-controls label(for="project-select") Select a Project span(ng-show="state.inFlight.projects") | &nbsp; i.fa.fa-spinner.fa-spin select.form-control( name="project-select" ng-model="data.selectedProjectId" ng-disabled="!shouldEnableProjectSelect()" ) option(value="" disabled selected) - Please Select a Project option( ng-repeat="project in data.projects" value="{{ project._id }}" ) {{ project.name }} small(ng-if="hasNoProjects() && shouldEnableProjectSelect() ") | No other projects found, please create another project first .form-controls.row-spaced-small(ng-if="!state.isOutputFilesMode") label(for="project-entity-select") Select a File span(ng-show="state.inFlight.entities") | &nbsp; i.fa.fa-spinner.fa-spin select.form-control( name="project-entity-select" ng-model="data.selectedProjectEntity" ng-disabled="!shouldEnableProjectEntitySelect()" ) option(value="" disabled selected) - Please Select a File option( ng-repeat="projectEntity in data.projectEntities" value="{{ projectEntity.path }}" ) {{ projectEntity.path.slice(1) }} .form-controls.row-spaced-small(ng-if="state.isOutputFilesMode") label(for="project-entity-select") Select an Output File span(ng-show="state.inFlight.compile") | &nbsp; i.fa.fa-spinner.fa-spin select.form-control( name="project-output-file-select" ng-model="data.selectedProjectOutputFile" ng-disabled="!shouldEnableProjectOutputFileSelect()" ) option(value="" disabled selected) - Please Select an Output File option( ng-repeat="outputFile in data.projectOutputFiles" value="{{ outputFile.path }}" ) {{ outputFile.path }} div.toggle-output-files-button | or&nbsp; a( href="#" ng-click="toggleOutputFilesMode()" ) span(ng-show="state.isOutputFilesMode") select from source files span(ng-show="!state.isOutputFilesMode") select from output files .form-controls.row-spaced-small label(for="name") #{translate("file_name_in_this_project")} input.form-control( type="text" placeholder="example.tex" required ng-model="data.name" name="name" ) div.alert.alert-danger.row-spaced-small(ng-if="error") div(ng-switch="error") span(ng-switch-when="already exists") #{translate("file_already_exists")} span(ng-switch-when="too many files") #{translate("project_has_too_many_files")} span(ng-switch-default) Error, something went wrong! div(ng-if="type == 'url'", ng-controller="UrlLinkedFileModalController") form(novalidate, name="newLinkedFileForm") label(for="url") URL to fetch the file from input.form-control( type="text", placeholder="www.example.com/my_file", required, ng-model="inputs.url", focus-on="open", on-enter="create()", name="url" ) .row-spaced-small label(for="name") #{translate("file_name_in_this_project")} input.form-control( type="text", placeholder="my_file", required, ng-model="inputs.name", ng-change="nameChangedByUser = true" valid-file, on-enter="create()", name="name" ) .text-danger.row-spaced-small(ng-show="newDocForm.name.$error.validFile") | #{translate('files_cannot_include_invalid_characters')} div.alert.alert-danger.row-spaced-small(ng-if="error") div(ng-switch="error") span(ng-switch-when="already exists") #{translate("file_already_exists")} span(ng-switch-when="too many files") #{translate("project_has_too_many_files")} span(ng-switch-default) {{error}} != moduleIncludes("newFileModal:panel", locals) .modal-footer .modal-footer-left.approaching-file-limit(ng-if="file_count > 1900 && file_count < 2000") | #{translate("project_approaching_file_limit")} ({{file_count}}/2000) .alert.alert-warning.at-file-limit(ng-if="file_count >= 2000") | #{translate("project_has_too_many_files")} button.btn.btn-default( ng-disabled="state.inflight" ng-click="cancel()" ) #{translate("cancel")} button.btn.btn-primary( ng-disabled="state.inflight || !state.valid" ng-click="create()" ng-hide="type == 'upload'" ) span(ng-hide="state.inflight") #{translate("create")} span(ng-show="state.inflight") #{translate("creating")}… script(type="text/template", id="qq-file-uploader-template") div.qq-uploader-selector div(qq-hide-dropzone="").qq-upload-drop-area-selector.qq-upload-drop-area span.qq-upload-drop-area-text-selector #{translate('drop_files_here_to_upload')} div Drag here div.row-spaced-small.small #{translate('or')} div.row-spaced-small div.qq-upload-button-selector.btn.btn-primary | Select from your computer ul.qq-upload-list-selector li div.qq-progress-bar-container-selector div( role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" class="qq-progress-bar-selector qq-progress-bar" ) span.qq-upload-file-selector.qq-upload-file span.qq-upload-size-selector.qq-upload-size a(type="button").qq-btn.qq-upload-cancel-selector.qq-upload-cancel #{translate('cancel')} button(type="button").qq-btn.qq-upload-retry-selector.qq-upload-retry #{translate('retry')} span(role="status").qq-upload-status-text-selector.qq-upload-status-text
overleaf/web/app/views/project/editor/new-file-modal.pug/0
{ "file_path": "overleaf/web/app/views/project/editor/new-file-modal.pug", "repo_id": "overleaf", "token_count": 4354 }
531
extends ../../layout block vars - metadata = { viewport: true } block content script(type="template", id="overleaf-token-access-data")!= StringHelper.stringifyJsonForScript({ postUrl: postUrl, csrfToken: csrfToken}) div( ng-controller="TokenAccessPageController", ng-init="post()" ) .editor.full-size div | &nbsp; a(href="/project", style="font-size: 2rem; margin-left: 1rem; color: #ddd;") i.fa.fa-arrow-left .loading-screen( ng-show="mode == 'accessAttempt'" ) .loading-screen-brand-container .loading-screen-brand() h3.loading-screen-label.text-center | #{translate('join_project')} span(ng-show="accessInFlight == true") span.loading-screen-ellip . span.loading-screen-ellip . span.loading-screen-ellip . .global-alerts.text-center(ng-cloak) div(ng-show="accessError", ng-cloak) br div(ng-switch="accessError", ng-cloak) div(ng-switch-when="not_found") h4(aria-live="assertive") | Project not found div(ng-switch-default) .alert.alert-danger(aria-live="assertive") #{translate('token_access_failure')} p a(href="/") #{translate('home')} .loading-screen( ng-show="mode == 'v1Import'" ) .container .row .col-sm-8.col-sm-offset-2 h1.text-center span(ng-if="v1ImportData.status != 'mustLogin'") Overleaf v1 Project span(ng-if="v1ImportData.status == 'mustLogin'") Please Log In img.v2-import__img( src="/img/v1-import/v2-editor.png" alt="The new V2 editor." ) div(ng-if="v1ImportData.status == 'cannotImport'") h2.text-center | Cannot Access Overleaf v1 Project p.text-center.row-spaced-small | Please contact the project owner or | a(href="/contact") contact support | | for assistance. div(ng-if="v1ImportData.status == 'mustLogin'") p.text-center.row-spaced-small | You will need to log in to access this project. .row-spaced.text-center a.btn.btn-primary( href="/login?redir={{ currentPath() }}" ) Log In To Access Project div(ng-if="v1ImportData.status == 'canDownloadZip'") p.text-center.row-spaced.small | #[strong() {{ getProjectName() }}] has not yet been moved into | the new version of Overleaf. This project was created | anonymously and therefore cannot be automatically imported. | Please download a zip file of the project and upload that to | continue editing it. If you would like to delete this project | after you have made a copy, please contact support. .row-spaced.text-center a.btn.btn-primary(ng-href="{{ buildZipDownloadPath(v1ImportData.projectId) }}") | Download project zip file block append foot-scripts script(type="text/javascript", nonce=scriptNonce). $(document).ready(function () { setTimeout(function() { $('.loading-screen-brand').css('height', '20%') }, 500); });
overleaf/web/app/views/project/token/access.pug/0
{ "file_path": "overleaf/web/app/views/project/token/access.pug", "repo_id": "overleaf", "token_count": 1382 }
532
if (personalSubscription.recurly) include ./_personal_subscription_recurly include ./_personal_subscription_recurly_sync_email else include ./_personal_subscription_custom hr
overleaf/web/app/views/subscriptions/dashboard/_personal_subscription.pug/0
{ "file_path": "overleaf/web/app/views/subscriptions/dashboard/_personal_subscription.pug", "repo_id": "overleaf", "token_count": 57 }
533
extends ../layout block vars - metadata = { viewport: true } block content .content.content-alt main.login-register-container#main-content .card.login-register-card .login-register-header h1.login-register-header-heading #{translate("log_out")} form.login-register-form(name="logoutForm", action='/logout', method="POST" ng-init="$scope.inflight=true" auto-submit-form) input(name='_csrf', type='hidden', value=csrfToken) .actions button#submit-logout.btn-primary.btn.btn-block( type='submit', ng-disabled="$scope.inflight" ) span(ng-show="!$scope.inflight") #{translate("log_out")} span(ng-show="$scope.inflight" ng-cloak) #{translate("logging_out")}…
overleaf/web/app/views/user/logout.pug/0
{ "file_path": "overleaf/web/app/views/user/logout.pug", "repo_id": "overleaf", "token_count": 306 }
534
#!/bin/bash set -e # Branding mv app/views/external/robots.txt public/robots.txt mv app/views/external/googlebdb0f8f7f4a17241.html public/googlebdb0f8f7f4a17241.html
overleaf/web/bin/copy_external_pages/0
{ "file_path": "overleaf/web/bin/copy_external_pages", "repo_id": "overleaf", "token_count": 75 }
535
version: "2.3" volumes: data: services: test_unit: build: context: . target: base volumes: - .:/app working_dir: /app environment: BASE_CONFIG: SHARELATEX_CONFIG: MOCHA_GREP: ${MOCHA_GREP} NODE_OPTIONS: "--unhandled-rejections=strict" command: npm run --silent test:unit:app user: node test_acceptance: image: node:12.22.3 volumes: - .:/app working_dir: /app env_file: docker-compose.common.env environment: BASE_CONFIG: SHARELATEX_CONFIG: MOCHA_GREP: ${MOCHA_GREP} MONGO_SERVER_SELECTION_TIMEOUT: 600000 MONGO_SOCKET_TIMEOUT: 300000 # SHARELATEX_ALLOW_ANONYMOUS_READ_AND_WRITE_SHARING: 'true' extra_hosts: - 'www.overleaf.test:127.0.0.1' depends_on: - redis - mongo - saml - ldap command: npm run --silent test:acceptance:app test_karma: build: context: . dockerfile: Dockerfile.frontend volumes: - .:/app environment: NODE_OPTIONS: "--unhandled-rejections=strict" working_dir: /app command: npm run --silent test:karma:single test_frontend: build: context: . target: base volumes: - .:/app working_dir: /app environment: MOCHA_GREP: ${MOCHA_GREP} NODE_OPTIONS: "--unhandled-rejections=strict" command: npm run --silent test:frontend user: node redis: image: redis mongo: image: mongo:4.0.19 ldap: restart: always image: rroemhild/test-openldap:1.1 saml: restart: always image: gcr.io/overleaf-ops/saml-test environment: SAML_BASE_URL_PATH: 'http://saml/simplesaml/' SAML_TEST_SP_ENTITY_ID: 'sharelatex-test-saml' SAML_TEST_SP_LOCATION: 'http://www.overleaf.test:3000/saml/callback'
overleaf/web/docker-compose.yml/0
{ "file_path": "overleaf/web/docker-compose.yml", "repo_id": "overleaf", "token_count": 904 }
536
// TODO: This file was created by bulk-decaffeinate. // Fix any style issues and re-enable lint. /* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import App from '../base' export default App.directive('onEnter', () => (scope, element, attrs) => element.bind('keydown keypress', function (event) { if (event.which === 13) { scope.$apply(() => scope.$eval(attrs.onEnter, { event })) return event.preventDefault() } }) )
overleaf/web/frontend/js/directives/onEnter.js/0
{ "file_path": "overleaf/web/frontend/js/directives/onEnter.js", "repo_id": "overleaf", "token_count": 192 }
537
import PropTypes from 'prop-types' import { Trans } from 'react-i18next' import { Modal, Alert, Button, ControlLabel, FormControl, FormGroup, } from 'react-bootstrap' import AccessibleModal from '../../../shared/components/accessible-modal' export default function CloneProjectModalContent({ animation = true, show, cancel, handleSubmit, clonedProjectName, setClonedProjectName, error, inFlight, valid, }) { return ( <AccessibleModal animation={animation} show={show} onHide={cancel} id="clone-project-modal" > <Modal.Header closeButton> <Modal.Title> <Trans i18nKey="copy_project" /> </Modal.Title> </Modal.Header> <Modal.Body> <form id="clone-project-form" onSubmit={handleSubmit}> <FormGroup> <ControlLabel htmlFor="clone-project-form-name"> <Trans i18nKey="new_name" /> </ControlLabel> <FormControl id="clone-project-form-name" type="text" placeholder="New Project Name" required value={clonedProjectName} onChange={event => setClonedProjectName(event.target.value)} /> </FormGroup> </form> {error && ( <Alert bsStyle="danger"> {error.length ? ( error ) : ( <Trans i18nKey="generic_something_went_wrong" /> )} </Alert> )} </Modal.Body> <Modal.Footer> <Button type="button" disabled={inFlight} onClick={cancel}> <Trans i18nKey="cancel" /> </Button> <Button form="clone-project-form" type="submit" bsStyle="primary" disabled={inFlight || !valid} > {inFlight ? ( <> <Trans i18nKey="copying" />… </> ) : ( <Trans i18nKey="copy" /> )} </Button> </Modal.Footer> </AccessibleModal> ) } CloneProjectModalContent.propTypes = { animation: PropTypes.bool, show: PropTypes.bool.isRequired, cancel: PropTypes.func.isRequired, handleSubmit: PropTypes.func.isRequired, clonedProjectName: PropTypes.string, setClonedProjectName: PropTypes.func.isRequired, error: PropTypes.oneOfType([PropTypes.bool, PropTypes.string]), inFlight: PropTypes.bool.isRequired, valid: PropTypes.bool.isRequired, }
overleaf/web/frontend/js/features/clone-project-modal/components/clone-project-modal-content.js/0
{ "file_path": "overleaf/web/frontend/js/features/clone-project-modal/components/clone-project-modal-content.js", "repo_id": "overleaf", "token_count": 1190 }
538
import App from '../../../base' import { react2angular } from 'react2angular' import EditorNavigationToolbarRoot from '../components/editor-navigation-toolbar-root' import { rootContext } from '../../../shared/context/root-context' App.controller('EditorNavigationToolbarController', function ($scope, ide) { // wrapper is required to avoid scope problems with `this` inside `EditorManager` $scope.openDoc = (doc, args) => ide.editorManager.openDoc(doc, args) }) App.component( 'editorNavigationToolbarRoot', react2angular(rootContext.use(EditorNavigationToolbarRoot), [ 'openDoc', // `$scope.onlineUsersArray` is already populated by `OnlineUsersManager`, which also creates // a new array instance every time the list of online users change (which should refresh the // value passed to React as a prop, triggering a re-render) 'onlineUsersArray', // We're still including ShareController as part fo the React navigation toolbar. The reason is // the coupling between ShareController's $scope and Angular's ShareProjectModal. Once ShareProjectModal // is fully ported to React we should be able to repli 'openShareProjectModal', ]) )
overleaf/web/frontend/js/features/editor-navigation-toolbar/controllers/editor-navigation-toolbar-controller.js/0
{ "file_path": "overleaf/web/frontend/js/features/editor-navigation-toolbar/controllers/editor-navigation-toolbar-controller.js", "repo_id": "overleaf", "token_count": 332 }
539
import { Button } from 'react-bootstrap' import { useTranslation } from 'react-i18next' function FileTreeError() { const { t } = useTranslation() function reload() { location.reload() } return ( <div className="file-tree-error"> <p>{t('generic_something_went_wrong')}</p> <p>{t('please_refresh')}</p> <Button bsStyle="primary" onClick={reload}> {t('refresh')} </Button> </div> ) } export default FileTreeError
overleaf/web/frontend/js/features/file-tree/components/file-tree-error.js/0
{ "file_path": "overleaf/web/frontend/js/features/file-tree/components/file-tree-error.js", "repo_id": "overleaf", "token_count": 190 }
540
import { useRef, useEffect, useState } from 'react' import PropTypes from 'prop-types' import { useTranslation } from 'react-i18next' import { DndProvider, createDndContext, useDrag, useDrop } from 'react-dnd' import { HTML5Backend, getEmptyImage } from 'react-dnd-html5-backend' import { findAllInTreeOrThrow, findAllFolderIdsInFolders, } from '../util/find-in-tree' import { useFileTreeActionable } from './file-tree-actionable' import { useFileTreeMutable } from './file-tree-mutable' import { useFileTreeSelectable } from '../contexts/file-tree-selectable' import { useFileTreeMainContext } from './file-tree-main' // HACK ALERT // DnD binds drag and drop events on window and stop propagation if the dragged // item is not a DnD element. This break other drag and drop interfaces; in // particular in rich text. // This is a hacky workaround to avoid calling the DnD listeners when the // draggable or droppable element is not within a `dnd-container` element. const ModifiedBackend = (...args) => { function isDndChild(elt) { if (elt.getAttribute && elt.getAttribute('dnd-container')) return true if (!elt.parentNode) return false return isDndChild(elt.parentNode) } const instance = new HTML5Backend(...args) const dragDropListeners = [ 'handleTopDragStart', 'handleTopDragStartCapture', 'handleTopDragEndCapture', 'handleTopDragEnter', 'handleTopDragEnterCapture', 'handleTopDragLeaveCapture', 'handleTopDragOver', 'handleTopDragOverCapture', 'handleTopDrop', 'handleTopDropCapture', ] dragDropListeners.forEach(dragDropListener => { const originalListener = instance[dragDropListener] instance[dragDropListener] = (ev, ...extraArgs) => { if (isDndChild(ev.target)) originalListener(ev, ...extraArgs) } }) return instance } const DndContext = createDndContext(ModifiedBackend) const DRAGGABLE_TYPE = 'ENTITY' export function FileTreeDraggableProvider({ children }) { const DndManager = useRef(DndContext) return ( <DndProvider manager={DndManager.current.dragDropManager}> {children} </DndProvider> ) } FileTreeDraggableProvider.propTypes = { children: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.node), PropTypes.node, ]).isRequired, } export function useDraggable(draggedEntityId) { const { t } = useTranslation() const { hasWritePermissions } = useFileTreeMainContext() const { fileTreeData } = useFileTreeMutable() const { selectedEntityIds } = useFileTreeSelectable() const [isDraggable, setIsDraggable] = useState(hasWritePermissions) const item = { type: DRAGGABLE_TYPE } const [{ isDragging }, dragRef, preview] = useDrag({ item, // required, but overwritten by the return value of `begin` begin: () => { const draggedEntityIds = getDraggedEntityIds( selectedEntityIds, draggedEntityId ) const draggedItems = findAllInTreeOrThrow(fileTreeData, draggedEntityIds) const title = getDraggedTitle(draggedItems, t) const forbiddenFolderIds = getForbiddenFolderIds(draggedItems) return { ...item, title, forbiddenFolderIds, draggedEntityIds } }, collect: monitor => ({ isDragging: !!monitor.isDragging(), }), canDrag: () => isDraggable, }) // remove the automatic preview as we're using a custom preview via // FileTreeDraggablePreviewLayer useEffect(() => { preview(getEmptyImage()) }, [preview]) return { dragRef, isDragging, setIsDraggable, } } export function useDroppable(droppedEntityId) { const { finishMoving } = useFileTreeActionable() const [{ isOver }, dropRef] = useDrop({ accept: DRAGGABLE_TYPE, canDrop: (item, monitor) => { const isOver = monitor.isOver({ shallow: true }) if (!isOver) return false if (item.forbiddenFolderIds.has(droppedEntityId)) return false return true }, drop: (item, monitor) => { const didDropInChild = monitor.didDrop() if (didDropInChild) return finishMoving(droppedEntityId, item.draggedEntityIds) }, collect: monitor => ({ isOver: monitor.canDrop(), }), }) return { dropRef, isOver, } } // Get the list of dragged entity ids. If the dragged entity is one of the // selected entities then all the selected entites are dragged entities, // otherwise it's the dragged entity only. function getDraggedEntityIds(selectedEntityIds, draggedEntityId) { if (selectedEntityIds.size > 1 && selectedEntityIds.has(draggedEntityId)) { // dragging the multi-selected entities return new Set(selectedEntityIds) } else { // not dragging the selection; only the current item return new Set([draggedEntityId]) } } // Get the draggable title. This is the name of the dragged entities if there's // only one, otherwise it's the number of dragged entities. function getDraggedTitle(draggedItems, t) { if (draggedItems.size === 1) { const draggedItem = Array.from(draggedItems)[0] return draggedItem.entity.name } return t('n_items', { count: draggedItems.size }) } // Get all children folder ids of any of the dragged items. function getForbiddenFolderIds(draggedItems) { const draggedFoldersArray = Array.from(draggedItems) .filter(draggedItem => { return draggedItem.type === 'folder' }) .map(draggedItem => draggedItem.entity) const draggedFolders = new Set(draggedFoldersArray) return findAllFolderIdsInFolders(draggedFolders) }
overleaf/web/frontend/js/features/file-tree/contexts/file-tree-draggable.js/0
{ "file_path": "overleaf/web/frontend/js/features/file-tree/contexts/file-tree-draggable.js", "repo_id": "overleaf", "token_count": 1868 }
541
// This file is shared between the frontend and server code of web, so that // filename validation is the same in both implementations. // The logic in all copies must be kept in sync: // app/src/Features/Project/SafePath.js // frontend/js/ide/directives/SafePath.js // frontend/js/features/file-tree/util/safe-path.js // eslint-disable-next-line prefer-regex-literals const BADCHAR_RX = new RegExp( `\ [\ \\/\ \\\\\ \\*\ \\u0000-\\u001F\ \\u007F\ \\u0080-\\u009F\ \\uD800-\\uDFFF\ ]\ `, 'g' ) // eslint-disable-next-line prefer-regex-literals const BADFILE_RX = new RegExp( `\ (^\\.$)\ |(^\\.\\.$)\ |(^\\s+)\ |(\\s+$)\ `, 'g' ) // Put a block on filenames which match javascript property names, as they // can cause exceptions where the code puts filenames into a hash. This is a // temporary workaround until the code in other places is made safe against // property names. // // The list of property names is taken from // ['prototype'].concat(Object.getOwnPropertyNames(Object.prototype)) // eslint-disable-next-line prefer-regex-literals const BLOCKEDFILE_RX = new RegExp(`\ ^(\ prototype\ |constructor\ |toString\ |toLocaleString\ |valueOf\ |hasOwnProperty\ |isPrototypeOf\ |propertyIsEnumerable\ |__defineGetter__\ |__lookupGetter__\ |__defineSetter__\ |__lookupSetter__\ |__proto__\ )$\ `) const MAX_PATH = 1024 // Maximum path length, in characters. This is fairly arbitrary. export function clean(filename) { filename = filename.replace(BADCHAR_RX, '_') // for BADFILE_RX replace any matches with an equal number of underscores filename = filename.replace(BADFILE_RX, match => new Array(match.length + 1).join('_') ) // replace blocked filenames 'prototype' with '@prototype' filename = filename.replace(BLOCKEDFILE_RX, '@$1') return filename } export function isCleanFilename(filename) { return ( isAllowedLength(filename) && !filename.match(BADCHAR_RX) && !filename.match(BADFILE_RX) ) } export function isBlockedFilename(filename) { return BLOCKEDFILE_RX.test(filename) } // returns whether a full path is 'clean' - e.g. is a full or relative path // that points to a file, and each element passes the rules in 'isCleanFilename' export function isCleanPath(path) { const elements = path.split('/') const lastElementIsEmpty = elements[elements.length - 1].length === 0 if (lastElementIsEmpty) { return false } for (const element of Array.from(elements)) { if (element.length > 0 && !isCleanFilename(element)) { return false } } // check for a top-level reserved name if (BLOCKEDFILE_RX.test(path.replace(/^\/?/, ''))) { return false } // remove leading slash if present return true } export function isAllowedLength(pathname) { return pathname.length > 0 && pathname.length <= MAX_PATH }
overleaf/web/frontend/js/features/file-tree/util/safe-path.js/0
{ "file_path": "overleaf/web/frontend/js/features/file-tree/util/safe-path.js", "repo_id": "overleaf", "token_count": 976 }
542
import PropTypes from 'prop-types' import { Dropdown, OverlayTrigger, Tooltip } from 'react-bootstrap' import { useTranslation } from 'react-i18next' import PreviewDownloadFileList from './preview-download-file-list' import Icon from '../../../shared/components/icon' import ControlledDropdown from '../../../shared/components/controlled-dropdown' function PreviewDownloadButton({ isCompiling, outputFiles, pdfDownloadUrl, showText, }) { const { t } = useTranslation() let textStyle = {} if (!showText) { textStyle = { position: 'absolute', right: '-100vw', } } const pdfDownloadDisabled = isCompiling || !pdfDownloadUrl const buttonElement = ( <a className="btn btn-xs btn-info" disabled={pdfDownloadDisabled} download href={pdfDownloadUrl || '#'} style={{ pointerEvents: 'auto' }} > <Icon type="download" modifier="fw" /> <span className="toolbar-text" style={textStyle}> {t('download_pdf')} </span> </a> ) const hideTooltip = showText && pdfDownloadUrl return ( <ControlledDropdown id="download-dropdown" className="toolbar-item" disabled={isCompiling} > {hideTooltip ? ( buttonElement ) : ( <OverlayTrigger placement="bottom" overlay={ <Tooltip id="tooltip-download-pdf"> {pdfDownloadDisabled ? t('please_compile_pdf_before_download') : t('download_pdf')} </Tooltip> } > {buttonElement} </OverlayTrigger> )} <Dropdown.Toggle className="btn btn-xs btn-info dropdown-toggle" aria-label={t('toggle_output_files_list')} bsStyle="info" /> <Dropdown.Menu id="download-dropdown-list"> <PreviewDownloadFileList fileList={outputFiles} /> </Dropdown.Menu> </ControlledDropdown> ) } PreviewDownloadButton.propTypes = { isCompiling: PropTypes.bool.isRequired, outputFiles: PropTypes.array, pdfDownloadUrl: PropTypes.string, showText: PropTypes.bool.isRequired, } export default PreviewDownloadButton
overleaf/web/frontend/js/features/preview/components/preview-download-button.js/0
{ "file_path": "overleaf/web/frontend/js/features/preview/components/preview-download-button.js", "repo_id": "overleaf", "token_count": 897 }
543
import PropTypes from 'prop-types' import { Trans } from 'react-i18next' export default function MemberPrivileges({ privileges }) { switch (privileges) { case 'readAndWrite': return <Trans i18nKey="can_edit" /> case 'readOnly': return <Trans i18nKey="read_only" /> default: return null } } MemberPrivileges.propTypes = { privileges: PropTypes.string.isRequired, }
overleaf/web/frontend/js/features/share-project-modal/components/member-privileges.js/0
{ "file_path": "overleaf/web/frontend/js/features/share-project-modal/components/member-privileges.js", "repo_id": "overleaf", "token_count": 145 }
544
import { Tabs } from '@reach/tabs' import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { useTranslation } from 'react-i18next' import PropTypes from 'prop-types' import { matchSorter } from 'match-sorter' import symbols from '../data/symbols.json' import { buildCategorisedSymbols, createCategories } from '../utils/categories' import SymbolPaletteSearch from './symbol-palette-search' import SymbolPaletteBody from './symbol-palette-body' import SymbolPaletteTabs from './symbol-palette-tabs' // import SymbolPaletteInfoLink from './symbol-palette-info-link' import BetaBadge from '../../../shared/components/beta-badge' import '@reach/tabs/styles.css' export default function SymbolPaletteContent({ handleSelect }) { const [input, setInput] = useState('') const { t } = useTranslation() // build the list of categories with translated labels const categories = useMemo(() => createCategories(t), [t]) // group the symbols by category const categorisedSymbols = useMemo( () => buildCategorisedSymbols(categories), [categories] ) // select symbols which match the input const filteredSymbols = useMemo(() => { if (input === '') { return null } const words = input.trim().split(/\s+/) return words.reduceRight( (symbols, word) => matchSorter(symbols, word, { keys: ['command', 'description', 'character', 'aliases'], threshold: matchSorter.rankings.CONTAINS, }), symbols ) }, [input]) const inputRef = useRef(null) // allow the input to be focused const focusInput = useCallback(() => { if (inputRef.current) { inputRef.current.focus() } }, []) // focus the input when the symbol palette is opened useEffect(() => { if (inputRef.current) { inputRef.current.focus() } }, []) return ( <Tabs className="symbol-palette-container"> <div className="symbol-palette"> <div className="symbol-palette-header"> {input.length <= 0 ? ( <SymbolPaletteTabs categories={categories} /> ) : ( <div className="symbol-palette-search-hint"> {t('showing_symbol_search_results', { search: input })} </div> )} <div className="symbol-palette-header-group"> <BetaBadge tooltip={{ id: 'tooltip-symbol-palette-beta', text: 'The Symbol Palette is a beta feature. Click here to give feedback.', placement: 'top', }} url="https://forms.gle/BybHV5svGE8rJ6Ki9" /> {/* NOTE: replace the beta badge with this info link when rolling out to all users */} {/* <SymbolPaletteInfoLink /> */} <SymbolPaletteSearch setInput={setInput} inputRef={inputRef} /> </div> </div> <div className="symbol-palette-body"> <SymbolPaletteBody categories={categories} categorisedSymbols={categorisedSymbols} filteredSymbols={filteredSymbols} handleSelect={handleSelect} focusInput={focusInput} /> </div> </div> </Tabs> ) } SymbolPaletteContent.propTypes = { handleSelect: PropTypes.func.isRequired, }
overleaf/web/frontend/js/features/symbol-palette/components/symbol-palette-content.js/0
{ "file_path": "overleaf/web/frontend/js/features/symbol-palette/components/symbol-palette-content.js", "repo_id": "overleaf", "token_count": 1401 }
545
import i18n from 'i18next' import { initReactI18next } from 'react-i18next' const LANG = window.i18n.currentLangCode // Since we are rendering React from Angular, the initialisation is // synchronous on page load (but hidden behind the loading screen). This // means that translations must be initialised without any actual // translation strings, and load those manually ourselves later i18n.use(initReactI18next).init({ lng: LANG, react: { // Since we are manually waiting on the translations data to // load, we don't need to use Suspense useSuspense: false, // Trigger a re-render when a language is added. Since we load the // translation strings asynchronously, we need to trigger a re-render once // they've loaded bindI18nStore: 'added', }, interpolation: { // We use the legacy v1 JSON format, so configure interpolator to use // underscores instead of curly braces prefix: '__', suffix: '__', unescapeSuffix: 'HTML', // Disable nesting in interpolated values, preventing user input // injection via another nested value skipOnVariables: true, defaultVariables: { appName: window.ExposedSettings.appName, }, }, }) // The webpackChunkName here will name this chunk (and thus the requested // script) according to the file name. See https://webpack.js.org/api/module-methods/#magic-comments // for details const localesPromise = import( /* webpackChunkName: "[request]" */ `../../locales/${LANG}.json` ).then(lang => { i18n.addResourceBundle(LANG, 'translation', lang) }) export default localesPromise
overleaf/web/frontend/js/i18n.js/0
{ "file_path": "overleaf/web/frontend/js/i18n.js", "repo_id": "overleaf", "token_count": 497 }
546
/* eslint-disable max-len, no-return-assign, */ // TODO: This file was created by bulk-decaffeinate. // Fix any style issues and re-enable lint. /* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ // This file is shared between the frontend and server code of web, so that // filename validation is the same in both implementations. // The logic in all copies must be kept in sync: // app/src/Features/Project/SafePath.js // frontend/js/ide/directives/SafePath.js // frontend/js/features/file-tree/util/safe-path.js let SafePath // eslint-disable-next-line prefer-regex-literals const BADCHAR_RX = new RegExp( `\ [\ \\/\ \\\\\ \\*\ \\u0000-\\u001F\ \\u007F\ \\u0080-\\u009F\ \\uD800-\\uDFFF\ ]\ `, 'g' ) // eslint-disable-next-line prefer-regex-literals const BADFILE_RX = new RegExp( `\ (^\\.$)\ |(^\\.\\.$)\ |(^\\s+)\ |(\\s+$)\ `, 'g' ) // Put a block on filenames which match javascript property names, as they // can cause exceptions where the code puts filenames into a hash. This is a // temporary workaround until the code in other places is made safe against // property names. // // The list of property names is taken from // ['prototype'].concat(Object.getOwnPropertyNames(Object.prototype)) // eslint-disable-next-line prefer-regex-literals const BLOCKEDFILE_RX = new RegExp(`\ ^(\ prototype\ |constructor\ |toString\ |toLocaleString\ |valueOf\ |hasOwnProperty\ |isPrototypeOf\ |propertyIsEnumerable\ |__defineGetter__\ |__lookupGetter__\ |__defineSetter__\ |__lookupSetter__\ |__proto__\ )$\ `) const MAX_PATH = 1024 // Maximum path length, in characters. This is fairly arbitrary. export default SafePath = { clean(filename) { filename = filename.replace(BADCHAR_RX, '_') // for BADFILE_RX replace any matches with an equal number of underscores filename = filename.replace(BADFILE_RX, match => new Array(match.length + 1).join('_') ) // replace blocked filenames 'prototype' with '@prototype' filename = filename.replace(BLOCKEDFILE_RX, '@$1') return filename }, isCleanFilename(filename) { return ( SafePath.isAllowedLength(filename) && !filename.match(BADCHAR_RX) && !filename.match(BADFILE_RX) ) }, isAllowedLength(pathname) { return pathname.length > 0 && pathname.length <= MAX_PATH }, }
overleaf/web/frontend/js/ide/directives/SafePath.js/0
{ "file_path": "overleaf/web/frontend/js/ide/directives/SafePath.js", "repo_id": "overleaf", "token_count": 901 }
547
// TODO: This file was created by bulk-decaffeinate. // Fix any style issues and re-enable lint. const envs = [ 'abstract', 'align', 'align*', 'equation', 'equation*', 'gather', 'gather*', 'multline', 'multline*', 'split', 'verbatim', 'quote', 'center', ] const envsWithSnippets = [ 'array', 'figure', 'tabular', 'table', 'list', 'enumerate', 'itemize', 'frame', 'thebibliography', ] export default { all: envs.concat(envsWithSnippets), withoutSnippets: envs, }
overleaf/web/frontend/js/ide/editor/directives/aceEditor/auto-complete/snippets/Environments.js/0
{ "file_path": "overleaf/web/frontend/js/ide/editor/directives/aceEditor/auto-complete/snippets/Environments.js", "repo_id": "overleaf", "token_count": 213 }
548
import App from '../../../base' export default App.controller( 'FileTreeFolderController', function ($scope, ide, $modal, localStorage) { $scope.expanded = localStorage(`folder.${$scope.entity.id}.expanded`) || false $scope.toggleExpanded = function () { $scope.expanded = !$scope.expanded $scope._storeCurrentStateInLocalStorage() } $scope.$on('entity-file:selected', function () { $scope.expanded = true $scope._storeCurrentStateInLocalStorage() }) $scope._storeCurrentStateInLocalStorage = function () { localStorage(`folder.${$scope.entity.id}.expanded`, $scope.expanded) } } )
overleaf/web/frontend/js/ide/file-tree/controllers/FileTreeFolderController.js/0
{ "file_path": "overleaf/web/frontend/js/ide/file-tree/controllers/FileTreeFolderController.js", "repo_id": "overleaf", "token_count": 239 }
549
import _ from 'lodash' /* eslint-disable camelcase, max-len, no-return-assign, */ // TODO: This file was created by bulk-decaffeinate. // Fix any style issues and re-enable lint. /* * decaffeinate suggestions: * DS101: Remove unnecessary use of Array.from * DS102: Remove unnecessary code created because of implicit returns * DS205: Consider reworking code to avoid use of IIFEs * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import App from '../../../base' import displayNameForUser from '../util/displayNameForUser' App.controller('HistoryListController', function ($scope, $modal, ide) { $scope.hoveringOverListSelectors = false $scope.projectUsers = [] $scope.$watch('project.members', function (newVal) { if (newVal != null) { return ($scope.projectUsers = newVal.concat($scope.project.owner)) } }) // This method (and maybe the one below) will be removed soon. User details data will be // injected into the history API responses, so we won't need to fetch user data from other // local data structures. const _getUserById = id => _.find($scope.projectUsers, function (user) { const curUserId = (user != null ? user._id : undefined) || (user != null ? user.id : undefined) return curUserId === id }) $scope.getDisplayNameById = id => displayNameForUser(_getUserById(id)) $scope.deleteLabel = labelDetails => $modal.open({ templateUrl: 'historyV2DeleteLabelModalTemplate', controller: 'HistoryV2DeleteLabelModalController', resolve: { labelDetails() { return labelDetails }, }, }) $scope.loadMore = () => { return ide.historyManager.fetchNextBatchOfUpdates() } $scope.recalculateSelectedUpdates = function () { let beforeSelection = true let afterSelection = false $scope.history.selection.updates = [] return (() => { const result = [] for (const update of Array.from($scope.history.updates)) { var inSelection if (update.selectedTo) { inSelection = true beforeSelection = false } update.beforeSelection = beforeSelection update.inSelection = inSelection update.afterSelection = afterSelection if (inSelection) { $scope.history.selection.updates.push(update) } if (update.selectedFrom) { inSelection = false result.push((afterSelection = true)) } else { result.push(undefined) } } return result })() } $scope.recalculateHoveredUpdates = function () { let inHoverSelection let hoverSelectedFrom = false let hoverSelectedTo = false for (var update of Array.from($scope.history.updates)) { // Figure out whether the to or from selector is hovered over if (update.hoverSelectedFrom) { hoverSelectedFrom = true } if (update.hoverSelectedTo) { hoverSelectedTo = true } } if (hoverSelectedFrom) { // We want to 'hover select' everything between hoverSelectedFrom and selectedTo inHoverSelection = false for (update of Array.from($scope.history.updates)) { if (update.selectedTo) { update.hoverSelectedTo = true inHoverSelection = true } update.inHoverSelection = inHoverSelection if (update.hoverSelectedFrom) { inHoverSelection = false } } } if (hoverSelectedTo) { // We want to 'hover select' everything between hoverSelectedTo and selectedFrom inHoverSelection = false return (() => { const result = [] for (update of Array.from($scope.history.updates)) { if (update.hoverSelectedTo) { inHoverSelection = true } update.inHoverSelection = inHoverSelection if (update.selectedFrom) { update.hoverSelectedFrom = true result.push((inHoverSelection = false)) } else { result.push(undefined) } } return result })() } } $scope.resetHoverState = () => (() => { const result = [] for (const update of Array.from($scope.history.updates)) { delete update.hoverSelectedFrom delete update.hoverSelectedTo result.push(delete update.inHoverSelection) } return result })() return $scope.$watch('history.updates.length', () => $scope.recalculateSelectedUpdates() ) }) export default App.controller( 'HistoryListItemController', function ($scope, eventTracking) { $scope.$watch( 'update.selectedFrom', function (selectedFrom, oldSelectedFrom) { if (selectedFrom) { for (const update of Array.from($scope.history.updates)) { if (update !== $scope.update) { update.selectedFrom = false } } return $scope.recalculateSelectedUpdates() } } ) $scope.$watch('update.selectedTo', function (selectedTo, oldSelectedTo) { if (selectedTo) { for (const update of Array.from($scope.history.updates)) { if (update !== $scope.update) { update.selectedTo = false } } return $scope.recalculateSelectedUpdates() } }) $scope.select = function () { eventTracking.sendMB('history-view-change') $scope.update.selectedTo = true return ($scope.update.selectedFrom = true) } $scope.mouseOverSelectedFrom = function () { $scope.history.hoveringOverListSelectors = true $scope.update.hoverSelectedFrom = true return $scope.recalculateHoveredUpdates() } $scope.mouseOutSelectedFrom = function () { $scope.history.hoveringOverListSelectors = false return $scope.resetHoverState() } $scope.mouseOverSelectedTo = function () { $scope.history.hoveringOverListSelectors = true $scope.update.hoverSelectedTo = true return $scope.recalculateHoveredUpdates() } $scope.mouseOutSelectedTo = function () { $scope.history.hoveringOverListSelectors = false return $scope.resetHoverState() } return ($scope.displayName = displayNameForUser) } )
overleaf/web/frontend/js/ide/history/controllers/HistoryListController.js/0
{ "file_path": "overleaf/web/frontend/js/ide/history/controllers/HistoryListController.js", "repo_id": "overleaf", "token_count": 2550 }
550
import _ from 'lodash' /* eslint-disable no-return-assign, */ // TODO: This file was created by bulk-decaffeinate. // Fix any style issues and re-enable lint. /* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * DS205: Consider reworking code to avoid use of IIFEs * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import App from '../../../base' export default App.factory('metadata', function ($http, ide) { const debouncer = {} // DocId => Timeout const state = { documents: {} } const metadata = { state } metadata.onBroadcastDocMeta = function (data) { if (data.docId != null && data.meta != null) { return (state.documents[data.docId] = data.meta) } } metadata.onEntityDeleted = function (e, entity) { if (entity.type === 'doc') { return delete state.documents[entity.id] } } metadata.onFileUploadComplete = function (e, upload) { if (upload.entity_type === 'doc') { return metadata.loadDocMetaFromServer(upload.entity_id) } } metadata.getAllLabels = () => _.flattenDeep( (() => { const result = [] for (const docId in state.documents) { const meta = state.documents[docId] result.push(meta.labels) } return result })() ) metadata.getAllPackages = function () { const packageCommandMapping = {} for (const _docId in state.documents) { const meta = state.documents[_docId] for (const packageName in meta.packages) { const commandSnippets = meta.packages[packageName] packageCommandMapping[packageName] = commandSnippets } } return packageCommandMapping } metadata.loadProjectMetaFromServer = () => $http .get(`/project/${window.project_id}/metadata`) .then(function (response) { const { data } = response if (data.projectMeta) { return (() => { const result = [] for (const docId in data.projectMeta) { const docMeta = data.projectMeta[docId] result.push((state.documents[docId] = docMeta)) } return result })() } }) metadata.loadDocMetaFromServer = docId => $http .post(`/project/${window.project_id}/doc/${docId}/metadata`, { // Don't broadcast metadata when there are no other users in the // project. broadcast: ide.$scope.onlineUsersCount > 0, _csrf: window.csrfToken, }) .then(function (response) { const { data } = response // handle the POST response like a broadcast event when there are no // other users in the project. metadata.onBroadcastDocMeta(data) }) metadata.scheduleLoadDocMetaFromServer = function (docId) { if (ide.$scope.permissionsLevel === 'readOnly') { // The POST request is blocked for users without write permission. // The user will not be able to consume the meta data for edits anyways. return } // De-bounce loading labels with a timeout const existingTimeout = debouncer[docId] if (existingTimeout != null) { clearTimeout(existingTimeout) delete debouncer[docId] } return (debouncer[docId] = setTimeout(() => { metadata.loadDocMetaFromServer(docId) return delete debouncer[docId] }, 1000)) } return metadata })
overleaf/web/frontend/js/ide/metadata/services/metadata.js/0
{ "file_path": "overleaf/web/frontend/js/ide/metadata/services/metadata.js", "repo_id": "overleaf", "token_count": 1353 }
551
import { captureException } from '../../../infrastructure/error-reporter' const OError = require('@overleaf/o-error') let pendingWorkerSetup = Promise.resolve() function supportsServiceWorker() { return 'serviceWorker' in navigator } export function waitForServiceWorker() { return pendingWorkerSetup } export function loadServiceWorker(options) { if (supportsServiceWorker()) { const workerSetup = navigator.serviceWorker .register('/serviceWorker.js', { scope: '/project/', }) .then(() => { navigator.serviceWorker.addEventListener('message', event => { let ctx try { ctx = JSON.parse(event.data) } catch (e) { return } if (!ctx || !ctx.error || !ctx.extra) return const err = OError.tag(ctx.error, 'Error in serviceWorker') const fullError = new Error() fullError.name = err.name fullError.message = err.message fullError.stack = OError.getFullStack(err) captureException(fullError, { extra: ctx.extra }) }) }) .catch(error => captureException(OError.tag(error, 'Cannot register serviceWorker')) ) if (options && options.timeout > 0) { const workerTimeout = new Promise(resolve => { setTimeout(resolve, options.timeout) }) pendingWorkerSetup = Promise.race([workerSetup, workerTimeout]) } else { pendingWorkerSetup = workerSetup } } } export function unregisterServiceWorker() { if (supportsServiceWorker()) { if (navigator.serviceWorker.controller) { navigator.serviceWorker.controller.postMessage({ type: 'disable', }) } navigator.serviceWorker.getRegistrations().then(registrations => { registrations.forEach(worker => { worker.unregister() }) }) } }
overleaf/web/frontend/js/ide/pdfng/directives/serviceWorkerManager.js/0
{ "file_path": "overleaf/web/frontend/js/ide/pdfng/directives/serviceWorkerManager.js", "repo_id": "overleaf", "token_count": 760 }
552
/* eslint-disable max-len, */ // TODO: This file was created by bulk-decaffeinate. // Fix any style issues and re-enable lint. /* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import App from '../../../base' export default App.directive('reviewPanelCollapseHeight', $parse => ({ restrict: 'A', link(scope, element, attrs) { return scope.$watch( () => $parse(attrs.reviewPanelCollapseHeight)(scope), function (shouldCollapse) { const neededHeight = element.prop('scrollHeight') if (neededHeight > 0) { if (shouldCollapse) { return element.animate({ height: 0 }, 150) } else { return element.animate({ height: neededHeight }, 150) } } else { if (shouldCollapse) { return element.height(0) } } } ) }, }))
overleaf/web/frontend/js/ide/review-panel/directives/reviewPanelCollapseHeight.js/0
{ "file_path": "overleaf/web/frontend/js/ide/review-panel/directives/reviewPanelCollapseHeight.js", "repo_id": "overleaf", "token_count": 400 }
553
/** * localStorage can throw browser exceptions, for example if it is full We don't * use localStorage for anything critical, so in that case just fail gracefully. */ /** * Catch, log and otherwise ignore errors. * * @param {function} fn localStorage function to call * @param {string?} key Key passed to the localStorage function (if any) * @param {any?} value Value passed to the localStorage function (if any) */ const callSafe = function (fn, key, value) { try { return fn(key, value) } catch (e) { console.error('localStorage exception', e) return null } } const getItem = function (key) { return JSON.parse(localStorage.getItem(key)) } const setItem = function (key, value) { localStorage.setItem(key, JSON.stringify(value)) } const clear = function () { localStorage.clear() } const removeItem = function (key) { return localStorage.removeItem(key) } const customLocalStorage = { getItem: key => callSafe(getItem, key), setItem: (key, value) => callSafe(setItem, key, value), clear: () => callSafe(clear), removeItem: key => callSafe(removeItem, key), } export default customLocalStorage
overleaf/web/frontend/js/infrastructure/local-storage.js/0
{ "file_path": "overleaf/web/frontend/js/infrastructure/local-storage.js", "repo_id": "overleaf", "token_count": 352 }
554
/* eslint-disable max-len, no-return-assign, */ // TODO: This file was created by bulk-decaffeinate. // Fix any style issues and re-enable lint. /* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import App from '../base' import getMeta from '../utils/meta' export default App.controller( 'ClearSessionsController', function ($scope, $http) { $scope.state = { otherSessions: getMeta('ol-otherSessions'), error: false, success: false, } return ($scope.clearSessions = function () { console.log('>> clearing all sessions') return $http({ method: 'POST', url: '/user/sessions/clear', headers: { 'X-CSRF-Token': window.csrfToken }, }) .then(function () { $scope.state.otherSessions = [] $scope.state.error = false return ($scope.state.success = true) }) .catch(() => ($scope.state.error = true)) }) } )
overleaf/web/frontend/js/main/clear-sessions.js/0
{ "file_path": "overleaf/web/frontend/js/main/clear-sessions.js", "repo_id": "overleaf", "token_count": 426 }
555
import App from '../../base' import ColorManager from '../../ide/colors/ColorManager' App.controller('TagListController', function ($scope, $modal) { $scope.filterProjects = function (filter = 'all') { $scope._clearTags() $scope.setFilter(filter) } $scope._clearTags = () => $scope.tags.forEach(tag => { tag.selected = false }) $scope.selectTag = function (tag) { $scope._clearTags() tag.selected = true $scope.setFilter('tag') } $scope.selectUntagged = function () { $scope._clearTags() $scope.setFilter('untagged') } $scope.countProjectsForTag = function (tag) { return tag.project_ids.reduce((acc, projectId) => { const project = $scope.getProjectById(projectId) // There is a bug where the tag is not cleaned up when you leave a // project, so tag.project_ids can contain a project that the user can // no longer access. If the project cannot be found, ignore it if (!project) return acc // Ignore archived projects as they are not shown in the filter if (!(project.archived || project.trashed)) { return acc + 1 } else { return acc } }, 0) } $scope.getHueForTagId = tagId => ColorManager.getHueForTagId(tagId) $scope.deleteTag = function (tag) { const modalInstance = $modal.open({ templateUrl: 'deleteTagModalTemplate', controller: 'DeleteTagModalController', resolve: { tag() { return tag }, }, }) modalInstance.result.then(function () { // Remove tag from projects for (const project of $scope.projects) { if (!project.tags) { project.tags = [] } const index = project.tags.indexOf(tag) if (index > -1) { project.tags.splice(index, 1) } } // Remove tag in place to update the state everywhere $scope.tags.splice($scope.tags.indexOf(tag), 1) }) } $scope.renameTag = function (tag) { const modalInstance = $modal.open({ templateUrl: 'renameTagModalTemplate', controller: 'RenameTagModalController', resolve: { tag() { return tag }, }, }) modalInstance.result.then(newName => (tag.name = newName)) } }) App.controller('TagDropdownItemController', function ($scope) { $scope.recalculateProjectsInTag = function () { let partialSelection $scope.areSelectedProjectsInTag = false for (const projectId of $scope.getSelectedProjectIds()) { if ($scope.tag.project_ids.includes(projectId)) { $scope.areSelectedProjectsInTag = true } else { partialSelection = true } } if ($scope.areSelectedProjectsInTag && partialSelection) { $scope.areSelectedProjectsInTag = 'partial' } } $scope.addOrRemoveProjectsFromTag = function () { if ($scope.areSelectedProjectsInTag === true) { $scope.removeSelectedProjectsFromTag($scope.tag) $scope.areSelectedProjectsInTag = false } else if ( $scope.areSelectedProjectsInTag === false || $scope.areSelectedProjectsInTag === 'partial' ) { $scope.addSelectedProjectsToTag($scope.tag) $scope.areSelectedProjectsInTag = true } } $scope.$watch('selectedProjects', () => $scope.recalculateProjectsInTag()) $scope.recalculateProjectsInTag() }) App.controller( 'NewTagModalController', function ($scope, $modalInstance, $timeout, $http) { $scope.inputs = { newTagName: '' } $scope.state = { inflight: false, error: false, } $modalInstance.opened.then(() => $timeout(() => $scope.$broadcast('open'), 200) ) $scope.create = function () { const name = $scope.inputs.newTagName $scope.state.inflight = true $scope.state.error = false $http .post('/tag', { _csrf: window.csrfToken, name, }) .then(function (response) { const { data } = response $scope.state.inflight = false $modalInstance.close(data) }) .catch(function () { $scope.state.inflight = false $scope.state.error = true }) } $scope.cancel = () => $modalInstance.dismiss('cancel') } ) App.controller( 'RenameTagModalController', function ($scope, $modalInstance, $timeout, $http, tag) { $scope.inputs = { tagName: tag.name } $scope.state = { inflight: false, error: false, } $modalInstance.opened.then(() => $timeout(() => $scope.$broadcast('open'), 200) ) $scope.rename = function () { const name = $scope.inputs.tagName $scope.state.inflight = true $scope.state.error = false return $http .post(`/tag/${tag._id}/rename`, { _csrf: window.csrfToken, name, }) .then(function () { $scope.state.inflight = false $modalInstance.close(name) }) .catch(function () { $scope.state.inflight = false $scope.state.error = true }) } $scope.cancel = () => $modalInstance.dismiss('cancel') } ) export default App.controller( 'DeleteTagModalController', function ($scope, $modalInstance, $http, tag) { $scope.tag = tag $scope.state = { inflight: false, error: false, } $scope.delete = function () { $scope.state.inflight = true $scope.state.error = false return $http({ method: 'DELETE', url: `/tag/${tag._id}`, headers: { 'X-CSRF-Token': window.csrfToken, }, }) .then(function () { $scope.state.inflight = false $modalInstance.close() }) .catch(function () { $scope.state.inflight = false $scope.state.error = true }) } $scope.cancel = () => $modalInstance.dismiss('cancel') } )
overleaf/web/frontend/js/main/project-list/tag-controllers.js/0
{ "file_path": "overleaf/web/frontend/js/main/project-list/tag-controllers.js", "repo_id": "overleaf", "token_count": 2549 }
556
/* eslint-disable max-len, */ // TODO: This file was created by bulk-decaffeinate. // Fix any style issues and re-enable lint. /* * decaffeinate suggestions: * DS101: Remove unnecessary use of Array.from * DS102: Remove unnecessary code created because of implicit returns * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import App from '../base' export default App.factory('queuedHttp', function ($http, $q) { const pendingRequests = [] let inflight = false var processPendingRequests = function () { if (inflight) { return } const doRequest = pendingRequests.shift() if (doRequest != null) { inflight = true return doRequest() .then(function () { inflight = false return processPendingRequests() }) .catch(function () { inflight = false return processPendingRequests() }) } } const queuedHttp = function (...args) { // We can't use Angular's $q.defer promises, because it only passes // a single argument on error, and $http passes multiple. const promise = {} const successCallbacks = [] const errorCallbacks = [] // Adhere to the $http promise conventions promise.then = function (callback, errCallback) { successCallbacks.push(callback) if (errCallback != null) { errorCallbacks.push(errCallback) } return promise } promise.catch = function (callback) { errorCallbacks.push(callback) return promise } const doRequest = () => $http(...Array.from(args || [])) .then((...args) => Array.from(successCallbacks).map(cb => cb(...Array.from(args || []))) ) .catch((...args) => Array.from(errorCallbacks).map(cb => cb(...Array.from(args || []))) ) pendingRequests.push(doRequest) processPendingRequests() return promise } queuedHttp.post = (url, data) => queuedHttp({ method: 'POST', url, data }) return queuedHttp })
overleaf/web/frontend/js/services/queued-http.js/0
{ "file_path": "overleaf/web/frontend/js/services/queued-http.js", "repo_id": "overleaf", "token_count": 788 }
557
import { createContext, useContext } from 'react' import PropTypes from 'prop-types' const IdeContext = createContext() IdeContext.Provider.propTypes = { value: PropTypes.shape({ $scope: PropTypes.object.isRequired, }), } export function useIdeContext() { const context = useContext(IdeContext) if (!context) { throw new Error('useIdeContext is only available inside IdeProvider') } return context } export function IdeProvider({ ide, children }) { return <IdeContext.Provider value={ide}>{children}</IdeContext.Provider> } IdeProvider.propTypes = { children: PropTypes.any.isRequired, ide: PropTypes.shape({ $scope: PropTypes.object.isRequired, }).isRequired, }
overleaf/web/frontend/js/shared/context/ide-context.js/0
{ "file_path": "overleaf/web/frontend/js/shared/context/ide-context.js", "repo_id": "overleaf", "token_count": 216 }
558
/* eslint-disable camelcase, max-len, no-return-assign, no-unused-vars, */ // TODO: This file was created by bulk-decaffeinate. // Fix any style issues and re-enable lint. /* * decaffeinate suggestions: * DS101: Remove unnecessary use of Array.from * DS102: Remove unnecessary code created because of implicit returns * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ // Simple event emitter implementation, but has a slightly unusual API for // removing specific listeners. If a specific listener needs to be removed // (instead of all listeners), then it needs to use a "namespace": // Create a listener on the foo event with bar namespace: .on 'foo.bar' // Trigger all events for the foo event (including namespaces): .trigger 'foo' // Remove all listeners for the foo event (including namespaces): .off 'foo' // Remove a listener for the foo event with the bar namespace: .off 'foo.bar' let EventEmitter export default EventEmitter = class EventEmitter { on(event, callback) { let namespace if (!this.events) { this.events = {} } ;[event, namespace] = Array.from(event.split('.')) if (!this.events[event]) { this.events[event] = [] } return this.events[event].push({ callback, namespace, }) } off(event) { if (!this.events) { this.events = {} } if (event != null) { let namespace ;[event, namespace] = Array.from(event.split('.')) if (namespace == null) { // Clear all listeners for event return delete this.events[event] } else { // Clear only namespaced listeners const remaining_events = [] for (const callback of Array.from(this.events[event] || [])) { if (callback.namespace !== namespace) { remaining_events.push(callback) } } return (this.events[event] = remaining_events) } } else { // Remove all listeners return (this.events = {}) } } trigger(event, ...args) { if (!this.events) { this.events = {} } return Array.from(this.events[event] || []).map(callback => callback.callback(...Array.from(args || [])) ) } emit(...args) { return this.trigger(...Array.from(args || [])) } }
overleaf/web/frontend/js/utils/EventEmitter.js/0
{ "file_path": "overleaf/web/frontend/js/utils/EventEmitter.js", "repo_id": "overleaf", "token_count": 858 }
559