text
stringlengths
1
2.83M
id
stringlengths
16
152
metadata
dict
__index_level_0__
int64
0
949
--- title: SetSpawnInfo description: This function can be used to change the spawn information of a specific player. tags: [] --- ## คำอธิบาย This function can be used to change the spawn information of a specific player. It allows you to automatically set someone's spawn weapons, their team, skin and spawn position, normally used in case of minigames or automatic-spawn systems. This function is more crash-safe then using SetPlayerSkin in OnPlayerSpawn and/or OnPlayerRequestClass, even though this has been fixed in 0.2. | Name | Description | | -------------- | -------------------------------------------------------------------- | | playerid | The PlayerID of who you want to set the spawn information. | | team | The Team-ID of the chosen player. | | skin | The skin which the player will spawn with. | | Float:X | The X-coordinate of the player's spawn position. | | Float:Y | The Y-coordinate of the player's spawn position. | | Float:Z | The Z-coordinate of the player's spawn position. | | Float:rotation | The direction in which the player needs to be facing after spawning. | | weapon1 | The first spawn-weapon for the player. | | weapon1_ammo | The amount of ammunition for the primary spawnweapon. | | weapon2 | The second spawn-weapon for the player. | | weapon2_ammo | The amount of ammunition for the second spawnweapon. | | weapon3 | The third spawn-weapon for the player. | | weapon3_ammo | The amount of ammunition for the third spawnweapon. | ## ส่งคืน This function does not return any specific values. ## ตัวอย่าง ```c public OnPlayerRequestClass(playerid, classid) { // This simple example demonstrates how to spawn every player automatically with // CJ's skin, which is number 0. The player will spawn in Las Venturas, with // 36 Sawnoff-Shotgun rounds and 150 Tec9 rounds. SetSpawnInfo( playerid, 0, 0, 1958.33, 1343.12, 15.36, 269.15, 26, 36, 28, 150, 0, 0 ); } ``` ## ฟังก์ชั่นที่เกี่ยวข้องกัน - SetPlayerSkin: Set a player's skin. - SetPlayerTeam: Set a player's team. - SpawnPlayer: Force a player to spawn.
openmultiplayer/web/docs/translations/th/scripting/functions/SetSpawnInfo.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/SetSpawnInfo.md", "repo_id": "openmultiplayer", "token_count": 1053 }
451
--- title: SetWeather description: Set the world weather for all players. tags: [] --- ## คำอธิบาย Set the world weather for all players. | Name | Description | | --------- | ------------------- | | weatherid | The weather to set. | ## ส่งคืน This function does not return any specific values. ## ตัวอย่าง ```c if (!strcmp(cmdtext, "/sandstorm", true)) { SetWeather(19); return 1; } ``` ## บันทึก :::tip If TogglePlayerClock is enabled, weather will slowly change over time, instead of changing instantly. There are only valid 21 weather IDs in the game (0 - 20), however the game does not have any form of range check. ::: ## ฟังก์ชั่นที่เกี่ยวข้องกัน - SetPlayerWeather: Set a player's weather. - SetGravity: Set the global gravity.
openmultiplayer/web/docs/translations/th/scripting/functions/SetWeather.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/SetWeather.md", "repo_id": "openmultiplayer", "token_count": 333 }
452
--- title: TextDrawBoxColor description: Adjusts the text box colour (only used if TextDrawUseBox 'use' parameter is 1). tags: ["textdraw"] --- ## คำอธิบาย Adjusts the text box colour (only used if TextDrawUseBox 'use' parameter is 'true'). | Name | Description | | ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | text | The TextDraw to change | | color | The colour. Opacity is set by the alpha intensity of colour (eg. color 0x000000FF has a solid black box opacity, whereas 0x000000AA has a semi-transparent black box opacity). | ## ส่งคืน This function does not return any specific values. ## ตัวอย่าง ```c new Text:Example; public OnGameModeInit() { Example = TextDrawCreate(123.0, 123.0, "Example"); TextDrawUseBox(Example, true); TextDrawBoxColor(Example, 0xFFFFFFFF); return 1; } ``` ## บันทึก :::tip If you want to change the boxcolour of a textdraw that is already shown, you don't have to recreate it. Simply use [TextDrawShowForPlayer](TextDrawShowForPlayer)/[TextDrawShowForAll](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. - [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. - [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/TextDrawBoxColor.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/TextDrawBoxColor.md", "repo_id": "openmultiplayer", "token_count": 1232 }
453
--- title: TextDrawShowForAll description: Shows a textdraw for all players. tags: ["textdraw"] --- ## คำอธิบาย Shows a textdraw for all players. | Name | Description | | ---- | ----------------------------------------------------------- | | text | The ID of the textdraw to show. Returned by TextDrawCreate. | ## ส่งคืน 1: The function executed successfully. 0: The function failed to execute. This means the textdraw specified does not exist. ## ตัวอย่าง ```c new Text:textid = TextDrawCreate(100.0, 100.0, "Hello!"); TextDrawShowForAll(textid); ``` ## ฟังก์ชั่นที่เกี่ยวข้องกัน - [TextDrawShowForPlayer](../functions/TextDrawShowForPlayer.md): Show a textdraw for a certain player. - [TextDrawHideForPlayer](../functions/TextDrawHideForPlayer.md): Hide a textdraw for a certain player. - [TextDrawHideForAll](../functions/TextDrawHideForAll.md): Hide a textdraw for all players.
openmultiplayer/web/docs/translations/th/scripting/functions/TextDrawShowForAll.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/TextDrawShowForAll.md", "repo_id": "openmultiplayer", "token_count": 395 }
454
--- title: atan description: Get the inversed value of a tangent in degrees. tags: ["math"] --- <LowercaseNote /> ## คำอธิบาย Get the inversed value of a tangent in degrees. In trigonometrics, arc tangent is the inverse operation of tangent. Notice that because of the sign ambiguity, the function cannot determine with certainty in which quadrant the angle falls only by its tangent value. See [atan2](atan2) for an alternative that takes a fractional argument instead. | Name | Description | | ----------- | ------------------------------------ | | Float:value | value whose arc tangent is computed. | ## ส่งคืน The angle in degrees, in the interval [-90.0,+90.0]. ## ตัวอย่าง ```c //The arc tangent of 1.000000 is 45.000000 degrees. public OnGameModeInit() { new Float:param, Float:result; param = 1.0; result = atan(param); printf("The arc tangent of %f is %f degrees.", param, result); return 1; } ``` ## ฟังก์ชั่นที่เกี่ยวข้องกัน - [floatsin](floatsin): Get the sine from a specific angle. - [floatcos](floatcos): Get the cosine from a specific angle. - [floattan](floattan): Get the tangent from a specific angle. - [asin](asin): Get the inversed value of a sine in degrees. - [acos](acos): Get the inversed value of a cosine in degrees. - [atan2](atan2): Get the multi-valued inversed value of a tangent in degrees.
openmultiplayer/web/docs/translations/th/scripting/functions/atan.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/atan.md", "repo_id": "openmultiplayer", "token_count": 534 }
455
--- title: db_next_row description: Moves to the next row of the result allocated from db_query. tags: ["sqlite"] --- :::warning This function starts with lowercase letter. ::: ## คำอธิบาย Moves to the next row of the result allocated from db_query. | Name | Description | | ----------------- | ----------------------- | | DBResult:dbresult | The result of db_query. | ## ส่งคืน Returns 1 on success, otherwise 0 if DBResult:dbresult is a NULL reference or the last row is reached. ## ตัวอย่าง ```c // Callback public OnPlayerCommandText(playerid, cmdtext[]) { // If "cmdtext" equals "/EchoWoetJoinList" if (!strcmp(cmdtext, "/EchoWoetJoinList", true, 17)) { // Declare "db_result" and "info" new DBResult:db_result, info[2][30]; // Select the join list of the player "Woet" db_result = db_query(db_handle, "SELECT * FROM `join_log` WHERE `name`='Woet'"); // Do these do { // Store the data of "ip" into "info[0]" db_get_field_assoc(db_result, "ip", info[0], sizeof info[]); // Store the data of "time" into "info[1]" db_get_field_assoc(db_result, "time", info[1], sizeof info[]); // Print into the console printf("Print join list: Name: Woet IP: %s Date: %s", info[0], info[1]); } // While next row has been fetched while(db_next_row(db_result)); // Returns 1 return 1; } // Returns 0 return 0; } ``` ## บันทึก :::warning Using an invalid handle will crash your server! Get a valid handle by using db_query. But it's protected against NULL references. ::: ## ฟังก์ชั่นที่เกี่ยวข้องกัน - db_open: Open a connection to an SQLite database - db_close: Close the connection to an SQLite database - db_query: Query an SQLite database - db_free_result: Free result memory from a db_query - db_num_rows: Get the number of rows in a result - db_next_row: Move to the next row - db_num_fields: Get the number of fields in a result - db_field_name: Returns the name of a field at a particular index - db_get_field: Get content of field with specified ID from current result row - db_get_field_assoc: Get content of field with specified name from current result row - db_get_field_int: Get content of field as an integer with specified ID from current result row - db_get_field_assoc_int: Get content of field as an integer with specified name from current result row - db_get_field_float: Get content of field as a float with specified ID from current result row - db_get_field_assoc_float: Get content of field as a float with specified name from current result row - db_get_mem_handle: Get memory handle for an SQLite database that was opened with db_open. - db_get_result_mem_handle: Get memory handle for an SQLite query that was executed with db_query. - db_debug_openfiles - db_debug_openresults
openmultiplayer/web/docs/translations/th/scripting/functions/db_next_row.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/db_next_row.md", "repo_id": "openmultiplayer", "token_count": 1123 }
456
--- title: floatcmp description: floatcmp can be used to compare float values to each other, to validate the comparison. tags: [] --- :::warning This function starts with lowercase letter. ::: ## คำอธิบาย floatcmp can be used to compare float values to each other, to validate the comparison. | Name | Description | | ----- | ---------------------------------- | | oper1 | The first float value to compare. | | oper2 | The second float value to compare. | ## ส่งคืน 0 if value does match, 1 if the first value is bigger and -1 if the 2nd value is bigger. ## ตัวอย่าง ```c floatcmp(2.0, 2.0); // Returns 0 because they match. floatcmp(1.0, 2.0) // Returns -1 because the second value is bigger. floatcmp(2.0, 1.0) // Returns 1 because the first value is bigger. ``` ## ฟังก์ชั่นที่เกี่ยวข้องกัน
openmultiplayer/web/docs/translations/th/scripting/functions/floatcmp.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/floatcmp.md", "repo_id": "openmultiplayer", "token_count": 346 }
457
--- title: fputchar description: Write one character to a file. tags: [] --- :::warning This function starts with lowercase letter. ::: ## คำอธิบาย Write one character to a file. | Name | Description | | ------ | -------------------------------------------------------- | | handle | The File handle to use, earlier opened by fopen(). | | value | The character to write into the file. | | utf8 | If true, write in UTF8 mode, otherwise in extended ASCII | ## ส่งคืน This function does not return any specific values. ## ตัวอย่าง ```c // Open "file.txt" in "write only" mode new File:handle = fopen("file.txt", io_write); if (handle) { // Success // Write character "e" into "file.txt" fputchar(handle, 'e', false); // Close "file.txt" fclose(handle); } else { // Error print("Failed to open \"file.txt\"."); } ``` ## บันทึก :::warning Using an invalid handle will crash your server! Get a valid handle by using fopen or ftemp. ::: ## ฟังก์ชั่นที่เกี่ยวข้องกัน - [fopen](../functions/fopen): Open a file. - [fclose](../functions/fclose): Close a file. - [ftemp](../functions/ftemp): Create a temporary file stream. - [fremove](../functions/fremove): Remove a file. - [fwrite](../functions/fwrite): Write to a file. - [fread](../functions/fread): Read a file. - [fputchar](../functions/fputchar): Put a character in a file. - [fgetchar](../functions/fgetchar): Get a character from a file. - [fblockwrite](../functions/fblockwrite): Write blocks of data into a file. - [fblockread](../functions/fblockread): Read blocks of data from a file. - [fseek](../functions/fseek): Jump to a specific character in a file. - [flength](../functions/flength): Get the file length. - [fexist](../functions/fexist): Check, if a file exists. - [fmatch](../functions/fmatch): Check, if patterns with a file name matches.
openmultiplayer/web/docs/translations/th/scripting/functions/fputchar.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/fputchar.md", "repo_id": "openmultiplayer", "token_count": 773 }
458
--- title: strpack description: Pack a string. tags: [] --- :::warning This function starts with lowercase letter. ::: ## คำอธิบาย Pack a string. Packed strings use 75% less memory. | Name | Description | | ----------------------- | ------------------------------------------------------------------------- | | dest[] | The destination string to save the packed string in, passed by reference. | | const source[] | The source, original string. | | maxlength=sizeof string | The maximum size to insert. | ## ส่งคืน The number of characters packed. ## ตัวอย่าง ```c new string[32 char]; strpack(string, "Hi, how are you?"); ``` ## ฟังก์ชั่นที่เกี่ยวข้องกัน - strcmp: Compare two strings to see if they are the same. - strfind: Search for a substring in a string. - strtok: Search for a variable typed after a space. - strdel: Delete part/all of a string. - strins: Put a string into another string. - strlen: Check the length of a string. - strmid: Extract characters from a string. - strval: Find the value of a string. - strcat: Contact two strings into a destination reference.
openmultiplayer/web/docs/translations/th/scripting/functions/strpack.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/strpack.md", "repo_id": "openmultiplayer", "token_count": 582 }
459
--- title: Angle Modes description: SI unit constants for measuring angles. --- :::note To be used with [floatsin](../functions/Floatsin), [floatcos](../functions/Floatcos), or [floattan](../functions/Floattan). ::: | Modes | | ------- | | radian | | degrees | | grades |
openmultiplayer/web/docs/translations/th/scripting/resources/anglemodes.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/resources/anglemodes.md", "repo_id": "openmultiplayer", "token_count": 98 }
460
--- title: Object Edition Response Types --- Used in [OnPlayerEditObject](../callbacks/OnPlayerEditObject.md) and [OnPlayerEditAttachedObject](../callbacks/OnPlayerEditAttachedObject.md). ```c 0 - EDIT_RESPONSE_CANCEL // player cancelled (ESC) 1 - EDIT_RESPONSE_FINAL // player clicked on save 2 - EDIT_RESPONSE_UPDATE // player moved the object (edition did not stop at all) ```
openmultiplayer/web/docs/translations/th/scripting/resources/objecteditionresponsetypes.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/resources/objecteditionresponsetypes.md", "repo_id": "openmultiplayer", "token_count": 129 }
461
--- title: Textdraws description: As the name implies, a textdraw is text that is drawn on a player's screen. sidebar_label: Textdraws --- ## What is a Textdraw? As the name implies, a textdraw is text that is drawn on a player's screen. Unlike [client messages](../../scripting/functions/SendClientMessage.md) or [gametext](../../scripting/functions/GameTextForPlayer.md) however, textdraws can be shown on a player's screen for an indefinite period of time. Textdraws can be simple text on the screen such as a website address, or complex scripted dynamic textdraws such as progress bars. This 'textdraw editor' tool can make designing textdraws much easier. ## Global Textdraws Global textdraws can be created, then shown to all players. There is a [limit](../../scripting/resources/Limits.md) as to how many can be created, though. This means if you have a server with 500 players, creating more than 4 textdraws per-player is not possible. That's where **player**-textdraws come in. See further down. Here is a list of all the functions related to **global** textdraws: - [TextDrawCreate](../../scripting/functions/TextDrawCreate.md): Create a textdraw. - [TextDrawDestroy](../../scripting/functions/TextDrawDestroy.md): Destroy a textdraw. - [TextDrawColor](../../scripting/functions/TextDrawColor.md): Set the color of the text in a textdraw. - [TextDrawBoxColor](../../scripting/functions/TextDrawBoxColor.md): Set the color of the box in a textdraw. - [TextDrawBackgroundColor](../../scripting/functions/TextDrawBackgroundColor.md): Set the background color of a textdraw. - [TextDrawAlignment](../../scripting/functions/TextDrawAlignment.md): Set the alignment of a textdraw. - [TextDrawFont](../../scripting/functions/TextDrawFont.md): Set the font of a textdraw. - [TextDrawLetterSize](../../scripting/functions/TextDrawLetterSize.md): Set the letter size of the text in a textdraw. - [TextDrawTextSize](../../scripting/functions/TextDrawTextSize.md): Set the size of a textdraw box. - [TextDrawSetOutline](../../scripting/functions/TextDrawSetOutline.md): Choose whether the text has an outline. - [TextDrawSetShadow](../../scripting/functions/TextDrawSetShadow.md): Toggle shadows on a textdraw. - [TextDrawSetProportional](../../scripting/functions/TextDrawSetProportional.md): Scale the text spacing in a textdraw to a proportional ratio. - [TextDrawUseBox](../../scripting/functions/TextDrawUseBox.md): Toggle if the textdraw has a box or not. - [TextDrawSetString](../../scripting/functions/TextDrawSetString.md): Set the text in an existing textdraw. - [TextDrawShowForPlayer](../../scripting/functions/TextDrawShowForPlayer.md): Show a textdraw for a certain player. - [TextDrawHideForPlayer](../../scripting/functions/TextDrawHideForPlayer.md): Hide a textdraw for a certain player. - [TextDrawShowForAll](../../scripting/functions/TextDrawShowForAll.md): Show a textdraw for all players. - [TextDrawHideForAll](../../scripting/functions/TextDrawHideForAll.md): Hide a textdraw for all players. ## Player-textdraws Player-textdraws are only created for one specific player. Up to 256 textdraws can be created PER-PLAYER. That's 128,000 on a server with 500 players. A little more than 2048. Player-textdraws should be used for things that are not 'static'. Do not use them to display a website address for example, but for a vehicle health indicator. - [CreatePlayerTextDraw](../../scripting/functions/CreatePlayerTextDraw.md): Create a player-textdraw. - [PlayerTextDrawDestroy](../../scripting/functions/PlayerTextDrawDestroy.md): Destroy a player-textdraw. - [PlayerTextDrawColor](../../scripting/functions/PlayerTextDrawColor.md): Set the color of the text in a player-textdraw. - [PlayerTextDrawBoxColor](../../scripting/functions/PlayerTextDrawBoxColor.md): Set the color of a player-textdraw's box. - [PlayerTextDrawBackgroundColor](../../scripting/functions/PlayerTextDrawBackgroundColor.md): Set the background color of a player-textdraw. - [PlayerTextDrawAlignment](../../scripting/functions/PlayerTextDrawAlignment.md): Set the alignment of a player-textdraw. - [PlayerTextDrawFont](../../scripting/functions/PlayerTextDrawFont.md): Set the font of a player-textdraw. - [PlayerTextDrawLetterSize](../../scripting/functions/PlayerTextDrawLetterSize.md): Set the letter size of the text in a player-textdraw. - [PlayerTextDrawTextSize](../../scripting/functions/PlayerTextDrawTextSize.md): Set the size of a player-textdraw box (or clickable area for [PlayerTextDrawSetSelectable](../../scripting/functions/PlayerTextDrawSetSelectable.md)). - [PlayerTextDrawSetOutline](../../scripting/functions/PlayerTextDrawSetOutline.md): Toggle the outline on a player-textdraw. - [PlayerTextDrawSetShadow](../../scripting/functions/PlayerTextDrawSetShadow.md): Set the shadow on a player-textdraw. - [PlayerTextDrawSetProportional](../../scripting/functions/PlayerTextDrawSetProportional.md): Scale the text spacing in a player-textdraw to a proportional ratio. - [PlayerTextDrawUseBox](../../scripting/functions/PlayerTextDrawUseBox.md): Toggle the box on a player-textdraw. - [PlayerTextDrawSetString](../../scripting/functions/PlayerTextDrawSetString.md): Set the text of a player-textdraw. - [PlayerTextDrawShow](../../scripting/functions/PlayerTextDrawShow.md): Show a player-textdraw. - [PlayerTextDrawHide](../../scripting/functions/PlayerTextDrawHide.md): Hide a player-textdraw. ## Variable Declaration When creating a textdraw, you should always decide if the textdraw you're going to create has to be global (eg. your website address, global annoucement) or if it's going to differ per player (eg. kills, deaths, score). ### Global Textdraw A global textdraw is the easiest to create and requires only one variable. This variable is needed to modify the textdraw and to show it to the players later on. The declaration for such a textdraw needs to be a global variable in most cases. The textdraw variable also needs to be prefixed with the _Text:_ tag and should be initialized with the value _Text:INVALID_TEXT_DRAW_. If you omit the initialization, the textdraw may conflict with others as you add more textdraws. ```c new Text:gMyText = Text:INVALID_TEXT_DRAW; ``` ### Per-Player Textdraw A per-player textdraw is exactly the same as a regular 'global' textdraw, but only creates the textdraw for a single player. This is useful for textdraws that are unique to each player, such as a 'stats' bar showing their kills or score. This can be used to avoid going over the global-textdraw limit, as you can create 256 textdraws per player. They are also easier to manage, as they automatically destroy themselves when the player disconnects. ```c new PlayerText:gMyPlayerText = PlayerText:INVALID_TEXT_DRAW; ``` :::info IMPORTANT NOTE: An array is still needed for the variable, as the ID of the textdraws may differ from player to player, as other players may have more or less textdraws created than the other. ::: The function names only differ slightly, with 'TextDraw' becoming 'PlayerTextDraw', with one exception: [CreatePlayerTextDraw](../../scripting/functions/CreatePlayerTextDraw.md) ('TextDrawSetString' becomes 'PlayerTextDrawSetString'). ## Creating the Textdraw ![Image:320px-Textdraw_map.png](/images/textdraws/320px-Textdraw_map.png) Once you've declared a variable/array to store the ID of your textdraw(s) in, you can proceed to create the textdraw itself. For global textdraws that are always created, the code should be placed under [OnGameModeInit](../../scripting/callbacks/OnGameModeInit.md). To create the textdraw, the function [TextDrawCreate](../../scripting/functions/TextDrawCreate.md) must be used. Note that this function merely creates the textdraw, other functions are used to modify it and to show it to the player(s). **Parameters:** TextDrawCreate(Float:x, Float:y, text[]) | Name | Description | | ------ | -------------------------------------------- | | x | X coordinate at which to create the textdraw | | y | Y coordinate at which to create the textdraw | | text[] | The text in the textdraw. | **Return Values:** The ID of the created textdraw Let's proceed to create the textdraw: ```c public OnGameModeInit() { gMyText = TextDrawCreate(320.0, 240.0, "Hello World!"); return 1; } ``` We have created a textdraw in the center of the screen that says "Hello World!". ## Setting the font There are 4 fonts available for textdraw text: ![Image:320px-Textdraw_map.png](/images/textdraws/Textdraw_font_styles.png) | ID | Info | Tips | | --- | -------------------------------------------------------------- | ------------------------------------------------------ | | 0 | The _San Andreas_ Font. | Use for header or titles, not a whole page. | | 1 | Clear font that includes both upper and lower case characters. | Can be used for a lot of text. | | 2 | Clear font, but includes only capital letters. | Can be used in various instances. | | 3 | _GTA font_ | Retains quality when enlarged. Useful for large texts. | As of SA-MP 0.3d, a new font (id 4) can be set. This is used in combination with the [TextDrawCreate](../../scripting/functions/TextDrawCreate.md) and [TextDrawTextSize](../../scripting/functions/TextDrawTextSize.md) functions to show a texture 'sprite' on the player's screen. We'll cover this later. ## Showing the textdraw For this example, the textdraw has been created globally under OnGameModeInit and will be shown to player when they join the server. To show a textdraw for a single player, the function [TextDrawShowForPlayer](../../scripting/functions/TextDrawShowForPlayer.md) is used. **Parameters:** TextDrawShowForPlayer(playerid, Text:text) | Name | Description | | -------- | --------------------------------------------- | | playerid | The ID of the player to show the textdraw for | | text | The ID of the textdraw to show | **Return Values:** This function does not return any specific values. The playerid is passed through OnPlayerConnect, and the text-draw ID is stored in the 'gMyText' variable. ```c public OnGameModeInit() { gMyText = TextDrawCreate(320.0, 320.0, "Hello World!"); return 1; } public OnPlayerConnect(playerid) { TextDrawShowForPlayer(playerid, gMyText); return 1; } ``` ## Assorted Tips - Try to use whole number when specifying positions, this ensures the best compatibility on different resolutions. - Fonts appear to look the best with an X to Y ratio of 1 to 4 (e.g. if x = 0.5 then y should be 2).
openmultiplayer/web/docs/translations/th/scripting/resources/textdraws.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/scripting/resources/textdraws.md", "repo_id": "openmultiplayer", "token_count": 3381 }
462
--- title: Cooldowns description: A tutorial for writing cooldowns for limiting user actions using tick counts and avoiding the use of timers. --- This tutorial covers writing a commonly used gameplay mechanic in action games: cooldowns. A cooldown is a tool to limit the frequency at which a player can do something. This may be something like using an ability such as healing or writing chat messages. It allows you to slow the rate at which players do things either for gameplay balancing purposes or to prevent spam. First I'll example the _bad_ way of doing a cooldown by using `SetTimer` to update state. ## Using Timers Say for example you have a specific action that can only be performed once every so many seconds, I see a lot of people (including Southclaws, many years ago) doing something like this: ```c static bool:IsPlayerAllowedToDoThing[MAX_PLAYERS]; OnPlayerInteractWithServer(playerid) /* This can be any sort of input event a player makes such as: * Entering a command * Picking up a pickup * Entering a checkpoint * Pressing a button * Entering an area * Using a dialog */ { // This only works when the player is allowed to if (IsPlayerAllowedToDoThing[playerid]) { // Do the thing the player requested DoTheThingThePlayerRequested(); // Disallow the player IsPlayerAllowedToDoThing[playerid] = false; // Allow the player to do the thing again in 10 seconds SetTimerEx("AllowPlayer", 10000, false, "d", playerid); return 1; } else { SendClientMessage(playerid, -1, "You are not allowed to do that yet!"); return 0; } } // Called 10 seconds after the player does the thing public AllowPlayer(playerid) { IsPlayerAllowedToDoThing[playerid] = true; SendClientMessage(playerid, -1, "You are allowed to do the thing again! :D"); } ``` Now this is all well and good, it works, the player won't be able to do that thing again for 10 seconds after he uses it. Take another example here, this is a stopwatch that measures how long it takes for a player to do a simple point to point race: ```c static StopWatchTimerID[MAX_PLAYERS], StopWatchTotalTime[MAX_PLAYERS]; StartPlayerRace(playerid) { // Calls a function every second StopWatchTimerID[playerid] = SetTimerEx("StopWatch", 1000, true, "d", playerid); } public StopWatch(playerid) { // Increment the seconds counter StopWatchTotalTime[playerid]++; } OnPlayerFinishRace(playerid) { new str[128]; format(str, 128, "You took %d seconds to do that", StopWatchTotalTime[playerid]); SendClientMessage(playerid, -1, str); KillTimer(StopWatchTimerID[playerid]); } ``` These two examples are common and they may work fine. However, there is a much better way of achieving both of these outcomes, which is more way accurate and can give stopwatch timings down to the millisecond! ## Using `GetTickCount()` and `gettime()` `GetTickCount()` is a function that gives you the time in milliseconds since the server process was opened. `gettime()` returns the number of seconds since January 1st 1970, also known as a Unix Timestamp. If you call either of these functions at two different times, and subtract the first time from the second you suddenly have an interval between those two events in milliseconds or seconds respectively! Take a look at this example: ### A Cooldown ```c static PlayerAllowedTick[MAX_PLAYERS]; OnPlayerInteractWithServer(playerid) { if (GetTickCount() - PlayerAllowedTick[playerid] > 10000) // This only works when the current tick minus the last tick is above 10000. // In other words, it only works when the interval between the actions is over 10 seconds. { DoTheThingThePlayerRequested(); PlayerAllowedTick[playerid] = GetTickCount(); // Update the tick count with the latest time. return 1; } else { SendClientMessage(playerid, -1, "You are not allowed to do that yet!"); return 0; } } ``` Or, alternatively the `gettime()` version: ```c static PlayerAllowedSeconds[MAX_PLAYERS]; OnPlayerInteractWithServer(playerid) { if (gettime() - PlayerAllowedSeconds[playerid] > 10) // This only works when the current seconds minus the last seconds is above 10. // In other words, it only works when the interval between the actions is over 10 seconds. { DoTheThingThePlayerRequested(); PlayerAllowedSeconds[playerid] = gettime(); // Update the seconds count with the latest time. return 1; } else { SendClientMessage(playerid, -1, "You are not allowed to do that yet!"); return 0; } } ``` There's a lot less code there, no need for a public function or a timer. If you really want to, you can put the remaining time in the error message: (I'm using SendFormatMessage in this example) ```c SendFormatMessage( playerid, -1, "You are not allowed to do that yet! You can again in %d ms", 10000 - (GetTickCount() - PlayerAllowedTick[playerid]) ); ``` That's a very basic example, it would be better to convert that MS value into a string of `minutes:seconds.milliseconds` but I'll post that code at the end. ### A Stopwatch Hopefully you can see how powerful this is to get intervals between events, let's look at another example ```c static Stopwatch[MAX_PLAYERS]; StartPlayerRace(playerid) { Stopwatch[playerid] = GetTickCount(); } OnPlayerFinishRace(playerid) { new interval, str[128]; interval = GetTickCount() - Stopwatch[playerid]; format(str, 128, "You took %d milliseconds to do that", interval); SendClientMessage(playerid, -1, str); } ``` In this example, the tick count is saved to the player variable when he starts the race. When he finishes it, the current tick (of when he finished) has that initial tick (The smaller value) subtracted from it and thus leaves us with the amount of milliseconds in between the start and the end of the race. #### Breakdown Now lets break the code down a bit. ```c new Stopwatch[MAX_PLAYERS]; ``` This is a global variable, we need to use this so we can save the tick count and retrieve the value at another point in time (in other words, use it in another function, later on) ```c StartPlayerRace(playerid) { Stopwatch[playerid] = GetTickCount(); } ``` This is when the player starts the race, the tick count of now is recorded, if this happens is 1 minute after the server started, the value of that variable will be 60,000 because it is 60 seconds and each second has a thousand milliseconds. Okay, we now have that player's variable set at 60,000, now he finishes the race 1 minute 40 seconds later: ```c OnPlayerFinishRace(playerid) { new interval, str[128]; interval = GetTickCount() - Stopwatch[playerid]; format(str, 128, "You took %d milliseconds to do that", interval); SendClientMessage(playerid, -1, str); } ``` Here is where the calculation of the interval happens, well, I say calculation, it's just subtracting two values! GetTickCount() returns the current tick count, so it will be bigger than the initial tick count which means you subtract the initial tick count from the current tick count to get your interval between the two measures. So, as we said the player finishes the race 1 minute and 40 seconds later (100 seconds, or 100,000 milliseconds), GetTickCount will return 160,000. Subtract the initial value (Which is 60,000) from the new value (Which is 160,000) and you get 100,000 milliseconds, which is 1 minute 40 seconds, which is the time it took the player to do the race! ## Recap and Notes So! We learned that: - GetTickCount returns the amount of time in milliseconds since the computer system that the server is running on started. - And we can use that by calling it at two intervals, saving the first to a variable and comparing the two values can give you an accurate interval in milliseconds between those two events. Last of all, you don't want to be telling your players time values in milliseconds! What if they take an hour to complete a race? It's best to use a function that takes the milliseconds and converts it to a readable format, for instance, the earlier example the player took 100,000 milliseconds to do the race, if you told the player he took that long, it would take longer to read that 100,000 and figure out what it means in human-readable time. [This package](https://github.com/ScavengeSurvive/timeutil) contains a function to format milliseconds into a string. I hope this helped! I wrote it because I've helped a few people out recently who didn't know how to use `GetTickCount()` or `gettime()` as an alternative for timers or for getting intervals etc.
openmultiplayer/web/docs/translations/th/tutorials/cooldowns.md/0
{ "file_path": "openmultiplayer/web/docs/translations/th/tutorials/cooldowns.md", "repo_id": "openmultiplayer", "token_count": 2572 }
463
--- title: OnFilterScriptExit description: Bir filterscript unload edildiğinde tetiklenir. tags: [] --- ## Açıklama Bu callback bir filterscript unload edildiğinde tetiklenir. Sadece unload edilen filterscript içinde çalışır. ## Örnekler ```c public OnFilterScriptExit() { print("\n--------------------------------------"); print(" My filterscript unloaded"); print("--------------------------------------\n"); return 1; } ``` ## Bağlantılı Fonksiyonlar
openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnFilterScriptExit.md/0
{ "file_path": "openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnFilterScriptExit.md", "repo_id": "openmultiplayer", "token_count": 167 }
464
--- title: OnPlayerEnterCheckpoint description: Bu callback, bir oyuncu kendisi için oluşturulan checkpointe giriş yaptığında çağırılıyor. tags: ["player", "checkpoint"] --- ## Açıklama Bu callback, bir oyuncu kendisi için oluşturulan checkpointe giriş yaptığında çağırılıyor. | İsim | Açıklama | | -------- | -------------------------------------- | | playerid | Checkpointe giren oyuncunun ID'si. | ## Çalışınca Vereceği Sonuçlar Her zaman ilk olarak filterscriptlerde çağırılır. ## Örnekler ```c //Oyuncu spawnlandığında checkpoint oluşturulur ve oyuncu checkpointe girdiğinde bir araç spawnlanıp checkpoint silinir. public OnPlayerSpawn(playerid) { SetPlayerCheckpoint(playerid, 1982.6150, -220.6680, -0.2432, 3.0); return 1; } public OnPlayerEnterCheckpoint(playerid) { CreateVehicle(520, 1982.6150, -221.0145, -0.2432, 82.2873, -1, -1, 60000); DisablePlayerCheckpoint(playerid); return 1; } ``` ## Notlar <TipNPCCallbacks /> ## Bağlantılı Fonksiyonlar - [SetPlayerCheckpoint](../functions/SetPlayerCheckpoint): Create a checkpoint for a player. - [DisablePlayerCheckpoint](../functions/DisablePlayerCheckpoint): Disable the player's current checkpoint. - [IsPlayerInCheckpoint](../functions/IsPlayerInRaceCheckpoint): Check if a player is in a checkpoint. - [SetPlayerRaceCheckpoint](../functions/SetPlayerRaceCheckpoint): Create a race checkpoint for a player. - [DisablePlayerRaceCheckpoint](../functions/DisablePlayerRaceCheckpoint): Disable the player's current race checkpoint. - [IsPlayerInRaceCheckpoint](../functions/IsPlayerInRaceCheckpoint): Check if a player is in a race checkpoint.
openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnPlayerEnterCheckpoint.md/0
{ "file_path": "openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnPlayerEnterCheckpoint.md", "repo_id": "openmultiplayer", "token_count": 623 }
465
--- title: OnPlayerRequestSpawn description: Fonksiyon, Bir oyuncu SHIFT'e basarak veya 'Spawn' düğmesine tıklayarak sınıf seçimi yoluyla doğmaya çalıştığında çağrılır. tags: ["player"] --- ## Açıklama Fonksiyon, Bir oyuncu SHIFT'e basarak veya 'Spawn' düğmesine tıklayarak sınıf seçimi yoluyla doğmaya çalıştığında çağrılır. | Parametre | Açıklama | | --------- | --------------------------------------------- | | playerid | Doğmak isteyen oyuncunun ID'si. | ## Çalışınca Vereceği Sonuçlar Filterscript komut dosyalarında her zaman ilk olarak çağrılır, bu nedenle 0 döndürmek diğer komut dosyalarının da görmesini engeller. ## Örnekler ```c public OnPlayerRequestSpawn(playerid) { if (!IsPlayerAdmin(playerid)) { SendClientMessage(playerid, -1, "Doğamazsınız."); return 0; } return 1; } ``` ## Notlar <TipNPCCallbacks /> :::tip Oyuncuların belirli sınıflarla ortaya çıkmasını önlemek için son görüntülenen sınıf, OnPlayerRequestClass içinde bir değişkene kaydedilmelidir. ::: ## Bağlantılı Fonksiyonlar
openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnPlayerRequestSpawn.md/0
{ "file_path": "openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnPlayerRequestSpawn.md", "repo_id": "openmultiplayer", "token_count": 558 }
466
--- title: OnVehicleDeath description: Bu fonksiyon, bir araç imha edildiğinde çağrılır. - patladığında veya araç suya girdiğinde. tags: ["vehicle"] --- ## Açıklama Bu fonksiyon, bir araç imha edildiğinde çağrılır. - patladığında veya araç suya girdiğinde. | Parametre | Açıklama | | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | | vehicleid | İmha edilen aracın ID'si. | | killerid | Aracı imha eden oyuncu (senkronize eden) oyuncunun ID'si. (adı yanıltıcıdır). Genellikle sürücü, yolcu (eğer varsa) veya en yakın oyuncu. | ## Çalışınca Verdiği Sonuçlar Filterscript içerisinde her zaman ilk olarak çağrılır. ## Örnekler ```c public OnVehicleDeath(vehicleid, killerid) { new string[64]; format(string, sizeof(string), "%i ID'li araç imha edildi. Oyuncu %i tarafından bildirildi.", vehicleid, killerid); SendClientMessageToAll(0xFFFFFFFF, string); return 1; } ``` ## Notlar :::tip Bu fonksiyon, bir araç suya girdiğinde de çağrılacaktır, ancak araç ışınlanarak veya bir başka şey tarafından suya düşürüldüyse (yalnızca kısmen suya batırılmışsa) çağrılmaz. Fonksiyon, ikinci kez çağrılmaz, sürücü araçtan çıktığında veya kısa bir süre sonra araç kaybolabilir. ::: ## Bağlantılı fonksiyonlar - [SetVehicleHealth](../functions/SetVehicleHealth): Aracın can değerini düzenleme.
openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnVehicleDeath.md/0
{ "file_path": "openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnVehicleDeath.md", "repo_id": "openmultiplayer", "token_count": 949 }
467
--- title: AddStaticVehicle description: Oyun moduna bir "statik" araç ekler (modeller oyuncular için önceden yüklenir). tags: ["vehicle"] --- ## Description Oyun moduna bir "statik" araç ekler (modeller oyuncular için önceden yüklenir). | İsim | Açıklama | | ---------------------------------------- | ---------------------------------------- | | modelid | Aracın Model Kimliği. | | Float:spawn_X | Aracın X koordinatı. | | Float:spawn_Y | Aracın Y koordinatı. | | Float:spawn_Z | Aracın Z koordinatı. | | Float:z_angle | Araç açısının yönü. | | [color1](../resources/vehiclecolorid.md) | Birincil renk kimliği. rastgele için -1. | | [color2](../resources/vehiclecolorid.md) | İkincil renk kimliği. rastgele için -1. | ## Çalışınca Vereceği Sonuçlar Oluşturulan aracın araç kimliği (1 ile MAX_VEHICLES arasında). Araç oluşturulmamışsa INVALID_VEHICLE_ID (65535) (araç sınırına ulaşıldı veya geçersiz araç model kimliği). ## Örnekler ```c public OnGameModeInit() { // Oyuna bir Hydra ekle. AddStaticVehicle(520, 2109.1763, 1503.0453, 32.2887, 82.2873, 0, 1); return 1; } ``` ## Bağlantılı Fonksiyonlar - [AddStaticVehicleEx](AddStaticVehicleEx.md): Özel yeniden doğma süresine sahip statik bir araç ekleyin. - [CreateVehicle](CreateVehicle.md): Araç oluşturun. - [DestroyVehicle](DestroyVehicle.md): Araç yok edin.
openmultiplayer/web/docs/translations/tr/scripting/functions/AddStaticVehicle.md/0
{ "file_path": "openmultiplayer/web/docs/translations/tr/scripting/functions/AddStaticVehicle.md", "repo_id": "openmultiplayer", "token_count": 906 }
468
--- title: Ban description: Sunucuda olan birini yasaklama. tags: ["administration"] --- ## Açıklama Sunucuda aktif olan birisini yasaklayın. Yasaklanan kişi bir daha sunucuya giremez. Yasaklanan kişi IP tabanlı yasaklanır ve sunucu dizininde bulunan samp.ban dosyasına yasaklama kaydı oluşturulur. Özel bir neden göstemrek için BanEx kullanılabilir. IP yasaklamalarını kaldırmak/eklemek için RCON gişirinizden sonra banip ve unbanip komutlar kullanılabilir. | Parametre | Açıklama | | --------- | ----------------------------- | | playerid | Yasaklanacak oyuncunun ID'si. | ## Çalışınca Vereceği Sonuçlar Bu fonksiyon herhangi bir değer döndürmez. ## Örnekler ```c public OnPlayerCommandText(playerid, cmdtext[]) { if (strcmp(cmdtext, "/banme", true) == 0) { // Komutu kullanan kişi yasaklanır. Ban(playerid); return 1; } } // Oyuncuyu yasaklamadan önce bir mesaj (örn. yasaklanma açıklaması) göndermek için // bir zamanlayıcı (timer) oluşturmanız gerekir. Bu zamanlayıcının bir kaç milisaniye olması yeterlidir, // ancak alt taraftaki örnekte güvenli olması açısından tam bir saniye kullanılmıştır. forward DelayedBan(playerid); public DelayedBan(playerid) { Ban(playerid); } public OnPlayerCommandText(playerid, cmdtext[]) { if (strcmp(cmdtext, "/banme", true) == 0) { // Bu komutu kullanan oyuncu yasaklanır. // Yasaklandığına dair mesajı gönderiyoruz. SendClientMessage(playerid, 0xFF0000FF, "Yasaklandınız!"); // Ardından oyuncu bir zamanlayıcı içerisine giriyor ve sunucudan yasaklanıyor. SetTimerEx("DelayedBan", 1000, false, "d", playerid); return 1; } return 0; } ``` ## Notlar :::warning Ban() fonksiyonu kullanılmadan önce giden mesaj (örn. SendClientMessage) veya başka bir fonksiyon oyuncuya ulaşmayacaktır. Mesajın veya bir başka fonksiyonun oyuncuya ulaşması için zamanlayıcı (timer) kullanılmalıdır. ::: ## Bağlantılı Fonksiyonlar - [BanEx](BanEx): Oyuncuyu özel bir nedenle yasaklama. - [Kick](Kick): Oyuncuyu sunucudan atma (kick).
openmultiplayer/web/docs/translations/tr/scripting/functions/Ban.md/0
{ "file_path": "openmultiplayer/web/docs/translations/tr/scripting/functions/Ban.md", "repo_id": "openmultiplayer", "token_count": 998 }
469
--- title: DestroyActor description: CreateActor ile oluşturulan aktörü silin. tags: [] --- <VersionWarnTR version='SA-MP 0.3.7' /> ## Açıklama CreateActor ile oluşturulan aktörü silin. | Parametre | Açıklama | | ------- | -------------------------------------------------------- | | actorid | Silinecek aktörün ID'si. | ## Çalışınca Vereceği Sonuçlar 1: Fonksiyon çalıştı ve aktör başarıyla silindi. 0: Fonksiyon geçersiz aktör ID'si girildiği için çalışmadı. ## Örnekler ```c new MyActor; public OnFilterScriptInit() { MyActor = CreateActor(...); return 1; } public OnFilterScriptExit() { DestroyActor(MyActor); return 1; } ``` ## Bağlantılı Fonksiyonlar - [CreateActor](CreateActor): Aktör yaratma. (statik NPC).
openmultiplayer/web/docs/translations/tr/scripting/functions/DestroyActor.md/0
{ "file_path": "openmultiplayer/web/docs/translations/tr/scripting/functions/DestroyActor.md", "repo_id": "openmultiplayer", "token_count": 406 }
470
--- title: "Anahtar Kelimeler: İfadeler" --- ## `assert` Eğer ifade mantıksal olarak yanlış değerlendirilirse, çalışmayı durdurur ve bir çalışma zamanı hatası oluşturur. Sadece main() bloğunda çalıştığı görünüyor. Assert ifadesi, mantıksal (programcının) bir hatayı, asla çalışma zamanı (kullanıcının) hatasını göstermek için kullanılmalıdır. ```c main() { assert (MAX_PLAYERS == GetMaxPlayers()); // MAX_PLAYERS tanımının, kullanılan gerçek sunucu slot sayısıyla eşit olduğunu belirtmek için kullanılır } ``` ## `break` Bir döngüden hemen çıkar, yalnızca en üst düzey döngüden çıkar, tüm geçerli döngülerden çıkmaz. ```c for (new i = 0; i < 10; i++) { printf("%d", i); if (i == 5) { break; } } ``` Şunu üretecektir: ```c 0 1 2 3 4 5 ``` Oysa: ```c for (new i = 0; i < 10; i++) { if (i == 5) { break; } printf("%d", i); } ``` Şunu üretecektir: ```c 0 1 2 3 4 ``` Çünkü döngü hemen çıkıldığından her iki döngü de 10'a ulaşmaz ve ikincisi 5 sayısı yazdırılmadan önce biter. ## `case` Switch ifadesinde belirli bir sonucu işler. Sonuç, tek bir sayı, bir dizi sayı veya sayı aralığı olabilir: ```c new switchVar = 10; switch (switchVar) { case 1: { printf("switchVar 1'dir"); } case 4: { printf("switchVar 4'tür"); } case 2, 3, 5: { printf("switchVar 2, 3 veya 5'tir"); } case 7 .. 11: { printf("switchVar 7 ile 11 arasında veya eşit (7, 8, 9, 10 veya 11)"); } default: { printf("switchVar 1, 2, 3, 4, 5, 7, 8, 9, 10 veya 11 değildir"); } } ``` ## `continue` Break ile benzer, ancak sadece bir sonraki döngü iterasyonuna geçer. Hangi döngü türünü kullandığınıza bağlı olarak atlama noktasının değiştiğini unutmak önemlidir. ```c for (new i = 0; i < 10; i++) { if (i == 5) { continue; } printf("%d", i); } ``` Şunu üretecektir: ```c 0 1 2 3 4 6 7 8 9 ``` Print'ten sonra bir continue, temelde hiçbir şey yapmayacaktır. For döngüsünde continue, for ifadesinin üçüncü ifadesine atlar (bu örnekte "i++;" bölümü), bu, bir while döngüsünde nasıl davrandığından farklıdır: ```c new i = 0; while (i < 10) { if (i == 5) { continue; } printf("%d", i); i++; } ``` Bu, sonsuz bir döngü üretecek, çünkü continue, "i++;" hiç çağrılmamış olduğu için AFTER'a atlar ve "while (i < 10)" kısmına geri döner. Bu sırada "i" hala 5 olacak ve continue tekrar çağrılacak ve "i" sürekli olarak 5'te kalacaktır. ## `default` default, switch ifadesi tarafından açıkça ele alınmayan sonuçları işler. Bir örnek için case örneğine bakın. ## `do` do, while ile birlikte kullanılabilen ve her zaman en az bir kez çalıştırılacak bir döngü türüdür. Aşağıdaki örnekte while ()'den sonra gelen noktalı virgülü unutmayın: ```c new i = 10; do { printf("%d", i); i++; } while (i < 10); ``` "i" açıkça 10'dan küçük değil, ancak bu döngü yine de şunu üretecek: ```c 10 ``` her neyse. Benzer while döngüsü: ```c new i = 10; while (i < 10) { printf("%d", i); i++; } ``` } Koşul anında başarısız olacağından herhangi bir çıktı vermeyecek. Bu ayrıca çift kontrolleri önlemek için kullanışlıdır: ```c new checkVar = 10; if (checkVar == 10) { new i = 0; while (checkVar == 10) { checkVar = someFunction(i); i++; } } ``` Bu açıkça büyük bir sorun değil, ancak döngünün başında checkVar'ı hemen iki kez kontrol ediyorsunuz, bu oldukça anlamsızdır, ancak if gerekli çünkü koşul doğruysa ancak döngü dışında kod yapmanız gerekiyor (bu oldukça yaygın bir durumdur). Bunun yerine şunu yaparak iyileştirebilirsiniz: ```c new checkVar = 10; if (checkVar == 10) { new i = 0; do { checkVar = someFunction(i); i++; } while (checkVar == 10); } ``` Bu örnekte sonuç tamamen aynı olacaktır ancak önemli olan, bir tane daha anlamsız kontrol olmamasıdır. ## `else` else, bir if ifadesi başarısız olduğunda (varsa) çağrılır: ```c new checkVar = 5; if (checkVar == 10) { printf("Bu asla çağrılmayacak"); } else { printf("If ifadesi başarısız olduğundan bu görüntülenecek"); } ``` else, if ile birleştirilebilir: ```c new checkVar = 2; if (checkVar == 1) { printf("Bu çağrılmayacak"): } else if (checkVar == 2) { printf("İlk if başarısız olduğundan ikinci kontrol edildi ve doğru"); } else { printf("Bu çağrılmayacak çünkü if'lerden biri doğruydu"); } ``` ## `exit` Bu, mevcut programı anında sonlandırır. ```c main() { exit; return 0; } ``` ## `for` For döngüsü, üç aşamayı içeren bir döngü türüdür: başlatma, karşılaştırma ve güncelleme. Bunlar her biri bir noktalı virgülle ayrılır (gülücük ve her biri sadece bir boşluk ayarlayarak hariç tutulabilir). En temel for döngüsü şudur: ```c for ( ; ; ) {} ``` Bu başlatma, karşılaştırma ve güncelleme içermez ve sonuç olarak sonsuza kadar gider (karşılaştırma, yok olduğu için varsayılan olarak true olur). Daha yaygın olan döngülerden biri şudur: ```c for (new i = 0; i < MAX_PLAYERS; i++) { printf("%d", i); } ``` Bu döngüde başlatma şudur: ```c new i = 0; ``` Noktalı virgül başlangıcın sonunu işaretler. Bu, yalnızca bu döngüyle kullanılabilen i adında yeni bir değişkeni bildirir. Ardından karşılaştırma yapılır. Bu, i'yi MAX_PLAYERS (varsayılan 500 - #define'ye bakınız) ile karşılaştırır ve küçükse devam eder. Ardından döngünün içeriği çalıştırılır. Başlangıçta bunun "0" ı yazdırması gerekecektir. Son olarak güncelleme yapılır, "i++" bunun i değerini artırır. Şimdi tam bir iterasyon yapılır, döngü döner ve karşılaştırma aşamasına geri döner (başlatma sadece bir çağrı için bir kez yapılır). Bu döngünün sonucu, 0'dan 499'a kadar olan tüm sayıların yazdırılmasıdır. Eşdeğer while döngüsü (continue etkilerini göz ardı ederek) şu olacaktır: ```c new i = 0; while (i < MAX_PLAYERS) { printf("%d", i); i++; } ``` Üç aşama, ilk ve son bölümler için virgüller ve ortadaki bölüm için standart karşılaştırmaları kullanarak gerektiğinde çok daha karmaşık hale getirilebilir: ```c for (new i = 0, j = 200; i < MAX_PLAYERS && j > 10; i++, j -= 2) { printf("%d %d", i, j); } ``` Bu, iki yeni değişken oluşturur ve bunları sırasıyla 0 ve 200 olarak ayarlar, ardından biri 200'den küçük ve diğeri 10'dan büyük olduğu sürece döngü yapar, her seferinde birini artırır ve diğerini iki azaltır. Daha önce belirtildiği gibi, değişkenlerin kapsamı genellikle döngüyle sınırlıdır: ```c for (new i = 0; i < MAX_PLAYERS; i++) { printf("%d", i); } printf("%d", i); ``` Bu, hata verecektir çünkü "i" artık döngü bittikten sonra mevcut değil. Ancak: ```c new i = 0; for ( ; i < MAX_PLAYERS; i++) { printf("%d", i); } printf("%d", i); ``` Bu durumda "i" döngü içinde bildirilmediği için iyidir. Ayrıca "i" yi döngü içinde başlatıp orada bildirmeyi de seçebilirsiniz: ```c new i; for (i = 0; i < MAX_PLAYERS; i++) { printf("%d", i); } printf("%d", i); ``` ## `goto` Genellikle kodlama topluluğu tarafından goto ve etiketler önerilmez çünkü genellikle kodunuzu düzgün bir şekilde yeniden yapılandırmak daha iyidir. Ancak temelde goto, bir sıçramadır: ```c goto my_label; printf("Bu hiçbir zaman yazdırılmayacak"); my_label: printf("Bu yazdırılacak"); ``` Ancak derleyici goto'yu çok iyi işlemez, bu yüzden hiçbir şekilde optimize edilmez ve şunun gibi şeyler: ```c { new i = 5; if (i == 5) { goto my_label; } else { my_label: return 0; } } ``` Yürütme türleri arasında tutarsız bir dönüş türleri uyarısı verecektir, çünkü gerçekte true şubesinin hiçbir şey döndürmediğini düşünüyor, ancak aslında çok dolambaçlı bir şekilde yapar. Ayrıca: ```c MyFunction() { new i = 5; if (i == 5) { goto my_label; } return 0; my_label: return 1; } ``` Erişilemeyen kod uyarısı verecek, çünkü aslında erişilebilir olacaktır. Temel sözdizimi şudur: ```c etiket: goto etiket; ``` Etiket kendi başına bir satırda olmalı ve bir iki nokta üst üste ile biter, bir noktalı virgül DEĞİL. Etiketler değişkenler ve işlevler vb. İle aynı adlandırma kısıtlamalarını takip eder. ## `if` If, en önemli operatörlerden biridir. Bir şeyin yapılması gerekip gerekmediğini belirler ve buna göre hareket eder; goto ile birlikte neredeyse tüm diğer kontrol yapılarının temelidir: ```c for (new i = 0; i < 10; i++) { } ``` Eşdeğerdir: ```c new i = 0; for_loop: if (i < 10) { i++; goto for_loop; } ``` If'ın alabileceği koşullar bu gönderi için çok fazla olduğundan, bazıları aşağıda listelenmiştir: Operator Açıklama Örnek a=1, b=0 Durum a=1, b=1 Durum a=0, b=1 Durum a=0, b=0 Durum == Bir şeyin başka bir şeye eşit olup olmadığını kontrol eder if (a == b) false true false true != Bir şeyin başka bir şeye eşit olmadığını kontrol eder if (a != b) true false true false < Bir şeyin başka bir şeyden küçük olup olmadığını kontrol eder if (a < b) false false true false > Bir şeyin başka bir şeyden büyük olup olmadığını kontrol eder if (a > b) true false false false <= Bir şeyin başka bir şeyden küçük veya eşit olup olmadığını kontrol eder if (a <= b) false true true true >= Bir şeyin başka bir şeyden büyük veya eşit olup olmadığını kontrol eder if (a >= b) true true false true && İki şeyin doğru olup olmadığını kontrol eder (0 değil) if (a && b) false true false false || İki şeyden en az birinin doğru olup olmadığını kontrol eder (0 değil) if (a || b) true true true false ! Bir şeyin yanlış olup olmadığını kontrol eder if (!(a == b)) true false true false Bu ifadelerle karmaşık koşullar oluşturabilirsiniz: ```c if (a == b && (c != d || f < g)) ``` Bu, a'nın b'ye eşit olup olmadığını ve c'nin d'ye eşit olmaması veya f'nin g'den küçük olması durumunda doğru olacaktır (veya her ikisi birden). ## `return` Bu, bir fonksiyondan çıkar ve çağırılan fonksiyona veri döndürebilir: ```c MyFunction() { new someVar = OtherFunction(); } OtherFunction() { return 5; } ``` someVar şimdi 5 olacaktır. ```c MyFunction() { if (SomeFunction()) { printf("1 döndü"); } } SomeFunction() { return random(2); } ``` Bu, çağrılan fonksiyonun if ifadesine 1 veya 0 döndürecektir. 1 true ve 0 false olduğundan metin yalnızca 1 döndürüldüğünde görüntülenecektir. Ancak: ```c MyFunction() { if (SomeFunction()) { printf("1 ile 10 arasında bir şey döndü"); } } SomeFunction() { return random(11); } ``` Bu, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 veya 10 döndürecektir. 0 hariç herhangi bir şey true olduğundan metin, 1 ile 10 arasında bir şey döndürüldüğünde görüntülenecektir. Dizelerle de return kullanabilirsiniz: ```c MyFunction() { printf("%s", SomeFunction()); } SomeFunction() { new str[10] = "Merhaba"; return str; } ``` "Merhaba" (tırnak işaretleri olmadan) yazdırılacaktır. Ayrıca hiçbir şey döndürmek zorunda değilsiniz: ```c MyFunction() { SomeFunction(); } SomeFunction() { return; } ``` Ancak bunu yaparsanız, fonksiyonun dönüşünün asla kullanılmamasını sağlamalısınız: ```c MyFunction() { if (SomeFunction()) { printf("Sorun"); } } SomeFunction() { return; } ``` Burada SomeFunction hiçbir şey döndürmüyor olsa da, SomeFunction'dan dönen değerin true veya false olup olmadığını kontrol eden MyFunction hatası nedeniyle bir derleme hatası alacaksınız. Varsayılan dönüş hiçbir şeydir, bu nedenle: ```c SomeFunction() { return; } ``` Ve: ```c SomeFunction() { } ``` Aynıdır. Son olarak, return değerleri karıştıramazsınız: ```c MyFunction() { SomeFunction(); } SomeFunction() { if (random(2)) { return 1; } else { return; } } ``` Bunun dönüş değerini belirsiz olduğu için bir hata verecektir. ```c SomeFunction() { if (random(2)) { return 1; } } ``` Varsayılan dönüş hiçbir şey olduğu için de izin verilmez. ## `sleep` sleep, belirtilen milisaniye süresi boyunca yürütümü durduran bir taklit işlecidir: ```c printf("Zaman 0s"); sleep(1000); printf("Zaman 1s"); ``` Bu yalnızca main() içinde çalışır, ancak geri çağrılar için değil, çünkü PAWN iş parçasında çalıştırılır. ## `state` state, PAWN durum makinesinin ve otomatik sistemlerinin bir parçasıdır; daha fazla bilgi için [bu konuya](https://forum.sa-mp.com/showthread.php?t=86850) bakabilirsiniz. ## `switch` switch temelde yapılandırılmış bir if/else if/else sistemidir: ```c switch (someVar) { case 1: { printf("bir"); } case 2: { printf("iki"); } case 3: { printf("üç"); } default: { printf("diğer"); } } ``` Bu, biraz daha etkili (ve çok daha temiz) bir şekilde şu şekilde yazılabilir: ```c if (someVar == 1) { printf("bir"); } else if (someVar == 2) { printf("iki"); } else if (someVar == 3) { printf("üç"); } else { printf("diğer"); } ``` ## `while` while, for ve do..while gibi bir döngü türüdür. Temel işlem, eğer true ise bazı kodları gerçekleştiren bir if ifadesidir ve ardından if'ten sonra gider. False ise döngü kodlarından sonra gider - else yoktur. Goto örneğine geri dönersek: ```c new i = 0; for_loop: if (i < 10) { i++; goto for_loop; } ``` Bu aynı zamanda şu şekilde yazılabilir: ```c new i = 0; while (i < 10) { i++; } ``` Daha fazla bilgi için do ve for'a bakabilirsiniz.
openmultiplayer/web/docs/translations/tr/scripting/language/Statements.md/0
{ "file_path": "openmultiplayer/web/docs/translations/tr/scripting/language/Statements.md", "repo_id": "openmultiplayer", "token_count": 7185 }
471
--- title: Tutorials description: A collection of tutorials to help you write gamemodes and manage your server. --- In this section, you'll find a collection of tutorials to help you write gamemodes and manage your server. They are in no particular order.
openmultiplayer/web/docs/translations/tr/tutorials/_.md/0
{ "file_path": "openmultiplayer/web/docs/translations/tr/tutorials/_.md", "repo_id": "openmultiplayer", "token_count": 60 }
472
--- title: OnGameModeExit description: 当退出游戏模式时,即通过'gmx',关闭服务器,或者GameModeExit函数,该回调函数被调用。 tags: [] --- ## 描述 当退出游戏模式时,即通过'gmx',关闭服务器,或者 GameModeExit 函数,调用这个回调函数。 ## 案例 ```c public OnGameModeExit() { print("游戏模式 已退出。"); return 1; } ``` ## 要点 :::tip 因为更改游戏模式不会重新加载过滤脚本(filterscript),所以该函数也可以在过滤脚本中使用,用于检测是否使用了 RCON 指令(例如 changemode 或 gmx)更改游戏模式。 切记,当使用'rcon gmx'控制台指令时,可能会出现客户端 BUG。一种典型的情况是:在执行 OnGameModeInit 函数的过程中过度调用 RemoveBuildingForPlayer 函数,从而导致客户端崩溃。 当服务器崩溃或进程被其他方法终止(如使用 Linux kill 指令或在 Windows 控制台上按下关闭按钮)时,回调函数不会被触发。 ::: ## 相关函数 - [GameModeExit](../functions/GameModeExit): 退出当前游戏模式。
openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnGameModeExit.md/0
{ "file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnGameModeExit.md", "repo_id": "openmultiplayer", "token_count": 712 }
473
--- title: OnPlayerConnect description: 当玩家连接到服务器时,这个回调函数被调用。 tags: ["player"] --- ## 描述 当玩家连接到服务器时,这个回调函数被调用。 | 参数名 | 描述 | | -------- | --------------------------- | | playerid | 连接到服务器的该玩家的 ID。 | ## 返回值 0 - 将阻止其他过滤脚本接收到这个回调。 1 - 表示这个回调函数将被传递给下一个过滤脚本。 它在过滤脚本中总是先被调用。 ## 案例 ```c public OnPlayerConnect(playerid) { new string[64], playerName[MAX_PLAYER_NAME]; GetPlayerName(playerid, playerName, MAX_PLAYER_NAME); format(string, sizeof string, "%s 已加入服务器。欢迎!", playerName); SendClientMessageToAll(0xFFFFFFAA, string); return 1; } ``` ## 要点 <TipNPCCallbacksCN /> ## 相关回调
openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnPlayerConnect.md/0
{ "file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnPlayerConnect.md", "repo_id": "openmultiplayer", "token_count": 523 }
474
--- title: OnPlayerLeaveRaceCheckpoint description: 当玩家离开比赛检查点时,会调用此回调。 tags: ["player", "checkpoint", "racecheckpoint"] --- ## 描述 当玩家离开比赛检查点时,会调用此回调。 | 参数名 | 描述 | | -------- | --------------------------- | | playerid | 离开比赛检查点的玩家的 ID。 | ## 返回值 它在过滤脚本中总是先被调用。 ## 案例 ```c public OnPlayerLeaveRaceCheckpoint(playerid) { printf("玩家 %d 离开了一个比赛检查点!", 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/OnPlayerLeaveRaceCheckpoint.md/0
{ "file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnPlayerLeaveRaceCheckpoint.md", "repo_id": "openmultiplayer", "token_count": 665 }
475
--- title: OnRconCommand description: 当通过服务器控制台、远程RCON或通过游戏内“/RCON 指令”发送指令时,调用该回调。 tags: [] --- ## 描述 当通过服务器控制台、远程 RCON 或通过游戏内“/RCON 指令”发送指令时,调用该回调。 | 参数名 | 描述 | | ------ | ------------------------------------------------ | | cmd[] | 一个字符串,其中包含输入的指令和传递的任何参数。 | ## 返回值 它在过滤脚本中总是先被调用,所以返回 1 会阻止游戏模式看到它。 ## 案例 ```c public OnRconCommand(cmd[]) { printf("[RCON]: 你输入了'/rcon %s'!", cmd); return 0; } public OnRconCommand(cmd[]) { if (!strcmp(cmd, "hello", true)) { SendClientMessageToAll(0xFFFFFFAA, "你好 世界!"); print("你向世界问好。"); // 对于在聊天中输入rcon指令的玩家,将以白色文字显示。 return 1; } return 0; } ``` ## 要点 :::tip 当玩家输入指令时,“/rcon”不包含在“cmd”中。 如果你在这里使用“print”函数,它将向在游戏中输入指令的玩家发送消息以及日志。 当玩家没有以 RCON 管理员身份登录时,这个回调函数不会被调用。 如果玩家未以 RCON 管理员身份登录,并且使用/rcon login 指令,则不会调用此回调,而 OnRconLoginAttempt 将调用此回调。 然而,当玩家以 RCON 管理员的身份登录时,使用这个指令将调用这个回调。 ::: :::warning 你需要将这个回调包含在加载的过滤脚本中,以便它在游戏模式下工作! ::: ## 相关回调/函数 - [IsPlayerAdmin](../functions/IsPlayerAdmin): 检查一个玩家是否登录到 RCON。 - [OnRconLoginAttempt](OnRconLoginAttempt): 当试图登录到 RCON 时调用。
openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnRconCommand.md/0
{ "file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnRconCommand.md", "repo_id": "openmultiplayer", "token_count": 1182 }
476
--- title: AddPlayerClass description: 向玩家类选择器添加一个类。 tags: ["player"] --- ## 描述 向玩家类选择器添加一个类。类的作用是为了让玩家选择皮肤并重生。 | 参数名 | 说明 | | ------------- | ----------------------------- | | modelid | 玩家将用来重生的皮肤模型 id。 | | Float:spawn_x | 该类的重生点的 X 坐标。 | | Float:spawn_y | 该类的重生点的 Y 坐标。 | | Float:spawn_z | 该类的重生点的 Z 坐标。 | | Float:z_angle | 重生后玩家面对的方向。 | | weapon1 | 玩家的第一个重生武器。 | | weapon1_ammo | 第一个重生武器的弹药量。 | | weapon2 | 玩家的第二个重生武器。 | | weapon2_ammo | 第二个重生武器的弹药量。 | | weapon3 | 玩家的第三个重生武器。 | | weapon3_ammo | 第三个重生武器的弹药量。 | ## 返回值 刚添加的类的 ID。 如果达到类的最大数量限制(320),则为 319(最大的类 ID 是 319)。 ## 案例 ```c public OnGameModeInit() { // 玩家可以选择 CJ (0) 或 The Truth (1) 的皮肤. AddPlayerClass(0, 1958.33, 1343.12, 15.36, 269.15, 26, 36, 28, 150, 0, 0); // CJ AddPlayerClass(1, 1958.33, 1343.12, 15.36, 269.15, 26, 36, 28, 150, 0, 0); // The Truth return 1; } ``` ## 要点 :::tip 最大类 ID 为 319(从 0 开始,共 320 个类)。上限之后添加的任何类都将替换 ID 319。 ::: ## 相关函数 - [AddPlayerClassEx](AddPlayerClassEx): 添加具有默认团队的玩家类。 - [SetSpawnInfo](SetSpawnInfo): 设置玩家的重生信息。 - [SetPlayerSkin](SetPlayerSkin): 设置玩家的皮肤。
openmultiplayer/web/docs/translations/zh-cn/scripting/functions/AddPlayerClass.md/0
{ "file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/functions/AddPlayerClass.md", "repo_id": "openmultiplayer", "token_count": 1039 }
477
--- title: AttachCameraToPlayerObject description: 将玩家的视角附加在玩家物体上。 tags: ["player", "camera"] --- ## 描述 将玩家的视角附加在玩家物体上。当视角附加在物体上时,玩家可以移动视角。可与 MovePlayerObject 和 AttachPlayerObjectToVehicle 一起使用。 | 参数名 | 说明 | | -------------- | ------------------------------------- | | playerid | 将视角附加到玩家物体的玩家 ID。 | | playerobjectid | 玩家的视角将被附加到的玩家物体的 ID。 | ## 返回值 该函数不返回任何特定的值。 ## 案例 ```c public OnPlayerCommandText(playerid, cmdtext[]) { if (!strcmp(cmdtext, "/attach", false)) { new playerobject = CreatePlayerObject(playerid, 1245, 0.0, 0.0, 3.0, 0.0, 0.0, 0.0); AttachCameraToPlayerObject(playerid, playerobject); SendClientMessage(playerid, 0xFFFFFFAA, "你的视角现在已经附加到了一个物体上。"); return 1; } return 0; } ``` ## 要点 :::tip 在试图将玩家的视角附加到物体之前,必须先创建玩家物体。 ::: ## 相关函数 - [AttachCameraToObject](AttachCameraToObject): 将玩家的视角附加在一个全局物体上。 - [SetPlayerCameraPos](SetPlayerCameraPos): 设置玩家的视角位置。 - [SetPlayerCameraLookAt](SetPlayerCameraLookAt): 设置玩家的视角所看的方向。
openmultiplayer/web/docs/translations/zh-cn/scripting/functions/AttachCameraToPlayerObject.md/0
{ "file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/functions/AttachCameraToPlayerObject.md", "repo_id": "openmultiplayer", "token_count": 794 }
478
--- title: GetPlayerInterior description: 检索玩家当前的内部空间。 tags: ["player"] --- ## 描述 检索玩家当前的内部空间。目前已知的内部空间及其位置可以在[这里](../resources/interiorids)找到。 | 参数名 | 说明 | | -------- | ----------------- | | playerid | 要获取的玩家 ID。 | ## 返回值 玩家当前所处的内部空间 ID。 ## 案例 ```c public OnPlayerCommandText(playerid,text[]) { if (strcmp(cmdtext,"/int",true) == 0) { new string[128]; format(string, sizeof(string), "你所处的内部空间是 %i",GetPlayerInterior(playerid)); SendClientMessage(playerid, 0xFF8000FF, string); return 1; } return 0; } ``` ## 要点 :::tip 对于 npc 将始终返回 0。 ::: ## 相关函数 - [SetPlayerInterior](SetPlayerInterior): 设置某个玩家的内部空间。 - [GetPlayerVirtualWorld](GetPlayerVirtualWorld): 检索玩家所处的虚拟世界。
openmultiplayer/web/docs/translations/zh-cn/scripting/functions/GetPlayerInterior.md/0
{ "file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/functions/GetPlayerInterior.md", "repo_id": "openmultiplayer", "token_count": 529 }
479
--- title: floattan description: 从特定角度求正切值。 tags: ["math", "floating-point"] --- <LowercaseNote /> ## 描述 从特定角度求正切值。输入的角度可以是弧度、角度或分数。 | 参数名 | 说明 | | ----------- | ------------------------------------------------------------- | | Float:value | 求正切的角度。 | | anglemode | 要使用的[角度模式](../resources/anglemodes),取决于输入的值。 | ## 返回值 输入值的正切值。 ## 案例 ```c public OnGameModeInit() { printf("30° 的正切是 %f", floattan(30.0, degrees)); // 输出: 1 return 1; } ``` ## 要点 :::warning GTA/SA-MP 在大多数情况下使用角度来表示弧度,例如[GetPlayerFacingAngle](GetPlayerFacingAngle)。因此,你很可能想要使用“角度”模式,而不是弧度。还要注意 GTA 中的角度是逆时针的;270° 为东,90° 为西。南仍然是 180°,北仍然是 0°/360°。 ::: ## 相关函数 - [floatsin](floatsin): 从特定角度求正弦值。 - [floatcos](floatcos): 从特定角度求余弦值。
openmultiplayer/web/docs/translations/zh-cn/scripting/functions/floattan.md/0
{ "file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/functions/floattan.md", "repo_id": "openmultiplayer", "token_count": 718 }
480
--- title: Pickup Guide --- A short tutorial that describes how to use pickups. ## Define the pickupid The first thing to be done when creating pickups is creating a place to store their ID. This will be done in a global variable so it can be set when you create the pickup and read when you pick up a pickup, calling a callback with the ID of the pickup you picked up. For this example we will use the name "gMyPickup". ```c new gMyPickup; ``` ## Creating the pickup There are two ways to create pickups. [CreatePickup](../scripting/functions/CreatePickup) and [AddStaticPickup](../scripting/functions/AddStaticPickup). AddStaticPickup doesn't return an ID when it is created, can't be destroyed and can only be used under OnGameModeInit, so for this example we will use [CreatePickup](../scripting/functions/CreatePickup). **The syntax for [CreatePickup](../scripting/functions/CreatePickup) is:** **Parameters:** | model | The model you'd like to use for the pickup. | | ------------ | --------------------------------------------------------------------------------------------------------- | | type | The pickup spawn type, see further down this page. | | Float:X | The X-coordinate for the pickup to show. | | Float:Y | The Y-coordinate for the pickup to show. | | Float:Z | The Z-coordinate for the pickup to show. | | Virtualworld | The virtual world ID of the pickup. A value of -1 will cause the pickup to display in all virtual worlds. | For this example we will create a cash pickup at Grove Street. Now we need to decide on a model to appear in the world, there are lots of models to choose from, some are listed on the external site [here](https://dev.prineside.com/en/gtasa_samp_model_id), here choose model number 1274 which is dollar sign. Finally we need a [Type](../scripting/resources/pickuptypes) for the pickup, on the same page with the pickup models is a list of pickup types describing what the various ones do. We want this pickup to disappear when you pick it up, so you can't pick it up repeatedly, but to reappear after a few minutes so you can pick it up again, type 2 does just this. Pickups are most commonly created when the script starts, in [OnGameModeInit](../scripting/callbacks/OnGameModeInit) or [OnFilterScriptInit](../scripting/callbacks/OnFilterScriptInit) depending on the script type, however it can go in any function (for example you could create a weapon drop script which would use OnPlayerDeath to create weapon pickups). So here is the code to create our pickup, and store the ID in 'gMyPickup': ```c gMyPickup = CreatePickup(1274, 2, 2491.7900, -1668.1653, 13.3438, -1); ``` ### Choosing what it does When you pick up a pickup, [OnPlayerPickUpPickup](../scripting/callbacks/OnPlayerPickUpPickup) is called, passing playerid (the player that picked up a pickup) and pickupid (the ID of the pickup that was picked up). Some pickup types are designed to work automatically, so there is no need to do anything under OnPlayerPickUpPickup. Check out the [Pickup Types](../scripting/resources/pickuptypes) page for more information. When a player picks up our new pickup, we want to give them $100, to do this first we need to check that they have picked up our dollar pickup and not a different one. When we've done that, we can give them the $100: ```c public OnPlayerPickUpPickup(playerid, pickupid) { // Check that the pickup ID of the pickup they picked up is gMyPickup if(pickupid == gMyPickup) { // Message the player SendClientMessage(playerid, 0xFFFFFFFF, "You received $100!"); // Give the player the money GivePlayerMoney(playerid, 100); } // if you need to add more pickups, simply do this: else if (pickupid == (some other pickup)) { // Another pickup, do something else } return 1; } ``` Congratulations, you now know how to create and handle pickups! ## Further Reading You can use the [Streamer](https://github.com/samp-incognito/samp-streamer-plugin) plugin to create unlimited pickups with [CreateDynamicPickup](<https://github.com/samp-incognito/samp-streamer-plugin/wiki/Natives-(Pickups)>) You can also create per-player pickup with [CreatePlayerPickup](../scripting/functions/CreatePlayerPickup).
openmultiplayer/web/docs/tutorials/PickupGuide.md/0
{ "file_path": "openmultiplayer/web/docs/tutorials/PickupGuide.md", "repo_id": "openmultiplayer", "token_count": 1543 }
481
# সচরাচর জিজ্ঞাস্য <hr /> ## open.mp কি? open.mp (Open Multiplayer, OMP)সান অ্যান্ড্রিয়াসের জন্য বিকল্প মাল্টিপ্লেয়ার মোড SA:MP, আপডেট এবং পরিচালনার সমস্যাগুলির ক্ষেত্রে দুর্ভাগ্যজনক বৃদ্ধির প্রতিক্রিয়া হিসাবে শুরু করা হয়েছে:Open.mp। প্রাথমিক প্রকাশটি কেবল সার্ভারের জন্য একটি ড্রপ-ইন প্রতিস্থাপন হবে। বিদ্যমান SA:MP ক্লায়েন্টরা এই সার্ভারে সংযোগ করতে সক্ষম হবে।ভবিষ্যতে, একটি নতুন Open.mp ক্লায়েন্ট উপলব্ধ হবে, আরও আকর্ষণীয় আপডেট প্রকাশের অনুমতি দেয়। ## এটি কি SA:MP-র একটি অনুলিপি? না। এটি কয়েক দশকের জ্ঞান এবং অভিজ্ঞতার সুযোগ নিয়ে একটি সম্পূর্ণ পুনর্লিখন। এসএএমপি অনুলিপি করার চেষ্টা আগেও হয়েছিল, তবে আমরা বিশ্বাস করি এগুলির দুটি বড় সমস্যা ছিল: 1.এগুলি ফাঁস SA:MP উত্স কোডের ভিত্তিতে ছিল। এই মোডগুলির লেখকদের এই কোডটির কোনও আইনগত অধিকার ছিল না এবং তারা নৈতিক ও আইনীভাবে সর্বদা পশ্চাতপদ ছিল। আমরা এই কোডটি ব্যবহার করতে প্রত্যাখ্যান করি। এটি সামান্য উন্নয়নের গতিকে বাধাগ্রস্থ করে, তবে এটি দীর্ঘকালীন সঠিক পদক্ষেপ। 2. তারা একবারে খুব বেশি পুনরায় উদ্ভাবনের চেষ্টা করেছিল। হয় সমস্ত স্ক্রিপ্টিং ইঞ্জিন প্রতিস্থাপন, বা নতুন যুক্ত করার সময় বৈশিষ্ট্যগুলি অপসারণ, বা কেবল বেমানান উপায়ে জিনিস টুইট করা। এটি বিশাল কোডবেস এবং প্লেয়ারব্যাসগুলির সাথে বিদ্যমান সার্ভারগুলিকে ওপরে চলতে বাধা দেয়, কারণ তাদের কোডের কিছু নিই, আবার কিছু লিখতে হবে - একটি সম্ভাব্য বিশাল উদ্যোগ গ্রহণ। আমরা সময়ের সাথে সাথে বৈশিষ্ট্যগুলি যুক্ত করতে এবং জিনিসগুলিকে ঝাপটানোর জন্য পুরোপুরি ইচ্ছা করি, তবে আমরা বিদ্যমান সার্ভারগুলিকে সমর্থন করার ক্ষেত্রেও তাদের মনোনিবেশ করেছি, তাদের কোডগুলি পরিবর্তন না করে আমাদের কোড ব্যবহার করার অনুমতি দেয়। <hr /> ## আপনাদের করার প্রয়োজনীয়তা! SA:MP বিকাশের আনুষ্ঠানিকভাবে এগিয়ে যাওয়ার প্রচেষ্টার পরেও প্রস্তাবের আকারে, শেভভিং, এবং বেটা টিমের সহায়তার প্রস্তাব; একটি সম্প্রদায়ের পাশাপাশি একেবারে নতুন কোনও তার প্রাপ্তির তালিকায় নেই; কোন অগ্রগতি মোটেও দেখা যায়নি। এটি কেবল নেতৃত্বের পক্ষে আগ্রহের অভাবকেই বিস্তৃত বলে মনে করা হয়েছিল, এটি নিজের মধ্যে কোনও সমস্যা নয়, তবে উত্তরসূরির কোনও রেখা ছিল না। মোডে কাজ চালিয়ে যেতে আগ্রহীদের হাতে উন্নয়নের হাত তুলে দেওয়ার পরিবর্তে, প্রতিষ্ঠাতা কেবল সবকিছু দিয়ে নিজের আয়ত্তের মধ্যে আনতে চেয়েছিলেন, যতক্ষণ সম্ভব ন্যূনতম পরিশ্রমের জন্য ততক্ষন জিনিসগুলি চালিয়ে রেখেছিলেন। কেউ কেউ দাবি করেন এটি প্যাসিভ আয়ের কারণে, তবে এর কোনও প্রমাণ নেই। বিপুল আগ্রহ, এবং একটি পারিবারিক সম্প্রদায় থাকা সত্ত্বেও, তিনি বিশ্বাস করেছিলেন যে মোডে মাত্র 1-2 বছর বাকি ছিল, এবং যে সম্প্রদায়টি SA:MP তৈরি করার জন্য এত কঠোর পরিশ্রম করেছিল তা আজকের ধারাবাহিকতার দাবিদার নয়। আমরা একমত না। <hr /> ## Kalcor / SA:MP সম্পর্কে আপনার মতামত কী? আমরা SA:MP পছন্দ করি, এজন্য আমরা এখানে রয়েছি - এবং কালকোরের কাছে এটি তৈরি করা আমাদের ঋণগ্রস্ত থাকা। তিনি কয়েক বছর ধরে মোডের জন্য প্রচুর পরিমাণে কাজ করেছেন এবং সেই অবদানটি ভুলে যাওয়া বা উপেক্ষা করা উচিত নয়। Open.mp-র দিকে পরিচালিত পদক্ষেপগুলি নেওয়া হয়েছিল কারণ আমরা সাম্প্রতিক বেশ কয়েকটি সিদ্ধান্তের সাথে একমত নই, এবং মোডকে ভিন্ন দিকে পরিচালিত করার জন্য বারবার চেষ্টা করা সত্ত্বেও কোনও সমাধান আসন্ন হতে দেখা যায় নি। এইভাবে আমরা SA:MP কে চেষ্টা এবং অব্যাহত রাখার দুর্ভাগ্যজনক সিদ্ধান্ত নিতে বাধ্য হয়েছিলাম কালকোর ছাড়াই। এটি ব্যক্তিগতভাবে তার বিরুদ্ধে গৃহীত কোনও পদক্ষেপ নয় এবং ব্যক্তিগতভাবে তার উপর আক্রমণ হিসাবে দেখা উচিত নয়। আমরা Open.mp ইস্যুতে যেখানেই দাঁড়িয়ে থাকুক না কেন - আমরা কারও বিরুদ্ধে কোনও ব্যক্তিগত অবমাননা সহ্য করব না; অ্যাড-হোমনেম আক্রমণটিকে অবলম্বন না করে আমাদের যুক্তিসঙ্গত বিতর্ক করতে সক্ষম হওয়া উচিত। <hr /> ## এটি কি কেবল সম্প্রদায়কে বিভক্ত করছে না? এটা আমাদের উদ্দেশ্য নয়। আদর্শভাবে কোনও বিভাজনের প্রয়োজন হবে না, তবে কিছু ভাগ করে নেওয়া এবং সেই অংশটি সংরক্ষণ করা পুরো বিষয়টিকে চলে যাওয়ার থেকে ভাল। প্রকৃতপক্ষে, এই মোডটি ঘোষণার পর থেকে প্রচুর অন্যান্য ভাষা সম্প্রদায় ইংরেজি সম্প্রদায়ের সাথে পুনরায় জড়িত। এই সম্প্রদায়গুলি আগে ধীরে ধীরে ধাক্কা দিয়ে বাইরে সরানো হয়েছিল, সুতরাং তাদের পুনরায় অন্তর্ভুক্তি আসলে একটি বিভক্ত সম্প্রদায়কে আবার একত্রিত করছে। অফিসিয়াল SA:MP ফোরামগুলি থেকে বিপুল সংখ্যক লোককে নিষিদ্ধ করা হয়েছে (এবং কিছু ক্ষেত্রে তাদের পুরো পোস্ট ইতিহাস মুছে ফেলা হয়েছে), তবে কালাকর নিজেই উল্লেখ করেছেন যে অফিশিয়াল ফোরামগুলি SA:MP নয়, কেবল SA:MP একটি অংশ। অনেক প্লেয়ার এবং সার্ভারের মালিকরা কখনও এই ফোরামে পোস্ট করেনি, বা এমনকি যোগদানও করেন নি; সুতরাং এই লোকদের সাথে আবার কথা বলা সম্প্রদায়ের আরও অনেক অংশকে এক করে দিচ্ছে। <hr /> ## যেহেতু এটি "ওপেন" মাল্টিপ্লেয়ার, তাই এটি কি ওপেন সোর্স হবে? হ্যাঁ, শেষ পর্যন্ত এটি পরিকল্পনা। আপাতত আমরা যোগাযোগ ও স্বচ্ছতার দিক থেকে উন্নয়নকে উন্মুক্ত করার চেষ্টা করছি (যা নিজেই একটি উন্নতি) এবং যখন আমরা পারবো তখন ওপেন সোর্সিংয়ের দিকে এগিয়ে যাব, একবার যখন সমস্ত কিছু সাজানো এবং নিষ্পত্তি হয়ে যায়। <hr /> ## কখন প্রকাশ হবে? এটি পুরানো প্রশ্ন, দুর্ভাগ্যক্রমে এটির পুরানো উত্তর রয়েছে: এটি হয়ে গেলে। এর মতো একটি প্রকল্প কতটা সময় নেবে তা জানার সহজ উপায় নেই। এটি এখন কিছুক্ষণ চুপচাপ চলছে এবং লোকেরা কীভাবে ব্যস্ত তার উপর নির্ভর করে ক্রিয়াকলাপ স্তরে ইতিমধ্যে কয়েকটি ওঠানামা দেখাছে। তবে আশ্বাস-নিশ্চিতভাবে এটি ঠিক আছে, এবং কিছু মৌলিক নকশার সিদ্ধান্তের দ্রুত অগ্রগতি (আমরা পরে আর্কিটেকচার সম্পর্কে আরও কিছু বলব)। <hr /> ## আমি কিভাবে সাহায্য করতে পারি? ফোরাম চেক করুন। আমাদের ঠিক এটির জন্য একটি বিষয় আছে এবং আরও কাজ উপলব্ধ হওয়ার সাথে সাথে এটি আপডেট রাখা হবে। প্রকল্পটি কিছুটা আগে প্রকাশিত হওয়ার পরে, সময়ের অল্প কিছু আগে প্রকাশিত হওয়া প্রকল্পটি আমরা পেয়ে জায়ি তার মানে এই নয় যে আমাদের জানা সম্পূর্ণ ভাবে বন্দ করেদেবো। আগ্রহী হওয়ার জন্য এবং এই প্রকল্পে বিশ্বাস করার জন্য আপনাকে অগ্রিম ধন্যবাদ: ["আমি কিভাবে সাহায্য করতে পারি?" বিষয়](https://forum.open.mp/showthread.php?tid=99) <hr /> ## burgershot.gg কী? burgershot.gg একটি গেমিং ফোরাম, এর চেয়ে বেশি কিছুই নয়। অনেক লোক উভয়ের সাথেই জড়িত এবং কিছু OMP বিকাশ এবং আপডেটগুলি সেখানে পোস্ট করা হলেও তারা দুটি স্বতন্ত্র প্রকল্প। এগুলি OMP ফোরাম নয়, না OMP বার্গারশট সম্পত্তি। একবার একটি পূর্ণ OMP সাইট চালু হয়ে গেলে, দু'জন একে অপরের কাছ থেকে নিষ্ক্রিয় হতে পারে (অনেকটা SA:MP একবার নিজের সাইটটি শুরুর আগে GTAForums দ্বারা হোস্ট করা হয়েছিল)। <hr /> ## তাহলে OpenMP কী? সমান্তরাল কম্পিউটিং প্রকল্পটি "OpenMP" এবং আমরা "Open.mp" এটি সম্পূর্ণ আলাদা জিনিস।
openmultiplayer/web/frontend/content/bn/faq.mdx/0
{ "file_path": "openmultiplayer/web/frontend/content/bn/faq.mdx", "repo_id": "openmultiplayer", "token_count": 11090 }
482
# Open Multiplayer Eine kommende Mehrspieler-Modifikation für _Grand Theft Auto: San Andreas_, die vollständig mit der bereits existierenden Modifikation _San Andreas Multiplayer_ rückwärtskompatibel ist. <br /> Somit **funktionieren sowohl der originale SA:MP Client, als auch die existierenden SA:MP Skripte mit open.mp** und darüber hinaus werden viele der im SA:MP Server existierenden Bugs behoben, ohne dass Hacks und Workarounds nötig sind. Falls du dich fragst, wann der erste öffentliche Release geplant ist oder wie du zum Projekt beitragen kannst, dann [lese diesen Thread](https://forum.open.mp/showthread.php?tid=99) für weitere Informationen. # [FAQ](/faq)
openmultiplayer/web/frontend/content/de/index.mdx/0
{ "file_path": "openmultiplayer/web/frontend/content/de/index.mdx", "repo_id": "openmultiplayer", "token_count": 251 }
483
# FAQ <hr /> ## What is open.mp? open.mp (Open Multiplayer, OMP) is a substitute multiplayer mod for San Andreas, initiated in response to the unfortunate increase in problems with updates and management of SA:MP. The initial release is a drop-in replacement for the server only. Existing SA:MP clients are able to connect to this server. In the future, a new open.mp client will become available, allowing more interesting updates to be released. <hr /> ## Is it a fork? No. This is a complete rewrite, taking advantage of decades of knowledge and experience. There have been attempts to fork SA:MP before, but we believe these had two major problems: 1. They were based on leaked SA:MP source code. The authors of these mods had no legal right to this code, and were thus always on the back foot, both morally and legally. We outright refuse to use this code. This slightly hampers development speed, but is the right move in the long-run. 2. They tried to reinvent too much at once. Either replacing all the scripting engine, or removing features while adding new ones, or just tweaking things in incompatible ways. This prevents existing servers with huge codebases and playerbases from moving over, as they would have to rewrite some, if not all, of their code - a potentially massive undertaking. We fully intend to add features, and tweak things, over time, but we are also focussed on supporting existing servers, allowing them to use our code without changing theirs. <hr /> ## Why are you doing this? Despite numerous attempts to push SA:MP development forward officially, in the form of suggestions, chivvying, and offers of help from the beta team; alongside a community crying out for anything new at all; no progress was seen at all. This was widely believed to be simply down to a lack of interest on the part of the mod leadership, which is not a problem in itself, but there was no line of succession. Rather than handing development reigns over to those interested in continuing to work on the mod, the founder simply wanted to bring everything down with himself, while apparently stringing things along as long as possible for minimal effort. Some claim this is for passive income reasons, but there is no evidence of that. Despite huge interest, and a strong and familial community, he believed there was only 1-2 years left in the mod, and that the community that had worked so hard to make SA:MP what it is today did not deserve a continuation. We disagree. <hr /> ## What are your opinions on Kalcor/SA:MP/whatever? We love SA:MP, that's why we're here in the first place - and we owe creating that to Kalcor. He has done a huge amount for the mod over the years, and that contribution should not be forgotten or ignored. The actions leading to open.mp were taken because we disagreed with several recent decisions, and despite repeated attempts to guide the mod in a different direction, no solution was seen to be forthcoming. Thus we were forced to make the unfortunate decision to try and continue SA:MP in spirit without Kalcor. This is not an action taken against him personally, and should not be seen as an attack on him personally. We will not tolerate any personal insults against anyone - regardless of where they stand on the open.mp issue; we should be able to have a reasonable debate without resorting to ad-hominem attacks. <hr /> ## Isn't this just splitting the community? That is not our intention. Ideally no split would be required at all, but splitting off some and saving that part is better than watching the whole thing wither away. In fact, since this mod was announced a large number of non-English communities have re-engaged with the English community. These communities were slowly pushed out and side-lined previously, so their re-inclusion is actually bringing a split community back together. A large number of people have been banned from the official SA:MP forums (and in some cases, their entire post history purged), but Kalcor himself has pointed out that the official forums are not SA:MP, merely a part of SA:MP. Many players and server owners have never posted on, or even joined those forums; so talking to these people again is unifying yet more parts of the community. <hr /> ## How can I help? Keep your eyes on the forums. We have a topic for exactly this, and will keep it updated as more work becomes available. While the project was revealed a little earlier than intended, we are already well on the way to an initial release, but that doesn't mean more help is not always massively appreciated. Thank you in advance for taking an interest, and believing in the project: ["How to help" topic](https://forum.open.mp/showthread.php?tid=99) <hr /> ## What about OpenMP? The Open Multi-Processing project is "OpenMP", we are "open.mp". Totally different.
openmultiplayer/web/frontend/content/en/faq.mdx/0
{ "file_path": "openmultiplayer/web/frontend/content/en/faq.mdx", "repo_id": "openmultiplayer", "token_count": 1095 }
484
# Open Multiplayer En kommende flerspiller-klient for _Grand Theft Auto: San Andreas_ som vil være fullt bakoverkompatibel med den eksisterende _San Andreas Multiplayer._ <br /> Med dette menes det at **nåværende SA:MP klienter og alt av eksisterende kode og scripts vil fungere på open.mp** og, i tillegg så vil mange bugs bli fikset, uten at det krever stygge metoder og modifiseringer. Om du lurer på hvordan du kan være med å hjelpe, eller hvordan DU kan hjelpe til med prosjektet, ta en titt på <a href="https://forum.open.mp/showthread.php?tid=99">denne forum-posten</a> for mer info. # [Ofte stilte spørsmål](/faq)
openmultiplayer/web/frontend/content/no/index.mdx/0
{ "file_path": "openmultiplayer/web/frontend/content/no/index.mdx", "repo_id": "openmultiplayer", "token_count": 250 }
485
--- title: Форум и википедија угашени description: Питате се зашто су SA-MP сајт и википедија угашени? За више информација и шта да предузмете, прочитајте ово. --- # Зашто су википедија и форум угашени? 25. септембра 2020. цертификати и за forum.sa-mp.com и за wiki.sa-mp.com су истекли. Многи су ово приметили ово и пренели на дискорд. Ипак, сајт је још увек доступан заобилажењем HTTPS сигурности, било је очигледно да је нешто веће нетачно. Следећег дана, корисници су нашли оба сајта угашена са грешкама датабазе приказаним у претраживачи. ![https://i.imgur.com/hJLmVTo.png](https://i.imgur.com/hJLmVTo.png) Сада, ова грешка је честа, обично указује бекап датабазе, али због инцидента са SSL цертификатом, изгледало је да указује на нешто друго. Касније тог дана, оба сајта су комплетно угашена, чак нису ни одговарали страницом грешке. ![https://i.imgur.com/GjzURlq.png](https://i.imgur.com/GjzURlq.png) ## Шта ово значи? Постоји много спекулација на SA-MP заједници, али нема званичног обавештења о томе шта се догодило. Као што смо научили у прошлости, како год, најбоље је да претпоставимо најгоре. Форум и википедија се неће поново палити. Било би супер да грешимо. ## Замене За сад, википедијином садржају се још увек може приступити преко [the Archive.org copies](http://web-old.archive.org/web/20200314132548/https://wiki.sa-mp.com/wiki/Main_Page). Ово очигледно није трајно решење. Овим страницама треба дуго времена да се учитају и нарушавају рад Archive.org сервиса (који је довољно нефинансиран и веома битан део интернет историје). [Опорављена SA-MP википедија](/docs) је супер замена. Користи Markdown и одржава се помоћу GitHub и Vercel. Ми молимо кориснике да допринесу развоју колико год могу да бисмо пренели цео садржај старе википедије на нову. Више информација: https://github.com/openmultiplayer/wiki/issues/27
openmultiplayer/web/frontend/content/sr/missing-sites.mdx/0
{ "file_path": "openmultiplayer/web/frontend/content/sr/missing-sites.mdx", "repo_id": "openmultiplayer", "token_count": 1763 }
486
--- title: Turfs (formerly gangzones) module date: "2019-10-19T04:20:00" author: J0sh --- Привіт! Я щойно закінчив нашу реалізацію Turf на сервері, і я подумав опублікувати огляд цього модуля і показати, що ми не вийшли або щось подібне! ```pawn // Creates a Turf. A playerid can be passed in order to make it a player turf. native Turf:Turf_Create(Float:minx, Float:miny, Float:maxx, Float:maxy, Player:owner = INVALID_PLAYER_ID); // Destroys a turf. native Turf_Destroy(Turf:turf); // Shows a Turf to a player or players. // Will send to all players if playerid = INVALID_PLAYER_ID. native Turf_Show(Turf:turf, colour, Player:playerid = INVALID_PLAYER_ID); // Hides a Turf from a player or players. // Will send to all players if playerid = INVALID_PLAYER_ID. native Turf_Hide(Turf:turf, Player:playerid = INVALID_PLAYER_ID); // Flashes a Turf for a player or players. // Will send to all players if playerid = INVALID_PLAYER_ID. native Turf_Flash(Turf:turf, colour, Player:playerid = INVALID_PLAYER_ID); // Stops a Turf from flashing for player(s). // Will send to all players if playerid = INVALID_PLAYER_ID. native Turf_StopFlashing(Turf:turf, Player:playerid = INVALID_PLAYER_ID); ``` Це, очевидно, відрізняється від традиційного API, але, щоб не хвилюватися, для такого роду матеріалів будуть наявні обгортки, щоб переконатись, що звичайний сценарій можна перекомпілювати без проблем та без редагувань. Ще одним важливим фактом, який ви можете захотіти знати, є те, що кожна ділянка знаходиться в одному пулі, і з сценарію слід створити максимум 4,294,967,295 turfs. Однак клієнт може одночасно обробити лише 1024 turfs.
openmultiplayer/web/frontend/content/uk/blog/turfs-formerly-gangzones-module.mdx/0
{ "file_path": "openmultiplayer/web/frontend/content/uk/blog/turfs-formerly-gangzones-module.mdx", "repo_id": "openmultiplayer", "token_count": 1030 }
487
<h1>常见问题解答</h1> <hr /> <h2>open.mp是什么?</h2> open.mp (Open Multiplayer,OMP,开放多人游戏)是一个圣安地列斯的联机模组,目的是为了取代在开发上问题不断累积,以及几乎停止更新的 SA:MP。最初发布的版本只是用于临时替代 SA:MP 服务端。因此现有的 SA:MP 客户端依然能够连接到 OMP 服务器。在未来,新的 OMP 客户端也将发布,届时会有更多有趣的更新。 <hr /> <h2>这是一个派生分支吗?</h2> 不是的,这是我们利用长年累积的经验对其进行彻底的重写。我们曾尝试使用派生的 SA:MP,但我们认为主要存在两个问题: <ol> <li>它们基于泄露的 SA:MP 源码。这些联机模组的作者没有合法权利使用这些代码,因此无论在道德还是法律上都没有保障。我们断然拒绝使用这些代码,因此稍微阻碍了些开发速度,但从长远来看,这是最正确的举措。</li> <li>它们试图一次性改变太多东西。要么替换掉所有的脚本引擎,要么在添加新功能的同时删除功能,要么就是以不兼容的方式调整东西。这使得拥有庞大的代码量和玩家群体的现有服务器无法迁移过来,因为他们必须重写部分(甚至全部)代码,这将是一个巨大的工程。我们打算渐进式增加功能并做出调整,同时也专注于支持现有的服务器,允许他们使用而不需要对代码做出另外改变。</li> </ol> <hr /> <h2>你们为什么要这么做?</h2> 尽管测试团队以建议、劝说和提供帮助的形式,多次尝试推动 SA:MP 的官方开发; 社区中的人们也对任何新事物都充满了渴望; 但还是完全看不到任何进展。大多数人普遍认为只是因为联机模组领导层失去了兴趣,但这并不是主要的问题,主要问题是没有其他人能够继续开发。创始人并没有把开发权交给那些有兴趣继续开发联机模组的人,而是只想把所有的事情都拖垮,而显然用最少的努力就可以把事情拖得很久。有些人声称这是因为被动收入,但没有证据表明这一点。尽管我们有着巨大的兴趣和像家一样强大的社区,但创始人仍然认为联机模组只剩下 1-2 年的时间了,社区如此努力地运作却使 SA:MP 成为今天的样子,不值得继续下去。 <br /> 但我们并不这么认为。 <hr /> <h2>你们对Kalcor/SA:MP有什么看法?</h2> 我们热爱 SA:MP,这就是我们在这里的原因,我们要感谢 Kalcor 创造的这一切。多年来,他为联机模组做了大量的工作,这种贡献不应该被遗忘或忽视。导致 open.mp 项目的行动是因为我们不同意最近的几个决定,尽管一再尝试引导联机模组向不同的方向发展,但看不到有任何解决方案。因此,我们被迫做出不幸的决定,试图在没有 Kalcor 的情况下延续 SA:MP 的精神。这不是针对他个人的行动,也不应该被看作是对他个人的攻击。我们绝不容忍任何人对他人的侮辱--无论他们在 open.mp 问题上的立场如何;我们应该要理性辩论,而不是诉诸于人身攻击。 <hr /> <h2>这不是在分裂社区吗?</h2> 这不是我们的意图。理想情况下,根本不需要分裂,但分裂一些,保留一些,总比眼睁睁地看着整个社区凋零要好。事实上,自从 OMP 这一联机模组宣布以来,大量的非英语社区重新加入了英语社区。这些社区以前被慢慢地排挤,所以他们的重新加入实际上是将一个分裂的社区重新聚集在了一起。许多人被禁止进入 SA:MP 官方论坛(在某些情况下,他们的所有帖子历史都被清除),但 Kalcor 本人指出,官方论坛不是 SA:MP,只是 SA:MP 的一部分。许多玩家和服务器所有者从来没有在这些论坛上发帖,甚至没有加入过论坛;所以,能够再次和这些人交流,反而能将社区变得更加紧密团结。 <hr /> <h2>既然它是“开放”多人游戏,那么它会开源吗?</h2> 是的,这是最终计划。目前,我们正努力使开发在沟通和透明度方面变得开放(这本身就是一种改进),并将在一切都解决后,尽可能地向开源方向发展。 <hr /> <h2>什么时候会发布呢?</h2> 既然是个老问题,我们也用老答案回答吧:什么时候完成,什么时候发布。毕竟我们也无法预测像这样的项目需要多长时间。但请放心,它已经悄悄地运行了一段时间,并且已经看到了一些活跃水平的波动,这取决于人们的忙碌程度。由于一些基础的设计架构,目前正在顺利地进行,并且进展很快(稍后我们将详细讨论架构)。 <hr /> <h2>我该如何帮助你们?</h2> 请持续关注论坛。我们有一个关于这个问题的话题,并将随着更多工作的开展而不断更新。虽然这个项目比预定的时间早了一点,但我们已经在发布最初版本的路上了,但这并不意味着我们不欢迎更多的帮助。提前感谢你的兴趣和对项目的信心。 <br /> <a href="https://forum.open.mp/showthread.php?tid=99"> <u>话题 "如何帮助"</u> </a> <hr /> <h2>burgershot.gg 是什么呢?</h2> burgershot.gg 只是一个游戏论坛,仅此而已。很多人都参与了这两个项目,一些 OMP 的开发和更新也发布在那里,但它们是两个独立的项目。它们不是 OMP 论坛,OMP 也不是 burgershot 的一部分。一旦完整的 OMP 网站建设并运行,两者就可以相互分离(就像 SA:MP 在自己的网站建设之前,曾经由 GTAForums 托管一样)。 <hr /> <h2>那么OpenMP是什么呢?</h2> 开放多线程并发项目是"OpenMP",我们是"open.mp"。两者完全不同。
openmultiplayer/web/frontend/content/zh-cn/faq.mdx/0
{ "file_path": "openmultiplayer/web/frontend/content/zh-cn/faq.mdx", "repo_id": "openmultiplayer", "token_count": 3986 }
488
import { Button } from "@chakra-ui/button"; import { ArrowBackIcon } from "@chakra-ui/icons"; import { Link } from "@chakra-ui/layout"; import NextLink from "next/link"; import { FC } from "react"; type Props = { to: string; }; const BackLink: FC<Props> = ({ to }) => { return ( <NextLink href={to}> <Link className="black-80 hover-blue"> <Button leftIcon={<ArrowBackIcon />} variant="outline"> Back </Button> </Link> </NextLink> ); }; export default BackLink;
openmultiplayer/web/frontend/src/components/forum/BackLink.tsx/0
{ "file_path": "openmultiplayer/web/frontend/src/components/forum/BackLink.tsx", "repo_id": "openmultiplayer", "token_count": 205 }
489
import { Box } from "@chakra-ui/react"; import Image from "next/image"; import { FC } from "react"; import { API_ADDRESS } from "src/config"; const imageUrl = (id: string) => `${API_ADDRESS}/users/image/${id}`; type Props = { id: string; size?: string; }; const ProfilePicture: FC<Props> = ({ id, size = "1.5em" }) => { const src = imageUrl(id); return ( <Box overflow="hidden" borderRadius="50%" w={size}> <Image src={src} alt="User's profile picture" width={40} height={40} layout="responsive" objectFit="contain" /> </Box> ); }; export default ProfilePicture;
openmultiplayer/web/frontend/src/components/member/ProfilePicture.tsx/0
{ "file_path": "openmultiplayer/web/frontend/src/components/member/ProfilePicture.tsx", "repo_id": "openmultiplayer", "token_count": 270 }
490
import Admonition from "../../../Admonition"; export default function WarningVersion({ version, name = "function", }: { version: string; name: string; }) { return ( <Admonition type="warning"> <p> Ovo {name} je dodano u {version} i neće raditi u ranijim verzijama! </p> </Admonition> ); }
openmultiplayer/web/frontend/src/components/templates/translations/bs/version-warning.tsx/0
{ "file_path": "openmultiplayer/web/frontend/src/components/templates/translations/bs/version-warning.tsx", "repo_id": "openmultiplayer", "token_count": 142 }
491
import Admonition from "../Admonition"; export default function WarningVersion({ version, name = "function", }: { version: string; name: string; }) { return ( <Admonition type="warning"> <p> This {name} was added in {version} and will not work in earlier versions! </p> </Admonition> ); }
openmultiplayer/web/frontend/src/components/templates/version-warning.tsx/0
{ "file_path": "openmultiplayer/web/frontend/src/components/templates/version-warning.tsx", "repo_id": "openmultiplayer", "token_count": 131 }
492
import React from "react"; import { GetServerSidePropsContext, GetServerSidePropsResult } from "next"; const Page = () => ( <section className="center measure-wide"> <h1>{`>:(`}</h1> </section> ); export const getServerSideProps = async ( _: GetServerSidePropsContext ): Promise<GetServerSidePropsResult<unknown>> => { throw new Error(">:("); }; export default Page;
openmultiplayer/web/frontend/src/pages/angry.tsx/0
{ "file_path": "openmultiplayer/web/frontend/src/pages/angry.tsx", "repo_id": "openmultiplayer", "token_count": 128 }
493
import { Button } from "@chakra-ui/button"; import { Box, Flex, Stack, Text } from "@chakra-ui/layout"; import React, { FC, ReactElement, useCallback, useState } from "react"; import { CardList } from "src/components/generic/CardList"; import Measured from "src/components/generic/Measured"; const initial = [ Math.random(), Math.random(), Math.random(), Math.random(), Math.random(), Math.random(), Math.random(), Math.random(), Math.random(), Math.random(), Math.random(), Math.random(), Math.random(), Math.random(), Math.random(), Math.random(), Math.random(), Math.random(), Math.random(), Math.random(), Math.random(), Math.random(), Math.random(), Math.random(), ]; const ListControls: FC = ({ children }) => { return ( <Flex padding="0.5em" borderColor="blackAlpha.100" borderStyle="solid" borderWidth="1px" borderRadius="0.5em" > {children} </Flex> ); }; const Page: FC = () => { const [items, setItems] = useState(initial); const onAdd = useCallback( () => setItems([Math.random(), ...items]), [items, setItems] ); const onRemove = useCallback( (idx: number) => () => { const newItems = [...items]; newItems.splice(idx, 1); setItems(newItems); }, [items, setItems] ); const elements: ReactElement[] = items.map( (n, idx): ReactElement => ( <Box key={n}> <Text m="0">List item {n}</Text> <Button onClick={onRemove(idx)}>Remove</Button> <style jsx>{` div { max-width: 10em; } `}</style> </Box> ) ); return ( <Measured> <Stack> <ListControls> <Button onClick={onAdd}>Add</Button> </ListControls> <CardList>{elements}</CardList> </Stack> </Measured> ); }; export default Page;
openmultiplayer/web/frontend/src/pages/test.tsx/0
{ "file_path": "openmultiplayer/web/frontend/src/pages/test.tsx", "repo_id": "openmultiplayer", "token_count": 795 }
494
import * as z from "zod" export const UserSchema = z.object({ id: z.string(), email: z.string(), authMethod: z.string(), name: z.string(), bio: z.string().nullable(), admin: z.boolean(), threadCount: z.number(), postCount: z.number(), createdAt: z.string(), updatedAt: z.string(), deletedAt: z.string().nullable(), github: z.string().nullable(), discord: z.string().nullable(), }) export type User = z.infer<typeof UserSchema>
openmultiplayer/web/frontend/src/types/_generated_User.ts/0
{ "file_path": "openmultiplayer/web/frontend/src/types/_generated_User.ts", "repo_id": "openmultiplayer", "token_count": 163 }
495
package bs import ( "context" "go.uber.org/fx" ) func New(lc fx.Lifecycle) (*PrismaClient, error) { prisma := NewClient() lc.Append(fx.Hook{ OnStart: func(context.Context) error { return prisma.Connect() }, OnStop: func(context.Context) error { return prisma.Disconnect() }, }) return prisma, nil }
openmultiplayer/web/internal/bs/bs.go/0
{ "file_path": "openmultiplayer/web/internal/bs/bs.go", "repo_id": "openmultiplayer", "token_count": 136 }
496
package web import ( "context" "errors" "net/http" "go.uber.org/zap" ) // Error represents the object returned from the API for any form of problem // encountered during a request. // // Errors contain technical information as well as optional human-readable // error messages and suggestions for solutions. type Error struct { Message string `json:"message,omitempty"` // human readable message Suggestion string `json:"suggested,omitempty"` // suggestion for fix Error string `json:"error,omitempty"` // internal error string } // StatusNotFound writes a pretty error func StatusNotFound(w http.ResponseWriter, err error) { w.WriteHeader(http.StatusNotFound) if err == nil { errToWriter(w, errors.New("not found")) } else { errToWriter(w, err) } } // StatusInternalServerError writes a pretty error and logs func StatusInternalServerError(w http.ResponseWriter, err error) { if errors.Is(err, context.Canceled) { return } zap.L().Error("internal error", zap.Error(err)) w.WriteHeader(http.StatusInternalServerError) errToWriter(w, errors.New("something went wrong but the details have been omitted from this error for security reasons")) } // StatusUnauthorized writes a pretty error func StatusUnauthorized(w http.ResponseWriter, err error) { w.WriteHeader(http.StatusUnauthorized) errToWriter(w, err) } // StatusNotAcceptable writes a pretty error func StatusNotAcceptable(w http.ResponseWriter, err error) { w.WriteHeader(http.StatusNotAcceptable) errToWriter(w, err) } // StatusBadRequest writes a pretty error func StatusBadRequest(w http.ResponseWriter, err error) { w.WriteHeader(http.StatusBadRequest) errToWriter(w, err) } // HumanReadable is an error with a human readable description for displaying // on UI to end-users. It also contains an optional suggested solution field. type HumanReadable struct { err error desc string suggest string } // Error implements error func (h *HumanReadable) Error() string { return h.err.Error() } // WithDescription wraps an error with a human readable description. func WithDescription(err error, desc string) error { return &HumanReadable{err, desc, ""} } // WithSuggestion wraps an error with a human readable description and solution. func WithSuggestion(err error, desc, suggest string) error { return &HumanReadable{err, desc, suggest} } func errToWriter(w http.ResponseWriter, err error) { if err == nil { err = errors.New("Unknown or unspecified error") } var message string var suggest string herr, ok := err.(*HumanReadable) if ok { message = herr.desc suggest = herr.suggest } Write(w, Error{ Message: message, Suggestion: suggest, Error: err.Error(), }) }
openmultiplayer/web/internal/web/web.go/0
{ "file_path": "openmultiplayer/web/internal/web/web.go", "repo_id": "openmultiplayer", "token_count": 843 }
497
# Please do not edit this file manually # It should be added in your version-control system (i.e. Git) provider = "cockroachdb"
openmultiplayer/web/prisma/migrations/migration_lock.toml/0
{ "file_path": "openmultiplayer/web/prisma/migrations/migration_lock.toml", "repo_id": "openmultiplayer", "token_count": 36 }
498
ARG PROJECT_NAME ARG BRANCH_NAME ARG BUILD_NUMBER FROM ci/$PROJECT_NAME:$BRANCH_NAME-$BUILD_NUMBER USER root RUN wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - && \ echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list && \ apt-get update && apt-get install -y google-chrome-stable
overleaf/web/Dockerfile.frontend.ci/0
{ "file_path": "overleaf/web/Dockerfile.frontend.ci", "repo_id": "overleaf", "token_count": 158 }
499
const CollaboratorsGetter = require('../Collaborators/CollaboratorsGetter') const CollaboratorsHandler = require('../Collaborators/CollaboratorsHandler') const ProjectGetter = require('../Project/ProjectGetter') const { User } = require('../../models/User') const PrivilegeLevels = require('./PrivilegeLevels') const TokenAccessHandler = require('../TokenAccess/TokenAccessHandler') const PublicAccessLevels = require('./PublicAccessLevels') const Errors = require('../Errors/Errors') const { ObjectId } = require('mongodb') const { promisifyAll } = require('../../util/promises') const AuthorizationManager = { isRestrictedUser(userId, privilegeLevel, isTokenMember) { if (privilegeLevel === PrivilegeLevels.NONE) { return true } return ( privilegeLevel === PrivilegeLevels.READ_ONLY && (isTokenMember || !userId) ) }, isRestrictedUserForProject(userId, projectId, token, callback) { AuthorizationManager.getPrivilegeLevelForProject( userId, projectId, token, (err, privilegeLevel) => { if (err) { return callback(err) } CollaboratorsHandler.userIsTokenMember( userId, projectId, (err, isTokenMember) => { if (err) { return callback(err) } callback( null, AuthorizationManager.isRestrictedUser( userId, privilegeLevel, isTokenMember ) ) } ) } ) }, getPublicAccessLevel(projectId, callback) { if (!ObjectId.isValid(projectId)) { return callback(new Error('invalid project id')) } // Note, the Project property in the DB is `publicAccesLevel`, without the second `s` ProjectGetter.getProject( projectId, { publicAccesLevel: 1 }, function (error, project) { if (error) { return callback(error) } if (!project) { return callback( new Errors.NotFoundError(`no project found with id ${projectId}`) ) } callback(null, project.publicAccesLevel) } ) }, // Get the privilege level that the user has for the project // Returns: // * privilegeLevel: "owner", "readAndWrite", of "readOnly" if the user has // access. false if the user does not have access // * becausePublic: true if the access level is only because the project is public. // * becauseSiteAdmin: true if access level is only because user is admin getPrivilegeLevelForProject(userId, projectId, token, callback) { if (userId) { AuthorizationManager.getPrivilegeLevelForProjectWithUser( userId, projectId, token, callback ) } else { AuthorizationManager.getPrivilegeLevelForProjectWithoutUser( projectId, token, callback ) } }, // User is present, get their privilege level from database getPrivilegeLevelForProjectWithUser(userId, projectId, token, callback) { CollaboratorsGetter.getMemberIdPrivilegeLevel( userId, projectId, function (error, privilegeLevel) { if (error) { return callback(error) } if (privilegeLevel && privilegeLevel !== PrivilegeLevels.NONE) { // The user has direct access return callback(null, privilegeLevel, false, false) } AuthorizationManager.isUserSiteAdmin(userId, function (error, isAdmin) { if (error) { return callback(error) } if (isAdmin) { return callback(null, PrivilegeLevels.OWNER, false, true) } // Legacy public-access system // User is present (not anonymous), but does not have direct access AuthorizationManager.getPublicAccessLevel( projectId, function (err, publicAccessLevel) { if (err) { return callback(err) } if (publicAccessLevel === PublicAccessLevels.READ_ONLY) { return callback(null, PrivilegeLevels.READ_ONLY, true, false) } if (publicAccessLevel === PublicAccessLevels.READ_AND_WRITE) { return callback( null, PrivilegeLevels.READ_AND_WRITE, true, false ) } callback(null, PrivilegeLevels.NONE, false, false) } ) }) } ) }, // User is Anonymous, Try Token-based access getPrivilegeLevelForProjectWithoutUser(projectId, token, callback) { AuthorizationManager.getPublicAccessLevel( projectId, function (err, publicAccessLevel) { if (err) { return callback(err) } if (publicAccessLevel === PublicAccessLevels.READ_ONLY) { // Legacy public read-only access for anonymous user return callback(null, PrivilegeLevels.READ_ONLY, true, false) } if (publicAccessLevel === PublicAccessLevels.READ_AND_WRITE) { // Legacy public read-write access for anonymous user return callback(null, PrivilegeLevels.READ_AND_WRITE, true, false) } if (publicAccessLevel === PublicAccessLevels.TOKEN_BASED) { return AuthorizationManager.getPrivilegeLevelForProjectWithToken( projectId, token, callback ) } // Deny anonymous user access callback(null, PrivilegeLevels.NONE, false, false) } ) }, getPrivilegeLevelForProjectWithToken(projectId, token, callback) { // Anonymous users can have read-only access to token-based projects, // while read-write access must be logged in, // unless the `enableAnonymousReadAndWriteSharing` setting is enabled TokenAccessHandler.validateTokenForAnonymousAccess( projectId, token, function (err, isValidReadAndWrite, isValidReadOnly) { if (err) { return callback(err) } if (isValidReadOnly) { // Grant anonymous user read-only access return callback(null, PrivilegeLevels.READ_ONLY, false, false) } if (isValidReadAndWrite) { // Grant anonymous user read-and-write access return callback(null, PrivilegeLevels.READ_AND_WRITE, false, false) } // Deny anonymous access callback(null, PrivilegeLevels.NONE, false, false) } ) }, canUserReadProject(userId, projectId, token, callback) { AuthorizationManager.getPrivilegeLevelForProject( userId, projectId, token, function (error, privilegeLevel) { if (error) { return callback(error) } callback( null, [ PrivilegeLevels.OWNER, PrivilegeLevels.READ_AND_WRITE, PrivilegeLevels.READ_ONLY, ].includes(privilegeLevel) ) } ) }, canUserWriteProjectContent(userId, projectId, token, callback) { AuthorizationManager.getPrivilegeLevelForProject( userId, projectId, token, function (error, privilegeLevel) { if (error) { return callback(error) } callback( null, [PrivilegeLevels.OWNER, PrivilegeLevels.READ_AND_WRITE].includes( privilegeLevel ) ) } ) }, canUserWriteProjectSettings(userId, projectId, token, callback) { AuthorizationManager.getPrivilegeLevelForProject( userId, projectId, token, function (error, privilegeLevel, becausePublic) { if (error) { return callback(error) } if (privilegeLevel === PrivilegeLevels.OWNER) { return callback(null, true) } if ( privilegeLevel === PrivilegeLevels.READ_AND_WRITE && !becausePublic ) { return callback(null, true) } callback(null, false) } ) }, canUserAdminProject(userId, projectId, token, callback) { AuthorizationManager.getPrivilegeLevelForProject( userId, projectId, token, function (error, privilegeLevel, becausePublic, becauseSiteAdmin) { if (error) { return callback(error) } callback( null, privilegeLevel === PrivilegeLevels.OWNER, becauseSiteAdmin ) } ) }, isUserSiteAdmin(userId, callback) { if (!userId) { return callback(null, false) } User.findOne({ _id: userId }, { isAdmin: 1 }, function (error, user) { if (error) { return callback(error) } callback(null, (user && user.isAdmin) === true) }) }, } module.exports = AuthorizationManager module.exports.promises = promisifyAll(AuthorizationManager, { without: 'isRestrictedUser', })
overleaf/web/app/src/Features/Authorization/AuthorizationManager.js/0
{ "file_path": "overleaf/web/app/src/Features/Authorization/AuthorizationManager.js", "repo_id": "overleaf", "token_count": 3900 }
500
/* eslint-disable 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 */ const { ProjectInvite } = require('../../models/ProjectInvite') const OError = require('@overleaf/o-error') const logger = require('logger-sharelatex') const CollaboratorsEmailHandler = require('./CollaboratorsEmailHandler') const CollaboratorsHandler = require('./CollaboratorsHandler') const UserGetter = require('../User/UserGetter') const ProjectGetter = require('../Project/ProjectGetter') const Errors = require('../Errors/Errors') const Crypto = require('crypto') const NotificationsBuilder = require('../Notifications/NotificationsBuilder') const { promisifyAll } = require('../../util/promises') const CollaboratorsInviteHandler = { getAllInvites(projectId, callback) { if (callback == null) { callback = function (err, invites) {} } logger.log({ projectId }, 'fetching invites for project') return ProjectInvite.find({ projectId }, function (err, invites) { if (err != null) { OError.tag(err, 'error getting invites from mongo', { projectId, }) return callback(err) } logger.log( { projectId, count: invites.length }, 'found invites for project' ) return callback(null, invites) }) }, getInviteCount(projectId, callback) { if (callback == null) { callback = function (err, count) {} } logger.log({ projectId }, 'counting invites for project') return ProjectInvite.countDocuments({ projectId }, function (err, count) { if (err != null) { OError.tag(err, 'error getting invites from mongo', { projectId, }) return callback(err) } return callback(null, count) }) }, _trySendInviteNotification(projectId, sendingUser, invite, callback) { if (callback == null) { callback = function (err) {} } const { email } = invite return UserGetter.getUserByAnyEmail( email, { _id: 1 }, function (err, existingUser) { if (err != null) { OError.tag(err, 'error checking if user exists', { projectId, email, }) return callback(err) } if (existingUser == null) { logger.log({ projectId, email }, 'no existing user found, returning') return callback(null) } return ProjectGetter.getProject( projectId, { _id: 1, name: 1 }, function (err, project) { if (err != null) { OError.tag(err, 'error getting project', { projectId, email, }) return callback(err) } if (project == null) { logger.log( { projectId }, 'no project found while sending notification, returning' ) return callback(null) } return NotificationsBuilder.projectInvite( invite, project, sendingUser, existingUser ).create(callback) } ) } ) }, _tryCancelInviteNotification(inviteId, callback) { if (callback == null) { callback = function () {} } return NotificationsBuilder.projectInvite( { _id: inviteId }, null, null, null ).read(callback) }, _sendMessages(projectId, sendingUser, invite, callback) { if (callback == null) { callback = function (err) {} } logger.log( { projectId, inviteId: invite._id }, 'sending notification and email for invite' ) return CollaboratorsEmailHandler.notifyUserOfProjectInvite( projectId, invite.email, invite, sendingUser, function (err) { if (err != null) { return callback(err) } return CollaboratorsInviteHandler._trySendInviteNotification( projectId, sendingUser, invite, function (err) { if (err != null) { return callback(err) } return callback() } ) } ) }, inviteToProject(projectId, sendingUser, email, privileges, callback) { if (callback == null) { callback = function (err, invite) {} } logger.log( { projectId, sendingUserId: sendingUser._id, email, privileges }, 'adding invite' ) return Crypto.randomBytes(24, function (err, buffer) { if (err != null) { OError.tag(err, 'error generating random token', { projectId, sendingUserId: sendingUser._id, email, }) return callback(err) } const token = buffer.toString('hex') const invite = new ProjectInvite({ email, token, sendingUserId: sendingUser._id, projectId, privileges, }) return invite.save(function (err, invite) { if (err != null) { OError.tag(err, 'error saving token', { projectId, sendingUserId: sendingUser._id, email, }) return callback(err) } // Send email and notification in background CollaboratorsInviteHandler._sendMessages( projectId, sendingUser, invite, function (err) { if (err != null) { return logger.err( { err, projectId, email }, 'error sending messages for invite' ) } } ) return callback(null, invite) }) }) }, revokeInvite(projectId, inviteId, callback) { if (callback == null) { callback = function (err) {} } logger.log({ projectId, inviteId }, 'removing invite') return ProjectInvite.deleteOne( { projectId, _id: inviteId }, function (err) { if (err != null) { OError.tag(err, 'error removing invite', { projectId, inviteId, }) return callback(err) } CollaboratorsInviteHandler._tryCancelInviteNotification( inviteId, function () {} ) return callback(null) } ) }, resendInvite(projectId, sendingUser, inviteId, callback) { if (callback == null) { callback = function (err) {} } logger.log({ projectId, inviteId }, 'resending invite email') return ProjectInvite.findOne( { _id: inviteId, projectId }, function (err, invite) { if (err != null) { OError.tag(err, 'error finding invite', { projectId, inviteId, }) return callback(err) } if (invite == null) { logger.err( { err, projectId, inviteId }, 'no invite found, nothing to resend' ) return callback(null) } return CollaboratorsInviteHandler._sendMessages( projectId, sendingUser, invite, function (err) { if (err != null) { OError.tag(err, 'error resending invite messages', { projectId, inviteId, }) return callback(err) } return callback(null) } ) } ) }, getInviteByToken(projectId, tokenString, callback) { if (callback == null) { callback = function (err, invite) {} } logger.log({ projectId, tokenString }, 'fetching invite by token') return ProjectInvite.findOne( { projectId, token: tokenString }, function (err, invite) { if (err != null) { OError.tag(err, 'error fetching invite', { projectId, }) return callback(err) } if (invite == null) { logger.err({ err, projectId, token: tokenString }, 'no invite found') return callback(null, null) } return callback(null, invite) } ) }, acceptInvite(projectId, tokenString, user, callback) { if (callback == null) { callback = function (err) {} } logger.log({ projectId, userId: user._id, tokenString }, 'accepting invite') return CollaboratorsInviteHandler.getInviteByToken( projectId, tokenString, function (err, invite) { if (err != null) { OError.tag(err, 'error finding invite', { projectId, tokenString, }) return callback(err) } if (!invite) { err = new Errors.NotFoundError('no matching invite found') logger.log( { err, projectId, tokenString }, 'no matching invite found' ) return callback(err) } const inviteId = invite._id return CollaboratorsHandler.addUserIdToProject( projectId, invite.sendingUserId, user._id, invite.privileges, function (err) { if (err != null) { OError.tag(err, 'error adding user to project', { projectId, inviteId, userId: user._id, }) return callback(err) } // Remove invite logger.log({ projectId, inviteId }, 'removing invite') return ProjectInvite.deleteOne({ _id: inviteId }, function (err) { if (err != null) { OError.tag(err, 'error removing invite', { projectId, inviteId, }) return callback(err) } CollaboratorsInviteHandler._tryCancelInviteNotification( inviteId, function () {} ) return callback() }) } ) } ) }, } module.exports = CollaboratorsInviteHandler module.exports.promises = promisifyAll(CollaboratorsInviteHandler)
overleaf/web/app/src/Features/Collaborators/CollaboratorsInviteHandler.js/0
{ "file_path": "overleaf/web/app/src/Features/Collaborators/CollaboratorsInviteHandler.js", "repo_id": "overleaf", "token_count": 4836 }
501
/* eslint-disable camelcase, node/handle-callback-err, 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 * 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 ProjectGetter = require('../Project/ProjectGetter') const OError = require('@overleaf/o-error') const ProjectLocator = require('../Project/ProjectLocator') const ProjectEntityHandler = require('../Project/ProjectEntityHandler') const ProjectEntityUpdateHandler = require('../Project/ProjectEntityUpdateHandler') const logger = require('logger-sharelatex') const _ = require('lodash') module.exports = { getDocument(req, res, next) { if (next == null) { next = function (error) {} } const project_id = req.params.Project_id const { doc_id } = req.params const plain = __guard__(req != null ? req.query : undefined, x => x.plain) === 'true' return ProjectGetter.getProject( project_id, { rootFolder: true, overleaf: true }, function (error, project) { if (error != null) { return next(error) } if (project == null) { return res.sendStatus(404) } return ProjectLocator.findElement( { project, element_id: doc_id, type: 'doc' }, function (error, doc, path) { if (error != null) { OError.tag(error, 'error finding element for getDocument', { doc_id, project_id, }) return next(error) } return ProjectEntityHandler.getDoc( project_id, doc_id, function (error, lines, rev, version, ranges) { if (error != null) { OError.tag( error, 'error finding doc contents for getDocument', { doc_id, project_id, } ) return next(error) } if (plain) { res.type('text/plain') return res.send(lines.join('\n')) } else { const projectHistoryId = _.get(project, 'overleaf.history.id') const projectHistoryType = _.get( project, 'overleaf.history.display' ) ? 'project-history' : undefined // for backwards compatibility, don't send anything if the project is still on track-changes return res.json({ lines, version, ranges, pathname: path.fileSystem, projectHistoryId, projectHistoryType, }) } } ) } ) } ) }, setDocument(req, res, next) { if (next == null) { next = function (error) {} } const project_id = req.params.Project_id const { doc_id } = req.params const { lines, version, ranges, lastUpdatedAt, lastUpdatedBy } = req.body return ProjectEntityUpdateHandler.updateDocLines( project_id, doc_id, lines, version, ranges, lastUpdatedAt, lastUpdatedBy, function (error) { if (error != null) { OError.tag(error, 'error finding element for getDocument', { doc_id, project_id, }) return next(error) } logger.log( { doc_id, project_id }, 'finished receiving set document request from api (docupdater)' ) return res.sendStatus(200) } ) }, } function __guard__(value, transform) { return typeof value !== 'undefined' && value !== null ? transform(value) : undefined }
overleaf/web/app/src/Features/Documents/DocumentController.js/0
{ "file_path": "overleaf/web/app/src/Features/Documents/DocumentController.js", "repo_id": "overleaf", "token_count": 2021 }
502
const XRegExp = require('xregexp') // A note about SAFE_REGEX: // We have to escape the escape characters because XRegExp compiles it first. // So it's equivalent to `^[\p{L}\p{N}\s\-_!&\(\)]+$] // \p{L} = any letter in any language // \p{N} = any kind of numeric character // https://www.regular-expressions.info/unicode.html#prop is a good resource for // more obscure regex features. standard RegExp does not support these const HAN_REGEX = XRegExp('\\p{Han}') const SAFE_REGEX = XRegExp("^[\\p{L}\\p{N}\\s\\-_!'&\\(\\)]+$") const EMAIL_REGEX = XRegExp('^[\\p{L}\\p{N}.+_-]+@[\\w.-]+$') const SpamSafe = { isSafeUserName(name) { return SAFE_REGEX.test(name) && name.length <= 30 }, isSafeProjectName(name) { if (HAN_REGEX.test(name)) { return SAFE_REGEX.test(name) && name.length <= 30 } return SAFE_REGEX.test(name) && name.length <= 100 }, isSafeEmail(email) { return EMAIL_REGEX.test(email) && email.length <= 40 }, safeUserName(name, alternative, project) { if (project == null) { project = false } if (SpamSafe.isSafeUserName(name)) { return name } return alternative }, safeProjectName(name, alternative) { if (SpamSafe.isSafeProjectName(name)) { return name } return alternative }, safeEmail(email, alternative) { if (SpamSafe.isSafeEmail(email)) { return email } return alternative }, } module.exports = SpamSafe
overleaf/web/app/src/Features/Email/SpamSafe.js/0
{ "file_path": "overleaf/web/app/src/Features/Email/SpamSafe.js", "repo_id": "overleaf", "token_count": 575 }
503
const pug = require('pug-runtime') const SPLIT_REGEX = /<(\d+)>(.*?)<\/\1>/g function render(locale, components) { const output = [] function addPlainText(text) { if (!text) return output.push(pug.escape(text)) } // 'PRE<0>INNER</0>POST' -> ['PRE', '0', 'INNER', 'POST'] // '<0>INNER</0>' -> ['', '0', 'INNER', ''] // '<0></0>' -> ['', '0', '', ''] // '<0>INNER</0><0>INNER2</0>' -> ['', '0', 'INNER', '', '0', 'INNER2', ''] // '<0><1>INNER</1></0>' -> ['', '0', '<1>INNER</1>', ''] // 'PLAIN TEXT' -> ['PLAIN TEXT'] // NOTE: a test suite is verifying these cases: SafeHTMLSubstituteTests const chunks = locale.split(SPLIT_REGEX) // extract the 'PRE' chunk addPlainText(chunks.shift()) while (chunks.length) { // each batch consists of three chunks: ['0', 'INNER', 'POST'] const [idx, innerChunk, intermediateChunk] = chunks.splice(0, 3) const component = components[idx] const componentName = typeof component === 'string' ? component : component.name // pug is doing any necessary escaping on attribute values const attributes = (component.attrs && pug.attrs(component.attrs)) || '' output.push( `<${componentName + attributes}>`, ...render(innerChunk, components), `</${componentName}>` ) addPlainText(intermediateChunk) } return output.join('') } module.exports = { SPLIT_REGEX, render, }
overleaf/web/app/src/Features/Helpers/SafeHTMLSubstitution.js/0
{ "file_path": "overleaf/web/app/src/Features/Helpers/SafeHTMLSubstitution.js", "repo_id": "overleaf", "token_count": 625 }
504
/* 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 LinkedFilesHandler const FileWriter = require('../../infrastructure/FileWriter') const EditorController = require('../Editor/EditorController') const ProjectLocator = require('../Project/ProjectLocator') const { Project } = require('../../models/Project') const ProjectGetter = require('../Project/ProjectGetter') const _ = require('underscore') const { ProjectNotFoundError, V1ProjectNotFoundError, BadDataError, } = require('./LinkedFilesErrors') module.exports = LinkedFilesHandler = { getFileById(project_id, file_id, callback) { if (callback == null) { callback = function (err, file) {} } return ProjectLocator.findElement( { project_id, element_id: file_id, type: 'file', }, function (err, file, path, parentFolder) { if (err != null) { return callback(err) } return callback(null, file, path, parentFolder) } ) }, getSourceProject(data, callback) { if (callback == null) { callback = function (err, project) {} } const projection = { _id: 1, name: 1 } if (data.v1_source_doc_id != null) { return Project.findOne( { 'overleaf.id': data.v1_source_doc_id }, projection, function (err, project) { if (err != null) { return callback(err) } if (project == null) { return callback(new V1ProjectNotFoundError()) } return callback(null, project) } ) } else if (data.source_project_id != null) { return ProjectGetter.getProject( data.source_project_id, projection, function (err, project) { if (err != null) { return callback(err) } if (project == null) { return callback(new ProjectNotFoundError()) } return callback(null, project) } ) } else { return callback(new BadDataError('neither v1 nor v2 id present')) } }, importFromStream( project_id, readStream, linkedFileData, name, parent_folder_id, user_id, callback ) { if (callback == null) { callback = function (err, file) {} } callback = _.once(callback) return FileWriter.writeStreamToDisk( project_id, readStream, function (err, fsPath) { if (err != null) { return callback(err) } return EditorController.upsertFile( project_id, parent_folder_id, name, fsPath, linkedFileData, 'upload', user_id, (err, file) => { if (err != null) { return callback(err) } return callback(null, file) } ) } ) }, importContent( project_id, content, linkedFileData, name, parent_folder_id, user_id, callback ) { if (callback == null) { callback = function (err, file) {} } callback = _.once(callback) return FileWriter.writeContentToDisk( project_id, content, function (err, fsPath) { if (err != null) { return callback(err) } return EditorController.upsertFile( project_id, parent_folder_id, name, fsPath, linkedFileData, 'upload', user_id, (err, file) => { if (err != null) { return callback(err) } return callback(null, file) } ) } ) }, }
overleaf/web/app/src/Features/LinkedFiles/LinkedFilesHandler.js/0
{ "file_path": "overleaf/web/app/src/Features/LinkedFiles/LinkedFilesHandler.js", "repo_id": "overleaf", "token_count": 1846 }
505
const Path = require('path') const OError = require('@overleaf/o-error') const { ObjectId } = require('mongodb') module.exports = { buildFolderStructure } function buildFolderStructure(docEntries, fileEntries) { const builder = new FolderStructureBuilder() for (const docEntry of docEntries) { builder.addDocEntry(docEntry) } for (const fileEntry of fileEntries) { builder.addFileEntry(fileEntry) } return builder.rootFolder } class FolderStructureBuilder { constructor() { this.foldersByPath = new Map() this.entityPaths = new Set() this.rootFolder = this.createFolder('rootFolder') this.foldersByPath.set('/', this.rootFolder) this.entityPaths.add('/') } addDocEntry(docEntry) { this.recordEntityPath(docEntry.path) const folderPath = Path.dirname(docEntry.path) const folder = this.mkdirp(folderPath) folder.docs.push(docEntry.doc) } addFileEntry(fileEntry) { this.recordEntityPath(fileEntry.path) const folderPath = Path.dirname(fileEntry.path) const folder = this.mkdirp(folderPath) folder.fileRefs.push(fileEntry.file) } mkdirp(path) { const existingFolder = this.foldersByPath.get(path) if (existingFolder != null) { return existingFolder } // Folder not found, create it. this.recordEntityPath(path) const dirname = Path.dirname(path) const basename = Path.basename(path) const parentFolder = this.mkdirp(dirname) const newFolder = this.createFolder(basename) parentFolder.folders.push(newFolder) this.foldersByPath.set(path, newFolder) return newFolder } recordEntityPath(path) { if (this.entityPaths.has(path)) { throw new OError('entity already exists', { path }) } this.entityPaths.add(path) } createFolder(name) { return { _id: ObjectId(), name, folders: [], docs: [], fileRefs: [], } } }
overleaf/web/app/src/Features/Project/FolderStructureBuilder.js/0
{ "file_path": "overleaf/web/app/src/Features/Project/FolderStructureBuilder.js", "repo_id": "overleaf", "token_count": 720 }
506
const _ = require('underscore') const logger = require('logger-sharelatex') const async = require('async') const ProjectGetter = require('./ProjectGetter') const Errors = require('../Errors/Errors') const { promisifyMultiResult } = require('../../util/promises') function findElement(options, _callback) { // The search algorithm below potentially invokes the callback multiple // times. const callback = _.once(_callback) const { project, project_id: projectId, element_id: elementId, type, } = options const elementType = sanitizeTypeOfElement(type) let count = 0 const endOfBranch = function () { if (--count === 0) { logger.warn( `element ${elementId} could not be found for project ${ projectId || project._id }` ) callback(new Errors.NotFoundError('entity not found')) } } function search(searchFolder, path) { count++ const element = _.find( searchFolder[elementType], el => (el != null ? el._id : undefined) + '' === elementId + '' ) // need to ToString both id's for robustness if ( element == null && searchFolder.folders != null && searchFolder.folders.length !== 0 ) { _.each(searchFolder.folders, (folder, index) => { if (folder == null) { return } const newPath = {} for (const key of Object.keys(path)) { const value = path[key] newPath[key] = value } // make a value copy of the string newPath.fileSystem += `/${folder.name}` newPath.mongo += `.folders.${index}` search(folder, newPath) }) endOfBranch() } else if (element != null) { const elementPlaceInArray = getIndexOf( searchFolder[elementType], elementId ) path.fileSystem += `/${element.name}` path.mongo += `.${elementType}.${elementPlaceInArray}` callback(null, element, path, searchFolder) } else if (element == null) { endOfBranch() } } const path = { fileSystem: '', mongo: 'rootFolder.0' } const startSearch = project => { if (elementId + '' === project.rootFolder[0]._id + '') { callback(null, project.rootFolder[0], path, null) } else { search(project.rootFolder[0], path) } } if (project != null) { startSearch(project) } else { ProjectGetter.getProject( projectId, { rootFolder: true, rootDoc_id: true }, (err, project) => { if (err != null) { return callback(err) } if (project == null) { return callback(new Errors.NotFoundError('project not found')) } startSearch(project) } ) } } function findRootDoc(opts, callback) { const getRootDoc = project => { if (project.rootDoc_id != null) { findElement( { project, element_id: project.rootDoc_id, type: 'docs' }, (error, ...args) => { if (error != null) { if (error instanceof Errors.NotFoundError) { return callback(null, null) } else { return callback(error) } } callback(null, ...args) } ) } else { callback(null, null) } } const { project, project_id: projectId } = opts if (project != null) { getRootDoc(project) } else { ProjectGetter.getProject( projectId, { rootFolder: true, rootDoc_id: true }, (err, project) => { if (err != null) { logger.warn({ err }, 'error getting project') callback(err) } else { getRootDoc(project) } } ) } } function findElementByPath(options, callback) { const { project, project_id: projectId, path, exactCaseMatch } = options if (path == null) { return new Error('no path provided for findElementByPath') } if (project != null) { _findElementByPathWithProject(project, path, exactCaseMatch, callback) } else { ProjectGetter.getProject( projectId, { rootFolder: true, rootDoc_id: true }, (err, project) => { if (err != null) { return callback(err) } _findElementByPathWithProject(project, path, exactCaseMatch, callback) } ) } } function _findElementByPathWithProject( project, needlePath, exactCaseMatch, callback ) { let matchFn if (exactCaseMatch) { matchFn = (a, b) => a === b } else { matchFn = (a, b) => (a != null ? a.toLowerCase() : undefined) === (b != null ? b.toLowerCase() : undefined) } function getParentFolder(haystackFolder, foldersList, level, cb) { if (foldersList.length === 0) { return cb(null, haystackFolder) } const needleFolderName = foldersList[level] let found = false for (const folder of haystackFolder.folders) { if (matchFn(folder.name, needleFolderName)) { found = true if (level === foldersList.length - 1) { return cb(null, folder) } else { return getParentFolder(folder, foldersList, level + 1, cb) } } } if (!found) { cb( new Error( `not found project: ${project._id} search path: ${needlePath}, folder ${foldersList[level]} could not be found` ) ) } } function getEntity(folder, entityName, cb) { let result, type if (entityName == null) { return cb(null, folder, 'folder') } for (const file of folder.fileRefs || []) { if (matchFn(file != null ? file.name : undefined, entityName)) { result = file type = 'file' } } for (const doc of folder.docs || []) { if (matchFn(doc != null ? doc.name : undefined, entityName)) { result = doc type = 'doc' } } for (const childFolder of folder.folders || []) { if ( matchFn(childFolder != null ? childFolder.name : undefined, entityName) ) { result = childFolder type = 'folder' } } if (result != null) { cb(null, result, type) } else { cb( new Error( `not found project: ${project._id} search path: ${needlePath}, entity ${entityName} could not be found` ) ) } } if (project == null) { return callback(new Error('Tried to find an element for a null project')) } if (needlePath === '' || needlePath === '/') { return callback(null, project.rootFolder[0], 'folder') } if (needlePath.indexOf('/') === 0) { needlePath = needlePath.substring(1) } const foldersList = needlePath.split('/') const needleName = foldersList.pop() const rootFolder = project.rootFolder[0] const jobs = [] jobs.push(cb => getParentFolder(rootFolder, foldersList, 0, cb)) jobs.push((folder, cb) => getEntity(folder, needleName, cb)) async.waterfall(jobs, callback) } function sanitizeTypeOfElement(elementType) { const lastChar = elementType.slice(-1) if (lastChar !== 's') { elementType += 's' } if (elementType === 'files') { elementType = 'fileRefs' } return elementType } function getIndexOf(searchEntity, id) { const { length } = searchEntity let count = 0 while (count < length) { if ( (searchEntity[count] != null ? searchEntity[count]._id : undefined) + '' === id + '' ) { return count } count++ } } module.exports = { findElement, findElementByPath, findRootDoc, promises: { findElement: promisifyMultiResult(findElement, [ 'element', 'path', 'folder', ]), findElementByPath: promisifyMultiResult(findElementByPath, [ 'element', 'type', ]), findRootDoc: promisifyMultiResult(findRootDoc, [ 'element', 'path', 'folder', ]), }, }
overleaf/web/app/src/Features/Project/ProjectLocator.js/0
{ "file_path": "overleaf/web/app/src/Features/Project/ProjectLocator.js", "repo_id": "overleaf", "token_count": 3273 }
507
const RateLimiter = require('../../infrastructure/RateLimiter') const logger = require('logger-sharelatex') const SessionManager = require('../Authentication/SessionManager') const LoginRateLimiter = require('./LoginRateLimiter') const settings = require('@overleaf/settings') /* Do not allow more than opts.maxRequests from a single client in opts.timeInterval. Pass an array of opts.params to segment this based on parameters in the request URL, e.g.: app.get "/project/:project_id", RateLimiterMiddleware.rateLimit(endpointName: "open-editor", params: ["project_id"]) will rate limit each project_id separately. Unique clients are identified by user_id if logged in, and IP address if not. */ function rateLimit(opts) { return function (req, res, next) { const userId = SessionManager.getLoggedInUserId(req.session) || req.ip if ( settings.smokeTest && settings.smokeTest.userId && settings.smokeTest.userId.toString() === userId.toString() ) { // ignore smoke test user return next() } const params = (opts.params || []).map(p => req.params[p]) params.push(userId) let subjectName = params.join(':') if (opts.ipOnly) { subjectName = req.ip } if (opts.endpointName == null) { throw new Error('no endpointName provided') } const options = { endpointName: opts.endpointName, timeInterval: opts.timeInterval || 60, subjectName, throttle: opts.maxRequests || 6, } return RateLimiter.addCount(options, function (error, canContinue) { if (error != null) { return next(error) } if (canContinue) { return next() } else { logger.warn(options, 'rate limit exceeded') res.status(429) // Too many requests res.write('Rate limit reached, please try again later') return res.end() } }) } } function loginRateLimit(req, res, next) { const { email } = req.body if (!email) { return next() } LoginRateLimiter.processLoginRequest(email, function (err, isAllowed) { if (err) { return next(err) } if (isAllowed) { return next() } else { logger.warn({ email }, 'rate limit exceeded') res.status(429) // Too many requests res.write('Rate limit reached, please try again later') return res.end() } }) } const RateLimiterMiddleware = { rateLimit, loginRateLimit, } module.exports = RateLimiterMiddleware
overleaf/web/app/src/Features/Security/RateLimiterMiddleware.js/0
{ "file_path": "overleaf/web/app/src/Features/Security/RateLimiterMiddleware.js", "repo_id": "overleaf", "token_count": 927 }
508
const Settings = require('@overleaf/settings') const logger = require('logger-sharelatex') function ensurePlansAreSetupCorrectly() { Settings.plans.forEach(plan => { if (typeof plan.price !== 'number') { logger.fatal({ plan }, 'missing price on plan') process.exit(1) } }) } function findLocalPlanInSettings(planCode) { for (const plan of Settings.plans) { if (plan.planCode === planCode) { return plan } } return null } module.exports = { ensurePlansAreSetupCorrectly, findLocalPlanInSettings, }
overleaf/web/app/src/Features/Subscription/PlansLocator.js/0
{ "file_path": "overleaf/web/app/src/Features/Subscription/PlansLocator.js", "repo_id": "overleaf", "token_count": 199 }
509
const { User } = require('../../models/User') module.exports = { updateFeatures(userId, features, callback) { const conditions = { _id: userId } const update = { featuresUpdatedAt: new Date(), } for (const key in features) { const value = features[key] update[`features.${key}`] = value } User.updateOne(conditions, update, (err, result) => callback(err, features, (result ? result.nModified : 0) === 1) ) }, overrideFeatures(userId, features, callback) { const conditions = { _id: userId } const update = { features, featuresUpdatedAt: new Date() } User.updateOne(conditions, update, (err, result) => callback(err, (result ? result.nModified : 0) === 1) ) }, }
overleaf/web/app/src/Features/Subscription/UserFeaturesUpdater.js/0
{ "file_path": "overleaf/web/app/src/Features/Subscription/UserFeaturesUpdater.js", "repo_id": "overleaf", "token_count": 276 }
510
/* eslint-disable camelcase, node/handle-callback-err, 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 * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ let UpdateMerger const OError = require('@overleaf/o-error') const _ = require('underscore') const async = require('async') const fs = require('fs') const logger = require('logger-sharelatex') const EditorController = require('../Editor/EditorController') const FileTypeManager = require('../Uploads/FileTypeManager') const FileWriter = require('../../infrastructure/FileWriter') const ProjectEntityHandler = require('../Project/ProjectEntityHandler') module.exports = UpdateMerger = { mergeUpdate(user_id, project_id, path, updateRequest, source, callback) { if (callback == null) { callback = function (error) {} } return FileWriter.writeStreamToDisk( project_id, updateRequest, function (err, fsPath) { if (err != null) { return callback(err) } return UpdateMerger._mergeUpdate( user_id, project_id, path, fsPath, source, mergeErr => fs.unlink(fsPath, function (deleteErr) { if (deleteErr != null) { logger.err({ project_id, fsPath }, 'error deleting file') } return callback(mergeErr) }) ) } ) }, _findExistingFileType(project_id, path, callback) { ProjectEntityHandler.getAllEntities( project_id, function (err, docs, files) { if (err != null) { return callback(err) } var existingFileType = null if (_.some(files, f => f.path === path)) { existingFileType = 'file' } if (_.some(docs, d => d.path === path)) { existingFileType = 'doc' } callback(null, existingFileType) } ) }, _determineFileType(project_id, path, fsPath, callback) { if (callback == null) { callback = function (err, fileType) {} } // check if there is an existing file with the same path (we either need // to overwrite it or delete it) UpdateMerger._findExistingFileType( project_id, path, function (err, existingFileType) { if (err) { return callback(err) } // determine whether the update should create a doc or binary file FileTypeManager.getType( path, fsPath, function (err, { binary, encoding }) { if (err != null) { return callback(err) } // If we receive a non-utf8 encoding, we won't be able to keep things in // sync, so we'll treat non-utf8 files as binary const isBinary = binary || encoding !== 'utf-8' // Existing | Update | Action // ---------|-----------|------- // file | isBinary | existing-file // file | !isBinary | existing-file // doc | isBinary | new-file, delete-existing-doc // doc | !isBinary | existing-doc // null | isBinary | new-file // null | !isBinary | new-doc // if a binary file already exists, always keep it as a binary file // even if the update looks like a text file if (existingFileType === 'file') { return callback(null, 'existing-file') } // if there is an existing doc, keep it as a doc except when the // incoming update is binary. In that case delete the doc and replace // it with a new file. if (existingFileType === 'doc') { if (isBinary) { return callback(null, 'new-file', 'delete-existing-doc') } else { return callback(null, 'existing-doc') } } // if there no existing file, create a file or doc as needed return callback(null, isBinary ? 'new-file' : 'new-doc') } ) } ) }, _mergeUpdate(user_id, project_id, path, fsPath, source, callback) { if (callback == null) { callback = function (error) {} } return UpdateMerger._determineFileType( project_id, path, fsPath, function (err, fileType, deleteOriginalEntity) { if (err != null) { return callback(err) } async.series( [ function (cb) { if (deleteOriginalEntity) { // currently we only delete docs UpdateMerger.deleteUpdate(user_id, project_id, path, source, cb) } else { cb() } }, function (cb) { if (['existing-file', 'new-file'].includes(fileType)) { return UpdateMerger.p.processFile( project_id, fsPath, path, source, user_id, cb ) } else if (['existing-doc', 'new-doc'].includes(fileType)) { return UpdateMerger.p.processDoc( project_id, user_id, fsPath, path, source, cb ) } else { return cb(new Error('unrecognized file')) } }, ], callback ) } ) }, deleteUpdate(user_id, project_id, path, source, callback) { if (callback == null) { callback = function () {} } return EditorController.deleteEntityWithPath( project_id, path, source, user_id, function () { return callback() } ) }, p: { processDoc(project_id, user_id, fsPath, path, source, callback) { return UpdateMerger.p.readFileIntoTextArray( fsPath, function (err, docLines) { if (err != null) { OError.tag( err, 'error reading file into text array for process doc update', { project_id, } ) return callback(err) } logger.log({ docLines }, 'processing doc update from tpds') return EditorController.upsertDocWithPath( project_id, path, docLines, source, user_id, function (err) { return callback(err) } ) } ) }, processFile(project_id, fsPath, path, source, user_id, callback) { return EditorController.upsertFileWithPath( project_id, path, fsPath, null, source, user_id, function (err) { return callback(err) } ) }, readFileIntoTextArray(path, callback) { return fs.readFile(path, 'utf8', function (error, content) { if (content == null) { content = '' } if (error != null) { OError.tag(error, 'error reading file into text array', { path, }) return callback(error) } const lines = content.split(/\r\n|\n|\r/) return callback(error, lines) }) }, }, }
overleaf/web/app/src/Features/ThirdPartyDataStore/UpdateMerger.js/0
{ "file_path": "overleaf/web/app/src/Features/ThirdPartyDataStore/UpdateMerger.js", "repo_id": "overleaf", "token_count": 3746 }
511
const { callbackify } = require('util') const logger = require('logger-sharelatex') const moment = require('moment') const { User } = require('../../models/User') const { DeletedUser } = require('../../models/DeletedUser') const NewsletterManager = require('../Newsletter/NewsletterManager') const ProjectDeleter = require('../Project/ProjectDeleter') const SubscriptionHandler = require('../Subscription/SubscriptionHandler') const SubscriptionUpdater = require('../Subscription/SubscriptionUpdater') const SubscriptionLocator = require('../Subscription/SubscriptionLocator') const UserMembershipsHandler = require('../UserMembership/UserMembershipsHandler') const UserSessionsManager = require('./UserSessionsManager') const InstitutionsAPI = require('../Institutions/InstitutionsAPI') const Errors = require('../Errors/Errors') module.exports = { deleteUser: callbackify(deleteUser), deleteMongoUser: callbackify(deleteMongoUser), expireDeletedUser: callbackify(expireDeletedUser), ensureCanDeleteUser: callbackify(ensureCanDeleteUser), expireDeletedUsersAfterDuration: callbackify(expireDeletedUsersAfterDuration), promises: { deleteUser: deleteUser, deleteMongoUser: deleteMongoUser, expireDeletedUser: expireDeletedUser, ensureCanDeleteUser: ensureCanDeleteUser, expireDeletedUsersAfterDuration: expireDeletedUsersAfterDuration, }, } async function deleteUser(userId, options = {}) { if (!userId) { logger.warn('user_id is null when trying to delete user') throw new Error('no user_id') } try { const user = await User.findById(userId).exec() logger.log({ user }, 'deleting user') await ensureCanDeleteUser(user) await _cleanupUser(user) await _createDeletedUser(user, options) await ProjectDeleter.promises.deleteUsersProjects(user._id) await deleteMongoUser(user._id) } catch (error) { logger.warn({ error, userId }, 'something went wrong deleting the user') throw error } } /** * delete a user document only */ async function deleteMongoUser(userId) { if (!userId) { throw new Error('no user_id') } await User.deleteOne({ _id: userId }).exec() } async function expireDeletedUser(userId) { const deletedUser = await DeletedUser.findOne({ 'deleterData.deletedUserId': userId, }).exec() deletedUser.user = undefined deletedUser.deleterData.deleterIpAddress = undefined await deletedUser.save() } async function expireDeletedUsersAfterDuration() { const DURATION = 90 const deletedUsers = await DeletedUser.find({ 'deleterData.deletedAt': { $lt: new Date(moment().subtract(DURATION, 'days')), }, user: { $ne: null, }, }).exec() if (deletedUsers.length === 0) { return } for (let i = 0; i < deletedUsers.length; i++) { await expireDeletedUser(deletedUsers[i].deleterData.deletedUserId) } } async function ensureCanDeleteUser(user) { const subscription = await SubscriptionLocator.promises.getUsersSubscription( user ) if (subscription) { throw new Errors.SubscriptionAdminDeletionError({}) } } async function _createDeletedUser(user, options) { await DeletedUser.updateOne( { 'deleterData.deletedUserId': user._id }, { user: user, deleterData: { deletedAt: new Date(), deleterId: options.deleterUser ? options.deleterUser._id : undefined, deleterIpAddress: options.ipAddress, deletedUserId: user._id, deletedUserLastLoggedIn: user.lastLoggedIn, deletedUserSignUpDate: user.signUpDate, deletedUserLoginCount: user.loginCount, deletedUserReferralId: user.referal_id, deletedUserReferredUsers: user.refered_users, deletedUserReferredUserCount: user.refered_user_count, deletedUserOverleafId: user.overleaf ? user.overleaf.id : undefined, }, }, { upsert: true } ) } async function _cleanupUser(user) { await UserSessionsManager.promises.revokeAllUserSessions(user._id, []) await NewsletterManager.promises.unsubscribe(user, { delete: true }) await SubscriptionHandler.promises.cancelSubscription(user) await InstitutionsAPI.promises.deleteAffiliations(user._id) await SubscriptionUpdater.promises.removeUserFromAllGroups(user._id) await UserMembershipsHandler.promises.removeUserFromAllEntities(user._id) }
overleaf/web/app/src/Features/User/UserDeleter.js/0
{ "file_path": "overleaf/web/app/src/Features/User/UserDeleter.js", "repo_id": "overleaf", "token_count": 1472 }
512
module.exports = { group: { modelName: 'Subscription', readOnly: true, hasMembersLimit: true, fields: { primaryKey: '_id', read: ['invited_emails', 'teamInvites', 'member_ids'], write: null, access: 'manager_ids', name: 'teamName', }, baseQuery: { groupPlan: true, }, translations: { title: 'group_account', subtitle: 'members_management', remove: 'remove_from_group', }, pathsFor(id) { return { addMember: `/manage/groups/${id}/invites`, removeMember: `/manage/groups/${id}/user`, removeInvite: `/manage/groups/${id}/invites`, exportMembers: `/manage/groups/${id}/members/export`, } }, }, team: { // for metrics only modelName: 'Subscription', fields: { primaryKey: 'overleaf.id', access: 'manager_ids', }, baseQuery: { groupPlan: true, }, }, groupManagers: { modelName: 'Subscription', fields: { primaryKey: '_id', read: ['manager_ids'], write: 'manager_ids', access: 'manager_ids', name: 'teamName', }, baseQuery: { groupPlan: true, }, translations: { title: 'group_account', subtitle: 'managers_management', remove: 'remove_manager', }, pathsFor(id) { return { addMember: `/manage/groups/${id}/managers`, removeMember: `/manage/groups/${id}/managers`, } }, }, institution: { modelName: 'Institution', fields: { primaryKey: 'v1Id', read: ['managerIds'], write: 'managerIds', access: 'managerIds', name: 'name', }, translations: { title: 'institution_account', subtitle: 'managers_management', remove: 'remove_manager', }, pathsFor(id) { return { index: `/manage/institutions/${id}/managers`, addMember: `/manage/institutions/${id}/managers`, removeMember: `/manage/institutions/${id}/managers`, } }, }, publisher: { modelName: 'Publisher', fields: { primaryKey: 'slug', read: ['managerIds'], write: 'managerIds', access: 'managerIds', name: 'name', }, translations: { title: 'publisher_account', subtitle: 'managers_management', remove: 'remove_manager', }, pathsFor(id) { return { index: `/manage/publishers/${id}/managers`, addMember: `/manage/publishers/${id}/managers`, removeMember: `/manage/publishers/${id}/managers`, } }, }, }
overleaf/web/app/src/Features/UserMembership/UserMembershipEntityConfigs.js/0
{ "file_path": "overleaf/web/app/src/Features/UserMembership/UserMembershipEntityConfigs.js", "repo_id": "overleaf", "token_count": 1202 }
513
// TODO: This file was created by bulk-decaffeinate. // Sanity-check the conversion and remove this comment. module.exports = { queue: { web_to_tpds_http_requests: 'web_to_tpds_http_requests', tpds_to_web_http_requests: 'tpds_to_web_http_requests', }, }
overleaf/web/app/src/infrastructure/Keys.js/0
{ "file_path": "overleaf/web/app/src/infrastructure/Keys.js", "repo_id": "overleaf", "token_count": 105 }
514
const Metrics = require('@overleaf/metrics') const logger = require('logger-sharelatex') function computeValidationToken(req) { // this should be a deterministic function of the client-side sessionID, // prepended with a version number in case we want to change it later return 'v1:' + req.sessionID.slice(-4) } function checkValidationToken(req) { if (req.session) { const sessionToken = req.session.validationToken if (sessionToken) { const clientToken = computeValidationToken(req) // Reject invalid sessions. If you change the method for computing the // token (above) then you need to either check or ignore previous // versions of the token. if (sessionToken === clientToken) { Metrics.inc('security.session', 1, { status: 'ok' }) return true } else { logger.error( { sessionToken: sessionToken, clientToken: clientToken, }, 'session token validation failed' ) Metrics.inc('security.session', 1, { status: 'error' }) return false } } else { Metrics.inc('security.session', 1, { status: 'missing' }) } } return true // fallback to allowing session } module.exports = { enableValidationToken(sessionStore) { // generate an identifier from the sessionID for every new session const originalGenerate = sessionStore.generate sessionStore.generate = function (req) { originalGenerate(req) // add the validation token as a property that cannot be overwritten Object.defineProperty(req.session, 'validationToken', { value: computeValidationToken(req), enumerable: true, writable: false, }) Metrics.inc('security.session', 1, { status: 'new' }) } }, validationMiddleware(req, res, next) { if (!req.session.noSessionCallback) { if (!checkValidationToken(req)) { // the session must exist for it to fail validation return req.session.destroy(() => { return next(new Error('invalid session')) }) } } next() }, hasValidationToken(req) { if (req && req.session && req.session.validationToken) { return true } else { return false } }, }
overleaf/web/app/src/infrastructure/SessionStoreManager.js/0
{ "file_path": "overleaf/web/app/src/infrastructure/SessionStoreManager.js", "repo_id": "overleaf", "token_count": 848 }
515
const mongoose = require('../infrastructure/Mongoose') const { Schema } = mongoose const OauthApplicationSchema = new Schema( { id: String, clientSecret: String, grants: [String], name: String, redirectUris: [String], scopes: [String], }, { collection: 'oauthApplications', } ) exports.OauthApplication = mongoose.model( 'OauthApplication', OauthApplicationSchema ) exports.OauthApplicationSchema = OauthApplicationSchema
overleaf/web/app/src/models/OauthApplication.js/0
{ "file_path": "overleaf/web/app/src/models/OauthApplication.js", "repo_id": "overleaf", "token_count": 167 }
516
{ "enterprise": { "collaborator": { "USD": { "2": 252, "3": 376, "4": 495, "5": 615, "10": 1170, "20": 2160, "50": 4950 }, "EUR": { "2": 235, "3": 352, "4": 468, "5": 584, "10": 1090, "20": 2015, "50": 4620 }, "GBP": { "2": 198, "3": 296, "4": 394, "5": 492, "10": 935, "20": 1730, "50": 3960 } }, "professional": { "USD": { "2": 504, "3": 752, "4": 990, "5": 1230, "10": 2340, "20": 4320, "50": 9900 }, "EUR": { "2": 470, "3": 704, "4": 936, "5": 1168, "10": 2185, "20": 4030, "50": 9240 }, "GBP": { "2": 396, "3": 592, "4": 788, "5": 984, "10": 1870, "20": 3455, "50": 7920 } } }, "educational": { "collaborator": { "USD": { "2": 252, "3": 376, "4": 495, "5": 615, "10": 695, "20": 1295, "50": 2970 }, "EUR": { "2": 235, "3": 352, "4": 468, "5": 584, "10": 655, "20": 1210, "50": 2770 }, "GBP": { "2": 198, "3": 296, "4": 394, "5": 492, "10": 560, "20": 1035, "50": 2375 } }, "professional": { "USD": { "2": 504, "3": 752, "4": 990, "5": 1230, "10": 1390, "20": 2590, "50": 5940 }, "EUR": { "2": 470, "3": 704, "4": 936, "5": 1168, "10": 1310, "20": 2420, "50": 5545 }, "GBP": { "2": 396, "3": 592, "4": 788, "5": 984, "10": 1125, "20": 2075, "50": 4750 } } } }
overleaf/web/app/templates/plans/groups.json/0
{ "file_path": "overleaf/web/app/templates/plans/groups.json", "repo_id": "overleaf", "token_count": 1433 }
517
extends ../layout block content .content.content-alt .blog | !{content}
overleaf/web/app/views/blog/blog_holder.pug/0
{ "file_path": "overleaf/web/app/views/blog/blog_holder.pug", "repo_id": "overleaf", "token_count": 31 }
518
extends ../../layout block content .editor.full-size .loading-screen() .loading-screen-brand-container .loading-screen-brand( style="height: 20%;" ) h3.loading-screen-label() #{translate("Opening template")} span.loading-screen-ellip . span.loading-screen-ellip . span.loading-screen-ellip . form(id='create_form' method='POST' action='/project/new/template/' ng-non-bindable) input(type="hidden", name="_csrf", value=csrfToken) input(type="hidden" name="templateId" value=templateId) input(type="hidden" name="templateVersionId" value=templateVersionId) input(type="hidden" name="templateName" value=name) input(type="hidden" name="compiler" value=compiler) input(type="hidden" name="imageName" value=imageName) input(type="hidden" name="mainFile" value=mainFile) if brandVariationId input(type="hidden" name="brandVariationId" value=brandVariationId) block append foot-scripts script(type="text/javascript", nonce=scriptNonce). $(document).ready(function(){ $('#create_form').submit(); });
overleaf/web/app/views/project/editor/new_from_template.pug/0
{ "file_path": "overleaf/web/app/views/project/editor/new_from_template.pug", "repo_id": "overleaf", "token_count": 422 }
519
extends ../layout block content .content.content-alt .container.bonus .row .col-md-8.col-md-offset-2 .card .container-fluid(ng-controller="BonusLinksController") .row .col-md-12 .page-header h1 #{translate("help_us_spread_word")}. .row .col-md-10.col-md-offset-1 h2 #{translate("share_sl_to_get_rewards")} .row .col-md-8.col-md-offset-2.bonus-banner .bonus-top .row .col-md-8.col-md-offset-2.bonus-banner .title a(href='https://twitter.com/share?text='+encodeURIComponent(translate("bonus_twitter_share_text"))+'&url='+encodeURIComponent(buildReferalUrl("t"))+'&counturl='+settings.social.twitter.counturl, target="_blank").twitter i.fa.fa-fw.fa-2x.fa-twitter(aria-hidden="true") | | Tweet .row .col-md-8.col-md-offset-2.bonus-banner .title a(href='#').facebook i.fa.fa-fw.fa-2x.fa-facebook-square(aria-hidden="true") | | #{translate("post_on_facebook")} .row .col-md-8.col-md-offset-2.bonus-banner .title a(href='mailto:?subject='+encodeURIComponent(translate("bonus_email_share_header"))+'&body='+encodeURIComponent(translate("bonus_email_share_body")+' ')+encodeURIComponent(buildReferalUrl("e")), title='Share by Email').email i.fa.fa-fw.fa-2x.fa-envelope-open-o(aria-hidden="true") | | #{translate("email_us_to_your_friends")} .row .col-md-8.col-md-offset-2.bonus-banner .title a(href='#link-modal', data-toggle="modal", ng-click="openLinkToUsModal()").link i.fa.fa-fw.fa-2x.fa-globe(aria-hidden="true") | | #{translate("link_to_us")} .row .col-md-10.col-md-offset-1.bonus-banner h2.direct-link #{translate("direct_link")} pre.text-centered #{buildReferalUrl("d")} .row.ab-bonus .col-md-10.col-md-offset-1.bonus-banner p.thanks !{translate("sl_gives_you_free_stuff_see_progress_below")} .row.ab-bonus .col-md-10.col-md-offset-1.bonus-banner(style="position: relative; height: 30px; margin-top: 20px;") - for (var i = 0; i <= 10; i++) { if (refered_user_count == i) .number(style="left: "+i+"0%").active #{i} else .number(style="left: "+i+"0%") #{i} - } .row.ab-bonus .col-md-10.col-md-offset-1.bonus-banner .progress if (refered_user_count == 0) div(style="text-align: center; padding: 4px;") #{translate("spread_the_word_and_fill_bar")} .progress-bar.progress-bar-info(style="width: "+refered_user_count+"0%") .row.ab-bonus .col-md-10.col-md-offset-1.bonus-banner(style="position: relative; height: 110px;") .perk(style="left: 10%;", class = refered_user_count >= 1 ? "active" : "") #{translate("one_free_collab")} .perk(style="left: 30%;", class = refered_user_count >= 3 ? "active" : "") #{translate("three_free_collab")} .perk(style="left: 60%;", class = refered_user_count >= 6 ? "active" : "") #{translate("free_dropbox_and_history")} + #{translate("three_free_collab")} .perk(style="left: 90%;", class = refered_user_count >= 9 ? "active" : "") #{translate("free_dropbox_and_history")} + #{translate("unlimited_collabs")} .row &nbsp; .row.ab-bonus .col-md-10.col-md-offset-1.bonus-banner.bonus-status if (refered_user_count == 0) p.thanks !{translate("you_not_introed_anyone_to_sl")} else if (refered_user_count == 1) p.thanks !{translate("you_introed_small_number", {numberOfPeople: refered_user_count}, ['strong'])} else p.thanks !{translate("you_introed_high_number", {numberOfPeople: refered_user_count}, ['strong'])} script(type="text/ng-template", id="BonusLinkToUsModal") .modal-header button.close( type="button" data-dismiss="modal" ng-click="cancel()" aria-label="Close" ) span(aria-hidden="true") &times; h3 #{translate("link_to_sl")} .modal-body.modal-body-share.link-modal p #{translate("can_link_to_sl_with_html")} p textarea.col-md-12(readonly=true) <a href="#{buildReferalUrl("d")}">#{translate("bonus_share_link_text")}</a> p #{translate("thanks")}! .modal-footer() button.btn.btn-default( ng-click="cancel()", ) span #{translate("close")} block append foot-scripts script(type="text/javascript", nonce=scriptNonce). $(document).ready(function () { $.ajax({dataType: "script", cache: true, url: "//connect.facebook.net/en_US/all.js"}).done(function () { window.fbAsyncInit = function() { FB.init({appId: '#{settings.social.facebook.appId}', xfbml: true}); } }); }); function postToFeed() { // calling the API ... var obj = { method: 'feed', redirect_uri: '#{settings.social.facebook.redirectUri}', link: '!{buildReferalUrl("fb")}', picture: '#{settings.social.facebook.picture}', name: '#{translate("bonus_facebook_name").replace(/\'/g, "\\x27")}', caption: '#{translate("bonus_facebook_caption").replace(/\'/g, "\\x27")}', description: '#{translate("bonus_facebook_description").replace(/\'/g, "\\x27")}' }; if (typeof FB !== "undefined" && FB !== null) { FB.ui(obj); } } script(type="text/javascript", nonce=scriptNonce, src='//platform.twitter.com/widgets.js') script(type="text/javascript", nonce=scriptNonce). $(function() { $(".twitter").click(function() { ga('send', 'event', 'referal-button', 'clicked', "twitter") }); $(".email").click(function() { ga('send', 'event', 'referal-button', 'clicked', "email") }); $(".facebook").click(function(e) { ga('send', 'event', 'referal-button', 'clicked', "facebook") postToFeed() e.preventDefault() }); $(".link").click(function() { ga('send', 'event', 'referal-button', 'clicked', "direct-link") }); });
overleaf/web/app/views/referal/bonus.pug/0
{ "file_path": "overleaf/web/app/views/referal/bonus.pug", "repo_id": "overleaf", "token_count": 3114 }
520
p | Please | a(href="/contact") contact support | | to make changes to your plan
overleaf/web/app/views/subscriptions/dashboard/_personal_subscription_custom.pug/0
{ "file_path": "overleaf/web/app/views/subscriptions/dashboard/_personal_subscription_custom.pug", "repo_id": "overleaf", "token_count": 31 }
521
extends ../layout block vars - metadata = { viewport: true } block content main.content.content-alt#main-content .container .row .col-md-6.col-md-offset-3.col-lg-4.col-lg-offset-4 .card .page-header h1 We're back! p Overleaf is now running normally. p | Please | a(href="/login") log in | | to continue working on your projects.
overleaf/web/app/views/user/one_time_login.pug/0
{ "file_path": "overleaf/web/app/views/user/one_time_login.pug", "repo_id": "overleaf", "token_count": 201 }
522
#!/bin/bash KNOWN_HOSTS=/root/.ssh/known_hosts if [[ "$BRANCH_NAME" == "master" && "$COPYBARA" == "run" ]]; then set -e chmod -R 0600 /root/.ssh ssh-keyscan github.com > $KNOWN_HOSTS ssh-keygen -lf $KNOWN_HOSTS | grep "SHA256:nThbg6kXUpJWGl7E1IGOCspRomTxdCARLviKw6E5SY8 github.com" git config --global user.name Copybot git config --global user.email copybot@overleaf.com set +e copybara --git-committer-email=copybot@overleaf.com --git-committer-name=Copybot COPYBARA_EXIT_CODE=$? # Exit codes are documented in java/com/google/copybara/util/ExitCode.java # 0 is success, 4 is no-op (i.e. no change), anything else is an error if [[ $COPYBARA_EXIT_CODE -eq 0 || $COPYBARA_EXIT_CODE -eq 4 ]]; then exit 0 else exit $COPYBARA_EXIT_CODE fi fi
overleaf/web/bin/invoke-copybara/0
{ "file_path": "overleaf/web/bin/invoke-copybara", "repo_id": "overleaf", "token_count": 331 }
523
{ "access_your_projects_with_git": "", "account_not_linked_to_dropbox": "", "account_settings": "", "add_files": "", "also": "", "anyone_with_link_can_edit": "", "anyone_with_link_can_view": "", "ask_proj_owner_to_upgrade_for_git_bridge": "", "ask_proj_owner_to_upgrade_for_longer_compiles": "", "auto_compile": "", "autocompile_disabled": "", "autocompile_disabled_reason": "", "autocomplete": "", "autocomplete_references": "", "back_to_your_projects": "", "beta_badge_tooltip": "", "blocked_filename": "", "can_edit": "", "cancel": "", "cannot_invite_non_user": "", "cannot_invite_self": "", "cannot_verify_user_not_robot": "", "category_arrows": "", "category_greek": "", "category_misc": "", "category_operators": "", "category_relations": "", "change_or_cancel-cancel": "", "change_or_cancel-change": "", "change_or_cancel-or": "", "change_owner": "", "change_project_owner": "", "chat": "", "chat_error": "", "checking_dropbox_status": "", "checking_project_github_status": "", "clear_cached_files": "", "clone_with_git": "", "close": "", "clsi_maintenance": "", "clsi_unavailable": "", "code_check_failed": "", "code_check_failed_explanation": "", "collaborate_online_and_offline": "", "collabs_per_proj": "", "collapse": "", "commit": "", "common": "", "compile_error_description": "", "compile_error_entry_description": "", "compile_larger_projects": "", "compile_mode": "", "compile_terminated_by_user": "", "compiling": "", "conflicting_paths_found": "", "connected_users": "", "continue_github_merge": "", "copy": "", "copy_project": "", "copying": "", "create": "", "create_project_in_github": "", "creating": "", "delete": "", "deleting": "", "demonstrating_git_integration": "", "description": "", "dismiss": "", "dismiss_error_popup": "", "done": "", "download": "", "download_pdf": "", "drag_here": "", "dropbox_for_link_share_projs": "", "dropbox_sync": "", "duplicate_file": "", "easily_manage_your_project_files_everywhere": "", "editing": "", "error": "", "expand": "", "export_project_to_github": "", "fast": "", "file_already_exists": "", "file_already_exists_in_this_location": "", "file_name": "", "file_name_in_this_project": "", "file_outline": "", "files_cannot_include_invalid_characters": "", "find_out_more_about_latex_symbols": "", "find_out_more_about_the_file_outline": "", "first_error_popup_label": "", "following_paths_conflict": "", "free_accounts_have_timeout_upgrade_to_increase": "", "from_another_project": "", "from_external_url": "", "from_provider": "", "full_doc_history": "", "full_screen": "", "generic_linked_file_compile_error": "", "generic_something_went_wrong": "", "get_collaborative_benefits": "", "git_bridge_modal_description": "", "github_commit_message_placeholder": "", "github_credentials_expired": "", "github_file_name_error": "", "github_for_link_shared_projects": "", "github_large_files_error": "", "github_merge_failed": "", "github_private_description": "", "github_public_description": "", "github_repository_diverged": "", "github_symlink_error": "", "github_sync": "", "github_sync_error": "", "github_sync_repository_not_found_description": "", "github_timeout_error": "", "github_too_many_files_error": "", "github_validation_check": "", "give_feedback": "", "go_next_page": "", "go_page": "", "go_prev_page": "", "go_to_error_location": "", "have_an_extra_backup": "", "headers": "", "hide_outline": "", "history": "", "hotkey_add_a_comment": "", "hotkey_autocomplete_menu": "", "hotkey_beginning_of_document": "", "hotkey_bold_text": "", "hotkey_compile": "", "hotkey_delete_current_line": "", "hotkey_end_of_document": "", "hotkey_find_and_replace": "", "hotkey_go_to_line": "", "hotkey_indent_selection": "", "hotkey_insert_candidate": "", "hotkey_italic_text": "", "hotkey_redo": "", "hotkey_search_references": "", "hotkey_select_all": "", "hotkey_select_candidate": "", "hotkey_to_lowercase": "", "hotkey_to_uppercase": "", "hotkey_toggle_comment": "", "hotkey_toggle_review_panel": "", "hotkey_toggle_track_changes": "", "hotkey_undo": "", "hotkeys": "", "if_error_persists_try_relinking_provider": "", "ignore_validation_errors": "", "imported_from_another_project_at_date": "", "imported_from_external_provider_at_date": "", "imported_from_mendeley_at_date": "", "imported_from_the_output_of_another_project_at_date": "", "imported_from_zotero_at_date": "", "importing_and_merging_changes_in_github": "", "invalid_email": "", "invalid_file_name": "", "invalid_filename": "", "invalid_request": "", "invite_not_accepted": "", "learn_how_to_make_documents_compile_quickly": "", "learn_more_about_link_sharing": "", "link_sharing_is_off": "", "link_sharing_is_on": "", "link_to_github": "", "link_to_github_description": "", "link_to_mendeley": "", "link_to_zotero": "", "linked_file": "", "loading": "", "loading_recent_github_commits": "", "log_entry_description": "", "log_hint_extra_info": "", "logs_pane_info_message": "", "logs_pane_info_message_popup": "", "main_file_not_found": "", "make_private": "", "manage_files_from_your_dropbox_folder": "", "math_display": "", "math_inline": "", "maximum_files_uploaded_together": "", "mendeley_groups_loading_error": "", "mendeley_is_premium": "", "mendeley_reference_loading_error": "", "mendeley_reference_loading_error_expired": "", "mendeley_reference_loading_error_forbidden": "", "mendeley_sync_description": "", "menu": "", "n_errors": "", "n_errors_plural": "", "n_items": "", "n_items_plural": "", "n_warnings": "", "n_warnings_plural": "", "navigate_log_source": "", "navigation": "", "need_to_upgrade_for_more_collabs": "", "new_file": "", "new_folder": "", "new_name": "", "no_messages": "", "no_new_commits_in_github": "", "no_other_projects_found": "", "no_pdf_error_explanation": "", "no_pdf_error_reason_no_content": "", "no_pdf_error_reason_output_pdf_already_exists": "", "no_pdf_error_reason_unrecoverable_error": "", "no_pdf_error_title": "", "no_preview_available": "", "no_search_results": "", "no_symbols_found": "", "showing_symbol_search_results": "", "normal": "", "off": "", "ok": "", "on": "", "optional": "", "or": "", "other_logs_and_files": "", "other_output_files": "", "owner": "", "page_current": "", "pagination_navigation": "", "pdf_compile_in_progress_error": "", "pdf_compile_rate_limit_hit": "", "pdf_compile_try_again": "", "pdf_rendering_error": "", "please_compile_pdf_before_download": "", "please_refresh": "", "please_select_a_file": "", "please_select_a_project": "", "please_select_an_output_file": "", "please_set_main_file": "", "plus_upgraded_accounts_receive": "", "private": "", "processing": "", "proj_timed_out_reason": "", "project_approaching_file_limit": "", "project_flagged_too_many_compiles": "", "project_has_too_many_files": "", "project_not_linked_to_github": "", "project_ownership_transfer_confirmation_1": "", "project_ownership_transfer_confirmation_2": "", "project_synced_with_git_repo_at": "", "project_too_large": "", "project_too_large_please_reduce": "", "project_too_much_editable_text": "", "public": "", "pull_github_changes_into_sharelatex": "", "push_sharelatex_changes_to_github": "", "raw_logs": "", "raw_logs_description": "", "read_only": "", "reauthorize_github_account": "", "recent_commits_in_github": "", "recompile": "", "recompile_from_scratch": "", "reconnect": "", "reference_error_relink_hint": "", "refresh": "", "refresh_page_after_linking_dropbox": "", "refresh_page_after_starting_free_trial": "", "refreshing": "", "remote_service_error": "", "remove": "", "remove_collaborator": "", "rename": "", "repository_name": "", "resend": "", "review": "", "revoke": "", "revoke_invite": "", "run_syntax_check_now": "", "search": "", "select_a_file": "", "select_a_project": "", "select_an_output_file": "", "select_from_output_files": "", "select_from_source_files": "", "select_from_your_computer": "", "send_first_message": "", "server_error": "", "session_error": "", "session_expired_redirecting_to_login": "", "share": "", "share_project": "", "share_with_your_collabs": "", "show_outline": "", "something_went_wrong_rendering_pdf": "", "something_went_wrong_server": "", "somthing_went_wrong_compiling": "", "split_screen": "", "start_free_trial": "", "stop_compile": "", "stop_on_validation_error": "", "store_your_work": "", "submit_title": "", "sure_you_want_to_delete": "", "sync_project_to_github_explanation": "", "sync_to_dropbox": "", "sync_to_github": "", "terminated": "", "this_project_is_public": "", "this_project_is_public_read_only": "", "this_project_will_appear_in_your_dropbox_folder_at": "", "timedout": "", "to_add_more_collaborators": "", "to_change_access_permissions": "", "toggle_compile_options_menu": "", "toggle_output_files_list": "", "too_many_attempts": "", "too_many_files_uploaded_throttled_short_period": "", "too_many_requests": "", "too_recently_compiled": "", "total_words": "", "try_it_for_free": "", "turn_off_link_sharing": "", "turn_on_link_sharing": "", "unlimited_projects": "", "unlink_github_repository": "", "unlinking": "", "update_dropbox_settings": "", "upgrade": "", "upgrade_for_longer_compiles": "", "upload": "", "url_to_fetch_the_file_from": "", "use_your_own_machine": "", "validation_issue_description": "", "validation_issue_entry_description": "", "view_error": "", "view_error_plural": "", "view_logs": "", "view_pdf": "", "view_warning": "", "view_warning_plural": "", "we_cant_find_any_sections_or_subsections_in_this_file": "", "word_count": "", "work_offline": "", "work_with_non_overleaf_users": "", "your_message": "", "your_project_has_an_error": "", "your_project_has_an_error_plural": "", "zotero_groups_loading_error": "", "zotero_is_premium": "", "zotero_reference_loading_error": "", "zotero_reference_loading_error_expired": "", "zotero_reference_loading_error_forbidden": "", "zotero_sync_description": "" }
overleaf/web/frontend/extracted-translations.json/0
{ "file_path": "overleaf/web/frontend/extracted-translations.json", "repo_id": "overleaf", "token_count": 4380 }
524
// 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('rightClick', () => ({ restrict: 'A', link(scope, element, attrs) { return element.bind('contextmenu', function (e) { e.preventDefault() e.stopPropagation() return scope.$eval(attrs.rightClick) }) }, }))
overleaf/web/frontend/js/directives/rightClick.js/0
{ "file_path": "overleaf/web/frontend/js/directives/rightClick.js", "repo_id": "overleaf", "token_count": 195 }
525
import { useCallback, useEffect, useMemo, useState } from 'react' import PropTypes from 'prop-types' import { cloneProject } from '../utils/api' import CloneProjectModalContent from './clone-project-modal-content' function CloneProjectModal({ show, handleHide, projectId, projectName = '', openProject, }) { const [inFlight, setInFlight] = useState(false) const [error, setError] = useState() const [clonedProjectName, setClonedProjectName] = useState('') // set the cloned project name when the modal opens useEffect(() => { if (show) { setClonedProjectName(`${projectName} (Copy)`) } }, [show, projectName]) // reset error when the modal is opened useEffect(() => { if (show) { setError(undefined) } }, [show]) // close the modal if not in flight const cancel = useCallback(() => { if (!inFlight) { handleHide() } }, [handleHide, inFlight]) // valid if the cloned project has a name const valid = useMemo(() => !!clonedProjectName, [clonedProjectName]) // form submission: clone the project if the name is valid const handleSubmit = event => { event.preventDefault() if (!valid) { return } setError(false) setInFlight(true) // clone the project cloneProject(projectId, clonedProjectName) .then(data => { // open the cloned project openProject(data.project_id) }) .catch(({ response, data }) => { if (response?.status === 400) { setError(data.message) } else { setError(true) } }) .finally(() => { setInFlight(false) }) } return ( <CloneProjectModalContent show={show} cancel={cancel} inFlight={inFlight} valid={valid} error={error} clonedProjectName={clonedProjectName} setClonedProjectName={setClonedProjectName} handleSubmit={handleSubmit} /> ) } CloneProjectModal.propTypes = { handleHide: PropTypes.func.isRequired, projectId: PropTypes.string.isRequired, projectName: PropTypes.string, openProject: PropTypes.func.isRequired, show: PropTypes.bool.isRequired, } export default CloneProjectModal
overleaf/web/frontend/js/features/clone-project-modal/components/clone-project-modal.js/0
{ "file_path": "overleaf/web/frontend/js/features/clone-project-modal/components/clone-project-modal.js", "repo_id": "overleaf", "token_count": 842 }
526
import React from 'react' import ReactDOM from 'react-dom' import { Dropdown } from 'react-bootstrap' import { useFileTreeMainContext } from '../contexts/file-tree-main' import FileTreeItemMenuItems from './file-tree-item/file-tree-item-menu-items' function FileTreeContextMenu() { const { hasWritePermissions, contextMenuCoords, setContextMenuCoords, } = useFileTreeMainContext() if (!hasWritePermissions || !contextMenuCoords) return null function close() { // reset context menu setContextMenuCoords(null) } function handleToggle(wantOpen) { if (!wantOpen) close() } function handleClick() { handleToggle(false) } return ReactDOM.createPortal( <Dropdown onClick={handleClick} open id="dropdown-file-tree-context-menu" onToggle={handleToggle} > <FakeDropDownToggle bsRole="toggle" /> <Dropdown.Menu className="context-menu" style={contextMenuCoords}> <FileTreeItemMenuItems /> </Dropdown.Menu> </Dropdown>, document.querySelector('body') ) } // fake component required as Dropdowns require a Toggle, even tho we don't want // one for the context menu const FakeDropDownToggle = React.forwardRef((props, ref) => { return null }) FakeDropDownToggle.displayName = 'FakeDropDownToggle' export default FileTreeContextMenu
overleaf/web/frontend/js/features/file-tree/components/file-tree-context-menu.js/0
{ "file_path": "overleaf/web/frontend/js/features/file-tree/components/file-tree-context-menu.js", "repo_id": "overleaf", "token_count": 470 }
527
import PropTypes from 'prop-types' import classNames from 'classnames' import FileTreeDoc from './file-tree-doc' import FileTreeFolder from './file-tree-folder' import { fileCollator } from '../util/file-collator' function FileTreeFolderList({ folders, docs, files, classes = {}, dropRef = null, children, }) { const docsAndFiles = [...docs, ...files] return ( <ul className={classNames('list-unstyled', classes.root)} role="tree" ref={dropRef} dnd-container="true" > {folders.sort(compareFunction).map(folder => { return ( <FileTreeFolder key={folder._id} name={folder.name} id={folder._id} folders={folder.folders} docs={folder.docs} files={folder.fileRefs} /> ) })} {docsAndFiles.sort(compareFunction).map(doc => { return ( <FileTreeDoc key={doc._id} name={doc.name} id={doc._id} isLinkedFile={doc.linkedFileData && !!doc.linkedFileData.provider} /> ) })} {children} </ul> ) } FileTreeFolderList.propTypes = { folders: PropTypes.array.isRequired, docs: PropTypes.array.isRequired, files: PropTypes.array.isRequired, classes: PropTypes.exact({ root: PropTypes.string, }), dropRef: PropTypes.func, children: PropTypes.node, } function compareFunction(one, two) { return fileCollator.compare(one.name, two.name) } export default FileTreeFolderList
overleaf/web/frontend/js/features/file-tree/components/file-tree-folder-list.js/0
{ "file_path": "overleaf/web/frontend/js/features/file-tree/components/file-tree-folder-list.js", "repo_id": "overleaf", "token_count": 688 }
528
import { createContext, useContext, useState } from 'react' import PropTypes from 'prop-types' const FileTreeMainContext = createContext() export function useFileTreeMainContext() { const context = useContext(FileTreeMainContext) if (!context) { throw new Error( 'useFileTreeMainContext is only available inside FileTreeMainProvider' ) } return context } export const FileTreeMainProvider = function ({ projectId, hasWritePermissions, userHasFeature, refProviders, reindexReferences, setRefProviderEnabled, setStartedFreeTrial, children, }) { const [contextMenuCoords, setContextMenuCoords] = useState() return ( <FileTreeMainContext.Provider value={{ projectId, hasWritePermissions, userHasFeature, refProviders, reindexReferences, setRefProviderEnabled, setStartedFreeTrial, contextMenuCoords, setContextMenuCoords, }} > {children} </FileTreeMainContext.Provider> ) } FileTreeMainProvider.propTypes = { projectId: PropTypes.string.isRequired, hasWritePermissions: PropTypes.bool.isRequired, userHasFeature: PropTypes.func.isRequired, reindexReferences: PropTypes.func.isRequired, refProviders: PropTypes.object.isRequired, setRefProviderEnabled: PropTypes.func.isRequired, setStartedFreeTrial: PropTypes.func.isRequired, children: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.node), PropTypes.node, ]).isRequired, }
overleaf/web/frontend/js/features/file-tree/contexts/file-tree-main.js/0
{ "file_path": "overleaf/web/frontend/js/features/file-tree/contexts/file-tree-main.js", "repo_id": "overleaf", "token_count": 528 }
529
import { postJSON, deleteJSON } from '../../../infrastructure/fetch-json' export function syncRename(projectId, entityType, entityId, newName) { return postJSON( `/project/${projectId}/${getEntityPathName(entityType)}/${entityId}/rename`, { body: { name: newName, }, } ) } export function syncDelete(projectId, entityType, entityId) { return deleteJSON( `/project/${projectId}/${getEntityPathName(entityType)}/${entityId}` ) } export function syncMove(projectId, entityType, entityId, toFolderId) { return postJSON( `/project/${projectId}/${getEntityPathName(entityType)}/${entityId}/move`, { body: { folder_id: toFolderId, }, } ) } export function syncCreateEntity(projectId, parentFolderId, newEntityData) { const { endpoint, ...newEntity } = newEntityData return postJSON(`/project/${projectId}/${endpoint}`, { body: { parent_folder_id: parentFolderId, ...newEntity, }, }) } function getEntityPathName(entityType) { return entityType === 'fileRef' ? 'file' : entityType }
overleaf/web/frontend/js/features/file-tree/util/sync-mutation.js/0
{ "file_path": "overleaf/web/frontend/js/features/file-tree/util/sync-mutation.js", "repo_id": "overleaf", "token_count": 413 }
530
import PropTypes from 'prop-types' import { MenuItem } from 'react-bootstrap' import { useTranslation } from 'react-i18next' export const topFileTypes = ['bbl', 'gls', 'ind'] function PreviewDownloadFileList({ fileList = [] }) { const { t } = useTranslation() let topFiles = [] let otherFiles = [] if (fileList) { topFiles = fileList.filter(file => { return topFileTypes.includes(file.type) }) otherFiles = fileList.filter(file => { if (!topFileTypes.includes(file.type)) { return !(file.type === 'pdf' && file.main === true) } return false }) } return ( <> <MenuItem header>{t('other_output_files')}</MenuItem> <SubFileList subFileList={topFiles} listType="main" /> {otherFiles.length > 0 && topFiles.length > 0 ? ( <> <MenuItem divider /> </> ) : ( <></> )} {otherFiles.length > 0 ? ( <> <SubFileList subFileList={otherFiles} listType="other" /> </> ) : ( <></> )} </> ) } function SubFileList({ subFileList, listType }) { return subFileList.map((file, index) => { return ( <MenuItem download href={file.url} key={`${listType}${index}`}> <b>{file.fileName}</b> </MenuItem> ) }) } SubFileList.propTypes = { subFileList: PropTypes.array.isRequired, listType: PropTypes.string.isRequired, } PreviewDownloadFileList.propTypes = { fileList: PropTypes.array, } export default PreviewDownloadFileList
overleaf/web/frontend/js/features/preview/components/preview-download-file-list.js/0
{ "file_path": "overleaf/web/frontend/js/features/preview/components/preview-download-file-list.js", "repo_id": "overleaf", "token_count": 641 }
531
import { useProjectContext } from '../../../shared/context/project-context' import { Col, Row } from 'react-bootstrap' import { Trans } from 'react-i18next' export default function OwnerInfo() { const project = useProjectContext() return ( <Row className="project-member"> <Col xs={7}>{project.owner?.email}</Col> <Col xs={3} className="text-left"> <Trans i18nKey="owner" /> </Col> </Row> ) }
overleaf/web/frontend/js/features/share-project-modal/components/owner-info.js/0
{ "file_path": "overleaf/web/frontend/js/features/share-project-modal/components/owner-info.js", "repo_id": "overleaf", "token_count": 166 }
532
import { Button, OverlayTrigger, Tooltip } from 'react-bootstrap' import { useTranslation } from 'react-i18next' export default function SymbolPaletteInfoLink() { const { t } = useTranslation() return ( <OverlayTrigger placement="top" trigger={['hover', 'focus']} overlay={ <Tooltip id="tooltip-symbol-palette-info"> {t('find_out_more_about_latex_symbols')} </Tooltip> } > <Button bsStyle="link" bsSize="small" className="symbol-palette-info-link" href="https://www.overleaf.com/learn/latex/List_of_Greek_letters_and_math_symbols" target="_blank" rel="noopener noreferer" > <span className="info-badge" /> </Button> </OverlayTrigger> ) }
overleaf/web/frontend/js/features/symbol-palette/components/symbol-palette-info-link.js/0
{ "file_path": "overleaf/web/frontend/js/features/symbol-palette/components/symbol-palette-info-link.js", "repo_id": "overleaf", "token_count": 354 }
533
/* eslint-disable camelcase, max-len, no-cond-assign, no-return-assign, no-unused-vars, no-useless-escape, */ // 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 * 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 */ import App from './base' import FileTreeManager from './ide/file-tree/FileTreeManager' import LoadingManager from './ide/LoadingManager' import ConnectionManager from './ide/connection/ConnectionManager' import EditorManager from './ide/editor/EditorManager' import OnlineUsersManager from './ide/online-users/OnlineUsersManager' import HistoryManager from './ide/history/HistoryManager' import HistoryV2Manager from './ide/history/HistoryV2Manager' import PermissionsManager from './ide/permissions/PermissionsManager' import PdfManager from './ide/pdf/PdfManager' import BinaryFilesManager from './ide/binary-files/BinaryFilesManager' import ReferencesManager from './ide/references/ReferencesManager' import MetadataManager from './ide/metadata/MetadataManager' import ReviewPanelManager from './ide/review-panel/ReviewPanelManager' import OutlineManager from './features/outline/outline-manager' import SafariScrollPatcher from './ide/SafariScrollPatcher' import { loadServiceWorker, unregisterServiceWorker, } from './ide/pdfng/directives/serviceWorkerManager' import './ide/cobranding/CobrandingDataService' import './ide/settings/index' import './ide/chat/index' import './ide/clone/index' import './ide/file-view/index' import './ide/hotkeys/index' import './ide/wordcount/index' import './ide/directives/layout' import './ide/directives/validFile' import './ide/directives/verticalResizablePanes' import './ide/services/ide' import './directives/focus' import './directives/fineUpload' import './directives/scroll' import './directives/onEnter' import './directives/stopPropagation' import './directives/rightClick' import './directives/expandableTextArea' import './directives/videoPlayState' import './services/queued-http' import './services/validateCaptcha' import './services/validateCaptchaV3' import './services/wait-for' import './filters/formatDate' import './main/event' import './main/account-upgrade-angular' import './main/system-messages' import '../../modules/modules-ide.js' import './shared/context/controllers/root-context-controller' import './features/editor-navigation-toolbar/controllers/editor-navigation-toolbar-controller' import './features/share-project-modal/controllers/react-share-project-modal-controller' import getMeta from './utils/meta' App.controller( 'IdeController', function ( $scope, $timeout, ide, localStorage, eventTracking, metadata, $q, CobrandingDataService ) { // Don't freak out if we're already in an apply callback let err, pdfLayout, userAgent $scope.$originalApply = $scope.$apply $scope.$apply = function (fn) { if (fn == null) { fn = function () {} } const phase = this.$root.$$phase if (phase === '$apply' || phase === '$digest') { return fn() } else { return this.$originalApply(fn) } } $scope.state = { loading: true, load_progress: 40, error: null, } $scope.ui = { leftMenuShown: false, view: 'editor', chatOpen: false, pdfLayout: 'sideBySide', pdfHidden: false, pdfWidth: 0, reviewPanelOpen: localStorage(`ui.reviewPanelOpen.${window.project_id}`), miniReviewPanelVisible: false, chatResizerSizeOpen: 7, chatResizerSizeClosed: 0, } $scope.user = window.user $scope.settings = window.userSettings $scope.anonymous = window.anonymous $scope.isTokenMember = window.isTokenMember $scope.isRestrictedTokenMember = window.isRestrictedTokenMember $scope.cobranding = { isProjectCobranded: CobrandingDataService.isProjectCobranded(), logoImgUrl: CobrandingDataService.getLogoImgUrl(), submitBtnHtml: CobrandingDataService.getSubmitBtnHtml(), brandVariationName: CobrandingDataService.getBrandVariationName(), brandVariationHomeUrl: CobrandingDataService.getBrandVariationHomeUrl(), } $scope.chat = {} ide.toggleReviewPanel = $scope.toggleReviewPanel = function () { if (!$scope.project.features.trackChangesVisible) { return } $scope.ui.reviewPanelOpen = !$scope.ui.reviewPanelOpen eventTracking.sendMB('rp-toggle-panel', { value: $scope.ui.reviewPanelOpen, }) } $scope.$watch('ui.reviewPanelOpen', function (value) { if (value != null) { return localStorage(`ui.reviewPanelOpen.${window.project_id}`, value) } }) $scope.$on('layout:pdf:resize', function (_, layoutState) { $scope.ui.pdfHidden = layoutState.east.initClosed return ($scope.ui.pdfWidth = layoutState.east.size) }) $scope.$watch('ui.view', function (newView, oldView) { if (newView !== oldView) { $scope.$broadcast('layout:flat-screen:toggle') } if (newView != null && newView !== 'editor' && newView !== 'pdf') { eventTracking.sendMBOnce(`ide-open-view-${newView}-once`) } }) $scope.$watch('ui.chatOpen', function (isOpen) { if (isOpen) { eventTracking.sendMBOnce('ide-open-chat-once') } }) $scope.$watch('ui.leftMenuShown', function (isOpen) { if (isOpen) { eventTracking.sendMBOnce('ide-open-left-menu-once') } }) $scope.trackHover = feature => { eventTracking.sendMBOnce(`ide-hover-${feature}-once`) } // End of tracking code. window._ide = ide ide.validFileRegex = '^[^*/]*$' // Don't allow * and / const useFallbackWebsocket = window.location && window.location.search && window.location.search.match(/ws=fallback/) // if we previously failed to load the websocket fall back to null (the siteUrl) ide.wsUrl = useFallbackWebsocket ? null : window.sharelatex.wsUrl || null // websocket url (if defined) ide.project_id = $scope.project_id = window.project_id ide.$scope = $scope ide.referencesSearchManager = new ReferencesManager(ide, $scope) ide.loadingManager = new LoadingManager($scope) ide.connectionManager = new ConnectionManager(ide, $scope) ide.fileTreeManager = new FileTreeManager(ide, $scope) ide.editorManager = new EditorManager( ide, $scope, localStorage, eventTracking ) ide.onlineUsersManager = new OnlineUsersManager(ide, $scope) if (window.data.useV2History) { ide.historyManager = new HistoryV2Manager(ide, $scope, localStorage) } else { ide.historyManager = new HistoryManager(ide, $scope) } ide.pdfManager = new PdfManager(ide, $scope) ide.permissionsManager = new PermissionsManager(ide, $scope) ide.binaryFilesManager = new BinaryFilesManager(ide, $scope) ide.metadataManager = new MetadataManager(ide, $scope, metadata) ide.outlineManager = new OutlineManager(ide, $scope) let inited = false $scope.$on('project:joined', function () { if (inited) { return } inited = true if ( __guard__( $scope != null ? $scope.project : undefined, x => x.deletedByExternalDataSource ) ) { ide.showGenericMessageModal( 'Project Renamed or Deleted', `\ This project has either been renamed or deleted by an external data source such as Dropbox. We don't want to delete your data on Overleaf, so this project still contains your history and collaborators. If the project has been renamed please look in your project list for a new project under the new name.\ ` ) } return $timeout(function () { if ($scope.permissions.write) { let _labelsInitialLoadDone ide.metadataManager.loadProjectMetaFromServer() return (_labelsInitialLoadDone = true) } }, 200) }) // Count the first 'doc:opened' as a sign that the ide is loaded // and broadcast a message. This is a good event to listen for // if you want to wait until the ide is fully loaded and initialized let _loaded = false $scope.$on('doc:opened', function () { if (_loaded) { return } $scope.$broadcast('ide:loaded') return (_loaded = true) }) $scope.$on('cursor:editor:update', eventTracking.editingSessionHeartbeat) const DARK_THEMES = [ 'ambiance', 'chaos', 'clouds_midnight', 'cobalt', 'idle_fingers', 'merbivore', 'merbivore_soft', 'mono_industrial', 'monokai', 'pastel_on_dark', 'solarized_dark', 'terminal', 'tomorrow_night', 'tomorrow_night_blue', 'tomorrow_night_bright', 'tomorrow_night_eighties', 'twilight', 'vibrant_ink', ] $scope.darkTheme = false $scope.$watch('settings.editorTheme', function (theme) { if (Array.from(DARK_THEMES).includes(theme)) { return ($scope.darkTheme = true) } else { return ($scope.darkTheme = false) } }) ide.localStorage = localStorage ide.browserIsSafari = false $scope.switchToFlatLayout = function (view) { $scope.ui.pdfLayout = 'flat' $scope.ui.view = view return ide.localStorage('pdf.layout', 'flat') } $scope.switchToSideBySideLayout = function (view) { $scope.ui.pdfLayout = 'sideBySide' $scope.ui.view = view return localStorage('pdf.layout', 'split') } if ((pdfLayout = localStorage('pdf.layout'))) { if (pdfLayout === 'split') { $scope.switchToSideBySideLayout() } if (pdfLayout === 'flat') { $scope.switchToFlatLayout() } } else { $scope.switchToSideBySideLayout() } try { ;({ userAgent } = navigator) ide.browserIsSafari = userAgent && /.*Safari\/.*/.test(userAgent) && !/.*Chrome\/.*/.test(userAgent) && !/.*Chromium\/.*/.test(userAgent) } catch (error) { err = error console.error(err) } if (ide.browserIsSafari) { ide.safariScrollPatcher = new SafariScrollPatcher($scope) } // Fix Chrome 61 and 62 text-shadow rendering let browserIsChrome61or62 = false try { const chromeVersion = parseFloat(navigator.userAgent.split(' Chrome/')[1]) || null browserIsChrome61or62 = chromeVersion != null if (browserIsChrome61or62) { document.styleSheets[0].insertRule( '.ace_editor.ace_autocomplete .ace_completion-highlight { text-shadow: none !important; font-weight: bold; }', 1 ) } } catch (error1) { err = error1 console.error(err) } // User can append ?ft=somefeature to url to activate a feature toggle ide.featureToggle = __guard__( __guard__( typeof location !== 'undefined' && location !== null ? location.search : undefined, x1 => x1.match(/^\?ft=(\w+)$/) ), x => x[1] ) // Allow service worker to be removed via the websocket ide.$scope.$on('service-worker:unregister', unregisterServiceWorker) return ide.socket.on('project:publicAccessLevel:changed', data => { if (data.newAccessLevel != null) { ide.$scope.project.publicAccesLevel = data.newAccessLevel return $scope.$digest() } }) } ) if (getMeta('ol-resetServiceWorker')) { unregisterServiceWorker() } else if (getMeta('ol-enablePdfCaching')) { loadServiceWorker() } export default angular.bootstrap(document.body, ['SharelatexApp']) function __guard__(value, transform) { return typeof value !== 'undefined' && value !== null ? transform(value) : undefined }
overleaf/web/frontend/js/ide.js/0
{ "file_path": "overleaf/web/frontend/js/ide.js", "repo_id": "overleaf", "token_count": 4685 }
534
/* eslint-disable max-len, no-return-assign, no-useless-escape, */ // 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' import _ from 'lodash' import 'libs/jquery-layout' import 'libs/jquery.ui.touch-punch' export default App.directive('layout', ($parse, $compile, ide) => ({ compile() { return { pre(scope, element, attrs) { let customTogglerEl, spacingClosed, spacingOpen, state const name = attrs.layout const { customTogglerPane } = attrs const { customTogglerMsgWhenOpen } = attrs const { customTogglerMsgWhenClosed } = attrs const hasCustomToggler = customTogglerPane != null && customTogglerMsgWhenOpen != null && customTogglerMsgWhenClosed != null if (attrs.spacingOpen != null) { spacingOpen = parseInt(attrs.spacingOpen, 10) } else { spacingOpen = 7 } if (attrs.spacingClosed != null) { spacingClosed = parseInt(attrs.spacingClosed, 10) } else { spacingClosed = 7 } const options = { spacing_open: spacingOpen, spacing_closed: spacingClosed, slidable: false, enableCursorHotkey: false, onopen: pane => { return onPaneOpen(pane) }, onclose: pane => { return onPaneClose(pane) }, onresize: () => { return onInternalResize() }, maskIframesOnResize: scope.$eval( attrs.maskIframesOnResize || 'false' ), east: { size: scope.$eval(attrs.initialSizeEast), initClosed: scope.$eval(attrs.initClosedEast), }, west: { size: scope.$eval(attrs.initialSizeEast), initClosed: scope.$eval(attrs.initClosedWest), }, } // Restore previously recorded state if ((state = ide.localStorage(`layout.${name}`)) != null) { if (state.east != null) { if ( attrs.minimumRestoreSizeEast == null || (state.east.size >= attrs.minimumRestoreSizeEast && !state.east.initClosed) ) { options.east = state.east } } if (state.west != null) { if ( attrs.minimumRestoreSizeWest == null || (state.west.size >= attrs.minimumRestoreSizeWest && !state.west.initClosed) ) { options.west = state.west } } } options.east.resizerCursor = 'ew-resize' options.west.resizerCursor = 'ew-resize' const repositionControls = function () { state = element.layout().readState() if (state.east != null) { const controls = element.find('> .ui-layout-resizer-controls') if (state.east.initClosed) { return controls.hide() } else { controls.show() return controls.css({ right: state.east.size, }) } } } const repositionCustomToggler = function () { if (customTogglerEl == null) { return } state = element.layout().readState() const positionAnchor = customTogglerPane === 'east' ? 'right' : 'left' const paneState = state[customTogglerPane] if (paneState != null) { return customTogglerEl.css( positionAnchor, paneState.initClosed ? 0 : paneState.size ) } } const resetOpenStates = function () { state = element.layout().readState() if (attrs.openEast != null && state.east != null) { const openEast = $parse(attrs.openEast) return openEast.assign(scope, !state.east.initClosed) } } // Someone moved the resizer var onInternalResize = function () { state = element.layout().readState() scope.$broadcast(`layout:${name}:resize`, state) repositionControls() if (hasCustomToggler) { repositionCustomToggler() } return resetOpenStates() } let oldWidth = element.width() // Something resized our parent element const onExternalResize = function () { if ( attrs.resizeProportionally != null && scope.$eval(attrs.resizeProportionally) ) { const eastState = element.layout().readState().east if (eastState != null) { const newInternalWidth = (eastState.size / oldWidth) * element.width() oldWidth = element.width() element.layout().sizePane('east', newInternalWidth) return } } return element.layout().resizeAll() } element.layout(options) element.layout().resizeAll() if (attrs.resizeOn != null) { for (const event of Array.from(attrs.resizeOn.split(','))) { scope.$on(event, () => onExternalResize()) } } if (hasCustomToggler) { state = element.layout().readState() const customTogglerScope = scope.$new() customTogglerScope.isOpen = true customTogglerScope.isVisible = true if ( (state[customTogglerPane] != null ? state[customTogglerPane].initClosed : undefined) === true ) { customTogglerScope.isOpen = false } customTogglerScope.tooltipMsgWhenOpen = customTogglerMsgWhenOpen customTogglerScope.tooltipMsgWhenClosed = customTogglerMsgWhenClosed customTogglerScope.tooltipPlacement = customTogglerPane === 'east' ? 'left' : 'right' customTogglerScope.handleClick = function () { element.layout().toggle(customTogglerPane) return repositionCustomToggler() } customTogglerEl = $compile(`\ <a href \ ng-show=\"isVisible\" \ class=\"custom-toggler ${`custom-toggler-${customTogglerPane}`}\" \ ng-class=\"isOpen ? 'custom-toggler-open' : 'custom-toggler-closed'\" \ tooltip=\"{{ isOpen ? tooltipMsgWhenOpen : tooltipMsgWhenClosed }}\" \ tooltip-placement=\"{{ tooltipPlacement }}\" \ ng-click=\"handleClick()\">\ `)(customTogglerScope) element.append(customTogglerEl) } var onPaneOpen = function (pane) { if (!hasCustomToggler && pane !== customTogglerPane) { return } return customTogglerEl .scope() .$applyAsync(() => (customTogglerEl.scope().isOpen = true)) } var onPaneClose = function (pane) { if (!hasCustomToggler && pane !== customTogglerPane) { return } return customTogglerEl .scope() .$applyAsync(() => (customTogglerEl.scope().isOpen = false)) } // Save state when exiting $(window).unload(() => { // Save only the state properties for the current layout, ignoring sublayouts inside it. // If we save sublayouts state (`children`), the layout library will use it when // initializing. This raises errors when the sublayout elements aren't available (due to // being loaded at init or just not existing for the current project/user). const stateToSave = _.mapValues(element.layout().readState(), pane => _.omit(pane, 'children') ) ide.localStorage(`layout.${name}`, stateToSave) }) if (attrs.openEast != null) { scope.$watch(attrs.openEast, function (value, oldValue) { if (value != null && value !== oldValue) { if (value) { element.layout().open('east') } else { element.layout().close('east') } } return setTimeout(() => scope.$digest(), 0) }) } if (attrs.allowOverflowOn != null) { const layoutObj = element.layout() const overflowPane = scope.$eval(attrs.allowOverflowOn) const overflowPaneEl = layoutObj.panes[overflowPane] // Set the panel as overflowing (gives it higher z-index and sets overflow rules) layoutObj.allowOverflow(overflowPane) // Read the given z-index value and increment it, so that it's higher than synctex controls. const overflowPaneZVal = overflowPaneEl.zIndex() overflowPaneEl.css('z-index', overflowPaneZVal + 1) } resetOpenStates() onInternalResize() if (attrs.layoutDisabled != null) { return scope.$watch(attrs.layoutDisabled, function (value) { if (value) { element.layout().hide('east') } else { element.layout().show('east') } if (hasCustomToggler) { return customTogglerEl.scope().$applyAsync(function () { customTogglerEl.scope().isOpen = !value return (customTogglerEl.scope().isVisible = !value) }) } }) } }, post(scope, element, attrs) { const name = attrs.layout const state = element.layout().readState() return scope.$broadcast(`layout:${name}:linked`, state) }, } }, }))
overleaf/web/frontend/js/ide/directives/layout.js/0
{ "file_path": "overleaf/web/frontend/js/ide/directives/layout.js", "repo_id": "overleaf", "token_count": 4740 }
535
// 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 */ export default [ { caption: '\\begin{}', snippet: '\\begin{$1}', meta: 'env', score: 7.849662248028187, }, { caption: '\\end{}', snippet: '\\end{$1}', meta: 'env', score: 7.847906405228455, }, { caption: '\\usepackage[]{}', snippet: '\\usepackage[$1]{$2}', meta: 'pkg', score: 5.427890758130527, }, { caption: '\\item', snippet: '\\item', meta: 'cmd', score: 3.800886892251021, }, { caption: '\\item[]', snippet: '\\item[$1]', meta: 'cmd', score: 3.800886892251021, }, { caption: '\\section{}', snippet: '\\section{$1}', meta: 'cmd', score: 3.0952612541683835, }, { caption: '\\textbf{}', snippet: '\\textbf{$1}', meta: 'cmd', score: 2.627755982816738, }, { caption: '\\cite{}', snippet: '\\cite{$1}', meta: 'cmd', score: 2.341195220791228, }, { caption: '\\label{}', snippet: '\\label{$1}', meta: 'cmd', score: 1.897791904799601, }, { caption: '\\textit{}', snippet: '\\textit{$1}', meta: 'cmd', score: 1.6842996195493385, }, { caption: '\\includegraphics[]{}', snippet: '\\includegraphics[$1]{$2}', meta: 'cmd', score: 1.4595731795525781, }, { caption: '\\documentclass[]{}', snippet: '\\documentclass[$1]{$2}', meta: 'cmd', score: 1.4425339817971206, }, { caption: '\\documentclass{}', snippet: '\\documentclass{$1}', meta: 'cmd', score: 1.4425339817971206, }, { caption: '\\ref{}', snippet: '\\ref{$1}', meta: 'cross-reference', score: 0.014379554883991673, }, { caption: '\\frac{}{}', snippet: '\\frac{$1}{$2}', meta: 'cmd', score: 1.4341091141105058, }, { caption: '\\subsection{}', snippet: '\\subsection{$1}', meta: 'cmd', score: 1.3890912739512353, }, { caption: '\\hline', snippet: '\\hline', meta: 'cmd', score: 1.3209538327406387, }, { caption: '\\caption{}', snippet: '\\caption{$1}', meta: 'cmd', score: 1.2569477427490174, }, { caption: '\\centering', snippet: '\\centering', meta: 'cmd', score: 1.1642881814937829, }, { caption: '\\vspace{}', snippet: '\\vspace{$1}', meta: 'cmd', score: 0.9533807826673939, }, { caption: '\\title{}', snippet: '\\title{$1}', meta: 'cmd', score: 0.9202908262245683, }, { caption: '\\author{}', snippet: '\\author{$1}', meta: 'cmd', score: 0.8973590434087177, }, { caption: '\\author[]{}', snippet: '\\author[$1]{$2}', meta: 'cmd', score: 0.8973590434087177, }, { caption: '\\maketitle', snippet: '\\maketitle', meta: 'cmd', score: 0.7504160124360846, }, { caption: '\\textwidth', snippet: '\\textwidth', meta: 'cmd', score: 0.7355328080889112, }, { caption: '\\newcommand{}{}', snippet: '\\newcommand{$1}{$2}', meta: 'cmd', score: 0.7264891987129375, }, { caption: '\\newcommand{}[]{}', snippet: '\\newcommand{$1}[$2]{$3}', meta: 'cmd', score: 0.7264891987129375, }, { caption: '\\date{}', snippet: '\\date{$1}', meta: 'cmd', score: 0.7225518453076786, }, { caption: '\\emph{}', snippet: '\\emph{$1}', meta: 'cmd', score: 0.7060308784832261, }, { caption: '\\textsc{}', snippet: '\\textsc{$1}', meta: 'cmd', score: 0.6926466355384758, }, { caption: '\\multicolumn{}{}{}', snippet: '\\multicolumn{$1}{$2}{$3}', meta: 'cmd', score: 0.5473606021405326, }, { caption: '\\input{}', snippet: '\\input{$1}', meta: 'cmd', score: 0.4966021927742672, }, { caption: '\\alpha', snippet: '\\alpha', meta: 'cmd', score: 0.49520006391384913, }, { caption: '\\in', snippet: '\\in', meta: 'cmd', score: 0.4716039670146658, }, { caption: '\\mathbf{}', snippet: '\\mathbf{$1}', meta: 'cmd', score: 0.4682018419466319, }, { caption: '\\right', snippet: '\\right', meta: 'cmd', score: 0.4299239459457309, }, { caption: '\\left', snippet: '\\left', meta: 'cmd', score: 0.42937815279867964, }, { caption: '\\sum', snippet: '\\sum', meta: 'cmd', score: 0.42607994509619934, }, { caption: '\\chapter{}', snippet: '\\chapter{$1}', meta: 'cmd', score: 0.422097569591803, }, { caption: '\\par', snippet: '\\par', meta: 'cmd', score: 0.413853376001159, }, { caption: '\\lambda', snippet: '\\lambda', meta: 'cmd', score: 0.39389600578684125, }, { caption: '\\subsubsection{}', snippet: '\\subsubsection{$1}', meta: 'cmd', score: 0.3727781330132016, }, { caption: '\\bibitem{}', snippet: '\\bibitem{$1}', meta: 'cmd', score: 0.3689547570562042, }, { caption: '\\bibitem[]{}', snippet: '\\bibitem[$1]{$2}', meta: 'cmd', score: 0.3689547570562042, }, { caption: '\\text{}', snippet: '\\text{$1}', meta: 'cmd', score: 0.3608680734736821, }, { caption: '\\setlength{}{}', snippet: '\\setlength{$1}{$2}', meta: 'cmd', score: 0.354445763583904, }, { caption: '\\mathcal{}', snippet: '\\mathcal{$1}', meta: 'cmd', score: 0.35084018920966636, }, { caption: '\\newpage', snippet: '\\newpage', meta: 'cmd', score: 0.3277033727934986, }, { caption: '\\renewcommand{}{}', snippet: '\\renewcommand{$1}{$2}', meta: 'cmd', score: 0.3267437011085663, }, { caption: '\\theta', snippet: '\\theta', meta: 'cmd', score: 0.3210417159232142, }, { caption: '\\hspace{}', snippet: '\\hspace{$1}', meta: 'cmd', score: 0.3147206476372336, }, { caption: '\\beta', snippet: '\\beta', meta: 'cmd', score: 0.3061799530337638, }, { caption: '\\texttt{}', snippet: '\\texttt{$1}', meta: 'cmd', score: 0.3019066753744355, }, { caption: '\\times', snippet: '\\times', meta: 'cmd', score: 0.2957960629411553, }, { caption: '\\color{}', snippet: '\\color{$1}', meta: 'cmd', score: 0.2864294797053033, }, { caption: '\\mu', snippet: '\\mu', meta: 'cmd', score: 0.27635652476799255, }, { caption: '\\bibliography{}', snippet: '\\bibliography{$1}', meta: 'cmd', score: 0.2659628337907604, }, { caption: '\\linewidth', snippet: '\\linewidth', meta: 'cmd', score: 0.2639498312518439, }, { caption: '\\delta', snippet: '\\delta', meta: 'cmd', score: 0.2620578600722735, }, { caption: '\\sigma', snippet: '\\sigma', meta: 'cmd', score: 0.25940147926344487, }, { caption: '\\pi', snippet: '\\pi', meta: 'cmd', score: 0.25920934567729714, }, { caption: '\\hat{}', snippet: '\\hat{$1}', meta: 'cmd', score: 0.25264309033778715, }, { caption: '\\bibliographystyle{}', snippet: '\\bibliographystyle{$1}', meta: 'cmd', score: 0.25122317941387773, }, { caption: '\\small', snippet: '\\small', meta: 'cmd', score: 0.2447632045426295, }, { caption: '\\LaTeX', snippet: '\\LaTeX', meta: 'cmd', score: 0.2334089308452787, }, { caption: '\\cdot', snippet: '\\cdot', meta: 'cmd', score: 0.23029085545522762, }, { caption: '\\footnote{}', snippet: '\\footnote{$1}', meta: 'cmd', score: 0.2253056071787701, }, { caption: '\\newtheorem{}{}', snippet: '\\newtheorem{$1}{$2}', meta: 'cmd', score: 0.215689795055434, }, { caption: '\\Delta', snippet: '\\Delta', meta: 'cmd', score: 0.21386475063892618, }, { caption: '\\tau', snippet: '\\tau', meta: 'cmd', score: 0.21236188205859796, }, { caption: '\\hfill', snippet: '\\hfill', meta: 'cmd', score: 0.2058248088519886, }, { caption: '\\leq', snippet: '\\leq', meta: 'cmd', score: 0.20498894440637172, }, { caption: '\\footnotesize', snippet: '\\footnotesize', meta: 'cmd', score: 0.2038592081252624, }, { caption: '\\large', snippet: '\\large', meta: 'cmd', score: 0.20377416734108866, }, { caption: '\\sqrt{}', snippet: '\\sqrt{$1}', meta: 'cmd', score: 0.20240160977404634, }, { caption: '\\epsilon', snippet: '\\epsilon', meta: 'cmd', score: 0.2005136761359043, }, { caption: '\\Large', snippet: '\\Large', meta: 'cmd', score: 0.1987771081149759, }, { caption: '\\rho', snippet: '\\rho', meta: 'cmd', score: 0.1959287380541684, }, { caption: '\\omega', snippet: '\\omega', meta: 'cmd', score: 0.19326783415115262, }, { caption: '\\mathrm{}', snippet: '\\mathrm{$1}', meta: 'cmd', score: 0.19117752976172653, }, { caption: '\\boldsymbol{}', snippet: '\\boldsymbol{$1}', meta: 'cmd', score: 0.18137737738638837, }, { caption: '\\gamma', snippet: '\\gamma', meta: 'cmd', score: 0.17940276535431304, }, { caption: '\\clearpage', snippet: '\\clearpage', meta: 'cmd', score: 0.1789117552185788, }, { caption: '\\infty', snippet: '\\infty', meta: 'cmd', score: 0.17837290019711305, }, { caption: '\\phi', snippet: '\\phi', meta: 'cmd', score: 0.17405809173097808, }, { caption: '\\partial', snippet: '\\partial', meta: 'cmd', score: 0.17168102367966637, }, { caption: '\\include{}', snippet: '\\include{$1}', meta: 'cmd', score: 0.1547080054979312, }, { caption: '\\address{}', snippet: '\\address{$1}', meta: 'cmd', score: 0.1525055392611109, }, { caption: '\\quad', snippet: '\\quad', meta: 'cmd', score: 0.15242755832392743, }, { caption: '\\paragraph{}', snippet: '\\paragraph{$1}', meta: 'cmd', score: 0.152074250347974, }, { caption: '\\varepsilon', snippet: '\\varepsilon', meta: 'cmd', score: 0.05411564201390573, }, { caption: '\\zeta', snippet: '\\zeta', meta: 'cmd', score: 0.023330249803752954, }, { caption: '\\eta', snippet: '\\eta', meta: 'cmd', score: 0.11088718379889091, }, { caption: '\\vartheta', snippet: '\\vartheta', meta: 'cmd', score: 0.0025822992078068712, }, { caption: '\\iota', snippet: '\\iota', meta: 'cmd', score: 0.0024774003791525486, }, { caption: '\\kappa', snippet: '\\kappa', meta: 'cmd', score: 0.04887876299369008, }, { caption: '\\nu', snippet: '\\nu', meta: 'cmd', score: 0.09206962821059342, }, { caption: '\\xi', snippet: '\\xi', meta: 'cmd', score: 0.06496042899265699, }, { caption: '\\varpi', snippet: '\\varpi', meta: 'cmd', score: 0.0007039358167790341, }, { caption: '\\varrho', snippet: '\\varrho', meta: 'cmd', score: 0.0011279491613898612, }, { caption: '\\varsigma', snippet: '\\varsigma', meta: 'cmd', score: 0.0010424880711234978, }, { caption: '\\upsilon', snippet: '\\upsilon', meta: 'cmd', score: 0.00420715572598688, }, { caption: '\\varphi', snippet: '\\varphi', meta: 'cmd', score: 0.03351251516668212, }, { caption: '\\chi', snippet: '\\chi', meta: 'cmd', score: 0.043373492287805675, }, { caption: '\\psi', snippet: '\\psi', meta: 'cmd', score: 0.09994508706163642, }, { caption: '\\Gamma', snippet: '\\Gamma', meta: 'cmd', score: 0.04801549269801977, }, { caption: '\\Theta', snippet: '\\Theta', meta: 'cmd', score: 0.038090902146599444, }, { caption: '\\Lambda', snippet: '\\Lambda', meta: 'cmd', score: 0.032206594305977686, }, { caption: '\\Xi', snippet: '\\Xi', meta: 'cmd', score: 0.01060997225400494, }, { caption: '\\Pi', snippet: '\\Pi', meta: 'cmd', score: 0.021264671817473237, }, { caption: '\\Sigma', snippet: '\\Sigma', meta: 'cmd', score: 0.05769642802079917, }, { caption: '\\Upsilon', snippet: '\\Upsilon', meta: 'cmd', score: 0.00032875192955749566, }, { caption: '\\Phi', snippet: '\\Phi', meta: 'cmd', score: 0.0538724950042562, }, { caption: '\\Psi', snippet: '\\Psi', meta: 'cmd', score: 0.03056589143021648, }, { caption: '\\Omega', snippet: '\\Omega', meta: 'cmd', score: 0.09490387997853639, }, ]
overleaf/web/frontend/js/ide/editor/directives/aceEditor/auto-complete/snippets/TopHundredSnippets.js/0
{ "file_path": "overleaf/web/frontend/js/ide/editor/directives/aceEditor/auto-complete/snippets/TopHundredSnippets.js", "repo_id": "overleaf", "token_count": 6523 }
536
/* 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 */ import App from '../../../base' export default App.directive('fileEntity', RecursionHelper => ({ restrict: 'E', scope: { entity: '=', permissions: '=', depth: '=?', }, templateUrl: 'entityListItemTemplate', compile(element) { return RecursionHelper.compile( element, function (scope, element, attrs, ctrl) { // Don't freak out if we're already in an apply callback scope.$originalApply = scope.$apply return (scope.$apply = function (fn) { if (fn == null) { fn = function () {} } const phase = this.$root.$$phase if (phase === '$apply' || phase === '$digest') { return fn() } else { return this.$originalApply(fn) } }) } ) }, }))
overleaf/web/frontend/js/ide/file-tree/directives/fileEntity.js/0
{ "file_path": "overleaf/web/frontend/js/ide/file-tree/directives/fileEntity.js", "repo_id": "overleaf", "token_count": 482 }
537
/* 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' export default App.controller( 'HistoryV2AddLabelModalController', function ($scope, $modalInstance, ide, update) { $scope.update = update $scope.inputs = { labelName: null } $scope.state = { inflight: false, error: false, } $modalInstance.opened.then(() => $scope.$applyAsync(() => $scope.$broadcast('open')) ) return ($scope.addLabelModalFormSubmit = function () { $scope.state.inflight = true return ide.historyManager .labelCurrentVersion($scope.inputs.labelName) .then(function (response) { $scope.state.inflight = false return $modalInstance.close() }) .catch(function (response) { const { data, status } = response $scope.state.inflight = false if (status === 400) { return ($scope.state.error = { message: data }) } else { return ($scope.state.error = true) } }) }) } )
overleaf/web/frontend/js/ide/history/controllers/HistoryV2AddLabelModalController.js/0
{ "file_path": "overleaf/web/frontend/js/ide/history/controllers/HistoryV2AddLabelModalController.js", "repo_id": "overleaf", "token_count": 549 }
538
/* eslint-disable camelcase, node/handle-callback-err, 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 * DS206: Consider reworking classes to avoid initClass * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import ColorManager from '../colors/ColorManager' import 'crypto-js/md5' import './controllers/OnlineUsersController' let OnlineUsersManager export default OnlineUsersManager = (function () { OnlineUsersManager = class OnlineUsersManager { static initClass() { this.prototype.cursorUpdateInterval = 500 } constructor(ide, $scope) { this.ide = ide this.$scope = $scope this.$scope.onlineUsers = {} this.$scope.onlineUserCursorHighlights = {} this.$scope.onlineUsersArray = [] this.$scope.onlineUsersCount = 0 this.$scope.$on('cursor:editor:update', (event, position) => { return this.sendCursorPositionUpdate(position) }) this.$scope.$on('project:joined', () => { return this.ide.socket.emit( 'clientTracking.getConnectedUsers', (error, connectedUsers) => { this.$scope.onlineUsers = {} for (const user of Array.from(connectedUsers || [])) { if (user.client_id === this.ide.socket.publicId) { // Don't store myself continue } // Store data in the same format returned by clientTracking.clientUpdated this.$scope.onlineUsers[user.client_id] = { id: user.client_id, user_id: user.user_id, email: user.email, name: `${user.first_name} ${user.last_name}`, doc_id: user.cursorData != null ? user.cursorData.doc_id : undefined, row: user.cursorData != null ? user.cursorData.row : undefined, column: user.cursorData != null ? user.cursorData.column : undefined, } } return this.refreshOnlineUsers() } ) }) this.ide.socket.on('clientTracking.clientUpdated', client => { if (client.id !== this.ide.socket.publicId) { // Check it's not me! return this.$scope.$apply(() => { this.$scope.onlineUsers[client.id] = client return this.refreshOnlineUsers() }) } }) this.ide.socket.on('clientTracking.clientDisconnected', client_id => { return this.$scope.$apply(() => { delete this.$scope.onlineUsers[client_id] return this.refreshOnlineUsers() }) }) this.$scope.getHueForUserId = user_id => { return ColorManager.getHueForUserId(user_id) } } refreshOnlineUsers() { this.$scope.onlineUsersArray = [] for (var client_id in this.$scope.onlineUsers) { const user = this.$scope.onlineUsers[client_id] if (user.doc_id != null) { user.doc = this.ide.fileTreeManager.findEntityById(user.doc_id) } // If the user's name is empty use their email as display name // Otherwise they're probably an anonymous user if (user.name === null || user.name.trim().length === 0) { if (user.email) { user.name = user.email.trim() } else if (user.user_id === 'anonymous-user') { user.name = 'Anonymous' } } user.initial = user.name != null ? user.name[0] : undefined if (!user.initial || user.initial === ' ') { user.initial = '?' } this.$scope.onlineUsersArray.push(user) } // keep a count of the other online users this.$scope.onlineUsersCount = this.$scope.onlineUsersArray.length this.$scope.onlineUserCursorHighlights = {} for (client_id in this.$scope.onlineUsers) { const client = this.$scope.onlineUsers[client_id] const { doc_id } = client if (doc_id == null || client.row == null || client.column == null) { continue } if (!this.$scope.onlineUserCursorHighlights[doc_id]) { this.$scope.onlineUserCursorHighlights[doc_id] = [] } this.$scope.onlineUserCursorHighlights[doc_id].push({ label: client.name, cursor: { row: client.row, column: client.column, }, hue: ColorManager.getHueForUserId(client.user_id), }) } if (this.$scope.onlineUsersArray.length > 0) { delete this.cursorUpdateTimeout return (this.cursorUpdateInterval = 500) } else { delete this.cursorUpdateTimeout return (this.cursorUpdateInterval = 60 * 1000 * 5) } } sendCursorPositionUpdate(position) { if (position != null) { this.$scope.currentPosition = position // keep track of the latest position } if (this.cursorUpdateTimeout == null) { return (this.cursorUpdateTimeout = setTimeout(() => { const doc_id = this.$scope.editor.open_doc_id // always send the latest position to other clients this.ide.socket.emit('clientTracking.updatePosition', { row: this.$scope.currentPosition != null ? this.$scope.currentPosition.row : undefined, column: this.$scope.currentPosition != null ? this.$scope.currentPosition.column : undefined, doc_id, }) return delete this.cursorUpdateTimeout }, this.cursorUpdateInterval)) } } } OnlineUsersManager.initClass() return OnlineUsersManager })()
overleaf/web/frontend/js/ide/online-users/OnlineUsersManager.js/0
{ "file_path": "overleaf/web/frontend/js/ide/online-users/OnlineUsersManager.js", "repo_id": "overleaf", "token_count": 2629 }
539
/* eslint-disable no-return-assign, 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 PermissionsManager export default PermissionsManager = class PermissionsManager { constructor(ide, $scope) { this.ide = ide this.$scope = $scope this.$scope.permissions = { read: false, write: false, admin: false, comment: false, } this.$scope.$watch('permissionsLevel', permissionsLevel => { if (permissionsLevel != null) { if (permissionsLevel === 'readOnly') { this.$scope.permissions.read = true this.$scope.permissions.write = false this.$scope.permissions.admin = false this.$scope.permissions.comment = true } else if (permissionsLevel === 'readAndWrite') { this.$scope.permissions.read = true this.$scope.permissions.write = true this.$scope.permissions.comment = true } else if (permissionsLevel === 'owner') { this.$scope.permissions.read = true this.$scope.permissions.write = true this.$scope.permissions.admin = true this.$scope.permissions.comment = true } } if (this.$scope.anonymous) { return (this.$scope.permissions.comment = false) } }) } }
overleaf/web/frontend/js/ide/permissions/PermissionsManager.js/0
{ "file_path": "overleaf/web/frontend/js/ide/permissions/PermissionsManager.js", "repo_id": "overleaf", "token_count": 614 }
540
/* 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 */ import App from '../../../base' export default App.directive('reviewPanelSorted', $timeout => ({ link(scope, element, attrs) { let previous_focused_entry_index = 0 const layout = function (animate) { let entry, height, i, original_top, overflowTop, OVERVIEW_TOGGLE_HEIGHT, PADDING, TOOLBAR_HEIGHT, top if (animate == null) { animate = true } if (animate) { element.removeClass('no-animate') } else { element.addClass('no-animate') } if (scope.ui.reviewPanelOpen) { PADDING = 8 TOOLBAR_HEIGHT = 38 OVERVIEW_TOGGLE_HEIGHT = 57 } else { PADDING = 4 TOOLBAR_HEIGHT = 4 OVERVIEW_TOGGLE_HEIGHT = 0 } const entries = [] for (const el of Array.from(element.find('.rp-entry-wrapper'))) { entry = { $indicator_el: $(el).find('.rp-entry-indicator'), $box_el: $(el).find('.rp-entry'), $callout_el: $(el).find('.rp-entry-callout'), scope: angular.element(el).scope(), } if (scope.ui.reviewPanelOpen) { entry.$layout_el = entry.$box_el } else { entry.$layout_el = entry.$indicator_el } entry.height = entry.$layout_el.height() // Do all of our DOM reads first for perfomance, see http://wilsonpage.co.uk/preventing-layout-thrashing/ entries.push(entry) } entries.sort((a, b) => a.scope.entry.offset - b.scope.entry.offset) if (entries.length === 0) { return } const line_height = scope.reviewPanel.rendererData.lineHeight let focused_entry_index = Math.min( previous_focused_entry_index, entries.length - 1 ) for (i = 0; i < entries.length; i++) { entry = entries[i] if (entry.scope.entry.focused) { focused_entry_index = i break } } const entries_after = entries.slice(focused_entry_index + 1) const entries_before = entries.slice(0, focused_entry_index) const focused_entry = entries[focused_entry_index] previous_focused_entry_index = focused_entry_index sl_console.log('focused_entry_index', focused_entry_index) const positionLayoutEl = function ($callout_el, original_top, top) { if (original_top <= top) { $callout_el.removeClass('rp-entry-callout-inverted') return $callout_el.css({ top: original_top + line_height - 1, height: top - original_top, }) } else { $callout_el.addClass('rp-entry-callout-inverted') return $callout_el.css({ top: top + line_height, height: original_top - top, }) } } // Put the focused entry as close to where it wants to be as possible const focused_entry_top = Math.max( focused_entry.scope.entry.screenPos.y, TOOLBAR_HEIGHT ) focused_entry.$box_el.css({ top: focused_entry_top, // The entry element is invisible by default, to avoid flickering when positioning for // the first time. Here we make sure it becomes visible after having a "top" value. visibility: 'visible', }) focused_entry.$indicator_el.css({ top: focused_entry_top }) positionLayoutEl( focused_entry.$callout_el, focused_entry.scope.entry.screenPos.y, focused_entry_top ) let previousBottom = focused_entry_top + focused_entry.$layout_el.height() for (entry of Array.from(entries_after)) { original_top = entry.scope.entry.screenPos.y ;({ height } = entry) top = Math.max(original_top, previousBottom + PADDING) previousBottom = top + height entry.$box_el.css({ top, // The entry element is invisible by default, to avoid flickering when positioning for // the first time. Here we make sure it becomes visible after having a "top" value. visibility: 'visible', }) entry.$indicator_el.css({ top }) positionLayoutEl(entry.$callout_el, original_top, top) sl_console.log('ENTRY', { entry: entry.scope.entry, top }) } const lastBottom = previousBottom let previousTop = focused_entry_top entries_before.reverse() // Work through backwards, starting with the one just above for (i = 0; i < entries_before.length; i++) { entry = entries_before[i] original_top = entry.scope.entry.screenPos.y ;({ height } = entry) const original_bottom = original_top + height const bottom = Math.min(original_bottom, previousTop - PADDING) top = bottom - height previousTop = top entry.$box_el.css({ top, // The entry element is invisible by default, to avoid flickering when positioning for // the first time. Here we make sure it becomes visible after having a "top" value. visibility: 'visible', }) entry.$indicator_el.css({ top }) positionLayoutEl(entry.$callout_el, original_top, top) sl_console.log('ENTRY', { entry: entry.scope.entry, top }) } const lastTop = top if (lastTop < TOOLBAR_HEIGHT) { overflowTop = -lastTop + TOOLBAR_HEIGHT } else { overflowTop = 0 } return scope.$emit('review-panel:sizes', { overflowTop, height: previousBottom + OVERVIEW_TOGGLE_HEIGHT, }) } scope.$applyAsync(() => layout()) scope.$on('review-panel:layout', function (e, animate) { if (animate == null) { animate = true } return scope.$applyAsync(() => layout(animate)) }) scope.$watch('reviewPanel.rendererData.lineHeight', () => layout()) // # Scroll lock with Ace const scroller = element const list = element.find('.rp-entry-list-inner') // If we listen for scroll events in the review panel natively, then with a Mac trackpad // the scroll is very smooth (natively done I'd guess), but we don't get polled regularly // enough to keep Ace in step, and it noticeably lags. If instead, we borrow the manual // mousewheel/trackpad scrolling behaviour from Ace, and turn mousewheel events into // scroll events ourselves, then it makes the review panel slightly less smooth (barely) // noticeable, but keeps it perfectly in step with Ace. ace .require('ace/lib/event') .addMouseWheelListener(scroller[0], function (e) { const deltaY = e.wheelY const old_top = parseInt(list.css('top')) const top = old_top - deltaY * 4 scrollAce(-top) return e.preventDefault() }) // We always scroll by telling Ace to scroll and then updating the // review panel. This lets Ace manage the size of the scroller and // when it overflows. let ignoreNextAceEvent = false const scrollPanel = function (scrollTop, height) { if (ignoreNextAceEvent) { return (ignoreNextAceEvent = false) } else { const ignoreNextPanelEvent = true list.height(height) // console.log({height, scrollTop, top: height - scrollTop}) return list.css({ top: -scrollTop }) } } var scrollAce = scrollTop => scope.reviewPanelEventsBridge.emit('externalScroll', scrollTop) scope.reviewPanelEventsBridge.on('aceScroll', scrollPanel) scope.$on('$destroy', () => scope.reviewPanelEventsBridge.off('aceScroll')) return scope.reviewPanelEventsBridge.emit('refreshScrollPosition') }, }))
overleaf/web/frontend/js/ide/review-panel/directives/reviewPanelSorted.js/0
{ "file_path": "overleaf/web/frontend/js/ide/review-panel/directives/reviewPanelSorted.js", "repo_id": "overleaf", "token_count": 3331 }
541
// run `fn` in serie for all values, and resolve with an array of the resultss // inspired by https://stackoverflow.com/a/50506360/1314820 export function mapSeries(values, fn) { return values.reduce((promiseChain, value) => { return promiseChain.then(chainResults => fn(value).then(currentResult => [...chainResults, currentResult]) ) }, Promise.resolve([])) }
overleaf/web/frontend/js/infrastructure/promise.js/0
{ "file_path": "overleaf/web/frontend/js/infrastructure/promise.js", "repo_id": "overleaf", "token_count": 124 }
542
/* 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: * 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 moment from 'moment' import App from '../base' import '../modules/localStorage' const CACHE_KEY = 'mbEvents' // keep track of how many heartbeats we've sent so we can calculate how // long wait until the next one let heartbeatsSent = 0 let nextHeartbeat = new Date() App.factory('eventTracking', function ($http, localStorage) { const _getEventCache = function () { let eventCache = localStorage(CACHE_KEY) // Initialize as an empy object if the event cache is still empty. if (eventCache == null) { eventCache = {} localStorage(CACHE_KEY, eventCache) } return eventCache } const _eventInCache = function (key) { const curCache = _getEventCache() return curCache[key] || false } const _addEventToCache = function (key) { const curCache = _getEventCache() curCache[key] = true return localStorage(CACHE_KEY, curCache) } const _sendEditingSessionHeartbeat = () => $http({ url: `/editingSession/${window.project_id}`, method: 'PUT', headers: { 'X-CSRF-Token': window.csrfToken, }, }) return { send(category, action, label, value) { return ga('send', 'event', category, action, label, value) }, sendGAOnce(category, action, label, value) { if (!_eventInCache(action)) { _addEventToCache(action) return this.send(category, action, label, value) } }, editingSessionHeartbeat() { if (!(nextHeartbeat <= new Date())) { return } _sendEditingSessionHeartbeat() heartbeatsSent++ // send two first heartbeats at 0 and 30s then increase the backoff time // 1min per call until we reach 5 min const backoffSecs = heartbeatsSent <= 2 ? 30 : heartbeatsSent <= 6 ? (heartbeatsSent - 2) * 60 : 300 return (nextHeartbeat = moment().add(backoffSecs, 'seconds').toDate()) }, sendMB(key, segmentation) { if (segmentation == null) { segmentation = {} } fetch(`/event/${key}`, { method: 'POST', body: JSON.stringify(segmentation), keepalive: true, headers: { 'X-CSRF-Token': window.csrfToken, 'Content-Type': 'application/json', Accept: 'application/json', }, }) }, sendMBSampled(key, segmentation, rate = 0.01) { if (Math.random() < rate) { this.sendMB(key, segmentation) } }, sendMBOnce(key, segmentation) { if (!_eventInCache(key)) { _addEventToCache(key) this.sendMB(key, segmentation) } }, eventInCache(key) { return _eventInCache(key) }, } }) export default $('.navbar a').on('click', function (e) { const href = $(e.target).attr('href') if (href != null) { return ga('send', 'event', 'navigation', 'top menu bar', href) } })
overleaf/web/frontend/js/main/event.js/0
{ "file_path": "overleaf/web/frontend/js/main/event.js", "repo_id": "overleaf", "token_count": 1348 }
543
import _ from 'lodash' /* 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: * DS101: Remove unnecessary use of Array.from * 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.controller( 'RegisterUsersController', function ($scope, queuedHttp) { $scope.users = [] $scope.inputs = { emails: '' } const parseEmails = function (emailsString) { const regexBySpaceOrComma = /[\s,]+/ let emails = emailsString.split(regexBySpaceOrComma) emails = _.map(emails, email => (email = email.trim())) emails = _.filter(emails, email => email.indexOf('@') !== -1) return emails } return ($scope.registerUsers = function () { const emails = parseEmails($scope.inputs.emails) $scope.error = false return Array.from(emails).map(email => queuedHttp .post('/admin/register', { email, _csrf: window.csrfToken, }) .then(function (response) { const { data } = response const user = data $scope.users.push(user) return ($scope.inputs.emails = '') }) .catch(() => ($scope.error = true)) ) }) } )
overleaf/web/frontend/js/main/register-users.js/0
{ "file_path": "overleaf/web/frontend/js/main/register-users.js", "repo_id": "overleaf", "token_count": 607 }
544
/* global grecaptcha */ /* 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 */ import App from '../base' export default App.factory('validateCaptcha', function () { let _recaptchaCallbacks = [] const onRecaptchaSubmit = function (token) { for (const cb of _recaptchaCallbacks) { cb(token) } _recaptchaCallbacks = [] } let recaptchaId = null const validateCaptcha = (callback, captchaDisabled) => { if (callback == null) { callback = function (response) {} } if ( typeof grecaptcha === 'undefined' || grecaptcha === null || captchaDisabled ) { return callback() } const reset = () => grecaptcha.reset() _recaptchaCallbacks.push(callback) _recaptchaCallbacks.push(reset) if (recaptchaId == null) { const el = $('#recaptcha')[0] recaptchaId = grecaptcha.render(el, { callback: onRecaptchaSubmit }) } return grecaptcha.execute(recaptchaId) } return validateCaptcha })
overleaf/web/frontend/js/services/validateCaptcha.js/0
{ "file_path": "overleaf/web/frontend/js/services/validateCaptcha.js", "repo_id": "overleaf", "token_count": 440 }
545
import { createContext, useContext, useCallback, useMemo } from 'react' import PropTypes from 'prop-types' import useScopeValue from './util/scope-value-hook' import { useIdeContext } from './ide-context' export const LayoutContext = createContext() LayoutContext.Provider.propTypes = { value: PropTypes.shape({ view: PropTypes.string, setView: PropTypes.func.isRequired, chatIsOpen: PropTypes.bool, setChatIsOpen: PropTypes.func.isRequired, reviewPanelOpen: PropTypes.bool, setReviewPanelOpen: PropTypes.func.isRequired, leftMenuShown: PropTypes.bool, setLeftMenuShown: PropTypes.func.isRequired, pdfLayout: PropTypes.oneOf(['sideBySide', 'flat', 'split']).isRequired, }).isRequired, } export function LayoutProvider({ children }) { const { $scope } = useIdeContext() const [view, _setView] = useScopeValue('ui.view') const setView = useCallback( value => { _setView(oldValue => { // ensure that the "history:toggle" event is broadcast when switching in or out of history view if (value === 'history' || oldValue === 'history') { $scope.toggleHistory() } return value }) }, [$scope, _setView] ) const [chatIsOpen, setChatIsOpen] = useScopeValue('ui.chatOpen') const [reviewPanelOpen, setReviewPanelOpen] = useScopeValue( 'ui.reviewPanelOpen' ) const [leftMenuShown, setLeftMenuShown] = useScopeValue('ui.leftMenuShown') const [pdfLayout] = useScopeValue('ui.pdfLayout', $scope) const value = useMemo( () => ({ view, setView, chatIsOpen, setChatIsOpen, reviewPanelOpen, setReviewPanelOpen, leftMenuShown, setLeftMenuShown, pdfLayout, }), [ chatIsOpen, leftMenuShown, pdfLayout, reviewPanelOpen, setChatIsOpen, setLeftMenuShown, setReviewPanelOpen, setView, view, ] ) return ( <LayoutContext.Provider value={value}>{children}</LayoutContext.Provider> ) } LayoutProvider.propTypes = { children: PropTypes.any, } export function useLayoutContext(propTypes) { const data = useContext(LayoutContext) PropTypes.checkPropTypes(propTypes, data, 'data', 'LayoutContext.Provider') return data }
overleaf/web/frontend/js/shared/context/layout-context.js/0
{ "file_path": "overleaf/web/frontend/js/shared/context/layout-context.js", "repo_id": "overleaf", "token_count": 852 }
546
import _ from 'lodash' // cache for parsed values const cache = new Map() export default function getMeta(name, fallback) { if (cache.has(name)) return cache.get(name) const element = document.head.querySelector(`meta[name="${name}"]`) if (!element) { return fallback } const plainTextValue = element.content let value switch (element.dataset.type) { case 'boolean': // in pug: content=false -> no content field // in pug: content=true -> empty content field value = element.hasAttribute('content') break case 'json': if (!plainTextValue) { // JSON.parse('') throws value = undefined } else { value = JSON.parse(plainTextValue) } break default: value = plainTextValue } cache.set(name, value) return value } function convertMetaToWindowAttributes() { window.data = window.data || {} Array.from(document.querySelectorAll('meta[name^="ol-"]')) .map(element => element.name) // process short labels before long ones: // e.g. assign 'sharelatex' before 'sharelatex.templates' .sort() .forEach(nameWithNamespace => { const label = nameWithNamespace.slice('ol-'.length) _.set(window, label, getMeta(nameWithNamespace)) _.set(window.data, label, getMeta(nameWithNamespace)) }) } convertMetaToWindowAttributes()
overleaf/web/frontend/js/utils/meta.js/0
{ "file_path": "overleaf/web/frontend/js/utils/meta.js", "repo_id": "overleaf", "token_count": 511 }
547
import PropTypes from 'prop-types' import CloneProjectModal from '../js/features/clone-project-modal/components/clone-project-modal' import useFetchMock from './hooks/use-fetch-mock' export const Interactive = ({ mockResponse = 200, mockResponseDelay = 500, ...args }) => { useFetchMock(fetchMock => { fetchMock.post( 'express:/project/:projectId/clone', () => { switch (mockResponse) { case 400: return { status: 400, body: 'The project name is not valid' } default: return mockResponse } }, { delay: mockResponseDelay } ) }) return <CloneProjectModal {...args} /> } Interactive.propTypes = { mockResponse: PropTypes.number, mockResponseDelay: PropTypes.number, } export default { title: 'Modals / Clone Project', component: CloneProjectModal, args: { projectId: 'original-project', projectName: 'Project Title', show: true, }, argTypes: { handleHide: { action: 'close modal' }, openProject: { action: 'open project' }, mockResponse: { name: 'Mock Response Status', type: { name: 'number', required: false }, description: 'The status code that should be returned by the mock server', defaultValue: 200, control: { type: 'radio', options: [200, 500, 400], }, }, mockResponseDelay: { name: 'Mock Response Delay', type: { name: 'number', required: false }, description: 'The delay before returning a response from the mock server', defaultValue: 500, control: { type: 'range', min: 0, max: 2500, step: 250, }, }, }, }
overleaf/web/frontend/stories/clone-project-modal.stories.js/0
{ "file_path": "overleaf/web/frontend/stories/clone-project-modal.stories.js", "repo_id": "overleaf", "token_count": 685 }
548
import FileTreeCreateNameInput from '../../../js/features/file-tree/components/file-tree-create/file-tree-create-name-input' import FileTreeCreateNameProvider from '../../../js/features/file-tree/contexts/file-tree-create-name' import { BlockedFilenameError, DuplicateFilenameError, } from '../../../js/features/file-tree/errors' import { ModalBodyDecorator, ModalContentDecorator } from '../modal-decorators' export const DefaultLabel = args => ( <FileTreeCreateNameProvider initialName="example.tex"> <FileTreeCreateNameInput {...args} /> </FileTreeCreateNameProvider> ) export const CustomLabel = args => ( <FileTreeCreateNameProvider initialName="example.tex"> <FileTreeCreateNameInput {...args} /> </FileTreeCreateNameProvider> ) CustomLabel.args = { label: 'File Name in this Project', } export const FocusName = args => ( <FileTreeCreateNameProvider initialName="example.tex"> <FileTreeCreateNameInput {...args} /> </FileTreeCreateNameProvider> ) FocusName.args = { focusName: true, } export const CustomPlaceholder = args => ( <FileTreeCreateNameProvider> <FileTreeCreateNameInput {...args} /> </FileTreeCreateNameProvider> ) CustomPlaceholder.args = { placeholder: 'Enter a file name…', } export const DuplicateError = args => ( <FileTreeCreateNameProvider initialName="main.tex"> <FileTreeCreateNameInput {...args} /> </FileTreeCreateNameProvider> ) DuplicateError.args = { error: new DuplicateFilenameError(), } export const BlockedError = args => ( <FileTreeCreateNameProvider initialName="main.tex"> <FileTreeCreateNameInput {...args} /> </FileTreeCreateNameProvider> ) BlockedError.args = { error: new BlockedFilenameError(), } export default { title: 'Modals / Create File / File Name Input', component: FileTreeCreateNameInput, decorators: [ModalBodyDecorator, ModalContentDecorator], }
overleaf/web/frontend/stories/modals/create-file/create-file-name-input.stories.js/0
{ "file_path": "overleaf/web/frontend/stories/modals/create-file/create-file-name-input.stories.js", "repo_id": "overleaf", "token_count": 584 }
549
.team-profile { clear: both; .img-container { float: left; overflow: hidden; margin: (@line-height-computed / 4) @line-height-computed @line-height-computed (@line-height-computed / 2); } }
overleaf/web/frontend/stylesheets/app/about-page.less/0
{ "file_path": "overleaf/web/frontend/stylesheets/app/about-page.less", "repo_id": "overleaf", "token_count": 86 }
550