text stringlengths 1 2.83M | id stringlengths 16 152 | metadata dict | __index_level_0__ int64 0 949 |
|---|---|---|---|
---
title: GetMaxPlayers
description: Returns the maximum number of players that can join the server, as set by the server variable 'maxplayers' in server.
tags: ["player"]
---
## คำอธิบาย
Returns the maximum number of players that can join the server, as set by the server variable 'maxplayers' in server.cfg.
| Name | Description |
| ---- | ----------- |
## ตัวอย่าง
```c
new str[128];
format(str, sizeof(str), "There are %i slots on this server!", GetMaxPlayers());
SendClientMessage(playerid, 0xFFFFFFFF, s);
```
## บันทึก
:::warning
This function can not be used in place of MAX_PLAYERS. It can not be used at compile time (e.g. for array sizes). MAX_PLAYERS should always be re-defined to what the 'maxplayers' var will be, or higher. See MAX_PLAYERS for more info.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [GetPlayerPoolSize](../functions/GetPlayerPoolSize): Gets the highest playerid connected to the server.
- [IsPlayerConnected](../functions/IsPlayerConnected): Check if a player is connected to the server.
| openmultiplayer/web/docs/translations/th/scripting/functions/GetMaxPlayers.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/GetMaxPlayers.md",
"repo_id": "openmultiplayer",
"token_count": 379
} | 397 |
---
title: GetPlayerCameraFrontVector
description: This function will return the current direction of player's aiming in 3-D space, the coords are relative to the camera position, see GetPlayerCameraPos.
tags: ["player"]
---
## คำอธิบาย
This function will return the current direction of player's aiming in 3-D space, the coords are relative to the camera position, see GetPlayerCameraPos.
| Name | Description |
| -------- | ------------------------------------------------------------------ |
| playerid | The ID of the player you want to obtain the camera front vector of |
| Float:x | A float to store the X coordinate, passed by reference. |
| Float:y | A float to store the Y coordinate, passed by reference. |
| Float:z | A float to store the Z coordinate, passed by reference. |
## ส่งคืน
The position is stored in the specified variables.
## ตัวอย่าง
```c
// A simple command to manipulate this vector using the
// positions from GetPlayerCameraPos. This command will create
// a hydra missile in the direction of where the player is looking.
public OnPlayerCommandText(playerid, cmdtext[])
{
if (!strcmp(cmdtext, "/test camera vector"))
{
new
Float:fPX, Float:fPY, Float:fPZ,
Float:fVX, Float:fVY, Float:fVZ,
Float:object_x, Float:object_y, Float:object_z;
// Change me to change the scale you want. A larger scale increases the distance from the camera.
// A negative scale will inverse the vectors and make them face in the opposite direction.
const
Float:fScale = 5.0;
GetPlayerCameraPos(playerid, fPX, fPY, fPZ);
GetPlayerCameraFrontVector(playerid, fVX, fVY, fVZ);
object_x = fPX + floatmul(fVX, fScale);
object_y = fPY + floatmul(fVY, fScale);
object_z = fPZ + floatmul(fVZ, fScale);
CreateObject(345, object_x, object_y, object_z, 0.0, 0.0, 0.0);
return 1;
}
return 0;
}
```
## บันทึก
:::tip
In 0.3a the camera front vector is only obtainable when player is inside a rhino, S.W.A.T tank, fire truck, or on foot. Since 0.3b the camera data can be obtained when the player is in any vehicle or on foot.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [GetPlayerCameraPos](../functions/GetPlayerCameraPos): Find out where the player's camera is.
| openmultiplayer/web/docs/translations/th/scripting/functions/GetPlayerCameraFrontVector.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/GetPlayerCameraFrontVector.md",
"repo_id": "openmultiplayer",
"token_count": 976
} | 398 |
---
title: GetPlayerInterior
description: Retrieves the player's current interior.
tags: ["player"]
---
## คำอธิบาย
Retrieves the player's current interior. A list of currently known interiors with their positions can be found on this page.
| Name | Description |
| -------- | ------------------------------------- |
| playerid | The player to get the interior ID of. |
## ส่งคืน
The interior ID the player is currently in
## ตัวอย่าง
```c
public OnPlayerCommandText(playerid,text[])
{
if (strcmp(cmdtext,"/int",true) == 0)
{
new string[128];
format(string, sizeof(string), "You are in interior %i",GetPlayerInterior(playerid));
SendClientMessage(playerid, 0xFF8000FF, string);
return 1;
}
return 0;
}
```
## บันทึก
:::tip
Always returns 0 for NPCs.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [SetPlayerInterior](../functions/SetPlayerInterior): Set a player's interior.
- [GetPlayerVirtualWorld](../functions/GetPlayerVirtualWorld): Check what virtual world a player is in.
| openmultiplayer/web/docs/translations/th/scripting/functions/GetPlayerInterior.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/GetPlayerInterior.md",
"repo_id": "openmultiplayer",
"token_count": 460
} | 399 |
---
title: GetPlayerSkin
description: Returns the class of the players skin.
tags: ["player"]
---
## คำอธิบาย
Returns the class of the players skin
| Name | Description |
| -------- | ---------------------------------------- |
| playerid | The player you want to get the skin from |
## ส่งคืน
The skin id (0 if invalid)
## ตัวอย่าง
```c
playerskin = GetPlayerSkin(playerid);
```
## บันทึก
:::tip
Returns the new skin after SetSpawnInfo is called but before the player actually respawns to get the new skin. Returns the old skin if the player was spawned through SpawnPlayer function.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- SetPlayerSkin: Set a player's skin.
| openmultiplayer/web/docs/translations/th/scripting/functions/GetPlayerSkin.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/GetPlayerSkin.md",
"repo_id": "openmultiplayer",
"token_count": 314
} | 400 |
---
title: GetPlayerWeaponData
description: Get the weapon and ammo in a specific player's weapon slot (e.
tags: ["player"]
---
## คำอธิบาย
Get the weapon and ammo in a specific player's weapon slot (e.g. the weapon in the 'SMG' slot).
| Name | Description |
| -------- | ---------------------------------------------------------------- |
| playerid | The ID of the player whose weapon data to retrieve. |
| slot | The weapon slot to get data for (0-12). |
| &weapons | A variable in which to store the weapon ID, passed by reference. |
| &ammo | A variable in which to store the ammo, passed by reference. |
## ส่งคืน
1: The function was executed successfully.
0: The function failed to execute. The player isn't connected and/or the weapon slot specified is invalid (valid is 0-12).
## ตัวอย่าง
```c
// Common use: get all weapons and store info in an array containing 13 slots
// The first value is the weapon ID, and second is the ammo
new weapons[13][2];
for (new i = 0; i <= 12; i++)
{
GetPlayerWeaponData(playerid, i, weapons[i][0], weapons[i][1]);
}
```
## บันทึก
:::tip
Old weapons with no ammo left are still returned.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- GetPlayerWeapon: Check what weapon a player is currently holding.
- GivePlayerWeapon: Give a player a weapon.
| openmultiplayer/web/docs/translations/th/scripting/functions/GetPlayerWeaponData.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/GetPlayerWeaponData.md",
"repo_id": "openmultiplayer",
"token_count": 568
} | 401 |
---
title: GetVehicleDistanceFromPoint
description: This function can be used to calculate the distance (as a float) between a vehicle and another map coordinate.
tags: ["vehicle"]
---
## คำอธิบาย
This function can be used to calculate the distance (as a float) between a vehicle and another map coordinate. This can be useful to detect how far a vehicle away is from a location.
| Name | Description |
| --------- | ---------------------------------------------------- |
| vehicleid | The ID of the vehicle to calculate the distance for. |
| Float:X | The X map coordinate. |
| Float:Y | The Y map coordinate. |
| Float:Z | The Z map coordinate. |
## ส่งคืน
A float containing the distance from the point specified in the coordinates.
## ตัวอย่าง
```c
/* when the player types 'vendingmachine' in to the chat box, they'll see this.*/
public OnPlayerText(playerid, text[])
{
if (strcmp(text, "vendingmachine", true) == 0)
{
new
Float: fDistance = GetVehicleDistanceFromPoint(GetPlayerVehicleID(playerid), 237.9, 115.6, 1010.2),
szMessage[44];
format(szMessage, sizeof(szMessage), "You're %f away from our vending machine.", fDistance);
SendClientMessage(playerid, 0xA9C4E4FF, szMessage);
}
return 0;
}
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- GetPlayerDistanceFromPoint: Get the distance between a player and a point.
- GetVehiclePos: Get the position of a vehicle.
| openmultiplayer/web/docs/translations/th/scripting/functions/GetVehicleDistanceFromPoint.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/GetVehicleDistanceFromPoint.md",
"repo_id": "openmultiplayer",
"token_count": 676
} | 402 |
---
title: IsPlayerInVehicle
description: Checks if a player is in a specific vehicle.
tags: ["player", "vehicle"]
---
## คำอธิบาย
Checks if a player is in a specific vehicle.
| Name | Description |
| --------- | ----------------------------------------- |
| playerid | ID of the player. |
| vehicleid | ID of the vehicle. Note: NOT the modelid! |
## ส่งคืน
1 - Player IS in the vehicle.
0 - Player is NOT in the vehicle.
## ตัวอย่าง
```c
new specialcar;
public OnGameModeInit()
{
specialcar = AddStaticVehicle(411, 0.0, 0.0, 5.0, 0.0, -1, -1);
return 1;
}
public OnPlayerCommandText(playerid, cmdtext[])
{
if (strcmp(cmdtext, "/specialcar", true) == 0)
{
if (IsPlayerInVehicle(playerid, specialcar))
{
SendClientMessage(playerid, -1, "You're in the special car!");
}
return 1;
}
return 0;
}
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [IsPlayerInAnyVehicle](../../scripting/functions/IsPlayerInAnyVehicle.md): Check if a player is in any vehicle.
- [GetPlayerVehicleSeat](../../scripting/functions/GetPlayerVehicleSeat.md): Check what seat a player is in.
| openmultiplayer/web/docs/translations/th/scripting/functions/IsPlayerInVehicle.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/IsPlayerInVehicle.md",
"repo_id": "openmultiplayer",
"token_count": 561
} | 403 |
---
title: MoveObject
description: Move an object to a new position with a set speed.
tags: []
---
## คำอธิบาย
Move an object to a new position with a set speed. Players/vehicles will 'surf' the object as it moves.
| Name | Description |
| ----------- | --------------------------------------------------------- |
| objectid | The ID of the object to move. |
| Float:X | The X coordinate to move the object to. |
| Float:Y | The Y coordinate to move the object to. |
| Float:Z | The Z coordinate to move the object to. |
| Float:Speed | The speed at which to move the object (units per second). |
| Float:RotX | The FINAL X rotation (optional). |
| Float:RotY | The FINAL Y rotation (optional). |
| Float:RotZ | The FINAL Z rotation (optional). |
## ส่งคืน
The time it will take for the object to move in milliseconds.
## ตัวอย่าง
```c
new obj; // Somewhere at the top of your script
public OnGameModeInit()
{
obj = CreateObject(980, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
return 1;
}
public OnPlayerCommandText(playerid, cmdtext[])
{
if (strcmp(cmdtext, "/moveobject", true) == 0)
{
new string[50];
new movetime = MoveObject(obj, 0, 0, 10, 2.00);
format(string, sizeof(string), "Object will finish moving in %d milliseconds", movetime);
SendClientMessage(playerid, 0xFF000000, string);
return 1;
}
return 0;
}
```
## บันทึก
:::warning
This function can be used to make objects rotate smoothly. In order to achieve this however, the object must also be moved. The specified rotation is the rotation the object will have after the movement. Hence the object will not rotate when no movement is applied. For a script example take a look at the ferriswheel.pwn filterscript made by Kye included in the server package (SA-MP 0.3d and above). To fully understand the above note, you can (but not limited to) increase the z position by (+0.001) and then (-0.001) after moving it again, as not changing the X,Y or Z will not rotate the object.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [CreateObject](../functions/CreateObject.md): Create an object.
- [DestroyObject](../functions/DestroyObject.md): Destroy an object.
- [IsValidObject](../functions/IsValidObject.md): Checks if a certain object is vaild.
- [IsObjectMoving](../functions/IsObjectMoving.md): Check if the object is moving.
- [StopObject](../functions/StopObject.md): Stop an object from moving.
- [SetObjectPos](../functions/SetObjectPos.md): Set the position of an object.
- [SetObjectRot](../functions/SetObjectRot.md): Set the rotation of an object.
- [GetObjectPos](../functions/GetObjectPos.md): Locate an object.
- [GetObjectRot](../functions/GetObjectRot.md): Check the rotation of an object.
- [AttachObjectToPlayer](../functions/AttachObjectToPlayer.md): Attach an object to a player.
- [CreatePlayerObject](../functions/CreatePlayerObject.md): Create an object for only one player.
- [DestroyPlayerObject](../functions/DestroyPlayerObject.md): Destroy a player object.
- [IsValidPlayerObject](../functions/IsValidPlayerObject.md): Checks if a certain player object is vaild.
- [MovePlayerObject](../functions/MovePlayerObject.md): Move a player object.
- [StopPlayerObject](../functions/StopPlayerObject.md): Stop a player object from moving.
- [IsPlayerObjectMoving](../functions/IsPlayerObjectMoving.md): Check if the player object is moving.
- [SetPlayerObjectPos](../functions/SetPlayerObjectPos.md): Set the position of a player object.
- [SetPlayerObjectRot](../functions/SetPlayerObjectRot.md): Set the rotation of a player object.
- [GetPlayerObjectPos](../functions/GetPlayerObjectPos.md): Locate a player object.
- [GetPlayerObjectRot](../functions/GetPlayerObjectRot.md): Check the rotation of a player object.
- [AttachPlayerObjectToPlayer](../functions/AttachPlayerObjectToPlayer.md): Attach a player object to a player.
| openmultiplayer/web/docs/translations/th/scripting/functions/MoveObject.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/MoveObject.md",
"repo_id": "openmultiplayer",
"token_count": 1469
} | 404 |
---
title: PlayerTextDrawAlignment
description: Set the text alignment of a player-textdraw.
tags: ["player", "textdraw", "playertextdraw"]
---
## คำอธิบาย
Set the text alignment of a player-textdraw.
| Name | Description |
| --------- | ------------------------------------------------------------------- |
| playerid | The ID of the player whose player-textdraw to set the alignment of. |
| Text:text | The ID of the player-textdraw to set the alignment of. |
| alignment | 1-left 2-centered 3-right |
## ส่งคืน
Note
For alignment 2 (center) the x and y values of TextSize need to be swapped, see notes at PlayerTextDrawTextSize.
## ตัวอย่าง
```c
new PlayerText:MyTextdraw[MAX_PLAYERS];
public OnPlayerConnect(playerid)
{
MyTextdraw[playerid] = CreatePlayerTextDraw(playerid, 320.0, 425.0, "This is an example textdraw");
PlayerTextDrawAlignment(playerid, MyTextdraw[playerid], 2); // Align the textdraw in the center
return 1;
}
```
## บันทึก
:::tip
For alignment 2 (center) the x and y values of TextSize need to be swapped, see notes at PlayerTextDrawTextSize.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- CreatePlayerTextDraw: Create a player-textdraw.
- PlayerTextDrawDestroy: Destroy a player-textdraw.
- PlayerTextDrawColor: Set the color of the text in a player-textdraw.
- PlayerTextDrawBoxColor: Set the color of a player-textdraw's box.
- PlayerTextDrawBackgroundColor: Set the background color of a player-textdraw.
- PlayerTextDrawFont: Set the font of a player-textdraw.
- PlayerTextDrawLetterSize: Set the letter size of the text in a player-textdraw.
- PlayerTextDrawTextSize: Set the size of a player-textdraw box (or clickable area for PlayerTextDrawSetSelectable).
- PlayerTextDrawSetOutline: Toggle the outline on a player-textdraw.
- PlayerTextDrawSetShadow: Set the shadow on a player-textdraw.
- PlayerTextDrawSetProportional: Scale the text spacing in a player-textdraw to a proportional ratio.
- PlayerTextDrawUseBox: Toggle the box on a player-textdraw.
- PlayerTextDrawSetString: Set the text of a player-textdraw.
- PlayerTextDrawShow: Show a player-textdraw.
- PlayerTextDrawHide: Hide a player-textdraw.
| openmultiplayer/web/docs/translations/th/scripting/functions/PlayerTextDrawAlignment.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/PlayerTextDrawAlignment.md",
"repo_id": "openmultiplayer",
"token_count": 834
} | 405 |
---
title: PlayerTextDrawShow
description: Show a player-textdraw to the player it was created for.
tags: ["player", "textdraw", "playertextdraw"]
---
## คำอธิบาย
Show a player-textdraw to the player it was created for
| Name | Description |
| -------- | --------------------------------------------- |
| playerid | The ID of the player to show the textdraw for |
| text | The ID of the textdraw to show |
## ส่งคืน
This function does not return any specific values.
## บันทึก
:::tip
The player-textdraw is only valid for the player it is created for. This means that you can't show a player-textdraw created for a particular player to another player.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- PlayerTextDrawHide: Hide a player-textdraw.
- CreatePlayerTextDraw: Create a player-textdraw.
- PlayerTextDrawDestroy: Destroy a player-textdraw.
- PlayerTextDrawColor: Set the color of the text in a player-textdraw.
- PlayerTextDrawBoxColor: Set the color of a player-textdraw's box.
- PlayerTextDrawBackgroundColor: Set the background color of a player-textdraw.
- PlayerTextDrawAlignment: Set the alignment of a player-textdraw.
- PlayerTextDrawFont: Set the font of a player-textdraw.
- PlayerTextDrawLetterSize: Set the letter size of the text in a player-textdraw.
- PlayerTextDrawTextSize: Set the size of a player-textdraw box (or clickable area for PlayerTextDrawSetSelectable).
- PlayerTextDrawSetOutline: Toggle the outline on a player-textdraw.
- PlayerTextDrawSetShadow: Set the shadow on a player-textdraw.
- PlayerTextDrawSetProportional: Scale the text spacing in a player-textdraw to a proportional ratio.
- PlayerTextDrawUseBox: Toggle the box on a player-textdraw.
- PlayerTextDrawSetString: Set the text of a player-textdraw.
| openmultiplayer/web/docs/translations/th/scripting/functions/PlayerTextDrawShow.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/PlayerTextDrawShow.md",
"repo_id": "openmultiplayer",
"token_count": 612
} | 406 |
---
title: SendClientMessageToAll
description: Displays a message in chat to all players.
tags: []
---
## คำอธิบาย
Displays a message in chat to all players. This is a multi-player equivalent of SendClientMessage.
| Name | Description |
| --------------- | ------------------------------------------------- |
| color | The color of the message (0xRRGGBBAA Hex format). |
| const message[] | The message to show (max 144 characters). |
## ส่งคืน
This function always returns true (1).
## ตัวอย่าง
```c
public OnPlayerCommandText(playerid, cmdtext[])
{
if (strcmp(cmdtext, "/helloworld", true) == 0)
{
// Send a message to everyone.
SendClientMessageToAll(-1, "Hello!");
return 1;
}
return 0;
}
```
## บันทึก
:::warning
Avoid using format specifiers in your messages without formatting the string that is sent. It will result in crashes otherwise.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- SendClientMessage: Send a message to a certain player.
- SendPlayerMessageToAll: Force a player to send text for all players.
| openmultiplayer/web/docs/translations/th/scripting/functions/SendClientMessageToAll.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/SendClientMessageToAll.md",
"repo_id": "openmultiplayer",
"token_count": 487
} | 407 |
---
title: SetNameTagDrawDistance
description: Set the maximum distance to display the names of players.
tags: []
---
## คำอธิบาย
Set the maximum distance to display the names of players.
| Name | Description |
| -------------- | -------------------- |
| Float:distance | The distance to set. |
## ส่งคืน
This function does not return any specific values.
## ตัวอย่าง
```c
SetNameTagDrawDistance(20.0);
```
## บันทึก
:::tip
Default distance is 70 SA units
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- LimitGlobalChatRadius: Limit the distance between players needed to see their chat.
- ShowNameTags: Set nametags on or off.
- ShowPlayerNameTagForPlayer: Show or hide a nametag for a certain player.
| openmultiplayer/web/docs/translations/th/scripting/functions/SetNameTagDrawDistance.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/SetNameTagDrawDistance.md",
"repo_id": "openmultiplayer",
"token_count": 318
} | 408 |
---
title: SetPlayerChatBubble
description: Creates a chat bubble above a player's name tag.
tags: ["player"]
---
## คำอธิบาย
Creates a chat bubble above a player's name tag.
| Name | Description |
| ------------ | ---------------------------------------------------------------- |
| playerid | The player which should have the chat bubble. |
| text[] | The text to display. |
| color | The text color |
| drawdistance | The distance from where players are able to see the chat bubble. |
| expiretime | The time in miliseconds the bubble should be displayed for. |
## ส่งคืน
This function does not return any specific values.
## ตัวอย่าง
```c
public OnPlayerText(playerid, text[])
{
SetPlayerChatBubble(playerid, text, 0xFF0000FF, 100.0, 10000);
return 1;
}
```
## บันทึก
:::tip
You can't see your own chatbubbles. The same applies to attached 3D text labels.
:::
:::tip
You can use color embedding for multiple colors in the message. Using '-1' as the color will make the text white (for the simple reason that -1, when represented in hexadecimal notation, is 0xFFFFFFFF).
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
| openmultiplayer/web/docs/translations/th/scripting/functions/SetPlayerChatBubble.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/SetPlayerChatBubble.md",
"repo_id": "openmultiplayer",
"token_count": 620
} | 409 |
---
title: SetPlayerObjectRot
description: Set the rotation of an object on the X, Y and Z axis.
tags: ["player"]
---
## คำอธิบาย
Set the rotation of an object on the X, Y and Z axis.
| Name | Description |
| ---------- | --------------------------------------------------- |
| playerid | The ID of the player whose player-object to rotate. |
| objectid | The ID of the player-object to rotate. |
| Float:RotX | The X rotation to set. |
| Float:RotY | The Y rotation to set. |
| Float:RotZ | The Z rotation to set. |
## ส่งคืน
1: The function executed successfully.
0: The function failed to execute.
## ตัวอย่าง
```c
SetPlayerObjectRot(playerid, objectid, RotX, RotY, RotZ);
```
## บันทึก
:::tip
To smoothly rotate an object, see MovePlayerObject.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- CreatePlayerObject: Create an object for only one player.
- DestroyPlayerObject: Destroy a player object.
- IsValidPlayerObject: Checks if a certain player object is vaild.
- MovePlayerObject: Move a player object.
- StopPlayerObject: Stop a player object from moving.
- SetPlayerObjectPos: Set the position of a player object.
- GetPlayerObjectPos: Locate a player object.
- GetPlayerObjectRot: Check the rotation of a player object.
- AttachPlayerObjectToPlayer: Attach a player object to a player.
- CreateObject: Create an object.
- DestroyObject: Destroy an object.
- IsValidObject: Checks if a certain object is vaild.
- MoveObject: Move an object.
- StopObject: Stop an object from moving.
- SetObjectPos: Set the position of an object.
- SetObjectRot: Set the rotation of an object.
- GetObjectPos: Locate an object.
- GetObjectRot: Check the rotation of an object.
- AttachObjectToPlayer: Attach an object to a player.
| openmultiplayer/web/docs/translations/th/scripting/functions/SetPlayerObjectRot.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/SetPlayerObjectRot.md",
"repo_id": "openmultiplayer",
"token_count": 737
} | 410 |
---
title: SetSVarFloat
description: Set a float server variable.
tags: []
---
:::warning
This function was added in SA-MP 0.3.7 R2 and will not work in earlier versions!
:::
## คำอธิบาย
Set a float server variable.
| Name | Description |
| ----------- | -------------------------------- |
| varname[] | The name of the server variable. |
| float_value | The float to be set. |
## ส่งคืน
1: The function executed successfully.
0: The function failed to execute. The variable name is null or over 40 characters.
## ตัวอย่าง
```c
// set "Version"
SetSVarFloat("Version", 0.37);
// will print version that server has
printf("Version: %f", GetSVarFloat("Version"));
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- SetSVarInt: Set an integer for a server variable.
- GetSVarInt: Get a player server as an integer.
- SetSVarString: Set a string for a server variable.
- GetSVarString: Get the previously set string from a server variable.
- GetSVarFloat: Get the previously set float from a server variable.
- DeleteSVar: Delete a server variable.
| openmultiplayer/web/docs/translations/th/scripting/functions/SetSVarFloat.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/SetSVarFloat.md",
"repo_id": "openmultiplayer",
"token_count": 429
} | 411 |
---
title: SetVehicleVelocity
description: Sets the X, Y and Z velocity of a vehicle.
tags: ["vehicle"]
---
## คำอธิบาย
Sets the X, Y and Z velocity of a vehicle.
| Name | Description |
| --------- | --------------------------------------------- |
| vehicleid | The ID of the vehicle to set the velocity of. |
| Float:X | The velocity in the X direction. |
| Float:Y | The velocity in the Y direction . |
| Float:Z | The velocity in the Z direction. |
## ส่งคืน
1: The function executed successfully.
0: The function failed to execute. The vehicle does not exist.
## ตัวอย่าง
```c
public OnPlayerCommandText(playerid, cmdtext[])
{
if (!strcmp("/jump", cmdtext))
{
if (IsPlayerInAnyVehicle(playerid))
SetVehicleVelocity(GetPlayerVehicleID(playerid), 0.0, 0.0, 0.2);
return 1;
}
}
```
## บันทึก
:::warning
This function has no affect on un-occupied vehicles and does not affect trains.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
| openmultiplayer/web/docs/translations/th/scripting/functions/SetVehicleVelocity.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/SetVehicleVelocity.md",
"repo_id": "openmultiplayer",
"token_count": 492
} | 412 |
---
title: StopRecordingPlayerData
description: Stops all the recordings that had been started with StartRecordingPlayerData for a specific player.
tags: ["player"]
---
## คำอธิบาย
Stops all the recordings that had been started with StartRecordingPlayerData for a specific player.
| Name | Description |
| -------- | ---------------------------------------------- |
| playerid | The player you want to stop the recordings of. |
## ส่งคืน
This function does not return any specific values.
## ตัวอย่าง
```c
public OnPlayerCommandText(playerid, cmdtext[])
{
if (!strcmp("/stoprecording", cmdtext))
{
StopRecordingPlayerData(playerid);
SendClientMessage(playerid, 0xFFFFFFFF, "Your recorded file has been saved to the scriptfiles folder!");
return 1;
}
}
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [StartRecordingPlayerData](../functions/StartRecordingPlayerData.md): Start recording player data.
| openmultiplayer/web/docs/translations/th/scripting/functions/StopRecordingPlayerData.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/StopRecordingPlayerData.md",
"repo_id": "openmultiplayer",
"token_count": 387
} | 413 |
---
title: TextDrawSetSelectable
description: Sets whether a textdraw can be selected (clicked on) or not.
tags: ["textdraw"]
---
## คำอธิบาย
Sets whether a textdraw can be selected (clicked on) or not
| Name | Description |
|----------|---------------------------------------------------------------------|
| text | The ID of the textdraw to make selectable. |
| bool:set | 'true' to make it selectable, or 'false' to make it not selectable. |
## ส่งคืน
This function does not return any specific values.
## ตัวอย่าง
```c
public OnPlayerCommandText(playerid, cmdtext[])
{
if (!strcmp(cmdtext, "/selectd", true))
{
for (new i = 0; i < MAX_TEXT_DRAWS; i++)
{
TextDrawSetSelectable(Text:i, true);
}
SendClientMessage(playerid, 0xFFFFFFAA, "SERVER: All textdraws can be selected now!");
return 1;
}
return 0;
}
```
## บันทึก
:::tip
Use [TextDrawTextSize](TextDrawTextSize) to define the clickable area.
:::
:::warning
TextDrawSetSelectable must be used BEFORE the textdraw is shown to players for it to be selectable.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [SelectTextDraw](../functions/SelectTextDraw.md): Enables the mouse, so the player can select a textdraw
- [CancelSelectTextDraw](../functions/CancelSelectTextDraw.md): Cancel textdraw selection with the mouse
## Related Callbacks
- [OnPlayerClickTextDraw](../callbacks/OnPlayerClickTextDraw.md): Called when a player clicks on a textdraw.
| openmultiplayer/web/docs/translations/th/scripting/functions/TextDrawSetSelectable.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/TextDrawSetSelectable.md",
"repo_id": "openmultiplayer",
"token_count": 676
} | 414 |
---
title: VectorSize
description: Returns the norm (length) of the provided vector.
tags: []
---
## คำอธิบาย
Returns the norm (length) of the provided vector.
| Name | Description |
| ------- | ------------------------------------- |
| Float:X | The vector's magnitude on the X axis. |
| Float:Y | The vector's magnitude on the Y axis. |
| Float:Z | The vector's magnitude on the Z axis. |
## ส่งคืน
The norm (length) of the provided vector as a float.
## ตัวอย่าง
```c
stock Float:GetDistanceBetweenPoints(Float:x1, Float:y1, Float:z1, Float:x2, Float:y2, Float:z2)
{
return VectorSize(x1-x2, y1-y2, z1-z2);
}
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [GetPlayerDistanceFromPoint](../functions/GetPlayerDistanceFromPoint.md): Get the distance between a player and a point.
- [GetVehicleDistanceFromPoint](../functions/GetVehicleDistanceFromPoint.md): Get the distance between a vehicle and a point.
- [floatsqroot](../functions/floatsqroot.md): Calculate the square root of a floating point value.
| openmultiplayer/web/docs/translations/th/scripting/functions/VectorSize.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/VectorSize.md",
"repo_id": "openmultiplayer",
"token_count": 428
} | 415 |
---
title: float
description: Converts an integer into a float.
tags: []
---
:::warning
This function starts with lowercase letter.
:::
## คำอธิบาย
Converts an integer into a float.
| Name | Description |
| ----- | ----------------------------------- |
| value | Integer value to convert to a float |
## ส่งคืน
The given integer as a float
## ตัวอย่าง
```c
new Float:FloatValue;
new Value = 52;
FloatValue = float(Value); // Converts Value(52) into a float and stores it in 'FloatValue' (52.0)
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [floatround](../functions/floatround): Convert a float to an integer (rounding).
- [floatstr](../functions/floatstr): Convert an string to a float.
| openmultiplayer/web/docs/translations/th/scripting/functions/float.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/float.md",
"repo_id": "openmultiplayer",
"token_count": 319
} | 416 |
---
title: fmatch
description: Find a filename matching a pattern.
tags: []
---
:::warning
This function starts with lowercase letter.
:::
## คำอธิบาย
Find a filename matching a pattern.
| Name | Description |
| ------------- | -------------------------------------------------------------- |
| name | The string to hold the result in, returned as a packed string. |
| const pattern | The pattern that should be matched. May contain wildcards. |
| index | The number of the file, in case there are multiple matches. |
| size | The maximum size of parameter name |
## ส่งคืน
true on success, false on failure
## บันทึก
:::warning
This function does not work in the current SA:MP version!
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [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/fmatch.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/fmatch.md",
"repo_id": "openmultiplayer",
"token_count": 672
} | 417 |
---
title: strins
description: Insert a string into another string.
tags: []
---
:::warning
This function starts with lowercase letter.
:::
## คำอธิบาย
Insert a string into another string.
| Name | Description |
| ----------------------- | ------------------------------------------ |
| string[] | The string you want to insert substr in. |
| const substr[] | The string you want to insert into string. |
| pos | The position to start inserting. |
| maxlength=sizeof string | The maximum size to insert. |
## ส่งคืน
This function does not return any specific values.
## ตัวอย่าง
```c
// Add an [AFK] tag to the start of players' names
new playerName[MAX_PLAYER_NAME+1];
GetPlayerName(playerid, playerName, MAX_PLAYER_NAME);
strins(playerName, "[AFK]", 0);
SetPlayerName(playerid, playerName);
// WARNING: Players with names that are 20+ characters long can not have an [AFK] tag, as that would make their name 25 characters long and the limit is 24.
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- strcmp: Compare two strings to check if they are the same.
- strfind: Search for a string in another string.
- strtok: Get the next 'token' (word/parameter) in a string.
- strdel: Delete part of a string.
- strlen: Get the length of a string.
- strmid: Extract part of a string into another string.
- strpack: Pack a string into a destination string.
- strval: Convert a string into an integer.
- strcat: Concatenate two strings into a destination reference.
| openmultiplayer/web/docs/translations/th/scripting/functions/strins.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/strins.md",
"repo_id": "openmultiplayer",
"token_count": 616
} | 418 |
---
title: Material Text Alignments
description: A list of Material Text Alignments
---
## Text alignments
| ID | Value |
| --------------------------------- | ----- |
| OBJECT_MATERIAL_TEXT_ALIGN_LEFT | 0 |
| OBJECT_MATERIAL_TEXT_ALIGN_CENTER | 1 |
| OBJECT_MATERIAL_TEXT_ALIGN_RIGHT | 2 |
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [SetObjectMaterialText](/docs/scripting/functions/SetObjectMaterialText): Replace the texture of an object with text.
| openmultiplayer/web/docs/translations/th/scripting/resources/materialtextalignment.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/resources/materialtextalignment.md",
"repo_id": "openmultiplayer",
"token_count": 232
} | 419 |
---
title: OnClientMessage
description: Bu callback, NPC bir ClientMessage algılandığında tetiklenir.
tags: []
---
## Açıklama
Bu callback, NPC bir ClientMessage algılandığında tetiklenir. Bu, örneğin bir SendClientMessageToAll fonksiyonu gönderdiğinizde oyuncuya SendClientMessage fonksiyonu yansıdığı anda tetiklenecektir. Birisi chat'e mesaj gönderdiği zaman tetiklenmeyecek fakat bunu yapmak isterseniz bkz. NPC:OnPlayerText
| Name | Description |
| ------ | ------------------------- |
| color | ClientMessage rengi. |
| text[] | Gönderilen mesaj içeriği. |
## Çalışınca Vereceği Sonuçlar
Bu callback herhangi bir sonuç vermez.
## Örnekler
```c
public OnClientMessage(color, text[])
{
if(strfind(text,"Banka Parası: $0") != -1) SendChat("Ben fikirim. :(");
}
```
## Bağlantılı Fonksiyonlar
| openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnClientMessage.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnClientMessage.md",
"repo_id": "openmultiplayer",
"token_count": 354
} | 420 |
---
title: OnPlayerDisconnect
description: Bu callback oyuncu sunucudan ayrıldığında çağrılır.
tags: ["player"]
---
## Açıklama
Bu callback oyuncu sunucudan ayrıldığında çağrılır.
| İsim | Açıklama |
| -------- | ---------------------------------- |
| playerid | Sunucudan ayrılan oyuncunun id'si. |
| reason | Sunucudan ayrılma sebebi. |
## Çalışınca Vereceği Sonuçlar
0 - Diğer filterscriptlerde çağrılmasını engeller.
1 - Diğer filterscriptlerde aranması için pas geçirilir.
Her zaman öncelikle filterscriptlerde çağrılır.
## Örnekler
```c
public OnPlayerDisconnect(playerid, reason)
{
new
szString[64],
playerName[MAX_PLAYER_NAME];
GetPlayerName(playerid, playerName, MAX_PLAYER_NAME);
new szDisconnectReason[3][] =
{
"Zaman Aşımı",
"Kendi İsteğiyle",
"Kick/Ban"
};
format(szString, sizeof szString, "%s sunucudan ayrıldı. (%s).", playerName, szDisconnectReason[reason]);
SendClientMessageToAll(0xC4C4C4FF, szString);
return 1;
}
```
## Notlar
:::tip
Bu callback içerisinde bazı fonksiyonlar doğru bilgiler vermez (GetPlayerIp ve GetPlayerPos gibi)
:::
## Bağlı Fonksiyonlar
| openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnPlayerDisconnect.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnPlayerDisconnect.md",
"repo_id": "openmultiplayer",
"token_count": 583
} | 421 |
---
title: OnPlayerPickUpPickup
description: Fonksiyon, oyuncu CreatePickup ile oluşturulan bir işaretin (pickup) üstüne geldiğinde çağrılır.
tags: ["player"]
---
## Açıklama
Fonksiyon, oyuncu CreatePickup ile oluşturulan bir işaretin (pickup) üstüne geldiğinde çağrılır.
| Parametre | Açıklama |
| --------- | -------------------------------------------------- |
| playerid | İşaretin üstüne gelen oyuncunun ID'si. |
| pickupid | CreatePickup tarafından döndürülen işaretin ID'si. |
## Çalışınca Vereceği Sonuçlar
Oyun modunda her zaman ilk olarak çağrılır.
## Örnekler
```c
new pickup_Cash;
new pickup_Health;
public OnGameModeInit()
{
pickup_Cash = CreatePickup(1274, 2, 0.0, 0.0, 9.0);
pickup_Health = CreatePickup(1240, 2, 0.0, 0.0, 9.0);
return 1;
}
public OnPlayerPickUpPickup(playerid, pickupid)
{
if (pickupid == pickup_Cash)
{
GivePlayerMoney(playerid, 1000);
}
else if (pickupid == pickup_Health)
{
SetPlayerHealth(playerid, 100.0);
}
return 1;
}
```
## Bağlantılı Fonksiyonlar
- [CreatePickup](../functions/CreatePickup): İşaret (pickup) oluşturma.
- [DestroyPickup](../functions/DestroyPickup): İşaret (pickup) silme.
| openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnPlayerPickUpPickup.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnPlayerPickUpPickup.md",
"repo_id": "openmultiplayer",
"token_count": 598
} | 422 |
---
title: OnTrailerUpdate
description: Bu fonksiyon, oyuncu aracına römork bağladığında çağrılır.
tags: []
---
## Açıklama
Bu fonksiyon, oyuncu aracına römork bağladığında çağrılır.
| Parametre | Açıklama |
| --------- | ----------------------------------------------- |
| playerid | Römork güncellemesi gönderen oyuncunun ID'si. |
| vehicleid | Güncellemesi gönderilen römork'un ID'si. (araç) |
## Çalışınca Vereceği Sonuçlar
0 - Herhangi bir römork güncellemelerinin diğer oyunculara gönderilmesini iptal eder. Güncelleme, güncelleyen oyuncuya hala gönderilir.
1 - Römork güncellemesini normal şekilde işler ve tüm oyuncular arasında senkronize eder.
Filterscript komutlarında her zaman ilk olarak çağrılır.
## Örnekler
```c
public OnTrailerUpdate(playerid, vehicleid)
{
DetachTrailerFromVehicle(GetPlayerVehicleID(playerid));
return 0;
}
```
## Notlar
:::warning
Bu fonksiyon, her römork için saniyede çok sık çağrılır. Bu çağrıda yoğun hesaplamalar veya yoğun dosya yazma / okuma işlemleri yapmaktan kaçınmalısınız.
:::
## Bağlantılı Fonksiyonlar
- [GetVehicleTrailer](../functions/GetVehicleTrailer): Aracın hangi römorku çektiğini kontrol etme.
- [IsTrailerAttachedToVehicle](../functions/IsTrailerAttachedToVehicle): Araca römork bağlanıp bağlanmadığını kontrol edin.
- [AttachTrailerToVehicle](../functions/AttachTrailerToVehicle): Araca bir römork takma.
- [DetachTrailerFromVehicle](../functions/DetachTrailerFromVehicle): Araca bağlanan römorku çıkarma.
| openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnTrailerUpdate.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnTrailerUpdate.md",
"repo_id": "openmultiplayer",
"token_count": 722
} | 423 |
---
title: AddSimpleModel
description: İndirmek için yeni bir özel basit nesne modeli ekler.
tags: []
---
:::warning
Bu işlev SA-MP 0.3.DL R1'e eklenmiştir ve önceki sürümlerde çalışmayacaktır!
:::
## Açıklama
İndirmek için yeni bir özel basit nesne modeli ekler. Model dosyaları, oynatıcının belgelerinde\GTA San Andreas Kullanıcı dosyaları\SAMP\cache'te, CRC biçiminde dosya adında Sunucu IP'si ve Bağlantı Noktası klasörü altında saklanır.
| İsim | Açıklama |
| ------------ | ----------------------------------------------------------------------------------------------------------------------------- |
| virtualworld | Modeli adresinde kullanılabilir hale getirmek için sanal dünya kimliği. Tüm dünyalar için -1 kullanın. |
| baseid | Kullanılacak temel nesne model kimliği (indirme başarısız olduğunda kullanılacak orijinal nesne). |
| newid | Yeni obje model kimliği daha sonra CreateObject veya CreatePlayerObject ile -1000 ile -30000 arasında (29000 yuva) sıralandı. |
| dffname | Modellerde bulunan .dff modeli çarpışma dosyasının adı varsayılan olarak sunucu klasörü (çalışma yolu ayarı) |
| txdname | Modeller sunucu klasöründe varsayılan olarak bulunan .txd model kaplama dosyasının adı (çalışma yolu ayarı). |
## Çalışınca Vereceği Sonuçlar
1: İşlev başarıyla yürütüldü.
0: İşlev yürütülemedi.
## Örnekler
```c
public OnGameModeInit()
{
AddSimpleModel(-1, 19379, -2000, "wallzzz.dff", "wallzzz.txd");
return 1;
}
```
```c
AddSimpleModel(-1, 19379, -2000, "wallzzz.dff", "wallzzz.txd");
```
## Notlar
:::tip
Sanal dünya ayarlandığında bunun çalışması için öncelikle sunucu ayarlarında userartwork etkinleştirilmesi gerekir; oynatıcı belirli bir dünyaya girdiğinde modeller indirilir.
:::
:::warning
Şu anda bu fonksiyonu ne zaman arayabileceğiniz konusunda herhangi bir kısıtlama yoktur, ancak OnFilterScriptInit/OnGameModeInit içinde aramamanız durumunda, halihazırda sunucuda bulunan bazı oyuncuların modelleri indirmemiş olma riskini çalıştırdığınızı unutmayın.
:::
## Bağlantılı Fonksiyonlar
- [OnPlayerFinishedDownloading](../callbacks/OnPlayerFinishedDownloading.md): Bir oyuncu özel modelleri indirmeyi bitirdiğinde çağrılır.
| openmultiplayer/web/docs/translations/tr/scripting/functions/AddSimpleModel.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/tr/scripting/functions/AddSimpleModel.md",
"repo_id": "openmultiplayer",
"token_count": 1215
} | 424 |
---
title: AttachObjectToPlayer
description: Objeyi oyuncuya bağlama.
tags: ["player"]
---
## Açıklama
Bir objeyi oyuncuya bağlar.
| Parametre | Açıklama |
| ------------- | ------------------------------------------------------------------ |
| objectid | Bağlanılacak objenin ID'si. |
| playerid | Bağlanacak oyuncunun ID'si. |
| Float:OffsetX | Oyuncunun obje ile arasındaki X değeri. |
| Float:OffsetY | Oyuncunun obje ile arasındaki Y değeri. |
| Float:OffsetZ | Oyuncunun obje ile arasındaki Z değeri. |
| Float:RotX | Oyuncunun obje ile arasındaki X açısının değeri. |
| Float:RotY | Oyuncunun obje ile arasındaki Y açısının değeri. |
| Float:RotZ | Oyuncunun obje ile arasındaki Z açısının değeri. |
## Çalışınca Vereceği Sonuçlar
Bu fonksiyon her zaman 0 döndürür.
## Örnekler
```c
new gMyObject;
gMyObject = CreateObject(19341, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0); // Objeyi oluşturduk
AttachObjectToPlayer(gMyObject, playerid, 1.5, 0.5, 0.0, 0.0, 1.5, 2); // Objeyi oyuncuya bağladık.
```
## Bağlantılı Fonksiyonlar
- [AttachObjectToVehicle](AttachObjectToVehicle): Bir objeyi araca bağlama.
- [AttachObjectToObject](AttachObjectToObject): Bir objeyi bir diğer objeye bağlama.
- [AttachPlayerObjectToPlayer](AttachPlayerObjectToPlayer): Bir oyuncu objesini bir objeye bağlama.
- [CreateObject](CreateObject): Obje oluşturma.
- [DestroyObject](DestroyObject): Obje silme.
- [IsValidObject](IsValidObject): Objenin oluşturulup oluşturulmadığını kontrol etme.
- [MoveObject](MoveObject): Objeyi hareket ettirme.
- [StopObject](StopObject): Hareket eden bir objeyi durdurma.
- [SetObjectPos](SetObjectPos): Objenin pozisyonunu değiştirme.
- [SetObjectRot](SetObjectRot): Objenin rotasyonunu değiştirme.
- [GetObjectPos](GetObjectPos): Objenin pozisyonunu kontrol etme.
- [GetObjectRot](GetObjectRot): Objenin rotasyonunu kontrol etme.
- [CreatePlayerObject](CreatePlayerObject): Oyuncu objesi oluşturma.
- [DestroyPlayerObject](DestroyPlayerObject): Oyuncu objesini kaldırma.
- [IsValidPlayerObject](IsValidPlayerObject): Oyuncu objesinin oluşturulup oluşturulmadığını kontrol etme.
- [MovePlayerObject](MovePlayerObject): Oyuncu objesini hareket ettirme.
- [StopPlayerObject](StopPlayerObject): Hareket eden oyuncu objesini durdurma.
- [SetPlayerObjectPos](SetPlayerObjectPos): Oyuncu objesinin pozisyonunu değiştirme.
- [SetPlayerObjectRot](SetPlayerObjectRot): Oyuncu objesinin rotasyonunu değiştirme.
- [GetPlayerObjectPos](GetPlayerObjectPos): Oyuncu objesinin pozisyonunu kontrol etme.
- [GetPlayerObjectRot](GetPlayerObjectRot): Oyuncu objesinin rotasyonunu kontrol etme.
| openmultiplayer/web/docs/translations/tr/scripting/functions/AttachObjectToPlayer.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/tr/scripting/functions/AttachObjectToPlayer.md",
"repo_id": "openmultiplayer",
"token_count": 1329
} | 425 |
---
title: CreateExplosionForPlayer
description: Tek bir oyuncunun gördüğü patlama oluşturma.
tags: ["player"]
---
## Açıklama
Tek bir oyuncunun gördüğü patlama oluşturma. Bu, patlamaları diğer oyunculardan izole etmek veya yalnızca belirli sanal dünyalarda görünmelerini sağlamak için kullanılabilir.
| Parametre | Açıklama |
| ------------ | ------------------------------------------------- |
| playerid | Patlamayı görecek oyuncu ID'si. |
| Float:X | Patlamanın oluşacağı X koordinatı. |
| Float:Y | Patlamanın oluşacağı Y koordinatı. |
| Float:Z | Patlamanın oluşacağı Z koordinatı. |
| type | Oluşacak patlamanın türü. |
| Float:Radius | Oluşacak patlamanın yarıçapı. |
## Çalışınca Vereceği Sonuçlar
Fonksiyon, oyuncu ID'si, patlama türü veya patlamanın yarıçapı geçersiz olsa bile her zaman 1 olarak döndürülür.
## Örnekler
```c
if (strcmp(cmdtext, "/burnme", true) == 0)
{
new Float: playerPos[3];
GetPlayerPos(playerid, playerPos[0], playerPos[1], playerPos[2]);
CreateExplosionForPlayer(playerid, playerPos[0], playerPos[1], playerPos[2], 1, 10.0);
return 1;
}
```
## Notlar
:::tip
Bir oyuncu maksimum 10 tane patlama görebilir.
:::
## Bağlantılı Fonksiyonlar
- [CreateExplosion](CreateExplosion): Patlama oluşturma.
| openmultiplayer/web/docs/translations/tr/scripting/functions/CreateExplosionForPlayer.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/tr/scripting/functions/CreateExplosionForPlayer.md",
"repo_id": "openmultiplayer",
"token_count": 744
} | 426 |
---
title: "Anahtar Kelimeler: Direktifler"
---
Direktifler, derleyiciye kaynak kodunuzu nasıl yorumlaması gerektiğini kontrol etmek için iletilen talimatlardır.
## `#assert`
Bu, sabit ifadenin doğru olup olmadığını kontrol eder ve doğru değilse derlemeyi duraklatır.
```c
#define MOO 10
#assert MOO > 5
```
Bu sorunsuz derlenir.
```c
#define MOO 1
#assert MOO > 5
```
Bu derlenmez ve bir ölümcül hata verir. Bu, aşağıdakiyle benzerdir:
```c
#define MOO 1
#if MOO <= 5
#error MOO check failed
#endif
```
Ancak, assert, bir hata mesajı olarak:
```
Assertation failed: 1 > 5
```
verirken, ikinci örnekte bir hata mesajı şöyle olacaktır:
```
User error: Moo check failed
```
Hangisi daha faydalı olabilir veya olmayabilir.
## `#define`
`#define`, bir metin değiştirme direktifidir; define'in ilk sembolü her nerede bulunursa, geri kalanı yerine konacaktır.
```c
#define MOO 7
printf("%d", MOO);
```
Aşağıdaki gibi değiştirilecektir:
```c
printf("%d", 7);
```
Bu nedenle, tüm tanımlamaların dekompilasyonda kaybolduğu bir durumdur (tüm direktifler önceden işlenir). Define'lerin sayıları içermesi gerekmez:
```c
#define PL new i = 0; i < MAX_PLAYERS; i++) if (IsPlayerConnected(i)
for(PL) printf("%d connected", i);
```
Bu, hepimizin (nefret ettiğimiz) oyuncu döngüsüne derlenir. Burada parantezlerin nasıl kullanıldığına dikkat edin, bunlar hem for'dan hem de define makrosundan (değiştirme) gelir.
Define'lerin çok satırlı olabileceğini, yeni satıra kaçarak yapabileceğinizi bilmek ilginçtir. Genellikle yeni satır tanımı sonlandırır, ancak aşağıdaki geçerlidir:
```c
#define PL \
new i = 0; i < MAX_PLAYERS; i++) \
if (IsPlayerConnected(i)
printf("%d", MOO(6));
```
Bu, 42 çıktısını verecektir (rastgele seçilmedi). Define içindeki aşırı parantezlere dikkat edin. Define'lar düz metin değiştirmeleri olduğundan, bu, şöyle derlenir:
```c
printf("%d", ((6) * 7));
```
Bu durumda her şey yolunda, ancak bu örneği ele alalım:
```c
printf("%d", MOO(5 + 6));
```
Bunu 77 ((5 + 6) \* 7) çıktısına derlenmesini beklersiniz ve parantezlerle birlikte bu şekilde derlenir, ancak parantez olmadan şu şekildedir:
```c
#define MOO(%0) \
%0 * 7
printf("%d", MOO(5 + 6));
```
Bu, şuna dönüşür:
```c
printf("%d", MOO(5 + 6 * 7));
```
Operasyonların sırasına bağlı olarak, bunun (5 + (6 \* 7)) olarak derlendiği ve çok yanlış olduğu bir durumda 47'ye dönüşür. Parametrelerle ilgili ilginç bir gerçek şudur ki, çok fazla varsa, en sondaki tüm fazla olanlardır. Bu nedenle:
```c
#define PP(%0,%1) \
printf(%0, %1)
PP(%s %s %s, "hi", "hello", "hi");
```
Gerçekte şunu yazdırır:
```
hi hello hi
```
Çünkü `%1` "hi", "hello", "hi" içerir. Ayrıca, bir kelimeyi dizeye çevirmek için bir metni `#` kullanarak dönüştürebileceğinizi fark etmiş olabilirsiniz. Bu, yalnızca SA-MP'ye özgü bir özelliktir ve kullanışlı olabilir. Bu, bir değişkenle kullanıldığında kullanılabilir.
## `#else`
`#else`, #if'in normal if'e olan karşılığıdır.
## `#elseif`
`#elseif`, #if için else if'e benzer.
```c
#define MOO 10
#if MOO == 9
printf("if");
#elseif MOO == 8
printf("else if");
#else
printf("else");
#endif
```
## `#emit`
Bu direktif, PAWN için bir iç derleyici gibidir. AMX'ye özgü komutları doğrudan kodunuza yerleştirmek için kullanılabilir. Tek bir argüman kullanmasına izin verir. Söntax: `#emit <opcode> <argument>`. `<argument>` bir rasyonel sayı, tam sayı veya (yerel veya global) sembol (değişkenler, işlevler ve etiketler) olabilir. OPCODE'ların listesi ve anlamları Pawn Toolkit ver. 3664'te bulunabilir.
## `#endif`
`#endif`, bir #if için kapanış süslü parantez gibidir. #if süslü parantez kullanmaz, her şey karşılık gelen #endif'e kadar koşullu olarak eklenir.
## `#endinput, #endscript`
Bu, bir dosyanın tek bir dosyanın dahil edilmesini durdurur.
## `#error`
Bu, derleyiciyi anında duraklatır ve özel bir hata mesajı verir. Bir örnek için #assert'e bakın.
## `#if`
`#if`, derleyici için if'in kod için olanıdır. İşte aşağıdaki kod örneği:
```c
#define LIMIT
10
if (LIMIT < 10)
{
printf("Limit too low");
}
```
Bu, şu şekilde derlenir:
```c
if (10 < 10)
{
printf("Limit too low");
}
```
Bu, açıkça hiçbir zaman doğru olmayacak ve derleyici bunu biliyor - bu nedenle "sabit ifade" uyarısı verir. Soru şu, asla doğru olmayacaksa neden hiç dahil ediyoruz? Kodu kaldırabilirdiniz, ancak LIMIT'i değiştirseler ve yeniden derleseler bile hiçbir kontrol olmayacaktır. İşte #if bunun için kullanılır. Normal bir if, ifadenin sabit olması durumunda bir uyarı verir, ancak #if ifadeleri SABİT olmalıdır. Bu nedenle:
```c
#define LIMIT 10
#if LIMIT < 10
#error Limit too low
#endif
```
Bu, sınırın çok küçük olup olmadığını derlediğinizde kontrol eder ve öyleyse bir derleme zamanı hatası verir, böylece modu kontrol edip kontrol etmediklerini kontrol etmek zorunda kalmazsınız. Ayrıca, gereksiz kod üretilmez. Parantez olmadan kullanabilirsiniz, gerekirse bunları kullanabilirsiniz ve daha karmaşık ifadelerde ihtiyaç duyulabilirler, ancak gerekli değildir.
İşte başka bir örnek:
```c
#define LIMIT 10
#if LIMIT < 10
printf("Limit less than 10");
#else
printf("Limit equal to or above 10");
#endif
```
Tekrar sabit bir kontrol, bir uyarı verecek olsa da, iki printf derlenir ve sadece birinin çalışacağını BİLİYORUZ. #if bu durumda şu şekildedir:
```c
#define LIMIT 10
#if LIMIT < 10
printf("Limit less than 10");
#else
printf("Limit equal to or above 10");
#endif
```
Bu şekilde yalnızca gerekli olan printf derlenir ve diğeri, değişiklik yaparlarsa ve tekrar derlerlerse kodlarında bulunur, ancak gerekli değildir. Bu şekilde ayrıca anlamsız if her seferinde kodunuz çalıştırılmaz, her zaman iyidir.
## `#include`
Bu, belirtilen bir dosyanın tüm kodunu alır ve bunu kodunuzun belirli bir noktasına ekler. İki tür include vardır: göreceli ve sistem (bu terimleri uydurdum, daha iyi olanlarınız varsa lütfen söyleyin). Göreceli olanlar çift tırnak içinde dosya adını kullanır ve bu dosya, dahil edilen dosyanın bulunduğu mevcut dizine göre yerleştirilir, bu nedenle:
```c
#include "me.pwn"
```
Belirtilen dosya olan "me.pwn" dosyasını, bu dosyayı içeren dosyanın aynı dizininden dahil eder. Diğer tür, sistem, dosyayı aşağıdaki dizindeki "include" dizininden alır ve bu dizin ya Pawn derleyicisinin bulunduğu dizinde ya da bu dizinin üst dizinindedir (yollar: "include", "../include"):
```c
#include "<me>"
```
Bu, pawno kullanıyorsanız pawno/include dizininden "me.inc" dosyasını dahil eder (uzantı, .p (pwn olmayan) veya .inc olmadığı sürece belirtilebilir). Her iki tür de dizinleri içerebilir:
```c
#include "folder/me.pwn"
```
```c
#include <folder/me>
```
Her ikisi de, ilgili varsayılan dizinlerinden bir dizin aşağıdaki bir dosyayı içerir. Dosya mevcut değilse derleme başarısız olur.
## `#pragma`
Bu, en karmaşık direktiflerden biridir. Kodunuzun nasıl çalıştığını kontrol etmek için bir dizi seçeneğe sahiptir. Bir ayar örneği şu şekildedir:
```c
#pragma ctrlchar '$'
```
Bu, kaçış karakterini \ yerine $ olarak değiştirir, bu nedenle bir yeni satır, "\r\n" yerine "$r\$n" olacaktır. Birçok seçenek gömülü sistemler için AMX derlemesini kontrol etmek ve bu sisteme özgü sınırlamalar getirmek üzere tasarlanmıştır, ancak tümü pawn-lang.pdf'de listelenmiştir ve SA: MP ile ilgili olanları burada seçilmiştir:
| Adı | Değerler | Açıklama |
| ---------- | ------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| codepage | ad/değer | Dizeler için kullanılacak Unicode kod sayfasını ayarlar. |
| compress | 1/0 | SA-MP'de desteklenmiyor - kullanmaya çalışmayın. |
| deprecated | sembol | Kullanıcıların kullanılabilir daha iyi bir sürüm olduğunu bildirmek için kullanılan sembolü belirten bir uyarı oluşturur. |
| dynamic | değer (genellikle bir 2 kuvveti) | Yığın ve heap'e atanmış bellek boyutunu (hücre cinsinden) ayarlar. Derlemeden sonra aşırı bellek kullanım uyarısı alıyorsanız gereklidir. (Derleyici telif hakkı satırından sonraki garip bir tablo) |
| library | dll adı | SA-MP'de yaygın olarak yanlış kullanılır. Bu, dosyadaki native işlevleri almak için belirtilen dll'yi tanımlar. Bir dosyayı KÜTÜPHANE olarak tanımlamaz. |
| pack | 1/0 | !"" ve ""'nin anlamlarını takas eder. Paketlenmiş dize hakkında daha fazla bilgi için pawn-lang.pdf'ye bakın. |
| tabsize | değer | Bu, uyarıları engellemek için bir sekme boyutunu ayarlamak için kullanılmalıdır; uyarılar, boşlukların ve sekme karakterlerinin değiştirilebilir olarak kullanılması nedeniyle yanlıştır. SA: MP'de bu, pawno'da bir sekmenin boyutu olduğundan 4'e ayarlanmıştır. Bu, tüm girinti uyarılarını bastırmak için 0'a ayarlanabilir, ancak bu, tamamen okunaksız bir kodu mümkün kılar ve şiddetle tavsiye edilmez. |
| unused | sembol | Kullanılmayan bir sembol uyarısını engellemek için deprecated gibi sembolün üzerine bu eklenir. Genellikle bunu yapmanın tercih edilen yolu, sembolü koruyarak geriye dönük uyumluluğu korumak için stok kullanmaktır, ancak bu her zaman uygulanabilir değildir (örneğin, işlev parametreleri derlenemez). |
### Deprecated
```c
new
gOldVariable = 5;
#pragma deprecated gOldVariable
main() {printf("%d", gOldVariable);}
```
Bu, gOldVariable'ın artık kullanılmaması gerektiği bir uyarı verecektir. Bu genellikle geriye dönük uyumluluğu korumak için stok kullanmak için kullanışlıdır.
### `#tryinclude`
Bu, #include gibi, ancak dosya mevcut değilse derleme başarısız olmaz. Bu, yalnızca komut dosyanızın doğru eklentiyi yüklediğinden emin olmak için kullanışlıdır (veya en azından eklenti dahilini):
**myinc.inc**
```c
#if defined _MY_INC_INC
#endinput
#endif
#define _MY_INC_INC
stock MyIncFunc() {printf("Hello");}
```
**Oyunmodu:**
```c
#tryinclude <myinc>
main()
{
#if defined _MY_INC_INC
MyIncFunc();
#endif
}
```
Bu, dosya bulunursa ve derlenirse MyIncFunc'i çağıracaktır. Bu, özellikle IRC eklentileri gibi şeyler için kullanışlıdır, eklentinin doğru olduğunu kontrol etmek için.
### `#undef`
Önceden tanımlanmış bir makro veya sabit sembolü kaldırır.
```c
#define MOO 10
printf("%d", MOO);
#undef MOO
printf("%d", MOO);
```
Bu, ikinci printf'e ulaşıldığında MOO artık var olmadığından derlenmez.
```c
enum {
e_example = 300
};
printf("%d", e_example);
#undef e_example
printf("%d", e_example); // ölümcül hata
```
| openmultiplayer/web/docs/translations/tr/scripting/language/Directives.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/tr/scripting/language/Directives.md",
"repo_id": "openmultiplayer",
"token_count": 7041
} | 427 |
---
title: "Gecikme Telafisi"
description: Gecikme telafisi açıklaması.
---
SA-MP sunucularında 0.3z'den bu yana ateş edilen mermiler için gecikme telafisi varsayılan olarak etkindir. [server.cfg](server.cfg) dosyasında `lagcompmode` sunucu değişkenini kullanarak etkinleştirilebilir veya devre dışı bırakılabilir. Bu değişkeni 0 olarak ayarlamak, gecikme telafisini tamamen devre dışı bırakacak ve oyuncuların atışlarını hedeflerinin önünden yapmalarını gerektirecektir.
Gecikme Telafisi devre dışı bırakıldığında [OnPlayerWeaponShot](../scripting/callbacks/OnPlayerWeaponShot) çağrılmayacaktır.
Bu değişken yalnızca [server.cfg](server.cfg) dosyasından ayarlanabilir.
| openmultiplayer/web/docs/translations/tr/server/LagCompensation.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/tr/server/LagCompensation.md",
"repo_id": "openmultiplayer",
"token_count": 308
} | 428 |
---
title: OnEnterExitModShop
description: 当玩家进入或离开改装店时,这个回调函数被调用。
tags: []
---
## 描述
当玩家进入或离开改装店时,这个回调函数被调用。
| 参数名 | 描述 |
| ---------- | ------------------------------------------- |
| playerid | 进入或离开改装店的玩家的 ID |
| enterexit | 1 表示玩家进入,0 表示玩家离开 |
| interiorid | 玩家正在进入改装店的内部空间 ID(离开时为 0) |
## 返回值
它在过滤脚本中总是先被调用。
## 案例
```c
public OnEnterExitModShop(playerid, enterexit, interiorid)
{
if (enterexit == 0) // 如果enterexit返回为0,则表示它们正在离开
{
SendClientMessage(playerid, COLOR_WHITE, "好车!您付了一百美元的税。");
GivePlayerMoney(playerid, -100);
}
return 1;
}
```
## 要点
:::warning
已知的 Bug:玩家进入同一个改装店时会发生碰撞。
:::
## 相关函数
- [AddVehicleComponent](../functions/AddVehicleComponent): 向车辆添加零部件。
| openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnEnterExitModShop.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnEnterExitModShop.md",
"repo_id": "openmultiplayer",
"token_count": 687
} | 429 |
---
title: OnPlayerClickPlayerTextDraw
description: 这个回调函数在玩家点击玩家-文本绘制时被调用。
tags: ["player", "textdraw", "playertextdraw"]
---
## 描述
这个回调函数在玩家点击玩家-文本绘制时被调用。当玩家取消选择模式(ESC)时它不被调用,不过,OnPlayerClickTextDraw 回调会调用。
| 参数名 | 描述 |
| ------------ | ------------------------------ |
| playerid | 选择文本绘制的玩家的 ID |
| playertextid | 玩家选择的玩家-文本绘制的 ID。 |
## 返回值
它在过滤脚本中总是先被调用,所以返回 1 会阻止其他脚本看到它。
## 案例
```c
new PlayerText:gPlayerTextDraw[MAX_PLAYERS];
public OnPlayerConnect(playerid)
{
// 创建文本绘制
gPlayerTextDraw[playerid] = CreatePlayerTextDraw(playerid, 10.000000, 141.000000, "MyTextDraw");
PlayerTextDrawTextSize(playerid, gPlayerTextDraw[playerid], 60.000000, 20.000000);
PlayerTextDrawAlignment(playerid, gPlayerTextDraw[playerid],0);
PlayerTextDrawBackgroundColor(playerid, gPlayerTextDraw[playerid],0x000000ff);
PlayerTextDrawFont(playerid, gPlayerTextDraw[playerid], 1);
PlayerTextDrawLetterSize(playerid, gPlayerTextDraw[playerid], 0.250000, 1.000000);
PlayerTextDrawColor(playerid, gPlayerTextDraw[playerid], 0xffffffff);
PlayerTextDrawSetProportional(playerid, gPlayerTextDraw[playerid], 1);
PlayerTextDrawSetShadow(playerid, gPlayerTextDraw[playerid], 1);
// 使它可被选择
PlayerTextDrawSetSelectable(playerid, gPlayerTextDraw[playerid], 1);
// 向玩家展示它
PlayerTextDrawShow(playerid, gPlayerTextDraw[playerid]);
return 1;
}
public OnPlayerKeyStateChange(playerid, KEY:newkeys, KEY:oldkeys)
{
if (newkeys == KEY_SUBMISSION)
{
SelectTextDraw(playerid, 0xFF4040AA);
}
return 1;
}
public OnPlayerClickPlayerTextDraw(playerid, PlayerText:playertextid)
{
if (playertextid == gPlayerTextDraw[playerid])
{
SendClientMessage(playerid, 0xFFFFFFAA, "你点击了一个文本绘制。");
CancelSelectTextDraw(playerid);
return 1;
}
return 0;
}
```
## 要点
:::warning
当一个玩家按 ESC 取消了选择一个文本绘制,OnPlayerClickTextDraw 回调函数被调用时,文本绘制 ID 为 INVALID_TEXT_DRAW(无效\_文本\_绘制),也不会调用 OnPlayerClickPlayerTextDraw 回调函数。
:::
## 相关回调和函数
- [PlayerTextDrawSetSelectable](../functions/PlayerTextDrawSetSelectable): 通过 SelectTextDraw 函数设置玩家文本绘制是否可选择。
- [OnPlayerClickTextDraw](OnPlayerClickTextDraw): 当玩家点击文本绘制时调用。
- [OnPlayerClickPlayer](OnPlayerClickPlayer): 当一个玩家点击另一个玩家时调用。
| openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnPlayerClickPlayerTextDraw.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnPlayerClickPlayerTextDraw.md",
"repo_id": "openmultiplayer",
"token_count": 1369
} | 430 |
---
title: OnPlayerInteriorChange
description: 当某个玩家的内部空间改变时调用。
tags: ["player"]
---
## 描述
当某个玩家的内部空间改变时调用。可以由 [SetPlayerInterior](../functions/SetPlayerInterior) 触发,或者当玩家进入/离开建筑物时触发。
| 参数名 | 描述 |
| ------------- | --------------------------- |
| playerid | 改变了内部空间的玩家 ID。 |
| newinteriorid | 这个玩家现在的内部空间 ID。 |
| oldinteriorid | 这个玩家先前的内部空间 ID。 |
## 返回值
它在游戏模式中总是先被调用。
## 案例
```c
public OnPlayerInteriorChange(playerid, newinteriorid, oldinteriorid)
{
new string[42];
format(string, sizeof(string), "你从内部空间 %d 跑到了内部空间 %d!", oldinteriorid, newinteriorid);
SendClientMessage(playerid, COLOR_ORANGE, string);
return 1;
}
```
## 相关函数
- [SetPlayerInterior](../functions/SetPlayerInterior): 设置某个玩家的内部空间。
- [GetPlayerInterior](../functions/GetPlayerInterior): 获取某个玩家目前的内部空间。
- [LinkVehicleToInterior](../functions/LinkVehicleToInterior): 改变某个载具所处的内部空间。
- [OnPlayerStateChange](OnPlayerStateChange): 当玩家改变状态时,这个回调函数被调用。
| openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnPlayerInteriorChange.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnPlayerInteriorChange.md",
"repo_id": "openmultiplayer",
"token_count": 716
} | 431 |
---
title: OnPlayerText
description: 当玩家发送聊天消息时调用。
tags: ["player"]
---
## 描述
当玩家发送聊天消息时调用。
| 参数名 | 描述 |
| -------- | --------------------- |
| playerid | 输入文本的玩家的 ID。 |
| text[] | 玩家输入的文本。 |
## 返回值
它在过滤脚本中总是先被调用,因此在那里返回 0 会阻止其他脚本看到它。
## 案例
```c
public OnPlayerText(playerid, text[])
{
new pText[144];
format(pText, sizeof (pText), "(%d) %s", playerid, text);
SendPlayerMessageToAll(playerid, pText);
return 0; // 忽略默认文本并发送自定义文本
}
```
## 要点
<TipNPCCallbacksCN />
## 相关函数
- [SendPlayerMessageToPlayer](../functions/SendPlayerMessageToPlayer): 强制一个玩家为另一个玩家发送消息。
- [SendPlayerMessageToAll](../functions/SendPlayerMessageToAll): 强制一个玩家为所有玩家发送消息。
| openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnPlayerText.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnPlayerText.md",
"repo_id": "openmultiplayer",
"token_count": 531
} | 432 |
---
title: OnVehicleStreamOut
description: 当一辆车为玩家的客户端流出时,这个回调被调用(离太远了,以至于玩家看不到它)。
tags: ["vehicle"]
---
## 描述
当一辆车为玩家的客户端流出时,这个回调被调用(离太远了,以至于玩家看不到它)。
| 参数名 | 描述 |
| ----------- | ------------------------- |
| vehicleid | 为玩家流出的车辆 ID。 |
| forplayerid | 不再流入该车辆的玩家 ID。 |
## 返回值
它在过滤脚本中总是先被调用。
## 案例
```c
public OnVehicleStreamOut(vehicleid, forplayerid)
{
new string[48];
format(string, sizeof(string), "你的客户端不再流入车辆 %d", vehicleid);
SendClientMessage(forplayerid, 0xFFFFFFFF, string);
return 1;
}
```
## 要点
<TipNPCCallbacksCN />
| openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnVehicleStreamOut.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnVehicleStreamOut.md",
"repo_id": "openmultiplayer",
"token_count": 488
} | 433 |
---
title: Attach3DTextLabelToPlayer
description: 将三维文本标签附加到玩家身上。
tags: ["player", "3dtextlabel"]
---
## 描述
将三维文本标签附加到玩家身上。
| 参数名 | 说明 |
| --------- | ------------------------------------------------------ |
| Text3D:textid | 要附加的三维文本标签的 ID。由 Create3DTextLabel 返回。 |
| playerid | 要附加的玩家 ID。 |
| OffsetX | 距离玩家的 X 坐标偏移量。 |
| OffsetY | 距离玩家的 Y 坐标偏移量。 |
| OffsetZ | 距离玩家的 Z 坐标偏移量。 |
## 返回值
1:函数执行成功。
0:函数执行失败。这意味着玩家(和/或标签)不存在。
## 案例
```c
public OnPlayerConnect(playerid)
{
new Text3D:textLabel = Create3DTextLabel("你好,我是新来的!", 0x008080FF, 30.0, 40.0, 50.0, 40.0, 0);
Attach3DTextLabelToPlayer(textLabel, playerid, 0.0, 0.0, 0.7);
return 1;
}
```
## 相关函数
- [Create3DTextLabel](Create3DTextLabel): 创建一个三维文本标签。
- [Delete3DTextLabel](Delete3DTextLabel): 删除一个三维文本标签。
- [Attach3DTextLabelToVehicle](Attach3DTextLabelToVehicle): 将一个三维文本标签附加到载具。
- [Update3DTextLabelText](Update3DTextLabelText): 改变三维文本标签的文本内容和颜色。
- [CreatePlayer3DTextLabel](CreatePlayer3DTextLabel): 为玩家创建一个三维文本标签。
- [DeletePlayer3DTextLabel](DeletePlayer3DTextLabel): 删除一个为玩家创建的三维文本标签。
- [UpdatePlayer3DTextLabelText](UpdatePlayer3DTextLabelText): 改变玩家的三维文本标签的文本内容和颜色。
| openmultiplayer/web/docs/translations/zh-cn/scripting/functions/Attach3DTextLabelToPlayer.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/functions/Attach3DTextLabelToPlayer.md",
"repo_id": "openmultiplayer",
"token_count": 1052
} | 434 |
---
title: GetPlayerCameraPos
description: 获取玩家视角的位置。
tags: ["player", "camera"]
---
## 描述
获取玩家视角的位置。
| 参数名 | 说明 |
| -------- | --------------------------------------- |
| playerid | 要获得视角位置的玩家 ID。 |
| Float:x | 通过引用传递,存储 X 坐标的浮点型变量。 |
| Float:y | 通过引用传递,存储 Y 坐标的浮点型变量。 |
| Float:z | 通过引用传递,存储 Z 坐标的浮点型变量。 |
## 返回值
玩家的视角位置存储在引用传递的参数中。
## 案例
```c
public OnPlayerDisconnect(playerid)
{
new Float:x, Float:y, Float:z;
GetPlayerCameraPos(playerid, x, y, z);
printf("玩家离开时,他的视角在 %f,%f,%f。", x, y, z);
// 你可以把这个写到用户文件中。
return 1;
}
```
## 要点
:::warning
玩家的视角位置每秒只更新一次,除非是瞄准。如果你想根据玩家的视角位置做点什么,建议设置 1 秒的计时器。
:::
## 相关函数
- [SetPlayerCameraPos](SetPlayerCameraPos): 设置玩家的视角位置。
- [GetPlayerCameraZoom](GetPlayerCameraZoom): 获取玩家视角的缩放级别。
- [GetPlayerCameraAspectRatio](GetPlayerCameraAspectRatio): 获取玩家视角的纵横比。
- [GetPlayerCameraMode](GetplayerCameraMode): 获取玩家的视角模式。
- [GetPlayerCameraFrontVector](GetPlayerCameraFrontVector): 获取玩家视角的前向量。
| openmultiplayer/web/docs/translations/zh-cn/scripting/functions/GetPlayerCameraPos.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/functions/GetPlayerCameraPos.md",
"repo_id": "openmultiplayer",
"token_count": 891
} | 435 |
---
title: atan
description: 以度为单位求正切的多值倒数。
tags: ["math"]
---
<LowercaseNoteCN />
:::warning
请注意,y 值是第一个参数,x 值是第二个参数。这是因为数学符号是 y/x(即 y 除以 x),而惯例是按照对它们执行的操作顺序写入操作数。
:::
## 描述
以度为单位求正切的多值倒数。在三角函数中,反正切是正切的逆运算。为了计算该值,该函数会考虑两个参数的符号以确定象限。
| 参数名 | 说明 |
| ------- | --------------------- |
| Float:y | 表示 y 坐标比例的值。 |
| Float:x | 表示 x 坐标比例的值。 |
## 返回值
以度为单位的角度,在[-180.0,+180.0]的区间内。
## 案例
```c
// (x=-10.000000,y=10.000000)的反正切是135.000000度。
public OnGameModeInit()
{
new Float:x, Float:y, Float:result;
x = -10.0;
y = 10.0;
result = atan2(y, x);
printf("(x=%f,y=%f)的反正切为%f度。", x, y, result);
return 1;
}
```
## 相关函数
- [floatsin](floatsin): 从特定角度求正弦值。
- [floatcos](floatcos): 从特定角度求余弦值。
- [floattan](floattan): 从特定角度求正切值。
- [asin](asin): 以度为单位求正弦值的倒数。
- [acos](acos): 以度为单位求余弦函数的倒数。
- [atan](atan): 以度为单位求正切值的倒数。
| openmultiplayer/web/docs/translations/zh-cn/scripting/functions/atan2.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/functions/atan2.md",
"repo_id": "openmultiplayer",
"token_count": 859
} | 436 |
---
title: "Advanced Structures"
---
## Array manipulation
### Finding an empty slot properly
This example shows how to find an empty slot in an array using standard coding practices.
```c
new
gMyArray[10];
stock FindEmptySlot()
{
new
i = 0;
while (i < sizeof (gMyArray) && gMyArray[i])
{
i++;
}
if (i == sizeof (gMyArray)) return -1;
return i;
}
```
This basic example assumes an array slot is empty if its value is 0. The loop loops through all values in the array (could also be done with a constant) as long as the values are not 0. When it reaches one which is 0 the while condition will fail and the loop ends without using a break as is common practice but discouraged in situations like this. This function also returns -1 if a free slot is not found, which would need to be checked at the other end. More commonly you would use the found id straight away:
```c
MyFunction()
{
new
i = 0;
while (i < sizeof (gMyArray) && gMyArray[i])
{
i++;
}
if (i == sizeof (gMyArray))
{
printf("No free slot found");
return 0;
}
printf("Slot %d is empty", i);
// Use the found slot in your code for whatever
return 1;
}
```
Obviously you would replace the "gMyArray[i]" expression with your own indication of a slot in use.
### List
#### Introduction
Lists are a very useful type of structure, they're basically an array where the next piece or relevant data is pointed to by the last piece.
Example:
Say you have the following array:
```c
3, 1, 64, 2, 4, 786, 2, 9
```
If you wanted to sort the array you would end up with:
```c
1, 2, 2, 3, 4, 9, 64, 786
```
If however you wanted to leave the data in the original order but still know the numbers in order for some reason (it's just an example), you have a problem, how are you meant to have numbers in two orders at once? This would be a good use of lists. To construct a list from this data you would need to make the array into a 2d array, where the second dimension was 2 cells big, the first dimension containing the original number, the other containing the index of the next largest number. You would also need a separate variable to hold the index of the lowest number, so your new array would look like:
```c
start = 1
3, 1, 64, 2, 4, 786, 2, 9
4, 3, 5, 6, 7, -1, 0, 2
```
The next index associated with 786 is -1, this is an invalid array index and indicates the end of the list, i.e. there are no more numbers. The two 2's could obviously be either way round, the first one in the array is the first on in the list too as it's the more likely one to be encountered first.
The other advantage of this method of sorting the numbers is adding more numbers is a lot faster. If you wanted to add another number 3 to the sorted array you would need to first shift at least 4 numbers one slot to the right to make space, not terrible here but very slow in larger arrays. With the list version you could just append the 3 to the end of the array and modify a single value in the list;
```c
start = 1
3, 1, 64, 2, 4, 786, 2, 9, 3
8, 3, 5, 6, 7, -1, 0, 2, 4
^ modify this value ^ next highest slot
```
None of the other numbers have moved so none of the other indexes need updating, just make the next lowest number point to the new number and make the new number point the number the next lowest used to be pointing to. Removing a value is even easier:
```c
start = 1
3, 1, 64, X, 4, 786, 2, 9, 3
8, 6, 5, 6, 7, -1, 0, 2, 4
^ Changed to jump over the removed value
```
Here the first 2 has been removed and the number which pointed to that number (the 1) has been updated to point to the number the removed number was pointing to. In this example neither the removed number's pointer nor number have been removed, but you cannot possibly get to that slot following the list so it doesn't matter, it is effectively removed.
#### Types
The lists in the examples above were just basic single lists, you can also have double lists where every value points to the next value and the last value, these tend to have a pointer to the end of the list too to go backwards (e.g. to get the numbers in descending order):
```c
start = 1
end = 5
value: 3, 1, 64, 2, 4, 786, 2, 9, 3
next: 8, 3, 5, 6, 7, -1, 0, 2, 4
last: 6, -1, 7, 1, 8, 2, 3, 4, 0
```
You have to be careful with these, especially when you have more than one of any value, that the last pointer points to the number who's next pointer goes straight back again, e.g this is wrong:
```c
2, 3, 3
1, 2, -1
-1, 2, 0
```
The 2's next pointer points to the 3 in slot one, but that 3's last pointer doesn't go back to the two, both lists are in order on their own (as the two threes can be either way round) but together they are wrong, the correct version would be:
```c
2, 3, 3
1, 2, -1
-1, 0, 2
```
Both of those lists start and end on the end two numbers, the back list in the wrong example started on the middle number.
The other type of list is the looping one where the last value points back to the first. The obvious advantage to this is that you can get to any value from any other value without knowing in advance whether the target is before or after the start point, you just need to be careful not to get into an infinite loop as there's no explicit -1 end point. These lists do still have start points. You can also do double looping lists where you have a next and last list, both of which loop round:
```c
start = 1
end = 5
3, 1, 64, 2, 4, 786, 2, 9, 3
8, 3, 5, 6, 7, 1, 0, 2, 4
6, 5, 7, 1, 8, 2, 3, 4, 0
```
#### Mixed lists
Mixed lists are arrays containing multiple lists at once. An example could be an array of values, sorted by a list, with another list linking all unused slots so you know where you can add a new value. Example (X means unused (free) slot):
```c
sortedStart = 3
unusedStart = 1
value: 34, X, X, 6, 34, 46, X, 54, 23, 25, X, 75, X, 45
sort: 4, 8, 13, 7, 11, 9, 0, -1, 5
free: 2, 6, 10, 12, -1
```
Obviously the two lists never interact so both can use the same slot for their next value:
```c
sortedStart = 3
unusedStart = 1
value: 34, X, X, 6, 34, 46, X, 54, 23, 25, X, 75, X, 45
next: 4, 2, 6, 8, 13, 7, 10, 11, 9, 0, 12, -1, -1, 5
```
#### Code
Before you start the code you need to decide what sort of list is best suited for your application, this is entirely based on application can't easily be covered here. All these examples are mixed lists, one list for the required values, one for unused slots.
This example shows how to write code for a list sorted numerically ascending.
```c
#define NUMBER_OF_VALUES (10)
enum E_DATA_LIST
{
E_DATA_LIST_VALUE,
E_DATA_LIST_NEXT
}
new
gListData[NUMBER_OF_VALUES][E_DATA_LIST],
gUnusedStart = 0,
gListStart = -1; // Starts off with no list
// This function initializes the list
List_Setup()
{
new
i,
size = NUMBER_OF_VALUES;
size--;
for (i = 0; i < size; i++)
{
// To start with all slots are unused
gListData[i][E_DATA_LIST_NEXT] = i + 1;
}
// End the list
gListData[size][E_DATA_LIST_NEXT] = -1;
}
// This function adds a value to the list (using basic sorting)
List_Add(value)
{
// Check if there are free slots in the array
if (gUnusedStart == -1) return -1;
new
pointer = gListStart,
last = -1,
slot = gUnusedStart;
// Add the value to the array
gListData[slot][E_DATA_LIST_VALUE] = value;
// Update the empty list
gUnusedStart = gListData[slot][E_DATA_LIST_NEXT];
// Loop through the list till we get to bigger/same size number
while (pointer != -1 && gListData[pointer][E_DATA_LIST_VALUE] < value)
{
// Save the position of the last value
last = pointer;
// Move on to the next slot
pointer = gListData[pointer][E_DATA_LIST_NEXT];
}
// If we got here we ran out of values or reached a larger one
// Check if we checked any numbers
if (last == -1)
{
// The first number was bigger or there is no list
// Either way add the new value to the start of the list
gListData[slot][E_DATA_LIST_NEXT] = gListStart;
gListStart = slot;
}
else
{
// Place the new value in the list
gListData[slot][E_DATA_LIST_NEXT] = pointer;
gListData[last][E_DATA_LIST_NEXT] = slot;
}
return slot;
}
// This function removes a value from a given slot in the array (returned by List_Add)
List_Remove(slot)
{
// Is this a valid slot
if (slot < 0 || slot >= NUMBER_OF_VALUES) return 0;
// First find the slot before
new
pointer = gListStart,
last = -1;
while (pointer != -1 && pointer != slot)
{
last = pointer;
pointer = gListData[pointer][E_DATA_LIST_NEXT];
}
// Did we find the slot in the list
if (pointer == -1) return 0;
if (last == -1)
{
// The value is the first in the list
// Skip over this slot in the list
gListStart = gListData[slot][E_DATA_LIST_NEXT];
}
else
{
// The value is in the list
// Skip over this slot in the list
gListData[last][E_DATA_LIST_NEXT] = gListData[slot][E_DATA_LIST_NEXT];
}
// Add this slot to the unused list
// The unused list isn't in any order so this doesn't matter
gListData[slot][E_DATA_LIST_NEXT] = gUnusedStart;
gUnusedStart = slot;
return 1;
}
```
### Binary Trees
#### Introduction
Binary trees are a very fast method of searching for data in an array by using a very special list system. The most well known binary tree is probably the 20 questions game, with just 20 yes/no questions you can have over 1048576 items. A binary tree, as its name implies, is a type of tree, similar to a family tree, where every item has 0, 1 or 2 children. They are not used for ordering data like a list but sorting data for very efficient searching. Basically you start with an item somewhere near the middle of the ordered list of objects (e.g. the middle number in a sorted array) and compare that to the value you want to find. If it's the same you've found your item, if it's greater you move to the item to the right (not immediately to the right, the item to the right of the middle item would be the item at the three quarter mark), if it's less you move left, then repeat the process.
**Example**
```c
1 2 5 6 7 9 12 14 17 19 23 25 28 33 38
```
You have the preceding ordered array and you want to find what slot the number 7 is in (if it's in at all), in this example it's probably more efficient to just loop straight through the array to find it but that's not the point, that method increases in time linearly with the size of the array, a binary search time increases linearly as the array increases exponentially in size. I.e. an array 128 big will take twice as long to search straight through as an array 64 big, but a binary search 128 big will only take one check more than a binary search 64 big, not a lot at all.
If we construct a binary tree from the data above we get: 
If you read left to right, ignoring the vertical aspect you can see that the numbers are in order. Now we can try to find the 7.
The start number is 14, 7 is less than 14 so we go to the slot pointed to by the left branch of 14. This brings us to 6, 7 is bigger than 6 so we go right to 9, then left again to 7. This method took 4 comparisons to find the number (including the final check to confirm that we are on 7), using a straight search would have taken 5.
Lets say there is no 7, we would end up with this binary tree: 
This, unlike the example above, has a single child number (the 9), as well as 2 and 0 child numbers. You only get a perfect tree when there are (2^n)-1 numbers (0, 1, 3, 7, 15, 31 ...), any other numbers will give a not quite full tree. In this case when we get to the 9, where the 7 will be, we'll find there is no left branch, meaning the 7 doesn't exist (it cannot possibly be anywhere else in the tree, think about it), so we return -1 for invalid slot.
#### Balanced and unbalanced
The trees in the examples above are called balanced binary trees, this means as near as possible all the branches are the same length (obviously in the second there aren't enough numbers for this to be the case but it's as near as possible). Constructing balanced trees is not easy, the generally accepted method of constructing almost balanced trees is putting the numbers in in a random order, this may mean you end up with something like this: 
Obviously this tree is still valid but the right side is much larger than the left, however finding 25 still only takes 7 comparisons in this compared to 12 in the straight list. Also, as long as you start with a fairly middle number the random insertion method should produce a fairly balanced tree. The worst possible thing you can do is put the numbers in in order as then there will be no left branches at all (or right branches if done the other way), however even in this worst case the binary tree will take no longer to search than the straight list.
**Modification**
#### Addition
Adding a value to a binary tree is relatively easy, you just follow the tree through, using the value you want to add as a reference untill you reach an empty branch and add the number there. E.g. if you wanted to add the number 15 to our original balanced tree it would end up on the left branch of the 17. If we wanted to add the number 8 to the second balanced tree (the one without the 7) it would end up in the 7's old slot on the left of the 9.
#### Deletion
Deleting a number from a binary tree can be hard or it can be easy. If the number is at the end of a branch (e.g. 1, 5, 7, 12 etc in the original tree) you simply remove them. If a number only has one child (e.g. the 9 in the second example) you simply move that child (e.g. the 12) up into their position (so 6's children would be 2 and 12 in the new second example with 9 removed). Deletion only gets interesting when a node has two children. There are at least four ways of doing this:
The first method is the simplest computationally. Basically you choose one of the branches (left or right, assume right for this explanation) and replace the node you've removed with the first node of that branch (i.e. the right child of the node you've removed). You then go left through the new branch till you reach the end and place the left branch there. E.g. if you removed the 14 from the original exampe you would end up with 25 taking its place at the top of the tree and 6 attached to the left branch of 17. This method is fast but ends up with very unbalanced trees very quickly.
The second method is to get all the numbers which are children of the node you just removed and rebuild a new binary tree from them, then put the top of that tree into the node you've just removed. This keeps the tree fairly well balanced but is obviously slower.
The third method is to combine the two methods above and rebuild the tree inline, this is more complex to code but keeps the tree balanced and is faster than the second method (though no-where near as fast as the first).
The final menthod listed here is to simply set a flag on a value saying it's not used any more, this is even faster than the first method and maintains the structure but means you can't re-use slots unless you can find a value to replace it with later.
| openmultiplayer/web/docs/tutorials/AdvancedStructures.md/0 | {
"file_path": "openmultiplayer/web/docs/tutorials/AdvancedStructures.md",
"repo_id": "openmultiplayer",
"token_count": 4819
} | 437 |
{
"printWidth": 999,
"proseWrap": "never"
}
| openmultiplayer/web/frontend/content/.prettierrc/0 | {
"file_path": "openmultiplayer/web/frontend/content/.prettierrc",
"repo_id": "openmultiplayer",
"token_count": 23
} | 438 |
# Open Multiplayer
Nadolazeći mod za _Grand Theft Auto: San Andreas_ koji će u potpunosti biti kompatibilan sa postojećim multiplayer modom _San Andreas Multiplayer._
<br />
Ovo znači da će **postojeći SA:MP klijent i sve SA:MP skripte raditi sa/na open.mp** i, pored toga, mnoge će greške također biti ispravljene unutar serverskog softvera bez potrebe za hakiranjem i zaobilaznim rješenjima.
Ako se pitate kada je planirano javno objavljivanje ili kako možete pomoći u doprinosu projektu, pogledajte [ovaj forum thread](https://forum.open.mp/showthread.php?tid=99) za više informacija.
# [FAQ](/faq)
| openmultiplayer/web/frontend/content/bs/index.mdx/0 | {
"file_path": "openmultiplayer/web/frontend/content/bs/index.mdx",
"repo_id": "openmultiplayer",
"token_count": 259
} | 439 |
---
title: Turfs (formerly gangzones) module
date: "2019-10-19T04:20:00"
author: J0sh
---
Hello! I have just finished our Turf implementation into the server and I thought of posting a overview of this module and to show we haven't quit or anything!
```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);
```
This is obviously different from the traditional API, but not to worry, there will be wrappers in place for this kind of stuff to make sure a normal script can be recompiled with no issues and without edits.
Another important fact that you may want to know is that every turf is in the same pool and there's a maximum of 4,294,967,295 turfs to be created from the script. However, the client can only handle 1024 turfs at one time.
| openmultiplayer/web/frontend/content/en/blog/turfs-formerly-gangzones-module.mdx/0 | {
"file_path": "openmultiplayer/web/frontend/content/en/blog/turfs-formerly-gangzones-module.mdx",
"repo_id": "openmultiplayer",
"token_count": 523
} | 440 |
# Open Multiplayer
Nadolazeći multiplayer mod za _Grand Theft Auto: San Andreas_ koji će biti u potpunosti kompatibilan sa već postojećim multiplayer modom, _San Andreas Multiplayer._
To znači da će **postojeći SA:MP klijent i sve postojeće SA:MP skripte biti kompatibilne sa open.mp-om,** a osim toga, mnoge pogreške bit će ispravljene i u samom serveru što znači da više neće biti potrebe za zaobilaznim rješenjima.
Ako se pitate kada je planirano javno izdanje ili kako Vi možete pomoći pridonijeti projektu, molimo posjetite <a href="https://forum.open.mp/showthread.php?tid=99">ovu temu</a> za više informacija.
[Često postavljana pitanja](/faq)
| openmultiplayer/web/frontend/content/hr/index.mdx/0 | {
"file_path": "openmultiplayer/web/frontend/content/hr/index.mdx",
"repo_id": "openmultiplayer",
"token_count": 282
} | 441 |
# FAQ
<hr />
## Wat is open.mp?
open.mp (Open Multiplayer, OMP) is een alternatieve multiplayer modificatie voor San Andreas,
gestart als reactie op de spijtige toename van problemen met updates en het management van SA:MP. De
eerste versie zal enkel een alternatief voor de server bevatten, en bestaande SA:MP clients zullen
met deze server verbindingen kunnen maken. In een later stadium zal een aparte open.mp client worden
toegevoegd die het mogelijk zal maken om interessantere updates uit te brengen.
<hr />
## Is het een fork?
Nee. Dit is compleet opnieuw geschreven, profijt van een decennium aan kennis en ervaring. Er zijn
pogingen geweest om SA:MP te forken, maar wij geloven dat deze twee belangrijke problemen hadden:
1. Ze baseerden zich op gelekte SA:MP broncode. De makers van deze modificaties hadden niet het
recht om de broncode legaal te gebruiken en werden, zowel op moreel als legaal vlak, in het
defensief gedrongen. Wij weigeren ronduit om deze code te gebruiken. Dit belemmert de
ontwikkelings snelheid enigszins maar het is de juiste zet op de lange termijn.
2. Ze probeerden te veel in één keer opnieuw uit te vinden; het vervangen van de scripting engine,
het verwijderen van functionaliteiten terwijl nieuwe toegevoegd werden, of gewoon dingen die
veranderd werden op een tegenstrijdige manier. Dit weerhield bestaande servers met enorme
hoeveelheden code en spelers om over te stappen; hun broncode zouden ze grotendeels, zoniet in
zijn geheel, hebben moeten herschrijven. Een hachelijke onderneming. Wij zijn absoluut van plan
om in der loop der tijd ook nieuwe mogelijkheden toe te voegen, maar wel op zo'n manier dat
bestaande servers hier geen hinder van ondervinden; wij veranderen onze code zodat zij de hunne
niet hoeven te veranderen.
<hr />
## Waarom doen jullie dit?
Ondanks een ontelbaar aantal pogingen om de ontwikkeling van SA:MP nieuw leven in te blazen — met
behulp van suggesties, hulp vanuit het beta team en een gemeenschap die schreeuwt om vernieuwing —
werd er geen vooruitgang geboekt. Algemeen werd aangenomen dat dit simpelweg om desinteresse ging
bij de leiding. Dat is op zich niet zo erg, maar er was geen lijn van opvolging. In plaats van de
fakkel door te geven zou de ontwikkelaar als het ware liever met het schip ten onder gaan, terwijl
hij in de tussentijd met minimale inspanningen het schip drijvend probeert te houden. Er gaan
geruchten dat dit vanwege een passief inkomen is, maar dat is niet bewezen. Ondanks overwelgende
interesse en een sterke en familiaire gemeenschap geloofde de ontwikkelaar dat de mod nog slechts 1
à 2 jaar te leven had en dat de gemeenschap die zo hard gewerkt had om SA:MP te maken wat het
vandaag is geen voortzetting verdiende.
Wij zijn het daar niet mee eens.
<hr />
## Wat is jullie mening over Kalcor/SA:MP/wat dan ook?
Wij houden van SA:MP, dat is waarom wij in eerste instantie bestaan — wij hebben de creatie van
open.mp te danken aan Kalcor. Hij heeft heel veel voor de modificatie gedaan, en die contributie
moet niet vergeten of genegeerd worden. De acties die tot open.mp hebben geleid waren genomen omdat
wij het oneens zijn met meerdere recente beslissingen en ondanks herhaalde pogingen om de
modificatie in andere banen te lijden, was er geen oplossing tegemoetgekomen. Dus waren wij
genoodzaakt om de ongelukkige keuze te maken en te proberen om door te gaan met SA:MP zonder Kalcor.
Het is geen actie die tegen hem persoonlijk is genomen, en zal daarom niet moeten worden aangezien
als persoonlijke aanval. Wij zullen geen enkele persoonlijke belediging tollereren, tegen niemand
niet — desondanks wat hun mening over de open.mp kwestie is; we dienen om een gezond debat te kunnen
houden zonder terug te vallen op tot persoon gerichte aanvallen.
<hr />
## Deze mod heet "Open" Multiplayer. Betekent dat dat de mod open source zal worden?
Op den duur is dat het plan, ja. Voor nu zijn we aan het proberen om de ontwikkeling open te houden
qua communicatie en transparantie (wat op zichzelf al een verbetering is). We zullen stappen
ondernemen om het project open source te maken zodra alles geregeld is en de rust is wedergekeerd.
<hr />
## Hoe kan ik helpen?
Hou je ogen open op het forum. We hebben een topic voor exact deze vraag, en zullen het updaten
wanneer er meer werk beschikbaar wordt. Hoewel het project iets eerder onthuld werd dan bedoeld zijn
we reeds goed op weg naar een eerste release, maar dat betekent uiteraard niet dat meer help niet
enorm gewaardeerd wordt. Alvast bedankt dat je interesse hebt en gelooft in dit project:
["Hoe te helpen" topic (burgershot.gg, Engels)](https://forum.open.mp/showthread.php?tid=99)
<hr />
## Wat is burgershot.gg?
burgershot.gg is een gaming forum, niets meer niets minder. Veel van de mensen zijn betrokken in
beiden, en sommige OMP ontwikkelingen en updates worden daar gepubliceerd, maar het zijn twee
onafhankelijke projecten. Het is niet het OMP forum, noch is OMP eigendom van burgershot. Als er
eenmaal een complete OMP site online is, kunnen de twee gescheiden worden (net als dat SA:MP ooit
gehost werd door GTAForums voordat haar eigen site online stond).
<hr />
## Hoe zit het met OpenMP?
Het Open Multi-Processing project is "OpenMP", wij zijn "open.mp". Compleet verschillend.
| openmultiplayer/web/frontend/content/nl/faq.mdx/0 | {
"file_path": "openmultiplayer/web/frontend/content/nl/faq.mdx",
"repo_id": "openmultiplayer",
"token_count": 2010
} | 442 |
---
title: Синхронизација возила
date: "2019-11-09T11:33:00"
author: Southclaws
---
Брза објава демонстрира еволуцију синхронизације возила.
<video autoPlay loop width="100%" controls>
<source src="https://assets.open.mp/assets/images/videos/vehicle_sync_01.mp4" type="video/mp4" />
Извините, Ваш претраживач не подржава уграђене видее.
</video>
<video autoPlay loop width="100%" controls>
<source src="https://assets.open.mp/assets/images/videos/vehicle_sync_02.mp4" type="video/mp4" />
Извините, Ваш претраживач не подржава уграђене видее.
</video>
<video autoPlay loop width="100%" controls>
<source src="https://assets.open.mp/assets/images/videos/vehicle_sync_03.mp4" type="video/mp4" />
Извините, Ваш претраживач не подржава уграђене видее.
</video>
| openmultiplayer/web/frontend/content/sr/blog/vehicle-sync.mdx/0 | {
"file_path": "openmultiplayer/web/frontend/content/sr/blog/vehicle-sync.mdx",
"repo_id": "openmultiplayer",
"token_count": 477
} | 443 |
---
title: How can I join the team?
date: "2021-08-29T01:24:09"
author: Potassium
---
➖ ЯК МОЖНА ПРИЄДНАТИСЯ ДО КОМАНДИ?
Нам це питання задають БАГАТО, тому ми подумали, що маємо написати про це повідомлення!
По-перше, величезне спасибі за зацікавленість зробити свій внесок!
Як ви знаєте, ми всі ветерани SA-MP гравців, які зібралися разом, щоб зберегти світ багатокористувацької гри SA. Ми захоплені тим, що проект призначений для гравців та для гравців, і саме тому він з часом буде з відкритим кодом.
ВАКАНСІЯ: РОЗРОБНИК
Наразі ми працюємо над останніми штрихами щодо бета-релізу. Як тільки випустимо, будемо вдячні за внески від спільноти! Нам знадобиться допомога при тестуванні функціональних можливостей і крайових випадків, і, звичайно, у пошуку помилок та інших питань, які потребують уваги.
Бета-тест стане надзвичайно важливою частиною шляху розвитку, і ми хотіли б, щоб усі були залучені, тому просимо вас слідкувати за анонсом бета-тесту, котрий, ми обіцяємо, буде дуже-дуже скоро!
ВАКАНСІЯ: РЕГІОНАЛЬНИЙ КООРДИНАТОР
Ви вільно володієте англійською та іншою мовою? Ми хотіли б, щоб ваша допомога була в перекладі наших вікі-сторінок, публікацій у блозі та публікацій у соціальних мережах, а також допомога у модеруванні мовних розділів нашого Discord та нашого форуму.
ІНШІ ШЛЯХИ ДОПОМОГИ:
- ДІЛІТЬСЯ нашими публікаціями в соціальних мережах
- ЗАПРОШУЙТЕ інших гравців SA до нашого Discord (discord.gg/samp)
- ДОЛУЧІТСЬЯ до нашої спільноті на Discord
- ДОПОМАГАЙТЕ іншим гравцям у Discord (скрипти, технічні питання, та що завгодно!)
| openmultiplayer/web/frontend/content/uk/blog/how-to-join-the-team.mdx/0 | {
"file_path": "openmultiplayer/web/frontend/content/uk/blog/how-to-join-the-team.mdx",
"repo_id": "openmultiplayer",
"token_count": 1780
} | 444 |
---
title: 地盘(原帮派区域)模块
date: "2019-10-19T04:20:00"
author: J0sh
---
大家好! 我刚刚完成了我们在服务器中的地盘的实现,我想在这里发表一下这个模块的概述,以表明我们没有放弃任何东西!
```pawn
// 创建一个地盘。为了使它成为某个玩家的地盘,可以传递玩家ID参数。
native Turf:Turf_Create(Float:minx, Float:miny, Float:maxx, Float:maxy, Player:owner = INVALID_PLAYER_ID);
// 销毁一个地盘。
native Turf_Destroy(Turf:turf);
// 向一个或多个玩家展示地盘。
// 当 playerid = INVALID_PLAYER_ID时,将给所有玩家展示。
native Turf_Show(Turf:turf, colour, Player:playerid = INVALID_PLAYER_ID);
// 向一个或多个玩家隐藏地盘。
// 当 playerid = INVALID_PLAYER_ID时,将给所有玩家隐藏。
native Turf_Hide(Turf:turf, Player:playerid = INVALID_PLAYER_ID);
// 为一个或多个玩家闪烁地盘。
// 当 playerid = INVALID_PLAYER_ID时,将给所有玩家闪烁。
native Turf_Flash(Turf:turf, colour, Player:playerid = INVALID_PLAYER_ID);
// 停止为一个或多个玩家闪烁地盘。
// 当 playerid = INVALID_PLAYER_ID时,将给所有玩家停止闪烁。
native Turf_StopFlashing(Turf:turf, Player:playerid = INVALID_PLAYER_ID);
```
这显然不同于传统的 API,但不用担心,对于这类东西,会有适当的包装类,以确保正常的脚本不需要编辑就可以重新编译,而不会出现问题。
另一个你可能想知道的重要事实是,每个地盘都在同一个池里,最多可以有 4,294,967,295 个地盘可以在脚本中创建。然而,客户端一次只能处理 1024 个地盘。
| openmultiplayer/web/frontend/content/zh-cn/blog/turfs-formerly-gangzones-module.mdx/0 | {
"file_path": "openmultiplayer/web/frontend/content/zh-cn/blog/turfs-formerly-gangzones-module.mdx",
"repo_id": "openmultiplayer",
"token_count": 992
} | 445 |
import useSWR from "swr";
import { apiSWR } from "src/fetcher/fetcher";
import { Link } from "src/types/_generated_GitHub";
import { User, UserSchema } from "src/types/_generated_User";
import { APIError } from "src/types/_generated_Error";
import { LinkSchema } from "src/types/_generated_Discord";
type Props = {
bg: string;
icon: JSX.Element;
type: string;
};
const OAuthButton = ({ bg, icon, type }: Props) => {
const { data: link } = useSWR<Link, APIError>(
`/auth/${type}/link`,
apiSWR({ schema: LinkSchema })
);
const { data, error } = useSWR<User, APIError>(
"/users/self",
apiSWR({ schema: UserSchema })
);
let text: string;
let href = link?.url;
if (type === "github") {
if (!error && data && data.github) {
text = data.github;
href = undefined;
} else {
text = "Login with GitHub";
href = link?.url;
}
} else if (type === "discord") {
if (!error && data && data.discord) {
text = data.discord;
href = undefined;
} else {
text = "Login with Discord";
href = link?.url;
}
} else {
throw new Error(`Unknown OAuth type: ${type}`);
}
return (
<li className="pv2">
<a
href={href}
className="link pa2 br3 h3 flex align-center justify-center"
>
<span className="pa2">{icon}</span>
<span className="pa2">
<h2 className="pa0 ma0">{text}</h2>
</span>
</a>
<style jsx>{`
a {
background-color: ${bg};
color: white;
}
span {
margin: auto 0 auto 0;
}
`}</style>
</li>
);
};
export default OAuthButton;
| openmultiplayer/web/frontend/src/components/OAuthButton.tsx/0 | {
"file_path": "openmultiplayer/web/frontend/src/components/OAuthButton.tsx",
"repo_id": "openmultiplayer",
"token_count": 748
} | 446 |
import { Flex, Link } from "@chakra-ui/layout";
import { useColorModeValue } from "@chakra-ui/react";
import NextLink from "next/link";
import React, { FC } from "react";
import { WEB_ADDRESS } from "src/config";
import { User } from "src/types/_generated_User";
import ProfilePicture from "./ProfilePicture";
type Props = {
user: Pick<User, "id" | "name">;
};
const MemberLink: FC<Props> = ({ user }) => {
return (
<NextLink href={`${WEB_ADDRESS}/members/${user.id}`} passHref>
<Link whiteSpace="nowrap">
<Flex fontStyle="normal" color={useColorModeValue('black', 'white')} gridGap="0.5em">
<ProfilePicture id={user.id} />
<span>
<em className="author">{user.name}</em>
</span>
</Flex>
</Link>
</NextLink>
);
};
export default MemberLink;
| openmultiplayer/web/frontend/src/components/member/MemberLink.tsx/0 | {
"file_path": "openmultiplayer/web/frontend/src/components/member/MemberLink.tsx",
"repo_id": "openmultiplayer",
"token_count": 339
} | 447 |
import Admonition from "../Admonition";
export default function TipNpcCallback() {
return (
<Admonition type="tip">
<p>This callback can also be called by NPC.</p>
</Admonition>
);
}
| openmultiplayer/web/frontend/src/components/templates/npc-callbacks-tip.tsx/0 | {
"file_path": "openmultiplayer/web/frontend/src/components/templates/npc-callbacks-tip.tsx",
"repo_id": "openmultiplayer",
"token_count": 73
} | 448 |
import Admonition from "../../../Admonition";
export default function NoteLowercase({ name = "函数" }) {
return (
<Admonition type="warning">
<p>这个${name}以小写字母开头。</p>
</Admonition>
);
}
| openmultiplayer/web/frontend/src/components/templates/translations/zh-cn/lowercase-note.tsx/0 | {
"file_path": "openmultiplayer/web/frontend/src/components/templates/translations/zh-cn/lowercase-note.tsx",
"repo_id": "openmultiplayer",
"token_count": 98
} | 449 |
import type { AppProps } from "next/app";
import Router from "next/router";
import { DefaultSeo } from "next-seo";
import { ToastContainer } from "react-nextjs-toast";
import NProgress from "nprogress";
import Nav from "src/components/site/Nav";
import Footer from "src/components/site/Footer";
import "normalize.css";
import "tachyons/css/tachyons.min.css";
import "nprogress/nprogress.css";
import "remark-admonitions/styles/classic.css";
import "src/styles/base.css";
import { AuthProvider } from "src/auth/hooks";
import { Chakra } from "src/components/Chakra";
import Fonts from "src/styles/Fonts";
import React from "react";
import { NextPage } from "next";
// Trigger client-side progress bar for client-side page transitions.
Router.events.on("routeChangeStart", () => NProgress.start());
Router.events.on("routeChangeComplete", () => NProgress.done());
Router.events.on("routeChangeError", () => NProgress.done());
const App: NextPage<AppProps> = ({ Component, pageProps, router }) => (
<Chakra cookies={pageProps.cookies}>
<Fonts />
{/*
Sets the default meta tags for all pages.
https://github.com/garmeeh/next-seo
*/}
<DefaultSeo
title="Open Multiplayer"
titleTemplate="open.mp | %s"
description="A multiplayer mod for Grand Theft Auto: San Andreas that is fully backwards compatible with San Andreas Multiplayer"
canonical="https://open.mp"
twitter={{
cardType: "summary",
site: "@openmultiplayer",
handle: "@openmultiplayer",
}}
/>
<ToastContainer align="right" />
<AuthProvider>
<Nav
items={[
{ name: "Home", path: "/", exact: true },
{ name: "FAQ", path: "/faq" },
{ name: "Forums", path: "https://forum.open.mp" },
{ name: "Servers", path: "/servers" },
{ name: "Partners", path: "/partners" },
{ name: "Docs", path: "/docs" },
{ name: "Blog", path: "/blog" },
]}
route={router.asPath}
/>
<main>
<Component {...pageProps} />
</main>
<Footer />
</AuthProvider>
<style jsx global>{`
html,
body,
#__next {
height: 100%;
}
#__next {
display: flex;
flex-direction: column;
}
main {
flex: 1 0 auto;
}
`}</style>
</Chakra>
);
export default App;
| openmultiplayer/web/frontend/src/pages/_app.tsx/0 | {
"file_path": "openmultiplayer/web/frontend/src/pages/_app.tsx",
"repo_id": "openmultiplayer",
"token_count": 976
} | 450 |
import { Box, Heading } from "@chakra-ui/react";
import { NextSeo } from "next-seo";
import ErrorBanner from "src/components/ErrorBanner";
import { CardList } from "src/components/generic/CardList";
import ServerRow from "src/components/listing/ServerRow";
import LoadingBanner from "src/components/LoadingBanner";
import { API_ADDRESS } from "src/config";
import { Essential } from "src/types/_generated_Server";
import useSWR from "swr";
const API_SERVERS = `${API_ADDRESS}/servers/`;
const getServers = async (): Promise<Array<Essential>> => {
const r: Response = await fetch(API_SERVERS);
const servers: Array<Essential> = await r.json();
return servers;
};
const dataToList = (items: Essential[]) => {
return items
.filter((s: Essential) => {
return s.pr === true;
})
.map((s: Essential) => <ServerRow key={s.ip} server={s} />);
};
const List = ({ data }: { data: Array<Essential> }) => {
return <CardList>{dataToList(data)}</CardList>;
};
const Page = () => {
const { data, error } = useSWR<Array<Essential>, TypeError>(
API_SERVERS,
getServers
);
if (error) {
return <ErrorBanner {...error} />;
}
if (!data) {
return <LoadingBanner />;
}
return (
<Box as="section" maxWidth="50em" margin="auto" padding="1em 2em">
<NextSeo
title="SA-MP Servers Index"
description="open.mp partners and beta testers"
/>
<Heading mb={"1em"}>Partners (BETA TESTERS)</Heading>
<Box py={4}>
<p>
Servers helping us in beta testing by running open.mp and reporting
bugs and issues are listed here. You can do the same by running your
server using open.mp and help us with finding bugs and issues; Then
tell us about your servers on{" "}
<a href="https://discord.gg/samp">our discord</a> so we can list them
here.
</p>
<p>
Those who are contributing to our community will have permanent perks
in future when we are releasing for public use and when our server
listing is ready.
</p>
<p>
<b>
Note: Partnership program is temporarily closed as we promised.
Servers reserving a slot can still join, but we do not take any new requests for now, if you are still interested,
you can ask your questions on our discord, but if it's about new ways of getting into the list, we do not have plans yet.
</b>
</p>
</Box>
<List data={data} />
</Box>
);
};
export default Page;
| openmultiplayer/web/frontend/src/pages/partners.tsx/0 | {
"file_path": "openmultiplayer/web/frontend/src/pages/partners.tsx",
"repo_id": "openmultiplayer",
"token_count": 987
} | 451 |
module github.com/openmultiplayer/web
go 1.14
require (
github.com/Masterminds/semver v1.5.0
github.com/PuerkitoBio/goquery v1.6.0
github.com/RoaringBitmap/roaring v0.9.4 // indirect
github.com/Southclaws/go-samp-query v1.2.1
github.com/Southclaws/qstring v1.1.0
github.com/Southclaws/sampctl v0.0.0-20210109143621-2daeb58d756a
github.com/Southclaws/supervillain v1.0.0
github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d
github.com/bbalet/stopwords v1.0.0
github.com/blevesearch/bleve/v2 v2.1.0
github.com/bwmarrin/discordgo v0.22.0
github.com/forPelevin/gomoji v0.0.0-20210718160015-5fcf0e405128
github.com/go-chi/chi v4.1.2+incompatible
github.com/go-chi/cors v1.1.1
github.com/goccy/go-json v0.10.2 // indirect
github.com/gomarkdown/markdown v0.0.0-20211105120026-16f708f914c3
github.com/google/go-github v0.0.0-20180819205025-d7732128a00e
github.com/google/go-github/v28 v28.1.1
github.com/gorilla/schema v1.2.0
github.com/gorilla/securecookie v1.1.1
github.com/gosimple/slug v1.10.0
github.com/iancoleman/strcase v0.2.0
github.com/joho/godotenv v1.5.1
github.com/kelseyhightower/envconfig v1.4.0
github.com/patrickmn/go-cache v2.1.0+incompatible
github.com/pkg/errors v0.9.1
github.com/prisma/prisma-client-go v0.16.2
github.com/prometheus/client_golang v1.11.0
github.com/russross/blackfriday v1.6.0
github.com/sethvargo/go-limiter v0.7.2
github.com/shopspring/decimal v1.3.1
github.com/steebchen/prisma-client-go v0.24.0
github.com/stretchr/testify v1.8.4
github.com/takuoki/gocase v1.0.0
github.com/thanhpk/randstr v1.0.4
github.com/victorspringer/http-cache v0.0.0-20220131145941-ef3624e6666f
go.etcd.io/bbolt v1.3.5
go.uber.org/fx v1.13.1
go.uber.org/multierr v1.6.0 // indirect
go.uber.org/zap v1.16.0
golang.org/x/oauth2 v0.0.0-20201203001011-0b49973bad19
golang.org/x/text v0.13.0
gopkg.in/yaml.v2 v2.4.0
nhooyr.io/websocket v1.8.6
)
| openmultiplayer/web/go.mod/0 | {
"file_path": "openmultiplayer/web/go.mod",
"repo_id": "openmultiplayer",
"token_count": 959
} | 452 |
package web
import (
"net/http"
)
// RouteUse is router.User but for individual routes.
func RouteUse(mws ...func(http.Handler) http.Handler) func(http.Handler) http.Handler {
return func(f http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var handler = f
for _, mw := range mws {
handler = mw(handler)
}
handler.ServeHTTP(w, r)
})
}
}
| openmultiplayer/web/internal/web/middleware.go/0 | {
"file_path": "openmultiplayer/web/internal/web/middleware.go",
"repo_id": "openmultiplayer",
"token_count": 159
} | 453 |
-- AlterTable
ALTER TABLE "Server" ADD COLUMN "pending" BOOL NOT NULL DEFAULT false;
-- CreateTable
CREATE TABLE "ServerIPBlacklist" (
"id" STRING NOT NULL,
"ip" STRING NOT NULL,
CONSTRAINT "ServerIPBlacklist_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "ServerIPBlacklist_ip_key" ON "ServerIPBlacklist"("ip");
| openmultiplayer/web/prisma/migrations/20231021221052_add_pending_status_and_blacklist_table/migration.sql/0 | {
"file_path": "openmultiplayer/web/prisma/migrations/20231021221052_add_pending_status_and_blacklist_table/migration.sql",
"repo_id": "openmultiplayer",
"token_count": 130
} | 454 |
{
"files.exclude": {
"node_modules": true,
"data": true
}
}
| overleaf/web/.vscode/settings.json/0 | {
"file_path": "overleaf/web/.vscode/settings.json",
"repo_id": "overleaf",
"token_count": 35
} | 455 |
const Errors = require('../Errors/Errors')
class InvalidEmailError extends Errors.BackwardCompatibleError {}
class InvalidPasswordError extends Errors.BackwardCompatibleError {}
module.exports = {
InvalidEmailError,
InvalidPasswordError,
}
| overleaf/web/app/src/Features/Authentication/AuthenticationErrors.js/0 | {
"file_path": "overleaf/web/app/src/Features/Authentication/AuthenticationErrors.js",
"repo_id": "overleaf",
"token_count": 64
} | 456 |
const { callbackify } = require('util')
const pLimit = require('p-limit')
const { ObjectId } = require('mongodb')
const OError = require('@overleaf/o-error')
const { Project } = require('../../models/Project')
const UserGetter = require('../User/UserGetter')
const ProjectGetter = require('../Project/ProjectGetter')
const PublicAccessLevels = require('../Authorization/PublicAccessLevels')
const Errors = require('../Errors/Errors')
const ProjectEditorHandler = require('../Project/ProjectEditorHandler')
const Sources = require('../Authorization/Sources')
const PrivilegeLevels = require('../Authorization/PrivilegeLevels')
module.exports = {
getMemberIdsWithPrivilegeLevels: callbackify(getMemberIdsWithPrivilegeLevels),
getMemberIds: callbackify(getMemberIds),
getInvitedMemberIds: callbackify(getInvitedMemberIds),
getInvitedMembersWithPrivilegeLevels: callbackify(
getInvitedMembersWithPrivilegeLevels
),
getInvitedMembersWithPrivilegeLevelsFromFields: callbackify(
getInvitedMembersWithPrivilegeLevelsFromFields
),
getMemberIdPrivilegeLevel: callbackify(getMemberIdPrivilegeLevel),
getInvitedCollaboratorCount: callbackify(getInvitedCollaboratorCount),
getProjectsUserIsMemberOf: callbackify(getProjectsUserIsMemberOf),
isUserInvitedMemberOfProject: callbackify(isUserInvitedMemberOfProject),
userIsTokenMember: callbackify(userIsTokenMember),
getAllInvitedMembers: callbackify(getAllInvitedMembers),
promises: {
getMemberIdsWithPrivilegeLevels,
getMemberIds,
getInvitedMemberIds,
getInvitedMembersWithPrivilegeLevels,
getInvitedMembersWithPrivilegeLevelsFromFields,
getMemberIdPrivilegeLevel,
getInvitedCollaboratorCount,
getProjectsUserIsMemberOf,
isUserInvitedMemberOfProject,
userIsTokenMember,
getAllInvitedMembers,
},
}
async function getMemberIdsWithPrivilegeLevels(projectId) {
const project = await ProjectGetter.promises.getProject(projectId, {
owner_ref: 1,
collaberator_refs: 1,
readOnly_refs: 1,
tokenAccessReadOnly_refs: 1,
tokenAccessReadAndWrite_refs: 1,
publicAccesLevel: 1,
})
if (!project) {
throw new Errors.NotFoundError(`no project found with id ${projectId}`)
}
const memberIds = _getMemberIdsWithPrivilegeLevelsFromFields(
project.owner_ref,
project.collaberator_refs,
project.readOnly_refs,
project.tokenAccessReadAndWrite_refs,
project.tokenAccessReadOnly_refs,
project.publicAccesLevel
)
return memberIds
}
async function getMemberIds(projectId) {
const members = await getMemberIdsWithPrivilegeLevels(projectId)
return members.map(m => m.id)
}
async function getInvitedMemberIds(projectId) {
const members = await getMemberIdsWithPrivilegeLevels(projectId)
return members.filter(m => m.source !== Sources.TOKEN).map(m => m.id)
}
async function getInvitedMembersWithPrivilegeLevels(projectId) {
let members = await getMemberIdsWithPrivilegeLevels(projectId)
members = members.filter(m => m.source !== Sources.TOKEN)
return _loadMembers(members)
}
async function getInvitedMembersWithPrivilegeLevelsFromFields(
ownerId,
collaboratorIds,
readOnlyIds
) {
const members = _getMemberIdsWithPrivilegeLevelsFromFields(
ownerId,
collaboratorIds,
readOnlyIds,
[],
[],
null
)
return _loadMembers(members)
}
async function getMemberIdPrivilegeLevel(userId, projectId) {
// In future if the schema changes and getting all member ids is more expensive (multiple documents)
// then optimise this.
if (userId == null) {
return PrivilegeLevels.NONE
}
const members = await getMemberIdsWithPrivilegeLevels(projectId)
for (const member of members) {
if (member.id === userId.toString()) {
return member.privilegeLevel
}
}
return PrivilegeLevels.NONE
}
async function getInvitedCollaboratorCount(projectId) {
const count = await _getInvitedMemberCount(projectId)
return count - 1 // Don't count project owner
}
async function isUserInvitedMemberOfProject(userId, projectId) {
const members = await getMemberIdsWithPrivilegeLevels(projectId)
for (const member of members) {
if (
member.id.toString() === userId.toString() &&
member.source !== Sources.TOKEN
) {
return true
}
}
return false
}
async function getProjectsUserIsMemberOf(userId, fields) {
const limit = pLimit(2)
const [
readAndWrite,
readOnly,
tokenReadAndWrite,
tokenReadOnly,
] = await Promise.all([
limit(() => Project.find({ collaberator_refs: userId }, fields).exec()),
limit(() => Project.find({ readOnly_refs: userId }, fields).exec()),
limit(() =>
Project.find(
{
tokenAccessReadAndWrite_refs: userId,
publicAccesLevel: PublicAccessLevels.TOKEN_BASED,
},
fields
).exec()
),
limit(() =>
Project.find(
{
tokenAccessReadOnly_refs: userId,
publicAccesLevel: PublicAccessLevels.TOKEN_BASED,
},
fields
).exec()
),
])
return { readAndWrite, readOnly, tokenReadAndWrite, tokenReadOnly }
}
async function getAllInvitedMembers(projectId) {
try {
const rawMembers = await getInvitedMembersWithPrivilegeLevels(projectId)
const { members } = ProjectEditorHandler.buildOwnerAndMembersViews(
rawMembers
)
return members
} catch (err) {
throw OError.tag(err, 'error getting members for project', { projectId })
}
}
async function userIsTokenMember(userId, projectId) {
userId = ObjectId(userId.toString())
projectId = ObjectId(projectId.toString())
const project = await Project.findOne(
{
_id: projectId,
$or: [
{ tokenAccessReadOnly_refs: userId },
{ tokenAccessReadAndWrite_refs: userId },
],
},
{
_id: 1,
}
).exec()
return project != null
}
async function _getInvitedMemberCount(projectId) {
const members = await getMemberIdsWithPrivilegeLevels(projectId)
return members.filter(m => m.source !== Sources.TOKEN).length
}
function _getMemberIdsWithPrivilegeLevelsFromFields(
ownerId,
collaboratorIds,
readOnlyIds,
tokenAccessIds,
tokenAccessReadOnlyIds,
publicAccessLevel
) {
const members = []
members.push({
id: ownerId.toString(),
privilegeLevel: PrivilegeLevels.OWNER,
source: Sources.OWNER,
})
for (const memberId of collaboratorIds || []) {
members.push({
id: memberId.toString(),
privilegeLevel: PrivilegeLevels.READ_AND_WRITE,
source: Sources.INVITE,
})
}
for (const memberId of readOnlyIds || []) {
members.push({
id: memberId.toString(),
privilegeLevel: PrivilegeLevels.READ_ONLY,
source: Sources.INVITE,
})
}
if (publicAccessLevel === PublicAccessLevels.TOKEN_BASED) {
for (const memberId of tokenAccessIds || []) {
members.push({
id: memberId.toString(),
privilegeLevel: PrivilegeLevels.READ_AND_WRITE,
source: Sources.TOKEN,
})
}
for (const memberId of tokenAccessReadOnlyIds || []) {
members.push({
id: memberId.toString(),
privilegeLevel: PrivilegeLevels.READ_ONLY,
source: Sources.TOKEN,
})
}
}
return members
}
async function _loadMembers(members) {
const limit = pLimit(3)
const results = await Promise.all(
members.map(member =>
limit(async () => {
const user = await UserGetter.promises.getUser(member.id, {
_id: 1,
email: 1,
features: 1,
first_name: 1,
last_name: 1,
signUpDate: 1,
})
if (user != null) {
return { user, privilegeLevel: member.privilegeLevel }
} else {
return null
}
})
)
)
return results.filter(r => r != null)
}
| overleaf/web/app/src/Features/Collaborators/CollaboratorsGetter.js/0 | {
"file_path": "overleaf/web/app/src/Features/Collaborators/CollaboratorsGetter.js",
"repo_id": "overleaf",
"token_count": 2906
} | 457 |
/* eslint-disable
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 CooldownMiddleware
const CooldownManager = require('./CooldownManager')
const logger = require('logger-sharelatex')
module.exports = CooldownMiddleware = {
freezeProject(req, res, next) {
const projectId = req.params.Project_id
if (projectId == null) {
return next(new Error('[Cooldown] No projectId parameter on route'))
}
return CooldownManager.isProjectOnCooldown(
projectId,
function (err, projectIsOnCooldown) {
if (err != null) {
return next(err)
}
if (projectIsOnCooldown) {
logger.log(
{ projectId },
'[Cooldown] project is on cooldown, denying request'
)
return res.sendStatus(429)
}
return next()
}
)
},
}
| overleaf/web/app/src/Features/Cooldown/CooldownMiddleware.js/0 | {
"file_path": "overleaf/web/app/src/Features/Cooldown/CooldownMiddleware.js",
"repo_id": "overleaf",
"token_count": 444
} | 458 |
function _getIndefiniteArticle(providerName) {
const vowels = ['a', 'e', 'i', 'o', 'u']
if (vowels.includes(providerName.charAt(0).toLowerCase())) return 'an'
return 'a'
}
function linkOrUnlink(accountLinked, providerName, email) {
const action = accountLinked ? 'linked' : 'no longer linked'
const actionDescribed = accountLinked ? 'was linked to' : 'was unlinked from'
const indefiniteArticle = _getIndefiniteArticle(providerName)
return {
to: email,
action: `${providerName} account ${action}`,
actionDescribed: `${indefiniteArticle} ${providerName} account ${actionDescribed} your account ${email}`,
}
}
module.exports = {
linkOrUnlink,
}
| overleaf/web/app/src/Features/Email/EmailOptionsHelper.js/0 | {
"file_path": "overleaf/web/app/src/Features/Email/EmailOptionsHelper.js",
"repo_id": "overleaf",
"token_count": 230
} | 459 |
function shouldDisplayFeature(req, name, variantFlag) {
if (req.query && req.query[name]) {
return req.query[name] === 'true'
} else {
return variantFlag === true
}
}
module.exports = { shouldDisplayFeature }
| overleaf/web/app/src/Features/Helpers/FeatureFlag.js/0 | {
"file_path": "overleaf/web/app/src/Features/Helpers/FeatureFlag.js",
"repo_id": "overleaf",
"token_count": 75
} | 460 |
const async = require('async')
const _ = require('underscore')
const { callbackify } = require('util')
const { ObjectId } = require('mongodb')
const Settings = require('@overleaf/settings')
const {
getInstitutionAffiliations,
promises: InstitutionsAPIPromises,
} = require('./InstitutionsAPI')
const FeaturesUpdater = require('../Subscription/FeaturesUpdater')
const UserGetter = require('../User/UserGetter')
const NotificationsBuilder = require('../Notifications/NotificationsBuilder')
const SubscriptionLocator = require('../Subscription/SubscriptionLocator')
const { Institution } = require('../../models/Institution')
const { Subscription } = require('../../models/Subscription')
const ASYNC_LIMIT = parseInt(process.env.ASYNC_LIMIT, 10) || 5
async function _getSsoUsers(institutionId, lapsedUserIds) {
let currentNotEntitledCount = 0
const ssoNonEntitledUsersIds = []
const allSsoUsersByIds = {}
const allSsoUsers = await UserGetter.promises.getSsoUsersAtInstitution(
institutionId,
{ samlIdentifiers: 1 }
)
allSsoUsers.forEach(user => {
allSsoUsersByIds[user._id] = user.samlIdentifiers.find(
identifer => identifer.providerId === institutionId.toString()
)
})
for (const userId in allSsoUsersByIds) {
if (!allSsoUsersByIds[userId].hasEntitlement) {
ssoNonEntitledUsersIds.push(userId)
}
}
if (ssoNonEntitledUsersIds.length > 0) {
currentNotEntitledCount = ssoNonEntitledUsersIds.filter(
id => !lapsedUserIds.includes(id)
).length
}
return {
allSsoUsers,
allSsoUsersByIds,
currentNotEntitledCount,
}
}
async function _checkUsersFeatures(userIds) {
const users = await UserGetter.promises.getUsers(userIds, { features: 1 })
const result = {
proUserIds: [],
nonProUserIds: [],
}
await new Promise((resolve, reject) => {
async.eachLimit(
users,
ASYNC_LIMIT,
(user, callback) => {
const hasProFeaturesOrBetter = FeaturesUpdater.isFeatureSetBetter(
user.features,
Settings.features.professional
)
if (hasProFeaturesOrBetter) {
result.proUserIds.push(user._id)
} else {
result.nonProUserIds.push(user._id)
}
callback()
},
error => {
if (error) return reject(error)
resolve()
}
)
})
return result
}
async function checkInstitutionUsers(institutionId) {
/*
v1 has affiliation data. Via getInstitutionAffiliationsCounts, v1 will send
lapsed_user_ids, which includes all user types
(not linked, linked and entitled, linked not entitled).
However, for SSO institutions, it does not know which email is linked
to SSO when the license is non-trivial. Here we need to split that
lapsed count into SSO (entitled and not) or just email users
*/
const result = {
emailUsers: {
total: 0, // v1 all users - v2 all SSO users
current: 0, // v1 current - v1 SSO entitled - (v2 calculated not entitled current)
lapsed: 0, // v1 lapsed user IDs that are not in v2 SSO users
pro: {
current: 0,
lapsed: 0,
},
nonPro: {
current: 0,
lapsed: 0,
},
},
ssoUsers: {
total: 0, // only v2
current: {
entitled: 0, // only v1
notEntitled: 0, // v2 non-entitled SSO users - v1 lapsed user IDs
},
lapsed: 0, // v2 SSO users that are in v1 lapsed user IDs
pro: {
current: 0,
lapsed: 0,
},
nonPro: {
current: 0,
lapsed: 0,
},
},
}
const {
user_ids: userIds, // confirmed and not removed users. Includes users with lapsed reconfirmations
current_users_count: currentUsersCount, // all users not with lapsed reconfirmations
lapsed_user_ids: lapsedUserIds, // includes all user types that did not reconfirm (sso entitled, sso not entitled, email only)
with_confirmed_email: withConfirmedEmail, // same count as affiliation metrics
entitled_via_sso: entitled, // same count as affiliation metrics
} = await InstitutionsAPIPromises.getInstitutionAffiliationsCounts(
institutionId
)
result.ssoUsers.current.entitled = entitled
const {
allSsoUsers,
allSsoUsersByIds,
currentNotEntitledCount,
} = await _getSsoUsers(institutionId, lapsedUserIds)
result.ssoUsers.total = allSsoUsers.length
result.ssoUsers.current.notEntitled = currentNotEntitledCount
// check if lapsed user ID an SSO user
const lapsedUsersByIds = {}
lapsedUserIds.forEach(id => {
lapsedUsersByIds[id] = true // create a map for more performant lookups
if (allSsoUsersByIds[id]) {
++result.ssoUsers.lapsed
} else {
++result.emailUsers.lapsed
}
})
result.emailUsers.current =
currentUsersCount - entitled - result.ssoUsers.current.notEntitled
result.emailUsers.total = userIds.length - allSsoUsers.length
// compare v1 and v2 counts.
if (
result.ssoUsers.current.notEntitled + result.emailUsers.current !==
withConfirmedEmail
) {
result.databaseMismatch = {
withConfirmedEmail: {
v1: withConfirmedEmail,
v2: result.ssoUsers.current.notEntitled + result.emailUsers.current,
},
}
}
// Add Pro/NonPro status for users
// NOTE: Users not entitled via institution could have Pro via another method
const { proUserIds, nonProUserIds } = await _checkUsersFeatures(userIds)
proUserIds.forEach(id => {
const userType = lapsedUsersByIds[id] ? 'lapsed' : 'current'
if (allSsoUsersByIds[id]) {
result.ssoUsers.pro[userType]++
} else {
result.emailUsers.pro[userType]++
}
})
nonProUserIds.forEach(id => {
const userType = lapsedUsersByIds[id] ? 'lapsed' : 'current'
if (allSsoUsersByIds[id]) {
result.ssoUsers.nonPro[userType]++
} else {
result.emailUsers.nonPro[userType]++
}
})
return result
}
const InstitutionsManager = {
refreshInstitutionUsers(institutionId, notify, callback) {
const refreshFunction = notify ? refreshFeaturesAndNotify : refreshFeatures
async.waterfall(
[
cb => fetchInstitutionAndAffiliations(institutionId, cb),
function (institution, affiliations, cb) {
affiliations = _.map(affiliations, function (affiliation) {
affiliation.institutionName = institution.name
affiliation.institutionId = institutionId
return affiliation
})
async.eachLimit(affiliations, ASYNC_LIMIT, refreshFunction, err =>
cb(err)
)
},
],
callback
)
},
checkInstitutionUsers: callbackify(checkInstitutionUsers),
getInstitutionUsersSubscriptions(institutionId, callback) {
getInstitutionAffiliations(institutionId, function (error, affiliations) {
if (error) {
return callback(error)
}
const userIds = affiliations.map(affiliation =>
ObjectId(affiliation.user_id)
)
Subscription.find({
admin_id: userIds,
planCode: { $not: /trial/ },
})
.populate('admin_id', 'email')
.exec(callback)
})
},
}
var fetchInstitutionAndAffiliations = (institutionId, callback) =>
async.waterfall(
[
cb =>
Institution.findOne({ v1Id: institutionId }, (err, institution) =>
cb(err, institution)
),
(institution, cb) =>
institution.fetchV1Data((err, institution) => cb(err, institution)),
(institution, cb) =>
getInstitutionAffiliations(institutionId, (err, affiliations) =>
cb(err, institution, affiliations)
),
],
callback
)
var refreshFeatures = function (affiliation, callback) {
const userId = ObjectId(affiliation.user_id)
FeaturesUpdater.refreshFeatures(userId, 'refresh-institution-users', callback)
}
var refreshFeaturesAndNotify = function (affiliation, callback) {
const userId = ObjectId(affiliation.user_id)
async.waterfall(
[
cb =>
FeaturesUpdater.refreshFeatures(
userId,
'refresh-institution-users',
(err, features, featuresChanged) => cb(err, featuresChanged)
),
(featuresChanged, cb) =>
getUserInfo(userId, (error, user, subscription) =>
cb(error, user, subscription, featuresChanged)
),
(user, subscription, featuresChanged, cb) =>
notifyUser(user, affiliation, subscription, featuresChanged, cb),
],
callback
)
}
var getUserInfo = (userId, callback) =>
async.waterfall(
[
cb => UserGetter.getUser(userId, cb),
(user, cb) =>
SubscriptionLocator.getUsersSubscription(user, (err, subscription) =>
cb(err, user, subscription)
),
],
callback
)
var notifyUser = (user, affiliation, subscription, featuresChanged, callback) =>
async.parallel(
[
function (cb) {
if (featuresChanged) {
NotificationsBuilder.featuresUpgradedByAffiliation(
affiliation,
user
).create(cb)
} else {
cb()
}
},
function (cb) {
if (
subscription &&
!subscription.planCode.match(/(free|trial)/) &&
!subscription.groupPlan
) {
NotificationsBuilder.redundantPersonalSubscription(
affiliation,
user
).create(cb)
} else {
cb()
}
},
],
callback
)
InstitutionsManager.promises = {
checkInstitutionUsers,
}
module.exports = InstitutionsManager
| overleaf/web/app/src/Features/Institutions/InstitutionsManager.js/0 | {
"file_path": "overleaf/web/app/src/Features/Institutions/InstitutionsManager.js",
"repo_id": "overleaf",
"token_count": 3847
} | 461 |
const settings = require('@overleaf/settings')
const UserAuditLogHandler = require('../User/UserAuditLogHandler')
const UserGetter = require('../User/UserGetter')
const OneTimeTokenHandler = require('../Security/OneTimeTokenHandler')
const EmailHandler = require('../Email/EmailHandler')
const AuthenticationManager = require('../Authentication/AuthenticationManager')
const { callbackify, promisify } = require('util')
function generateAndEmailResetToken(email, callback) {
UserGetter.getUserByAnyEmail(email, (err, user) => {
if (err || !user) {
return callback(err, null)
}
if (user.email !== email) {
return callback(null, 'secondary')
}
const data = { user_id: user._id.toString(), email: email }
OneTimeTokenHandler.getNewToken('password', data, (err, token) => {
if (err) {
return callback(err)
}
const emailOptions = {
to: email,
setNewPasswordUrl: `${
settings.siteUrl
}/user/password/set?passwordResetToken=${token}&email=${encodeURIComponent(
email
)}`,
}
EmailHandler.sendEmail('passwordResetRequested', emailOptions, err => {
if (err) {
return callback(err)
}
callback(null, 'primary')
})
})
})
}
function getUserForPasswordResetToken(token, callback) {
OneTimeTokenHandler.getValueFromTokenAndExpire(
'password',
token,
(err, data) => {
if (err != null) {
if (err.name === 'NotFoundError') {
return callback(null, null)
} else {
return callback(err)
}
}
if (data == null || data.email == null) {
return callback(null, null)
}
UserGetter.getUserByMainEmail(
data.email,
{ _id: 1, 'overleaf.id': 1, email: 1 },
(err, user) => {
if (err != null) {
callback(err)
} else if (user == null) {
callback(null, null)
} else if (
data.user_id != null &&
data.user_id === user._id.toString()
) {
callback(null, user)
} else if (
data.v1_user_id != null &&
user.overleaf != null &&
data.v1_user_id === user.overleaf.id
) {
callback(null, user)
} else {
callback(null, null)
}
}
)
}
)
}
async function setNewUserPassword(token, password, auditLog) {
const user = await PasswordResetHandler.promises.getUserForPasswordResetToken(
token
)
if (!user) {
return {
found: false,
reset: false,
userId: null,
}
}
const reset = await AuthenticationManager.promises.setUserPassword(
user,
password
)
await UserAuditLogHandler.promises.addEntry(
user._id,
'reset-password',
auditLog.initiatorId,
auditLog.ip
)
return { found: true, reset, userId: user._id }
}
const PasswordResetHandler = {
generateAndEmailResetToken,
setNewUserPassword: callbackify(setNewUserPassword),
getUserForPasswordResetToken,
}
PasswordResetHandler.promises = {
getUserForPasswordResetToken: promisify(
PasswordResetHandler.getUserForPasswordResetToken
),
setNewUserPassword,
}
module.exports = PasswordResetHandler
| overleaf/web/app/src/Features/PasswordReset/PasswordResetHandler.js/0 | {
"file_path": "overleaf/web/app/src/Features/PasswordReset/PasswordResetHandler.js",
"repo_id": "overleaf",
"token_count": 1402
} | 462 |
const { db } = require('../../infrastructure/mongodb')
const { normalizeQuery } = require('../Helpers/Mongo')
const OError = require('@overleaf/o-error')
const metrics = require('@overleaf/metrics')
const { promisifyAll } = require('../../util/promises')
const { Project } = require('../../models/Project')
const logger = require('logger-sharelatex')
const LockManager = require('../../infrastructure/LockManager')
const { DeletedProject } = require('../../models/DeletedProject')
const ProjectGetter = {
EXCLUDE_DEPTH: 8,
getProjectWithoutDocLines(projectId, callback) {
const excludes = {}
for (let i = 1; i <= ProjectGetter.EXCLUDE_DEPTH; i++) {
excludes[`rootFolder${Array(i).join('.folders')}.docs.lines`] = 0
}
ProjectGetter.getProject(projectId, excludes, callback)
},
getProjectWithOnlyFolders(projectId, callback) {
const excludes = {}
for (let i = 1; i <= ProjectGetter.EXCLUDE_DEPTH; i++) {
excludes[`rootFolder${Array(i).join('.folders')}.docs`] = 0
excludes[`rootFolder${Array(i).join('.folders')}.fileRefs`] = 0
}
ProjectGetter.getProject(projectId, excludes, callback)
},
getProject(projectId, projection, callback) {
if (typeof projection === 'function' && callback == null) {
callback = projection
projection = {}
}
if (projectId == null) {
return callback(new Error('no project id provided'))
}
if (typeof projection !== 'object') {
return callback(new Error('projection is not an object'))
}
if (projection.rootFolder || Object.keys(projection).length === 0) {
const ProjectEntityMongoUpdateHandler = require('./ProjectEntityMongoUpdateHandler')
LockManager.runWithLock(
ProjectEntityMongoUpdateHandler.LOCK_NAMESPACE,
projectId,
cb => ProjectGetter.getProjectWithoutLock(projectId, projection, cb),
callback
)
} else {
ProjectGetter.getProjectWithoutLock(projectId, projection, callback)
}
},
getProjectWithoutLock(projectId, projection, callback) {
if (typeof projection === 'function' && callback == null) {
callback = projection
projection = {}
}
if (projectId == null) {
return callback(new Error('no project id provided'))
}
if (typeof projection !== 'object') {
return callback(new Error('projection is not an object'))
}
let query
try {
query = normalizeQuery(projectId)
} catch (err) {
return callback(err)
}
db.projects.findOne(query, { projection }, function (err, project) {
if (err) {
OError.tag(err, 'error getting project', {
query,
projection,
})
return callback(err)
}
callback(null, project)
})
},
getProjectIdByReadAndWriteToken(token, callback) {
Project.findOne(
{ 'tokens.readAndWrite': token },
{ _id: 1 },
function (err, project) {
if (err) {
return callback(err)
}
if (project == null) {
return callback()
}
callback(null, project._id)
}
)
},
findAllUsersProjects(userId, fields, callback) {
const CollaboratorsGetter = require('../Collaborators/CollaboratorsGetter')
Project.find(
{ owner_ref: userId },
fields,
function (error, ownedProjects) {
if (error) {
return callback(error)
}
CollaboratorsGetter.getProjectsUserIsMemberOf(
userId,
fields,
function (error, projects) {
if (error) {
return callback(error)
}
const result = {
owned: ownedProjects || [],
readAndWrite: projects.readAndWrite || [],
readOnly: projects.readOnly || [],
tokenReadAndWrite: projects.tokenReadAndWrite || [],
tokenReadOnly: projects.tokenReadOnly || [],
}
callback(null, result)
}
)
}
)
},
/**
* Return all projects with the given name that belong to the given user.
*
* Projects include the user's own projects as well as collaborations with
* read/write access.
*/
findUsersProjectsByName(userId, projectName, callback) {
ProjectGetter.findAllUsersProjects(
userId,
'name archived trashed',
(err, allProjects) => {
if (err != null) {
return callback(err)
}
const { owned, readAndWrite } = allProjects
const projects = owned.concat(readAndWrite)
const lowerCasedProjectName = projectName.toLowerCase()
const matches = projects.filter(
project => project.name.toLowerCase() === lowerCasedProjectName
)
callback(null, matches)
}
)
},
getUsersDeletedProjects(userId, callback) {
DeletedProject.find(
{
'deleterData.deletedProjectOwnerId': userId,
},
callback
)
},
}
;['getProject', 'getProjectWithoutDocLines'].map(method =>
metrics.timeAsyncMethod(ProjectGetter, method, 'mongo.ProjectGetter', logger)
)
ProjectGetter.promises = promisifyAll(ProjectGetter)
module.exports = ProjectGetter
| overleaf/web/app/src/Features/Project/ProjectGetter.js/0 | {
"file_path": "overleaf/web/app/src/Features/Project/ProjectGetter.js",
"repo_id": "overleaf",
"token_count": 2090
} | 463 |
const { SamlLog } = require('../../models/SamlLog')
const logger = require('logger-sharelatex')
function log(providerId, sessionId, data) {
try {
const samlLog = new SamlLog()
samlLog.providerId = providerId = (providerId || '').toString()
samlLog.sessionId = sessionId = (sessionId || '').toString().substr(0, 8)
try {
samlLog.jsonData = JSON.stringify(data)
} catch (err) {
// log but continue on data errors
logger.error(
{ err, sessionId, providerId },
'SamlLog JSON.stringify Error'
)
}
samlLog.save(err => {
if (err) {
logger.error({ err, sessionId, providerId }, 'SamlLog Error')
}
})
} catch (err) {
logger.error({ err, sessionId, providerId }, 'SamlLog Error')
}
}
const SamlLogHandler = {
log,
}
module.exports = SamlLogHandler
| overleaf/web/app/src/Features/SamlLog/SamlLogHandler.js/0 | {
"file_path": "overleaf/web/app/src/Features/SamlLog/SamlLogHandler.js",
"repo_id": "overleaf",
"token_count": 348
} | 464 |
const async = require('async')
const OError = require('@overleaf/o-error')
const PlansLocator = require('./PlansLocator')
const _ = require('lodash')
const SubscriptionLocator = require('./SubscriptionLocator')
const UserFeaturesUpdater = require('./UserFeaturesUpdater')
const Settings = require('@overleaf/settings')
const logger = require('logger-sharelatex')
const ReferalFeatures = require('../Referal/ReferalFeatures')
const V1SubscriptionManager = require('./V1SubscriptionManager')
const InstitutionsFeatures = require('../Institutions/InstitutionsFeatures')
const UserGetter = require('../User/UserGetter')
const AnalyticsManager = require('../Analytics/AnalyticsManager')
const FeaturesUpdater = {
refreshFeatures(userId, reason, callback = () => {}) {
UserGetter.getUser(userId, { _id: 1, features: 1 }, (err, user) => {
if (err) {
return callback(err)
}
const oldFeatures = _.clone(user.features)
FeaturesUpdater._computeFeatures(userId, (error, features) => {
if (error) {
return callback(error)
}
logger.log({ userId, features }, 'updating user features')
const matchedFeatureSet = FeaturesUpdater._getMatchedFeatureSet(
features
)
AnalyticsManager.setUserProperty(
userId,
'feature-set',
matchedFeatureSet
)
UserFeaturesUpdater.updateFeatures(
userId,
features,
(err, newFeatures, featuresChanged) => {
if (err) {
return callback(err)
}
if (oldFeatures.dropbox === true && features.dropbox === false) {
logger.log({ userId }, '[FeaturesUpdater] must unlink dropbox')
const Modules = require('../../infrastructure/Modules')
Modules.hooks.fire('removeDropbox', userId, reason, err => {
if (err) {
logger.error(err)
}
return callback(null, newFeatures, featuresChanged)
})
} else {
return callback(null, newFeatures, featuresChanged)
}
}
)
})
})
},
_computeFeatures(userId, callback) {
const jobs = {
individualFeatures(cb) {
FeaturesUpdater._getIndividualFeatures(userId, cb)
},
groupFeatureSets(cb) {
FeaturesUpdater._getGroupFeatureSets(userId, cb)
},
institutionFeatures(cb) {
InstitutionsFeatures.getInstitutionsFeatures(userId, cb)
},
v1Features(cb) {
FeaturesUpdater._getV1Features(userId, cb)
},
bonusFeatures(cb) {
ReferalFeatures.getBonusFeatures(userId, cb)
},
featuresOverrides(cb) {
FeaturesUpdater._getFeaturesOverrides(userId, cb)
},
}
async.series(jobs, function (err, results) {
if (err) {
OError.tag(
err,
'error getting subscription or group for refreshFeatures',
{
userId,
}
)
return callback(err)
}
const {
individualFeatures,
groupFeatureSets,
institutionFeatures,
v1Features,
bonusFeatures,
featuresOverrides,
} = results
logger.log(
{
userId,
individualFeatures,
groupFeatureSets,
institutionFeatures,
v1Features,
bonusFeatures,
featuresOverrides,
},
'merging user features'
)
const featureSets = groupFeatureSets.concat([
individualFeatures,
institutionFeatures,
v1Features,
bonusFeatures,
featuresOverrides,
])
const features = _.reduce(
featureSets,
FeaturesUpdater._mergeFeatures,
Settings.defaultFeatures
)
callback(null, features)
})
},
_getIndividualFeatures(userId, callback) {
SubscriptionLocator.getUserIndividualSubscription(userId, (err, sub) =>
callback(err, FeaturesUpdater._subscriptionToFeatures(sub))
)
},
_getGroupFeatureSets(userId, callback) {
SubscriptionLocator.getGroupSubscriptionsMemberOf(userId, (err, subs) =>
callback(err, (subs || []).map(FeaturesUpdater._subscriptionToFeatures))
)
},
_getFeaturesOverrides(userId, callback) {
UserGetter.getUser(userId, { featuresOverrides: 1 }, (error, user) => {
if (error) {
return callback(error)
}
if (
!user ||
!user.featuresOverrides ||
user.featuresOverrides.length === 0
) {
return callback(null, {})
}
const activeFeaturesOverrides = []
for (const featuresOverride of user.featuresOverrides) {
if (
!featuresOverride.expiresAt ||
featuresOverride.expiresAt > new Date()
) {
activeFeaturesOverrides.push(featuresOverride.features)
}
}
const features = _.reduce(
activeFeaturesOverrides,
FeaturesUpdater._mergeFeatures,
{}
)
callback(null, features)
})
},
_getV1Features(userId, callback) {
V1SubscriptionManager.getPlanCodeFromV1(
userId,
function (err, planCode, v1Id) {
if (err) {
if ((err ? err.name : undefined) === 'NotFoundError') {
return callback(null, [])
}
return callback(err)
}
callback(
err,
FeaturesUpdater._mergeFeatures(
V1SubscriptionManager.getGrandfatheredFeaturesForV1User(v1Id) || {},
FeaturesUpdater.planCodeToFeatures(planCode)
)
)
}
)
},
_mergeFeatures(featuresA, featuresB) {
const features = Object.assign({}, featuresA)
for (const key in featuresB) {
// Special merging logic for non-boolean features
if (key === 'compileGroup') {
if (
features.compileGroup === 'priority' ||
featuresB.compileGroup === 'priority'
) {
features.compileGroup = 'priority'
} else {
features.compileGroup = 'standard'
}
} else if (key === 'collaborators') {
if (features.collaborators === -1 || featuresB.collaborators === -1) {
features.collaborators = -1
} else {
features.collaborators = Math.max(
features.collaborators || 0,
featuresB.collaborators || 0
)
}
} else if (key === 'compileTimeout') {
features.compileTimeout = Math.max(
features.compileTimeout || 0,
featuresB.compileTimeout || 0
)
} else {
// Boolean keys, true is better
features[key] = features[key] || featuresB[key]
}
}
return features
},
isFeatureSetBetter(featuresA, featuresB) {
const mergedFeatures = FeaturesUpdater._mergeFeatures(featuresA, featuresB)
return _.isEqual(featuresA, mergedFeatures)
},
_subscriptionToFeatures(subscription) {
return FeaturesUpdater.planCodeToFeatures(
subscription ? subscription.planCode : undefined
)
},
planCodeToFeatures(planCode) {
if (!planCode) {
return {}
}
const plan = PlansLocator.findLocalPlanInSettings(planCode)
if (!plan) {
return {}
} else {
return plan.features
}
},
compareFeatures(currentFeatures, expectedFeatures) {
currentFeatures = _.clone(currentFeatures)
expectedFeatures = _.clone(expectedFeatures)
if (_.isEqual(currentFeatures, expectedFeatures)) {
return {}
}
const mismatchReasons = {}
const featureKeys = [
...new Set([
...Object.keys(currentFeatures),
...Object.keys(expectedFeatures),
]),
]
featureKeys.sort().forEach(key => {
if (expectedFeatures[key] !== currentFeatures[key]) {
mismatchReasons[key] = expectedFeatures[key]
}
})
if (mismatchReasons.compileTimeout) {
// store the compile timeout difference instead of the new compile timeout
mismatchReasons.compileTimeout =
expectedFeatures.compileTimeout - currentFeatures.compileTimeout
}
if (mismatchReasons.collaborators) {
// store the collaborators difference instead of the new number only
// replace -1 by 100 to make it clearer
if (expectedFeatures.collaborators === -1) {
expectedFeatures.collaborators = 100
}
if (currentFeatures.collaborators === -1) {
currentFeatures.collaborators = 100
}
mismatchReasons.collaborators =
expectedFeatures.collaborators - currentFeatures.collaborators
}
return mismatchReasons
},
doSyncFromV1(v1UserId, callback) {
logger.log({ v1UserId }, '[AccountSync] starting account sync')
return UserGetter.getUser(
{ 'overleaf.id': v1UserId },
{ _id: 1 },
function (err, user) {
if (err != null) {
OError.tag(err, '[AccountSync] error getting user', {
v1UserId,
})
return callback(err)
}
if ((user != null ? user._id : undefined) == null) {
logger.warn({ v1UserId }, '[AccountSync] no user found for v1 id')
return callback(null)
}
logger.log(
{ v1UserId, userId: user._id },
'[AccountSync] updating user subscription and features'
)
return FeaturesUpdater.refreshFeatures(user._id, 'sync-v1', callback)
}
)
},
_getMatchedFeatureSet(features) {
for (const [name, featureSet] of Object.entries(Settings.features)) {
if (_.isEqual(features, featureSet)) {
return name
}
}
return 'mixed'
},
}
const refreshFeaturesPromise = (userId, reason) =>
new Promise(function (resolve, reject) {
FeaturesUpdater.refreshFeatures(
userId,
reason,
(error, features, featuresChanged) => {
if (error) {
reject(error)
} else {
resolve({ features, featuresChanged })
}
}
)
})
FeaturesUpdater.promises = {
refreshFeatures: refreshFeaturesPromise,
}
module.exports = FeaturesUpdater
| overleaf/web/app/src/Features/Subscription/FeaturesUpdater.js/0 | {
"file_path": "overleaf/web/app/src/Features/Subscription/FeaturesUpdater.js",
"repo_id": "overleaf",
"token_count": 4372
} | 465 |
const Settings = require('@overleaf/settings')
const RecurlyWrapper = require('./RecurlyWrapper')
const PlansLocator = require('./PlansLocator')
const SubscriptionFormatters = require('./SubscriptionFormatters')
const SubscriptionLocator = require('./SubscriptionLocator')
const V1SubscriptionManager = require('./V1SubscriptionManager')
const InstitutionsGetter = require('../Institutions/InstitutionsGetter')
const PublishersGetter = require('../Publishers/PublishersGetter')
const sanitizeHtml = require('sanitize-html')
const _ = require('underscore')
const async = require('async')
const SubscriptionHelper = require('./SubscriptionHelper')
const { promisify } = require('../../util/promises')
function buildHostedLink(recurlySubscription, type) {
const recurlySubdomain = Settings.apis.recurly.subdomain
const hostedLoginToken = recurlySubscription.account.hosted_login_token
let path = ''
if (type === 'billingDetails') {
path = 'billing_info/edit?ht='
}
if (hostedLoginToken && recurlySubdomain) {
return [
'https://',
recurlySubdomain,
'.recurly.com/account/',
path,
hostedLoginToken,
].join('')
}
}
function buildUsersSubscriptionViewModel(user, callback) {
async.auto(
{
personalSubscription(cb) {
SubscriptionLocator.getUsersSubscription(user, cb)
},
recurlySubscription: [
'personalSubscription',
(cb, { personalSubscription }) => {
if (
personalSubscription == null ||
personalSubscription.recurlySubscription_id == null ||
personalSubscription.recurlySubscription_id === ''
) {
return cb(null, null)
}
RecurlyWrapper.getSubscription(
personalSubscription.recurlySubscription_id,
{ includeAccount: true },
cb
)
},
],
recurlyCoupons: [
'recurlySubscription',
(cb, { recurlySubscription }) => {
if (!recurlySubscription) {
return cb(null, null)
}
const accountId = recurlySubscription.account.account_code
RecurlyWrapper.getAccountActiveCoupons(accountId, cb)
},
],
plan: [
'personalSubscription',
(cb, { personalSubscription }) => {
if (personalSubscription == null) {
return cb()
}
const plan = PlansLocator.findLocalPlanInSettings(
personalSubscription.planCode
)
if (plan == null) {
return cb(
new Error(
`No plan found for planCode '${personalSubscription.planCode}'`
)
)
}
cb(null, plan)
},
],
memberGroupSubscriptions(cb) {
SubscriptionLocator.getMemberSubscriptions(user, cb)
},
managedGroupSubscriptions(cb) {
SubscriptionLocator.getManagedGroupSubscriptions(user, cb)
},
confirmedMemberAffiliations(cb) {
InstitutionsGetter.getConfirmedAffiliations(user._id, cb)
},
managedInstitutions(cb) {
InstitutionsGetter.getManagedInstitutions(user._id, cb)
},
managedPublishers(cb) {
PublishersGetter.getManagedPublishers(user._id, cb)
},
v1SubscriptionStatus(cb) {
V1SubscriptionManager.getSubscriptionStatusFromV1(
user._id,
(error, status, v1Id) => {
if (error) {
return cb(error)
}
cb(null, status)
}
)
},
},
(err, results) => {
if (err) {
return callback(err)
}
let {
personalSubscription,
memberGroupSubscriptions,
managedGroupSubscriptions,
confirmedMemberAffiliations,
managedInstitutions,
managedPublishers,
v1SubscriptionStatus,
recurlySubscription,
recurlyCoupons,
plan,
} = results
if (memberGroupSubscriptions == null) {
memberGroupSubscriptions = []
}
if (managedGroupSubscriptions == null) {
managedGroupSubscriptions = []
}
if (confirmedMemberAffiliations == null) {
confirmedMemberAffiliations = []
}
if (managedInstitutions == null) {
managedInstitutions = []
}
if (v1SubscriptionStatus == null) {
v1SubscriptionStatus = {}
}
if (recurlyCoupons == null) {
recurlyCoupons = []
}
if (
personalSubscription &&
typeof personalSubscription.toObject === 'function'
) {
// Downgrade from Mongoose object, so we can add a recurly and plan attribute
personalSubscription = personalSubscription.toObject()
}
if (plan != null) {
personalSubscription.plan = plan
}
if (personalSubscription && recurlySubscription) {
const tax = recurlySubscription.tax_in_cents || 0
// Some plans allow adding more seats than the base plan provides.
// This is recorded as a subscription add on.
// Note: tax_in_cents already includes the tax for any addon.
let addOnPrice = 0
let additionalLicenses = 0
if (
plan.membersLimitAddOn &&
Array.isArray(recurlySubscription.subscription_add_ons)
) {
recurlySubscription.subscription_add_ons.forEach(addOn => {
if (addOn.add_on_code === plan.membersLimitAddOn) {
addOnPrice += addOn.quantity * addOn.unit_amount_in_cents
additionalLicenses += addOn.quantity
}
})
}
const totalLicenses = (plan.membersLimit || 0) + additionalLicenses
personalSubscription.recurly = {
tax,
taxRate: recurlySubscription.tax_rate
? parseFloat(recurlySubscription.tax_rate._)
: 0,
billingDetailsLink: buildHostedLink(
recurlySubscription,
'billingDetails'
),
accountManagementLink: buildHostedLink(recurlySubscription),
additionalLicenses,
totalLicenses,
nextPaymentDueAt: SubscriptionFormatters.formatDate(
recurlySubscription.current_period_ends_at
),
currency: recurlySubscription.currency,
state: recurlySubscription.state,
trialEndsAtFormatted: SubscriptionFormatters.formatDate(
recurlySubscription.trial_ends_at
),
trial_ends_at: recurlySubscription.trial_ends_at,
activeCoupons: recurlyCoupons,
account: recurlySubscription.account,
}
if (recurlySubscription.pending_subscription) {
const pendingPlan = PlansLocator.findLocalPlanInSettings(
recurlySubscription.pending_subscription.plan.plan_code
)
if (pendingPlan == null) {
return callback(
new Error(
`No plan found for planCode '${personalSubscription.planCode}'`
)
)
}
let pendingAdditionalLicenses = 0
let pendingAddOnTax = 0
let pendingAddOnPrice = 0
if (recurlySubscription.pending_subscription.subscription_add_ons) {
if (
pendingPlan.membersLimitAddOn &&
Array.isArray(
recurlySubscription.pending_subscription.subscription_add_ons
)
) {
recurlySubscription.pending_subscription.subscription_add_ons.forEach(
addOn => {
if (addOn.add_on_code === pendingPlan.membersLimitAddOn) {
pendingAddOnPrice +=
addOn.quantity * addOn.unit_amount_in_cents
pendingAdditionalLicenses += addOn.quantity
}
}
)
}
// Need to calculate tax ourselves as we don't get tax amounts for pending subs
pendingAddOnTax =
personalSubscription.recurly.taxRate * pendingAddOnPrice
}
const pendingSubscriptionTax =
personalSubscription.recurly.taxRate *
recurlySubscription.pending_subscription.unit_amount_in_cents
personalSubscription.recurly.price = SubscriptionFormatters.formatPrice(
recurlySubscription.pending_subscription.unit_amount_in_cents +
pendingAddOnPrice +
pendingAddOnTax +
pendingSubscriptionTax,
recurlySubscription.currency
)
const pendingTotalLicenses =
(pendingPlan.membersLimit || 0) + pendingAdditionalLicenses
personalSubscription.recurly.pendingAdditionalLicenses = pendingAdditionalLicenses
personalSubscription.recurly.pendingTotalLicenses = pendingTotalLicenses
personalSubscription.pendingPlan = pendingPlan
} else {
personalSubscription.recurly.price = SubscriptionFormatters.formatPrice(
recurlySubscription.unit_amount_in_cents + addOnPrice + tax,
recurlySubscription.currency
)
}
}
for (const memberGroupSubscription of memberGroupSubscriptions) {
if (memberGroupSubscription.teamNotice) {
memberGroupSubscription.teamNotice = sanitizeHtml(
memberGroupSubscription.teamNotice
)
}
}
callback(null, {
personalSubscription,
managedGroupSubscriptions,
memberGroupSubscriptions,
confirmedMemberAffiliations,
managedInstitutions,
managedPublishers,
v1SubscriptionStatus,
})
}
)
}
function buildPlansList(currentPlan) {
const { plans } = Settings
const allPlans = {}
plans.forEach(plan => {
allPlans[plan.planCode] = plan
})
const result = { allPlans }
if (currentPlan) {
result.planCodesChangingAtTermEnd = _.pluck(
_.filter(plans, plan => {
if (!plan.hideFromUsers) {
return SubscriptionHelper.shouldPlanChangeAtTermEnd(currentPlan, plan)
}
}),
'planCode'
)
}
result.studentAccounts = _.filter(
plans,
plan => plan.planCode.indexOf('student') !== -1
)
result.groupMonthlyPlans = _.filter(
plans,
plan => plan.groupPlan && !plan.annual
)
result.groupAnnualPlans = _.filter(
plans,
plan => plan.groupPlan && plan.annual
)
result.individualMonthlyPlans = _.filter(
plans,
plan =>
!plan.groupPlan &&
!plan.annual &&
plan.planCode !== 'personal' && // Prevent the personal plan from appearing on the change-plans page
plan.planCode.indexOf('student') === -1
)
result.individualAnnualPlans = _.filter(
plans,
plan =>
!plan.groupPlan && plan.annual && plan.planCode.indexOf('student') === -1
)
return result
}
module.exports = {
buildUsersSubscriptionViewModel,
buildPlansList,
promises: {
buildUsersSubscriptionViewModel: promisify(buildUsersSubscriptionViewModel),
},
}
| overleaf/web/app/src/Features/Subscription/SubscriptionViewModelBuilder.js/0 | {
"file_path": "overleaf/web/app/src/Features/Subscription/SubscriptionViewModelBuilder.js",
"repo_id": "overleaf",
"token_count": 4949
} | 466 |
const Settings = require('@overleaf/settings')
const request = require('request-promise-native')
async function getQueues(userId) {
return request({
uri: `${Settings.apis.tpdsworker.url}/queues/${userId}`,
json: true,
})
}
module.exports = {
promises: {
getQueues,
},
}
| overleaf/web/app/src/Features/ThirdPartyDataStore/TpdsQueueManager.js/0 | {
"file_path": "overleaf/web/app/src/Features/ThirdPartyDataStore/TpdsQueueManager.js",
"repo_id": "overleaf",
"token_count": 111
} | 467 |
const OError = require('@overleaf/o-error')
const { User } = require('../../models/User')
const { callbackify } = require('util')
const MAX_AUDIT_LOG_ENTRIES = 200
function _canHaveNoInitiatorId(operation, info) {
if (operation === 'reset-password') return true
if (operation === 'unlink-sso' && info.providerId === 'collabratec')
return true
}
/**
* Add an audit log entry
*
* The entry should include at least the following fields:
*
* - userId: the user on behalf of whom the operation was performed
* - operation: a string identifying the type of operation
* - initiatorId: who performed the operation
* - ipAddress: the IP address of the initiator
* - info: an object detailing what happened
*/
async function addEntry(userId, operation, initiatorId, ipAddress, info = {}) {
if (!operation || !ipAddress)
throw new OError('missing required audit log data', {
operation,
initiatorId,
ipAddress,
})
if (!initiatorId && !_canHaveNoInitiatorId(operation, info)) {
throw new OError('missing initiatorId for audit log', {
operation,
ipAddress,
})
}
const timestamp = new Date()
const entry = {
operation,
initiatorId,
info,
ipAddress,
timestamp,
}
const result = await User.updateOne(
{ _id: userId },
{
$push: {
auditLog: { $each: [entry], $slice: -MAX_AUDIT_LOG_ENTRIES },
},
}
).exec()
if (result.nModified === 0) {
throw new OError('user not found', { userId })
}
}
const UserAuditLogHandler = {
addEntry: callbackify(addEntry),
promises: {
addEntry,
},
}
module.exports = UserAuditLogHandler
| overleaf/web/app/src/Features/User/UserAuditLogHandler.js/0 | {
"file_path": "overleaf/web/app/src/Features/User/UserAuditLogHandler.js",
"repo_id": "overleaf",
"token_count": 580
} | 468 |
const logger = require('logger-sharelatex')
const OError = require('@overleaf/o-error')
const { db } = require('../../infrastructure/mongodb')
const { normalizeQuery } = require('../Helpers/Mongo')
const metrics = require('@overleaf/metrics')
const async = require('async')
const { callbackify, promisify } = require('util')
const UserGetter = require('./UserGetter')
const {
addAffiliation,
removeAffiliation,
promises: InstitutionsAPIPromises,
} = require('../Institutions/InstitutionsAPI')
const Features = require('../../infrastructure/Features')
const FeaturesUpdater = require('../Subscription/FeaturesUpdater')
const EmailHandler = require('../Email/EmailHandler')
const EmailHelper = require('../Helpers/EmailHelper')
const Errors = require('../Errors/Errors')
const NewsletterManager = require('../Newsletter/NewsletterManager')
const RecurlyWrapper = require('../Subscription/RecurlyWrapper')
const UserAuditLogHandler = require('./UserAuditLogHandler')
async function _sendSecurityAlertPrimaryEmailChanged(userId, oldEmail, email) {
// send email to both old and new primary email
const emailOptions = {
actionDescribed: `the primary email address on your account was changed to ${email}`,
action: 'change of primary email address',
}
const toOld = Object.assign({}, emailOptions, { to: oldEmail })
const toNew = Object.assign({}, emailOptions, { to: email })
try {
await EmailHandler.promises.sendEmail('securityAlert', toOld)
await EmailHandler.promises.sendEmail('securityAlert', toNew)
} catch (error) {
logger.error(
{ error, userId },
'could not send security alert email when primary email changed'
)
}
}
async function addEmailAddress(userId, newEmail, affiliationOptions, auditLog) {
newEmail = EmailHelper.parseEmail(newEmail)
if (!newEmail) {
throw new Error('invalid email')
}
await UserGetter.promises.ensureUniqueEmailAddress(newEmail)
await UserAuditLogHandler.promises.addEntry(
userId,
'add-email',
auditLog.initiatorId,
auditLog.ipAddress,
{
newSecondaryEmail: newEmail,
}
)
try {
await InstitutionsAPIPromises.addAffiliation(
userId,
newEmail,
affiliationOptions
)
} catch (error) {
throw OError.tag(error, 'problem adding affiliation while adding email')
}
try {
const reversedHostname = newEmail.split('@')[1].split('').reverse().join('')
const update = {
$push: {
emails: { email: newEmail, createdAt: new Date(), reversedHostname },
},
}
await UserUpdater.promises.updateUser(userId, update)
} catch (error) {
throw OError.tag(error, 'problem updating users emails')
}
}
async function clearSAMLData(userId, auditLog, sendEmail) {
const user = await UserGetter.promises.getUser(userId, {
email: 1,
emails: 1,
})
await UserAuditLogHandler.promises.addEntry(
userId,
'clear-institution-sso-data',
auditLog.initiatorId,
auditLog.ipAddress,
{}
)
const update = {
$unset: {
samlIdentifiers: 1,
'emails.$[].samlProviderId': 1,
},
}
await UserUpdater.promises.updateUser(userId, update)
for (const emailData of user.emails) {
await InstitutionsAPIPromises.removeEntitlement(userId, emailData.email)
}
await FeaturesUpdater.promises.refreshFeatures(
userId,
'clear-institution-sso-data'
)
if (sendEmail) {
await EmailHandler.promises.sendEmail('SAMLDataCleared', { to: user.email })
}
}
async function setDefaultEmailAddress(
userId,
email,
allowUnconfirmed,
auditLog,
sendSecurityAlert
) {
email = EmailHelper.parseEmail(email)
if (email == null) {
throw new Error('invalid email')
}
const user = await UserGetter.promises.getUser(userId, {
email: 1,
emails: 1,
})
if (!user) {
throw new Error('invalid userId')
}
const oldEmail = user.email
const userEmail = user.emails.find(e => e.email === email)
if (!userEmail) {
throw new Error('Default email does not belong to user')
}
if (!userEmail.confirmedAt && !allowUnconfirmed) {
throw new Errors.UnconfirmedEmailError()
}
await UserAuditLogHandler.promises.addEntry(
userId,
'change-primary-email',
auditLog.initiatorId,
auditLog.ipAddress,
{
newPrimaryEmail: email,
oldPrimaryEmail: oldEmail,
}
)
const query = { _id: userId, 'emails.email': email }
const update = { $set: { email } }
const res = await UserUpdater.promises.updateUser(query, update)
// this should not happen
if (res.n === 0) {
throw new Error('email update error')
}
if (sendSecurityAlert) {
// no need to wait, errors are logged and not passed back
_sendSecurityAlertPrimaryEmailChanged(userId, oldEmail, email)
}
try {
await NewsletterManager.promises.changeEmail(user, email)
} catch (error) {
logger.warn(
{ err: error, oldEmail, newEmail: email },
'Failed to change email in newsletter subscription'
)
}
try {
await RecurlyWrapper.promises.updateAccountEmailAddress(user._id, email)
} catch (error) {
// errors are ignored
}
}
async function confirmEmail(userId, email) {
// used for initial email confirmation (non-SSO and SSO)
// also used for reconfirmation of non-SSO emails
const confirmedAt = new Date()
email = EmailHelper.parseEmail(email)
if (email == null) {
throw new Error('invalid email')
}
logger.log({ userId, email }, 'confirming user email')
try {
await InstitutionsAPIPromises.addAffiliation(userId, email, { confirmedAt })
} catch (error) {
throw OError.tag(error, 'problem adding affiliation while confirming email')
}
const query = {
_id: userId,
'emails.email': email,
}
// only update confirmedAt if it was not previously set
const update = {
$set: {
'emails.$.reconfirmedAt': confirmedAt,
},
$min: {
'emails.$.confirmedAt': confirmedAt,
},
}
if (Features.hasFeature('affiliations')) {
update.$unset = {
'emails.$.affiliationUnchecked': 1,
}
}
const res = await UserUpdater.promises.updateUser(query, update)
if (res.n === 0) {
throw new Errors.NotFoundError('user id and email do no match')
}
await FeaturesUpdater.promises.refreshFeatures(userId, 'confirm-email')
}
const UserUpdater = {
addAffiliationForNewUser(userId, email, affiliationOptions, callback) {
if (callback == null) {
// affiliationOptions is optional
callback = affiliationOptions
affiliationOptions = {}
}
addAffiliation(userId, email, affiliationOptions, error => {
if (error) {
return callback(error)
}
UserUpdater.updateUser(
{ _id: userId, 'emails.email': email },
{ $unset: { 'emails.$.affiliationUnchecked': 1 } },
error => {
if (error) {
callback(
OError.tag(
error,
'could not remove affiliationUnchecked flag for user on create',
{
userId,
email,
}
)
)
} else {
callback()
}
}
)
})
},
updateUser(query, update, callback) {
if (callback == null) {
callback = () => {}
}
try {
query = normalizeQuery(query)
} catch (err) {
return callback(err)
}
db.users.updateOne(query, update, callback)
},
//
// DEPRECATED
//
// Change the user's main email address by adding a new email, switching the
// default email and removing the old email. Prefer manipulating multiple
// emails and the default rather than calling this method directly
//
changeEmailAddress(userId, newEmail, auditLog, callback) {
newEmail = EmailHelper.parseEmail(newEmail)
if (newEmail == null) {
return callback(new Error('invalid email'))
}
let oldEmail = null
async.series(
[
cb =>
UserGetter.getUserEmail(userId, (error, email) => {
oldEmail = email
cb(error)
}),
cb => UserUpdater.addEmailAddress(userId, newEmail, {}, auditLog, cb),
cb =>
UserUpdater.setDefaultEmailAddress(
userId,
newEmail,
true,
auditLog,
true,
cb
),
cb => UserUpdater.removeEmailAddress(userId, oldEmail, cb),
],
callback
)
},
// Add a new email address for the user. Email cannot be already used by this
// or any other user
addEmailAddress: callbackify(addEmailAddress),
// remove one of the user's email addresses. The email cannot be the user's
// default email address
removeEmailAddress(userId, email, callback) {
email = EmailHelper.parseEmail(email)
if (email == null) {
return callback(new Error('invalid email'))
}
removeAffiliation(userId, email, error => {
if (error != null) {
OError.tag(error, 'problem removing affiliation')
return callback(error)
}
const query = { _id: userId, email: { $ne: email } }
const update = { $pull: { emails: { email } } }
UserUpdater.updateUser(query, update, (error, res) => {
if (error != null) {
OError.tag(error, 'problem removing users email')
return callback(error)
}
if (res.n === 0) {
return callback(new Error('Cannot remove email'))
}
FeaturesUpdater.refreshFeatures(userId, 'remove-email', callback)
})
})
},
clearSAMLData: callbackify(clearSAMLData),
// set the default email address by setting the `email` attribute. The email
// must be one of the user's multiple emails (`emails` attribute)
setDefaultEmailAddress: callbackify(setDefaultEmailAddress),
confirmEmail: callbackify(confirmEmail),
removeReconfirmFlag(userId, callback) {
UserUpdater.updateUser(
userId.toString(),
{
$set: { must_reconfirm: false },
},
error => callback(error)
)
},
}
;[
'updateUser',
'changeEmailAddress',
'setDefaultEmailAddress',
'addEmailAddress',
'removeEmailAddress',
'removeReconfirmFlag',
].map(method =>
metrics.timeAsyncMethod(UserUpdater, method, 'mongo.UserUpdater', logger)
)
const promises = {
addAffiliationForNewUser: promisify(UserUpdater.addAffiliationForNewUser),
addEmailAddress,
confirmEmail,
setDefaultEmailAddress,
updateUser: promisify(UserUpdater.updateUser),
removeReconfirmFlag: promisify(UserUpdater.removeReconfirmFlag),
}
UserUpdater.promises = promises
module.exports = UserUpdater
| overleaf/web/app/src/Features/User/UserUpdater.js/0 | {
"file_path": "overleaf/web/app/src/Features/User/UserUpdater.js",
"repo_id": "overleaf",
"token_count": 4006
} | 469 |
/* eslint-disable
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
*/
const fs = require('fs')
const OError = require('@overleaf/o-error')
const logger = require('logger-sharelatex')
const uuid = require('uuid')
const _ = require('underscore')
const Settings = require('@overleaf/settings')
const request = require('request')
const { Transform, pipeline } = require('stream')
const { FileTooLargeError } = require('../Features/Errors/Errors')
const { promisifyAll } = require('../util/promises')
class SizeLimitedStream extends Transform {
constructor(options) {
options.autoDestroy = true
super(options)
this.bytes = 0
this.maxSizeBytes = options.maxSizeBytes
this.drain = false
this.on('error', () => {
this.drain = true
this.resume()
})
}
_transform(chunk, encoding, done) {
if (this.drain) {
// mechanism to drain the source stream on error, to avoid leaks
// we consume the rest of the incoming stream and don't push it anywhere
return done()
}
this.bytes += chunk.length
if (this.maxSizeBytes && this.bytes > this.maxSizeBytes) {
return done(
new FileTooLargeError({
message: 'stream size limit reached',
info: { size: this.bytes },
})
)
}
this.push(chunk)
done()
}
}
const FileWriter = {
ensureDumpFolderExists(callback) {
if (callback == null) {
callback = function (error) {}
}
return fs.mkdir(Settings.path.dumpFolder, function (error) {
if (error != null && error.code !== 'EEXIST') {
// Ignore error about already existing
return callback(error)
}
return callback(null)
})
},
writeLinesToDisk(identifier, lines, callback) {
if (callback == null) {
callback = function (error, fsPath) {}
}
return FileWriter.writeContentToDisk(identifier, lines.join('\n'), callback)
},
writeContentToDisk(identifier, content, callback) {
if (callback == null) {
callback = function (error, fsPath) {}
}
callback = _.once(callback)
const fsPath = `${Settings.path.dumpFolder}/${identifier}_${uuid.v4()}`
return FileWriter.ensureDumpFolderExists(function (error) {
if (error != null) {
return callback(error)
}
return fs.writeFile(fsPath, content, function (error) {
if (error != null) {
return callback(error)
}
return callback(null, fsPath)
})
})
},
writeStreamToDisk(identifier, stream, options, callback) {
if (typeof options === 'function') {
callback = options
options = {}
}
if (callback == null) {
callback = function (error, fsPath) {}
}
options = options || {}
const fsPath = `${Settings.path.dumpFolder}/${identifier}_${uuid.v4()}`
stream.pause()
FileWriter.ensureDumpFolderExists(function (error) {
const writeStream = fs.createWriteStream(fsPath)
if (error != null) {
return callback(error)
}
stream.resume()
const passThrough = new SizeLimitedStream({
maxSizeBytes: options.maxSizeBytes,
})
// if writing fails, we want to consume the bytes from the source, to avoid leaks
for (const evt of ['error', 'close']) {
writeStream.on(evt, function () {
passThrough.unpipe(writeStream)
passThrough.resume()
})
}
pipeline(stream, passThrough, writeStream, function (err) {
if (
options.maxSizeBytes &&
passThrough.bytes >= options.maxSizeBytes &&
!(err instanceof FileTooLargeError)
) {
err = new FileTooLargeError({
message: 'stream size limit reached',
info: { size: passThrough.bytes },
}).withCause(err || {})
}
if (err) {
OError.tag(
err,
'[writeStreamToDisk] something went wrong writing the stream to disk',
{
identifier,
fsPath,
}
)
return callback(err)
}
logger.log(
{ identifier, fsPath },
'[writeStreamToDisk] write stream finished'
)
callback(null, fsPath)
})
})
},
writeUrlToDisk(identifier, url, options, callback) {
if (typeof options === 'function') {
callback = options
options = {}
}
if (callback == null) {
callback = function (error, fsPath) {}
}
options = options || {}
callback = _.once(callback)
const stream = request.get(url)
stream.on('error', function (err) {
logger.warn(
{ err, identifier, url },
'[writeUrlToDisk] something went wrong with writing to disk'
)
callback(err)
})
stream.on('response', function (response) {
if (response.statusCode >= 200 && response.statusCode < 300) {
FileWriter.writeStreamToDisk(identifier, stream, options, callback)
} else {
const err = new Error(`bad response from url: ${response.statusCode}`)
logger.warn({ err, identifier, url }, `[writeUrlToDisk] ${err.message}`)
return callback(err)
}
})
},
}
module.exports = FileWriter
module.exports.promises = promisifyAll(FileWriter)
module.exports.SizeLimitedStream = SizeLimitedStream
| overleaf/web/app/src/infrastructure/FileWriter.js/0 | {
"file_path": "overleaf/web/app/src/infrastructure/FileWriter.js",
"repo_id": "overleaf",
"token_count": 2247
} | 470 |
module.exports = {
acceptsJson(req) {
return req.accepts(['html', 'json']) === 'json'
},
}
| overleaf/web/app/src/infrastructure/RequestContentTypeDetection.js/0 | {
"file_path": "overleaf/web/app/src/infrastructure/RequestContentTypeDetection.js",
"repo_id": "overleaf",
"token_count": 42
} | 471 |
const mongoose = require('../infrastructure/Mongoose')
const { DocSchema } = require('./Doc')
const { FileSchema } = require('./File')
const { Schema } = mongoose
const FolderSchema = new Schema({
name: { type: String, default: 'new folder' },
})
FolderSchema.add({
docs: [DocSchema],
fileRefs: [FileSchema],
folders: [FolderSchema],
})
exports.Folder = mongoose.model('Folder', FolderSchema)
exports.FolderSchema = FolderSchema
| overleaf/web/app/src/models/Folder.js/0 | {
"file_path": "overleaf/web/app/src/models/Folder.js",
"repo_id": "overleaf",
"token_count": 153
} | 472 |
const Settings = require('@overleaf/settings')
const mongoose = require('../infrastructure/Mongoose')
const TokenGenerator = require('../Features/TokenGenerator/TokenGenerator')
const { Schema } = mongoose
const { ObjectId } = Schema
// See https://stackoverflow.com/questions/386294/what-is-the-maximum-length-of-a-valid-email-address/574698#574698
const MAX_EMAIL_LENGTH = 254
const AuditLogEntrySchema = new Schema({
_id: false,
info: { type: Object },
initiatorId: { type: Schema.Types.ObjectId },
ipAddress: { type: String },
operation: { type: String },
userId: { type: Schema.Types.ObjectId },
timestamp: { type: Date },
})
const UserSchema = new Schema({
email: { type: String, default: '', maxlength: MAX_EMAIL_LENGTH },
emails: [
{
email: { type: String, default: '', maxlength: MAX_EMAIL_LENGTH },
reversedHostname: { type: String, default: '' },
createdAt: {
type: Date,
default() {
return new Date()
},
},
confirmedAt: { type: Date },
samlProviderId: { type: String },
affiliationUnchecked: { type: Boolean },
reconfirmedAt: { type: Date },
},
],
first_name: { type: String, default: '' },
last_name: { type: String, default: '' },
role: { type: String, default: '' },
institution: { type: String, default: '' },
hashedPassword: String,
isAdmin: { type: Boolean, default: false },
staffAccess: {
publisherMetrics: { type: Boolean, default: false },
publisherManagement: { type: Boolean, default: false },
institutionMetrics: { type: Boolean, default: false },
institutionManagement: { type: Boolean, default: false },
groupMetrics: { type: Boolean, default: false },
groupManagement: { type: Boolean, default: false },
adminMetrics: { type: Boolean, default: false },
},
signUpDate: {
type: Date,
default() {
return new Date()
},
},
lastLoggedIn: { type: Date },
lastLoginIp: { type: String, default: '' },
loginCount: { type: Number, default: 0 },
holdingAccount: { type: Boolean, default: false },
ace: {
mode: { type: String, default: 'none' },
theme: { type: String, default: 'textmate' },
overallTheme: { type: String, default: '' },
fontSize: { type: Number, default: '12' },
autoComplete: { type: Boolean, default: true },
autoPairDelimiters: { type: Boolean, default: true },
spellCheckLanguage: { type: String, default: 'en' },
pdfViewer: { type: String, default: 'pdfjs' },
syntaxValidation: { type: Boolean },
fontFamily: { type: String },
lineHeight: { type: String },
},
features: {
collaborators: {
type: Number,
default: Settings.defaultFeatures.collaborators,
},
versioning: { type: Boolean, default: Settings.defaultFeatures.versioning },
dropbox: { type: Boolean, default: Settings.defaultFeatures.dropbox },
github: { type: Boolean, default: Settings.defaultFeatures.github },
gitBridge: { type: Boolean, default: Settings.defaultFeatures.gitBridge },
compileTimeout: {
type: Number,
default: Settings.defaultFeatures.compileTimeout,
},
compileGroup: {
type: String,
default: Settings.defaultFeatures.compileGroup,
},
templates: { type: Boolean, default: Settings.defaultFeatures.templates },
references: { type: Boolean, default: Settings.defaultFeatures.references },
trackChanges: {
type: Boolean,
default: Settings.defaultFeatures.trackChanges,
},
mendeley: { type: Boolean, default: Settings.defaultFeatures.mendeley },
zotero: { type: Boolean, default: Settings.defaultFeatures.zotero },
referencesSearch: {
type: Boolean,
default: Settings.defaultFeatures.referencesSearch,
},
},
featuresOverrides: [
{
createdAt: {
type: Date,
default() {
return new Date()
},
},
expiresAt: { type: Date },
note: { type: String },
features: {
collaborators: { type: Number },
versioning: { type: Boolean },
dropbox: { type: Boolean },
github: { type: Boolean },
gitBridge: { type: Boolean },
compileTimeout: { type: Number },
compileGroup: { type: String },
templates: { type: Boolean },
trackChanges: { type: Boolean },
mendeley: { type: Boolean },
zotero: { type: Boolean },
referencesSearch: { type: Boolean },
},
},
],
featuresUpdatedAt: { type: Date },
// when auto-merged from SL and must-reconfirm is set, we may end up using
// `sharelatexHashedPassword` to recover accounts...
sharelatexHashedPassword: String,
must_reconfirm: { type: Boolean, default: false },
referal_id: {
type: String,
default() {
return TokenGenerator.generateReferralId()
},
},
refered_users: [{ type: ObjectId, ref: 'User' }],
refered_user_count: { type: Number, default: 0 },
refProviders: {
// The actual values are managed by third-party-references.
mendeley: Schema.Types.Mixed,
zotero: Schema.Types.Mixed,
},
alphaProgram: { type: Boolean, default: false }, // experimental features
betaProgram: { type: Boolean, default: false },
overleaf: {
id: { type: Number },
accessToken: { type: String },
refreshToken: { type: String },
},
awareOfV2: { type: Boolean, default: false },
samlIdentifiers: { type: Array, default: [] },
thirdPartyIdentifiers: { type: Array, default: [] },
migratedAt: { type: Date },
twoFactorAuthentication: {
createdAt: { type: Date },
enrolledAt: { type: Date },
secret: { type: String },
},
onboardingEmailSentAt: { type: Date },
auditLog: [AuditLogEntrySchema],
splitTests: Schema.Types.Mixed,
})
exports.User = mongoose.model('User', UserSchema)
exports.UserSchema = UserSchema
| overleaf/web/app/src/models/User.js/0 | {
"file_path": "overleaf/web/app/src/models/User.js",
"repo_id": "overleaf",
"token_count": 2101
} | 473 |
extends ../layout
block content
.content.content-alt
.container
.row
.col-xs-12
.card
.page-header
h1 Admin Panel
tabset(bookmarkable-tabset ng-cloak)
tab(heading="System Messages" bookmarkable-tab="system-messages")
each message in systemMessages
.alert.alert-info.row-spaced(ng-non-bindable) #{message.content}
hr
form(method='post', action='/admin/messages')
input(name="_csrf", type="hidden", value=csrfToken)
.form-group
label(for="content")
input.form-control(name="content", type="text", placeholder="Message…", required)
button.btn.btn-primary(type="submit") Post Message
hr
form(method='post', action='/admin/messages/clear')
input(name="_csrf", type="hidden", value=csrfToken)
button.btn.btn-danger(type="submit") Clear all messages
tab(heading="Open Sockets" bookmarkable-tab="open-sockets")
.row-spaced
ul
each agents, url in openSockets
li(ng-non-bindable) #{url} - total : #{agents.length}
ul
each agent in agents
li(ng-non-bindable) #{agent}
tab(heading="Open/Close Editor" bookmarkable-tab="open-close-editor")
if hasFeature('saas')
| The "Open/Close Editor" feature is not available in SAAS.
else
.row-spaced
form(method='post',action='/admin/closeEditor')
input(name="_csrf", type="hidden", value=csrfToken)
button.btn.btn-danger(type="submit") Close Editor
p.small Will stop anyone opening the editor. Will NOT disconnect already connected users.
.row-spaced
form(method='post',action='/admin/disconnectAllUsers')
input(name="_csrf", type="hidden", value=csrfToken)
button.btn.btn-danger(type="submit") Disconnect all users
p.small Will force disconnect all users with the editor open. Make sure to close the editor first to avoid them reconnecting.
.row-spaced
form(method='post',action='/admin/openEditor')
input(name="_csrf", type="hidden", value=csrfToken)
button.btn.btn-danger(type="submit") Reopen Editor
p.small Will reopen the editor after closing.
if hasFeature('saas')
tab(heading="TPDS/Dropbox Management" bookmarkable-tab="tpds")
h3 Flush project to TPDS
.row
form.col-xs-6(method='post',action='/admin/flushProjectToTpds')
input(name="_csrf", type="hidden", value=csrfToken)
.form-group
label(for='project_id') project_id
input.form-control(type='text', name='project_id', placeholder='project_id', required)
.form-group
button.btn-primary.btn(type='submit') Flush
hr
h3 Poll Dropbox for user
.row
form.col-xs-6(method='post',action='/admin/pollDropboxForUser')
input(name="_csrf", type="hidden", value=csrfToken)
.form-group
label(for='user_id') user_id
input.form-control(type='text', name='user_id', placeholder='user_id', required)
.form-group
button.btn-primary.btn(type='submit') Poll
tab(heading="Advanced" bookmarkable-tab="advanced")
.row-spaced
form(method='post',action='/admin/unregisterServiceWorker')
input(name="_csrf", type="hidden", value=csrfToken)
button.btn.btn-danger(type="submit") Unregister service worker
p.small Will force service worker reload for all users with the editor open.
| overleaf/web/app/views/admin/index.pug/0 | {
"file_path": "overleaf/web/app/views/admin/index.pug",
"repo_id": "overleaf",
"token_count": 1659
} | 474 |
div.binary-file-header
// Linked Files: URL
div(ng-if="openFile.linkedFileData.provider == 'url'")
p
i.fa.fa-fw.fa-external-link-square.fa-rotate-180.linked-file-icon
| Imported from
|
a(ng-href='{{openFile.linkedFileData.url}}') {{ displayUrl(openFile.linkedFileData.url) }}
|
| at {{ openFile.created | formatDate:'h:mm a' }} {{ openFile.created | relativeDate }}
// Linked Files: Project File
div(ng-if="openFile.linkedFileData.provider == 'project_file'")
p
i.fa.fa-fw.fa-external-link-square.fa-rotate-180.linked-file-icon
| Imported from
|
a(ng-if='!openFile.linkedFileData.v1_source_doc_id'
ng-href='/project/{{openFile.linkedFileData.source_project_id}}' target="_blank")
| Another project
span(ng-if='openFile.linkedFileData.v1_source_doc_id')
| Another project
| /{{ openFile.linkedFileData.source_entity_path.slice(1) }},
|
| at {{ openFile.created | formatDate:'h:mm a' }} {{ openFile.created | relativeDate }}
// Linked Files: Project Output File
div(ng-if="openFile.linkedFileData.provider == 'project_output_file'")
p
i.fa.fa-fw.fa-external-link-square.fa-rotate-180.linked-file-icon
| Imported from the output of
|
a(ng-if='!openFile.linkedFileData.v1_source_doc_id'
ng-href='/project/{{openFile.linkedFileData.source_project_id}}' target="_blank")
| Another project
span(ng-if='openFile.linkedFileData.v1_source_doc_id')
| Another project
| : {{ openFile.linkedFileData.source_output_file_path }},
|
| at {{ openFile.created | formatDate:'h:mm a' }} {{ openFile.created | relativeDate }}
!= moduleIncludes("binaryFile:linkedFileInfo", locals)
// Bottom Controls
span(ng-if="openFile.linkedFileData.provider")
button.btn.btn-success(
href, ng-click="refreshFile(openFile)",
ng-disabled="refreshing"
)
i.fa.fa-fw.fa-refresh(ng-class={'fa-spin': refreshing})
|
span(ng-show="!refreshing") Refresh
span(ng-show="refreshing") Refreshing…
|
a.btn.btn-info(
ng-href="/project/{{ project_id }}/file/{{ openFile.id }}"
)
i.fa.fa-fw.fa-download
|
| #{translate("download")}
// Refresh Error
div(ng-if="refreshError").row
br
.alert.alert-danger.col-md-6.col-md-offset-3
| Error: {{ refreshError}}
!= moduleIncludes("binaryFile:linkedFileRefreshError", locals)
| overleaf/web/app/views/project/editor/binary-file-header.pug/0 | {
"file_path": "overleaf/web/app/views/project/editor/binary-file-header.pug",
"repo_id": "overleaf",
"token_count": 1037
} | 475 |
.history-toolbar(
ng-controller="HistoryV2ToolbarController"
ng-if="ui.view == 'history' && history.isV2"
)
span.history-toolbar-selected-version(ng-show="history.loadingFileTree")
i.fa.fa-spin.fa-refresh
| #{translate("loading")}…
//- point-in-time mode info
span.history-toolbar-selected-version(
ng-show="!history.loadingFileTree && history.viewMode === HistoryViewModes.POINT_IN_TIME && !history.showOnlyLabels && currentUpdate && !history.error"
) #{translate("browsing_project_as_of")}
time.history-toolbar-time {{ currentUpdate.meta.end_ts | formatDate:'Do MMM YYYY, h:mm a' }}
span.history-toolbar-selected-version(
ng-show="!history.loadingFileTree && history.viewMode === HistoryViewModes.POINT_IN_TIME && history.showOnlyLabels && currentUpdate && !history.error"
)
span(ng-if="currentUpdate.labels.length > 0")
| #{translate("browsing_project_labelled")}
span.history-toolbar-selected-label(
ng-repeat="label in currentUpdate.labels"
)
| {{ label.comment }}
span(ng-if="!$last") ,
span.history-toolbar-selected-label(ng-if="currentUpdate.labels.length === 0 && history.labels[0].isPseudoCurrentStateLabel && currentUpdate.toV === history.labels[0].version")
| #{translate("browsing_project_latest_for_pseudo_label")}
//- compare mode info
span.history-toolbar-selected-version(ng-if="history.viewMode === HistoryViewModes.COMPARE && history.selection.diff && !history.selection.diff.binary && !history.selection.diff.loading && !history.selection.diff.error && !history.loadingFileTree")
| <strong>{{history.selection.diff.highlights.length}} </strong>
ng-pluralize(
count="history.selection.diff.highlights.length",
when="{\
'one': 'change',\
'other': 'changes'\
}"
)
| in <strong>{{history.selection.diff.pathname}}</strong>
//- point-in-time mode actions
div.history-toolbar-actions(
ng-if="history.viewMode === HistoryViewModes.POINT_IN_TIME && !history.error && history.updates.length > 0"
)
button.history-toolbar-btn(
ng-click="showAddLabelDialog();"
ng-if="!history.showOnlyLabels && permissions.write"
ng-disabled="isHistoryLoading() || history.selection.range.toV == null || history.selection.range.fromV == null"
)
i.fa.fa-tag
| #{translate("history_label_this_version")}
button.history-toolbar-btn(
ng-click="toggleHistoryViewMode();"
ng-disabled="isHistoryLoading()"
)
i.fa.fa-exchange
| #{translate("compare_to_another_version")}
a.history-toolbar-btn-danger.pull-right(
ng-hide="history.loadingFileTree || history.selection.range.toV == null"
ng-href="/project/{{ project_id }}/version/{{ history.selection.range.toV }}/zip"
target="_blank"
)
i.fa.fa-download
| #{translate("download_project_at_this_version")}
//- compare mode actions
div.history-toolbar-actions(
ng-if="history.viewMode === HistoryViewModes.COMPARE && !history.error && history.updates.length > 0"
)
button.history-toolbar-btn(
ng-click="toggleHistoryViewMode();"
ng-disabled="isHistoryLoading()"
)
i.fa
| #{translate("view_single_version")}
button.history-toolbar-btn-danger.pull-right(
ng-if="history.selection.file.deletedAtV"
ng-click="restoreDeletedFile()"
ng-show="!restoreState.error"
ng-disabled="restoreState.inflight"
)
i.fa.fa-fw.fa-step-backward
span(ng-show="!restoreState.inflight")
| Restore this deleted file
span(ng-show="restoreState.inflight")
| Restoring…
span.text-danger(ng-show="restoreState.error")
| Error restoring, sorry
.history-toolbar-entries-list(
ng-if="!history.error && history.updates.length > 0"
)
toggle-switch(
ng-model="toolbarUIConfig.showOnlyLabels"
label-true=translate("history_view_labels")
label-false=translate("history_view_all")
description=translate("history_view_a11y_description")
)
script(type="text/ng-template", id="historyV2AddLabelModalTemplate")
form(
name="addLabelModalForm"
ng-submit="addLabelModalFormSubmit();"
novalidate
)
.modal-header
h3 #{translate("history_add_label")}
.modal-body
.alert.alert-danger(ng-show="state.error.message") {{ state.error.message}}
.alert.alert-danger(ng-show="state.error && !state.error.message") #{translate("generic_something_went_wrong")}
.form-group
input.form-control(
type="text"
placeholder=translate("history_new_label_name")
ng-model="inputs.labelName"
focus-on="open"
required
)
p.help-block(ng-if="update")
| #{translate("history_new_label_added_at")}
strong {{ update.meta.end_ts | formatDate:'ddd Do MMM YYYY, h:mm a' }}
.modal-footer
button.btn.btn-default(
type="button"
ng-disabled="state.inflight"
ng-click="$dismiss()"
) #{translate("cancel")}
input.btn.btn-primary(
ng-disabled="addLabelModalForm.$invalid || state.inflight"
ng-value="state.inflight ? '" + translate("history_adding_label") + "' : '" + translate("history_add_label") + "'"
type="submit"
)
| overleaf/web/app/views/project/editor/history/toolbarV2.pug/0 | {
"file_path": "overleaf/web/app/views/project/editor/history/toolbarV2.pug",
"repo_id": "overleaf",
"token_count": 1989
} | 476 |
.row
.col-xs-12(ng-cloak)
form.project-search.form-horizontal(role="form")
.form-group.has-feedback.has-feedback-left.col-md-7.col-xs-12
input.form-control.col-md-7.col-xs-12(
placeholder=translate('search_projects')+"…",
aria-label=translate('search_projects')+"…",
autofocus='autofocus',
ng-model="searchText.value",
focus-on='search:clear',
ng-keyup="searchProjects()"
)
i.fa.fa-search.form-control-feedback-left(aria-hidden="true")
i.fa.fa-times.form-control-feedback(
ng-click="clearSearchText()",
style="cursor: pointer;",
ng-show="searchText.value.length > 0"
aria-hidden="true"
)
button.sr-only(
type="button"
ng-click="clearSearchText()"
ng-show="searchText.value.length > 0"
) #{translate('clear_search')}
.project-tools(ng-cloak)
.btn-toolbar
.btn-group(ng-hide="selectedProjects.length < 1")
a.btn.btn-default(
href,
aria-label=translate('download'),
tooltip=translate('download'),
tooltip-placement="bottom",
tooltip-append-to-body="true",
ng-click="downloadSelectedProjects()"
)
i.fa.fa-cloud-download(aria-hidden="true")
a.btn.btn-default(
href,
ng-if="filter !== 'archived'"
aria-label=translate("archive"),
tooltip=translate("archive"),
tooltip-placement="bottom",
tooltip-append-to-body="true",
ng-click="openArchiveProjectsModal()"
)
i.fa.fa-inbox(aria-hidden="true")
a.btn.btn-default(
href,
ng-if="filter !== 'trashed'"
aria-label=translate("trash"),
tooltip=translate("trash"),
tooltip-placement="bottom",
tooltip-append-to-body="true",
ng-click="openTrashProjectsModal()"
)
i.fa.fa-trash(aria-hidden="true")
.btn-group.dropdown(
ng-hide="selectedProjects.length < 1 || filter === 'archived' || filter === 'trashed'",
dropdown
)
a.btn.btn-default.dropdown-toggle(
href,
data-toggle="dropdown",
dropdown-toggle,
tooltip=translate('add_to_folders'),
tooltip-append-to-body="true",
tooltip-placement="bottom"
)
i.fa.fa-folder-open
|
span.caret
span.sr-only #{translate('add_to_folders')}
ul.dropdown-menu.dropdown-menu-right.js-tags-dropdown-menu.tags-dropdown-menu(
role="menu"
ng-controller="TagListController"
)
li.dropdown-header #{translate("add_to_folder")}
li(
ng-repeat="tag in tags | orderBy:'name'",
ng-controller="TagDropdownItemController"
)
a(href="#", ng-click="addOrRemoveProjectsFromTag()", stop-propagation="click")
i.fa(
ng-class="{\
'fa-check-square-o': areSelectedProjectsInTag == true,\
'fa-square-o': areSelectedProjectsInTag == false,\
'fa-minus-square-o': areSelectedProjectsInTag == 'partial'\
}"
)
span.sr-only Add or remove project from tag
| {{tag.name}}
li.divider
li
a(href, ng-click="openNewTagModal()", stop-propagation="click") #{translate("create_new_folder")}
.btn-group.dropdown(
ng-hide="selectedProjects.length != 1 || filter === 'archived' || filter === 'trashed'",
dropdown
)
a.btn.btn-default.dropdown-toggle(
href,
data-toggle="dropdown",
dropdown-toggle
) #{translate("more")}
span.caret
ul.dropdown-menu.dropdown-menu-right(role="menu")
li(ng-show="getFirstSelectedProject().accessLevel == 'owner'")
a(
href,
ng-click="openRenameProjectModal()"
) #{translate("rename")}
li
a(
href,
ng-click="openCloneProjectModal(getFirstSelectedProject())"
) #{translate("make_copy")}
.btn-group(ng-show="filter === 'archived' && selectedProjects.length > 0")
a.btn.btn-default(
href,
data-original-title=translate("unarchive"),
data-toggle="tooltip",
data-placement="bottom",
ng-click="unarchiveProjects(selectedProjects)"
) #{translate("unarchive")}
.btn-group(ng-show="filter === 'trashed' && selectedProjects.length > 0")
a.btn.btn-default(
href,
data-original-title=translate("untrash"),
data-toggle="tooltip",
data-placement="bottom",
ng-click="untrashProjects(selectedProjects)"
) #{translate("untrash")}
.btn-group(ng-show="filter === 'trashed' && selectedProjects.length > 0")
a.btn.btn-danger(
href,
ng-if="hasLeavableProjectsSelected() && !hasDeletableProjectsSelected()",
data-original-title=translate('leave'),
data-toggle="tooltip",
data-placement="bottom",
ng-click="openLeaveProjectsModal()"
) #{translate("leave")}
a.btn.btn-danger(
href,
ng-if="hasDeletableProjectsSelected() && !hasLeavableProjectsSelected()",
data-original-title=translate('delete'),
data-toggle="tooltip",
data-placement="bottom",
ng-click="openDeleteProjectsModal()"
) #{translate("delete")}
a.btn.btn-danger(
href,
ng-if="hasDeletableProjectsSelected() && hasLeavableProjectsSelected()",
data-original-title=translate('delete_and_leave'),
data-toggle="tooltip",
data-placement="bottom",
ng-click="openLeaveOrDeleteProjectsModal()"
) #{translate("delete_and_leave")}
.row.row-spaced
.col-xs-12
.card.card-thin.project-list-card
ul.list-unstyled.project-list.structured-list(
select-all-list,
ng-if="projects.length > 0",
max-height="projectListHeight - 25",
ng-cloak
)
table.project-list-table
tr.project-list-table-header-row
th.project-list-table-name-cell
.project-list-table-name-container
input.project-list-table-select-item(
select-all,
type="checkbox"
aria-label=translate('select_all_projects')
)
span.header.clickable.project-list-table-name(ng-click="changePredicate('name')") #{translate("title")}
i.tablesort.fa(ng-class="getSortIconClass('name')" aria-hidden="true")
button.sr-only(ng-click="changePredicate('name')") Sort by #{translate("title")}
th.project-list-table-owner-cell
span.header.clickable(ng-click="changePredicate('ownerName')") #{translate("owner")}
i.tablesort.fa(ng-class="getSortIconClass('ownerName')" aria-hidden="true")
button.sr-only(ng-click="changePredicate('ownerName')") Sort by #{translate("owner")}
th.project-list-table-lastupdated-cell
span.header.clickable(ng-click="changePredicate('lastUpdated')") #{translate("last_modified")}
i.tablesort.fa(ng-class="getSortIconClass('lastUpdated')" aria-hidden="true")
button.sr-only(ng-click="changePredicate('lastUpdated')") Sort by #{translate("last_modified")}
th.project-list-table-actions-cell
span.header #{translate("actions")}
tr.project-list-table-row(
ng-repeat="project in visibleProjects | orderBy:getValueForCurrentPredicate:reverse:comparator",
ng-controller="ProjectListItemController"
select-row
)
include ./item
tr(
ng-if="visibleProjects.length == 0",
ng-cloak
)
td(colspan="4").project-list-table-no-projects-cell
span.small #{translate("no_projects")}
div.welcome.text-centered(ng-if="projects.length == 0", ng-cloak)
h2 #{translate("welcome_to_sl")}
p #{translate("new_to_latex_look_at")}
a(href="/templates") #{translate("templates").toLowerCase()}
| #{translate("or")}
a(href="/learn") #{translate("latex_help_guide")}
| ,
br
| #{translate("or_create_project_left")}
| overleaf/web/app/views/project/list/project-list.pug/0 | {
"file_path": "overleaf/web/app/views/project/list/project-list.pug",
"repo_id": "overleaf",
"token_count": 3607
} | 477 |
each institution in managedInstitutions
p
| You are a manager of
|
strong(ng-non-bindable)= institution.name
p
a.btn.btn-primary(href="/metrics/institutions/" + institution.v1Id)
i.fa.fa-fw.fa-line-chart
|
| View metrics
p
a(href="/institutions/" + institution.v1Id + "/hub")
i.fa.fa-fw.fa-user-circle
|
| View hub
p
a(href="/manage/institutions/" + institution.v1Id + "/managers")
i.fa.fa-fw.fa-users
|
| Manage institution managers
div(ng-controller="MetricsEmailController", ng-cloak)
p
span Monthly metrics emails:
a(href ng-bind-html="institutionEmailSubscription('"+institution.v1Id+"')" ng-show="!subscriptionChanging" ng-click="changeInstitutionalEmailSubscription('"+institution.v1Id+"')")
span(ng-show="subscriptionChanging")
i.fa.fa-spin.fa-refresh(aria-hidden="true")
hr
| overleaf/web/app/views/subscriptions/dashboard/_managed_institutions.pug/0 | {
"file_path": "overleaf/web/app/views/subscriptions/dashboard/_managed_institutions.pug",
"repo_id": "overleaf",
"token_count": 358
} | 478 |
extends ../layout
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 #{translate("confirm_email")}
form(
async-form="confirm-email",
name="confirmEmailForm"
action="/user/emails/confirm",
method="POST",
id="confirmEmailForm",
auto-submit="true",
ng-cloak
)
input(type="hidden", name="_csrf", value=csrfToken)
input(type="hidden", name="token", value=token ng-non-bindable)
form-messages(for="confirmEmailForm")
.alert.alert-success(ng-show="confirmEmailForm.response.success")
| Thank you, your email is now confirmed
p.text-center(ng-show="!confirmEmailForm.response.success && !confirmEmailForm.response.error")
i.fa.fa-fw.fa-spin.fa-spinner(aria-hidden="true")
|
| Confirming your email…
| overleaf/web/app/views/user/confirm_email.pug/0 | {
"file_path": "overleaf/web/app/views/user/confirm_email.pug",
"repo_id": "overleaf",
"token_count": 447
} | 479 |
{
"presets": [
[
"@babel/react",
{
"runtime": "automatic"
}
],
[
"@babel/env",
{
"useBuiltIns": "usage",
"corejs": { "version": 3 }
}
]
],
"plugins": ["angularjs-annotate", "macros"],
// Target our current Node version in test environment, to transform and
// polyfill only what's necessary
"env": {
"test": {
"presets": [
[
"@babel/react",
{
"runtime": "automatic"
}
],
[
"@babel/env",
{
"targets": { "node": "12.21" },
"useBuiltIns": "usage",
"corejs": { "version": 3 }
}
]
]
}
}
}
| overleaf/web/babel.config.json/0 | {
"file_path": "overleaf/web/babel.config.json",
"repo_id": "overleaf",
"token_count": 413
} | 480 |
version: "2.3"
volumes:
data:
services:
test_unit:
build: .
image: ci/$PROJECT_NAME:$BRANCH_NAME-$BUILD_NUMBER
user: node
command: npm run test:unit:app
environment:
BASE_CONFIG:
SHARELATEX_CONFIG:
NODE_OPTIONS: "--unhandled-rejections=strict"
test_acceptance:
build: .
image: ci/$PROJECT_NAME:$BRANCH_NAME-$BUILD_NUMBER
working_dir: /app
env_file: docker-compose.common.env
environment:
BASE_CONFIG:
SHARELATEX_CONFIG:
extra_hosts:
- 'www.overleaf.test:127.0.0.1'
command: npm run test:acceptance:app
user: root
depends_on:
- redis
- mongo
- saml
- ldap
test_karma:
build:
context: .
dockerfile: Dockerfile.frontend.ci
args:
PROJECT_NAME: $PROJECT_NAME
BRANCH_NAME: $BRANCH_NAME
BUILD_NUMBER: $BUILD_NUMBER
working_dir: /app
command: npm run test:karma:single
user: node
environment:
NODE_OPTIONS: "--unhandled-rejections=strict"
test_frontend:
build: .
image: ci/$PROJECT_NAME:$BRANCH_NAME-$BUILD_NUMBER
user: node
command: npm run test:frontend
environment:
NODE_OPTIONS: "--unhandled-rejections=strict"
tar:
image: ci/$PROJECT_NAME:$BRANCH_NAME-$BUILD_NUMBER-webpack
volumes:
- ./:/tmp/build/
command: tar -cf /tmp/build/build.tar public/
user: root
redis:
image: redis
mongo:
image: mongo:4.0.19
ldap:
restart: always
image: rroemhild/test-openldap:1.1
saml:
restart: always
image: gcr.io/overleaf-ops/saml-test
environment:
SAML_BASE_URL_PATH: 'http://saml/simplesaml/'
SAML_TEST_SP_ENTITY_ID: 'sharelatex-test-saml'
SAML_TEST_SP_LOCATION: 'http://www.overleaf.test:3000/saml/callback'
| overleaf/web/docker-compose.ci.yml/0 | {
"file_path": "overleaf/web/docker-compose.ci.yml",
"repo_id": "overleaf",
"token_count": 877
} | 481 |
import _ from 'lodash'
/* global MathJax */
import App from '../base'
export default App.directive('mathjax', function ($compile, $parse) {
return {
link(scope, element, attrs) {
if (!(MathJax && MathJax.Hub)) return
if (attrs.delimiter !== 'no-single-dollar') {
const inlineMathConfig =
MathJax.Hub.config && MathJax.Hub.config.tex2jax.inlineMath
const alreadyConfigured = _.find(
inlineMathConfig,
c => c[0] === '$' && c[1] === '$'
)
if (!alreadyConfigured) {
MathJax.Hub.Config({
tex2jax: {
inlineMath: inlineMathConfig.concat([['$', '$']]),
},
})
}
}
setTimeout(() => {
MathJax.Hub.Queue(['Typeset', MathJax.Hub, element.get(0)])
}, 0)
},
}
})
| overleaf/web/frontend/js/directives/mathjax.js/0 | {
"file_path": "overleaf/web/frontend/js/directives/mathjax.js",
"repo_id": "overleaf",
"token_count": 412
} | 482 |
import App from '../../../base'
import { react2angular } from 'react2angular'
import { rootContext } from '../../../shared/context/root-context'
import ChatPane from '../components/chat-pane'
App.controller('ReactChatController', function ($scope, ide) {
$scope.chatIsOpen = ide.$scope.ui.chatOpen
ide.$scope.$watch('ui.chatOpen', newValue => {
$scope.$applyAsync(() => {
$scope.chatIsOpen = newValue
})
})
$scope.resetUnreadMessages = () =>
ide.$scope.$broadcast('chat:resetUnreadMessages')
})
App.component(
'chat',
react2angular(rootContext.use(ChatPane), [
'resetUnreadMessages',
'chatIsOpen',
])
)
| overleaf/web/frontend/js/features/chat/controllers/chat-controller.js/0 | {
"file_path": "overleaf/web/frontend/js/features/chat/controllers/chat-controller.js",
"repo_id": "overleaf",
"token_count": 233
} | 483 |
import React from 'react'
import PropTypes from 'prop-types'
import MenuButton from './menu-button'
import CobrandingLogo from './cobranding-logo'
import BackToProjectsButton from './back-to-projects-button'
import ChatToggleButton from './chat-toggle-button'
import OnlineUsersWidget from './online-users-widget'
import ProjectNameEditableLabel from './project-name-editable-label'
import TrackChangesToggleButton from './track-changes-toggle-button'
import HistoryToggleButton from './history-toggle-button'
import ShareProjectButton from './share-project-button'
import PdfToggleButton from './pdf-toggle-button'
import importOverleafModules from '../../../../macros/import-overleaf-module.macro'
const [publishModalModules] = importOverleafModules('publishModal')
const PublishButton = publishModalModules?.import.default
const ToolbarHeader = React.memo(function ToolbarHeader({
cobranding,
onShowLeftMenuClick,
chatIsOpen,
toggleChatOpen,
reviewPanelOpen,
toggleReviewPanelOpen,
historyIsOpen,
toggleHistoryOpen,
unreadMessageCount,
onlineUsers,
goToUser,
isRestrictedTokenMember,
hasPublishPermissions,
projectName,
renameProject,
hasRenamePermissions,
openShareModal,
pdfViewIsOpen,
pdfButtonIsVisible,
togglePdfView,
}) {
const shouldDisplayPublishButton = hasPublishPermissions && PublishButton
return (
<header className="toolbar toolbar-header toolbar-with-labels">
<div className="toolbar-left">
<MenuButton onClick={onShowLeftMenuClick} />
{cobranding && cobranding.logoImgUrl && (
<CobrandingLogo {...cobranding} />
)}
<BackToProjectsButton />
</div>
{pdfButtonIsVisible && (
<PdfToggleButton
onClick={togglePdfView}
pdfViewIsOpen={pdfViewIsOpen}
/>
)}
<ProjectNameEditableLabel
className="toolbar-center"
projectName={projectName}
hasRenamePermissions={hasRenamePermissions}
onChange={renameProject}
/>
<div className="toolbar-right">
<OnlineUsersWidget onlineUsers={onlineUsers} goToUser={goToUser} />
{!isRestrictedTokenMember && (
<TrackChangesToggleButton
onClick={toggleReviewPanelOpen}
disabled={historyIsOpen}
trackChangesIsOpen={reviewPanelOpen}
/>
)}
<ShareProjectButton onClick={openShareModal} />
{shouldDisplayPublishButton && (
<PublishButton cobranding={cobranding} />
)}
{!isRestrictedTokenMember && (
<>
<HistoryToggleButton
historyIsOpen={historyIsOpen}
onClick={toggleHistoryOpen}
/>
<ChatToggleButton
chatIsOpen={chatIsOpen}
onClick={toggleChatOpen}
unreadMessageCount={unreadMessageCount}
/>
</>
)}
</div>
</header>
)
})
ToolbarHeader.propTypes = {
onShowLeftMenuClick: PropTypes.func.isRequired,
cobranding: PropTypes.object,
chatIsOpen: PropTypes.bool,
toggleChatOpen: PropTypes.func.isRequired,
reviewPanelOpen: PropTypes.bool,
toggleReviewPanelOpen: PropTypes.func.isRequired,
historyIsOpen: PropTypes.bool,
toggleHistoryOpen: PropTypes.func.isRequired,
unreadMessageCount: PropTypes.number.isRequired,
onlineUsers: PropTypes.array.isRequired,
goToUser: PropTypes.func.isRequired,
isRestrictedTokenMember: PropTypes.bool,
hasPublishPermissions: PropTypes.bool,
projectName: PropTypes.string.isRequired,
renameProject: PropTypes.func.isRequired,
hasRenamePermissions: PropTypes.bool,
openShareModal: PropTypes.func.isRequired,
pdfViewIsOpen: PropTypes.bool,
pdfButtonIsVisible: PropTypes.bool,
togglePdfView: PropTypes.func.isRequired,
}
export default ToolbarHeader
| overleaf/web/frontend/js/features/editor-navigation-toolbar/components/toolbar-header.js/0 | {
"file_path": "overleaf/web/frontend/js/features/editor-navigation-toolbar/components/toolbar-header.js",
"repo_id": "overleaf",
"token_count": 1476
} | 484 |
import PropTypes from 'prop-types'
import { useTranslation } from 'react-i18next'
import Icon from '../../../shared/components/icon'
import iconTypeFromName from '../util/icon-type-from-name'
import { useSelectableEntity } from '../contexts/file-tree-selectable'
import FileTreeItemInner from './file-tree-item/file-tree-item-inner'
function FileTreeDoc({ name, id, isLinkedFile }) {
const { t } = useTranslation()
const { isSelected, props: selectableEntityProps } = useSelectableEntity(id)
const icons = (
<>
<Icon
type={iconTypeFromName(name)}
modifier="fw"
classes={{ icon: 'spaced' }}
>
{isLinkedFile ? (
<Icon
type="external-link-square"
modifier="rotate-180"
classes={{ icon: 'linked-file-highlight' }}
accessibilityLabel={t('linked_file')}
/>
) : null}
</Icon>
</>
)
return (
<li
role="treeitem"
{...selectableEntityProps}
aria-label={name}
tabIndex="0"
>
<FileTreeItemInner
id={id}
name={name}
isSelected={isSelected}
icons={icons}
/>
</li>
)
}
FileTreeDoc.propTypes = {
name: PropTypes.string.isRequired,
id: PropTypes.string.isRequired,
isLinkedFile: PropTypes.bool,
}
export default FileTreeDoc
| overleaf/web/frontend/js/features/file-tree/components/file-tree-doc.js/0 | {
"file_path": "overleaf/web/frontend/js/features/file-tree/components/file-tree-doc.js",
"repo_id": "overleaf",
"token_count": 588
} | 485 |
import { createContext, useContext, useState } from 'react'
import PropTypes from 'prop-types'
const FileTreeCreateFormContext = createContext()
export const useFileTreeCreateForm = () => {
const context = useContext(FileTreeCreateFormContext)
if (!context) {
throw new Error(
'useFileTreeCreateForm is only available inside FileTreeCreateFormProvider'
)
}
return context
}
export default function FileTreeCreateFormProvider({ children }) {
// is the form valid
const [valid, setValid] = useState(false)
return (
<FileTreeCreateFormContext.Provider value={{ valid, setValid }}>
{children}
</FileTreeCreateFormContext.Provider>
)
}
FileTreeCreateFormProvider.propTypes = {
children: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.node),
PropTypes.node,
]).isRequired,
}
| overleaf/web/frontend/js/features/file-tree/contexts/file-tree-create-form.js/0 | {
"file_path": "overleaf/web/frontend/js/features/file-tree/contexts/file-tree-create-form.js",
"repo_id": "overleaf",
"token_count": 260
} | 486 |
import { findInTree } from '../util/find-in-tree'
export function isNameUniqueInFolder(tree, parentFolderId, name) {
if (tree._id !== parentFolderId) {
tree = findInTree(tree, parentFolderId).entity
}
if (tree.docs.some(entity => entity.name === name)) return false
if (tree.fileRefs.some(entity => entity.name === name)) return false
if (tree.folders.some(entity => entity.name === name)) return false
return true
}
| overleaf/web/frontend/js/features/file-tree/util/is-name-unique-in-folder.js/0 | {
"file_path": "overleaf/web/frontend/js/features/file-tree/util/is-name-unique-in-folder.js",
"repo_id": "overleaf",
"token_count": 140
} | 487 |
import './controllers/outline-controller'
import { matchOutline, nestOutline } from './outline-parser'
import isValidTeXFile from '../../main/is-valid-tex-file'
class OutlineManager {
constructor(ide, scope) {
this.ide = ide
this.scope = scope
this.shareJsDoc = null
this.isTexFile = false
this.flatOutline = []
this.outline = []
this.highlightedLine = null
this.ignoreNextScroll = false
this.ignoreNextCursorUpdate = false
scope.$on('doc:after-opened', (ev, { isNewDoc }) => {
if (isNewDoc) {
// if a new doc is opened a cursor updates will be triggered before the
// content is loaded. We have to ignore it or the outline highlight
// will be incorrect. This doesn't happen when `doc:after-opened` is
// fired without a new doc opened.
this.ignoreNextCursorUpdate = true
}
// always ignore the next scroll update so the cursor update takes
// precedence
this.ignoreNextScroll = true
this.shareJsDoc = scope.editor.sharejs_doc
this.isTexFile = isValidTeXFile(scope.editor.open_doc_name)
this.updateOutline()
this.broadcastChangeEvent()
})
scope.$watch('openFile.name', openFileName => {
this.isTexFile = isValidTeXFile(openFileName)
this.updateOutline()
this.broadcastChangeEvent()
})
scope.$on('doc:changed', () => {
this.updateOutline()
this.broadcastChangeEvent()
})
scope.$on('file-view:file-opened', () => {
this.isTexFile = false
this.updateOutline()
this.broadcastChangeEvent()
})
scope.$on('cursor:editor:update', (event, cursorPosition) => {
if (this.ignoreNextCursorUpdate) {
this.ignoreNextCursorUpdate = false
return
}
this.updateHighlightedLine(cursorPosition.row + 1)
this.broadcastChangeEvent()
})
scope.$on('scroll:editor:update', (event, middleVisibleRow) => {
if (this.ignoreNextScroll) {
this.ignoreNextScroll = false
return
}
this.updateHighlightedLine(middleVisibleRow + 1)
})
scope.$watch('editor.showRichText', () => {
this.ignoreNextScroll = true
this.ignoreNextCursorUpdate = true
})
}
updateOutline() {
this.outline = []
if (this.isTexFile) {
const content = this.ide.editorManager.getCurrentDocValue()
if (content) {
this.flatOutline = matchOutline(content)
this.outline = nestOutline(this.flatOutline)
}
}
}
// set highlightedLine to the closest outline line above the editorLine
updateHighlightedLine(editorLine) {
let closestOutlineLine = null
for (let lineId = 0; lineId < this.flatOutline.length; lineId++) {
const outline = this.flatOutline[lineId]
if (editorLine < outline.line) break // editorLine is above
closestOutlineLine = outline.line
}
if (closestOutlineLine === this.highlightedLine) return
this.highlightedLine = closestOutlineLine
this.broadcastChangeEvent()
}
jumpToLine(line, syncToPdf) {
this.ignoreNextScroll = true
this.ide.editorManager.jumpToLine({ gotoLine: line, syncToPdf })
}
broadcastChangeEvent() {
this.scope.$broadcast('outline-manager:outline-changed', {
isTexFile: this.isTexFile,
outline: this.outline,
highlightedLine: this.highlightedLine,
})
}
}
export default OutlineManager
| overleaf/web/frontend/js/features/outline/outline-manager.js/0 | {
"file_path": "overleaf/web/frontend/js/features/outline/outline-manager.js",
"repo_id": "overleaf",
"token_count": 1303
} | 488 |
import { useCallback } from 'react'
import PropTypes from 'prop-types'
import { useShareProjectContext } from './share-project-modal'
import Icon from '../../../shared/components/icon'
import { Button, Col, Row, OverlayTrigger, Tooltip } from 'react-bootstrap'
import { Trans, useTranslation } from 'react-i18next'
import MemberPrivileges from './member-privileges'
import { resendInvite, revokeInvite } from '../utils/api'
import { useProjectContext } from '../../../shared/context/project-context'
export default function Invite({ invite, isAdmin }) {
return (
<Row className="project-invite">
<Col xs={7}>
<div>{invite.email}</div>
<div className="small">
<Trans i18nKey="invite_not_accepted" />
.
{isAdmin && <ResendInvite invite={invite} />}
</div>
</Col>
<Col xs={3} className="text-left">
<MemberPrivileges privileges={invite.privileges} />
</Col>
{isAdmin && (
<Col xs={2} className="text-center">
<RevokeInvite invite={invite} />
</Col>
)}
</Row>
)
}
Invite.propTypes = {
invite: PropTypes.object.isRequired,
isAdmin: PropTypes.bool.isRequired,
}
function ResendInvite({ invite }) {
const { monitorRequest } = useShareProjectContext()
const project = useProjectContext()
// const buttonRef = useRef(null)
//
const handleClick = useCallback(
() =>
monitorRequest(() => resendInvite(project, invite)).finally(() => {
// NOTE: disabled as react-bootstrap v0.33.1 isn't forwarding the ref to the `button`
// if (buttonRef.current) {
// buttonRef.current.blur()
// }
document.activeElement.blur()
}),
[invite, monitorRequest, project]
)
return (
<Button
bsStyle="link"
className="btn-inline-link"
onClick={handleClick}
// ref={buttonRef}
>
<Trans i18nKey="resend" />
</Button>
)
}
ResendInvite.propTypes = {
invite: PropTypes.object.isRequired,
}
function RevokeInvite({ invite }) {
const { t } = useTranslation()
const { updateProject, monitorRequest } = useShareProjectContext()
const project = useProjectContext()
function handleClick(event) {
event.preventDefault()
monitorRequest(() => revokeInvite(project, invite)).then(() => {
updateProject({
invites: project.invites.filter(existing => existing !== invite),
})
})
}
return (
<OverlayTrigger
placement="bottom"
overlay={
<Tooltip id="tooltip-revoke-invite">
<Trans i18nKey="revoke_invite" />
</Tooltip>
}
>
<Button
type="button"
bsStyle="link"
onClick={handleClick}
aria-label={t('revoke')}
className="btn-inline-link"
>
<Icon type="times" />
</Button>
</OverlayTrigger>
)
}
RevokeInvite.propTypes = {
invite: PropTypes.object.isRequired,
}
| overleaf/web/frontend/js/features/share-project-modal/components/invite.js/0 | {
"file_path": "overleaf/web/frontend/js/features/share-project-modal/components/invite.js",
"repo_id": "overleaf",
"token_count": 1202
} | 489 |
// window location-related functions in a separate module so they can be mocked/stubbed in tests
export function reload() {
window.location.reload()
}
export function assign(url) {
window.location.assign(url)
}
| overleaf/web/frontend/js/features/share-project-modal/utils/location.js/0 | {
"file_path": "overleaf/web/frontend/js/features/share-project-modal/utils/location.js",
"repo_id": "overleaf",
"token_count": 62
} | 490 |
import { getJSON } from '../../../infrastructure/fetch-json'
export function fetchWordCount(projectId, clsiServerId, options) {
let query = ''
if (clsiServerId) {
query = `?clsiserverid=${clsiServerId}`
}
return getJSON(`/project/${projectId}/wordcount${query}`, options)
}
| overleaf/web/frontend/js/features/word-count-modal/utils/api.js/0 | {
"file_path": "overleaf/web/frontend/js/features/word-count-modal/utils/api.js",
"repo_id": "overleaf",
"token_count": 103
} | 491 |
/*
EditorWatchdogManager is used for end-to-end checks of edits.
The editor UI is backed by Ace and CodeMirrors, which in turn are connected
to ShareJs documents in the frontend.
Edits propagate from the editor to ShareJs and are send through socket.io
and real-time to document-updater.
In document-updater edits are integrated into the document history and
a confirmation/rejection is sent back to the frontend.
Along the way things can get lost.
We have certain safe-guards in place, but are still getting occasional
reports of lost edits.
EditorWatchdogManager is implementing the basis for end-to-end checks on
two levels:
- local/ShareJsDoc: edits that pass-by a ShareJs document shall get
acknowledged eventually.
- global: any edits made in the editor shall get acknowledged eventually,
independent for which ShareJs document (potentially none) sees it.
How does this work?
===================
The global check is using a global EditorWatchdogManager that is available
via the angular factory 'ide'.
Local/ShareJsDoc level checks will connect to the global instance.
Each EditorWatchdogManager keeps track of the oldest un-acknowledged edit.
When ever a ShareJs document receives an acknowledgement event, a local
EditorWatchdogManager will see it and also notify the global instance about
it.
The next edit cycle will clear the oldest un-acknowledged timestamp in case
a new ack has arrived, otherwise it will bark loud! via the timeout handler.
Scenarios
=========
- User opens the CodeMirror editor
- attach global check to new CM instance
- detach Ace from the local EditorWatchdogManager
- when the frontend attaches the CM instance to ShareJs, we also
attach it to the local EditorWatchdogManager
- the internal attach process writes the document content to the editor,
which in turn emits 'change' events. These event need to be excluded
from the watchdog. EditorWatchdogManager.ignoreEditsFor takes care
of that.
- User opens the Ace editor (again)
- (attach global check to the Ace editor, only one copy of Ace is around)
- detach local EditorWatchdogManager from CM
- likewise with CM, attach Ace to the local EditorWatchdogManager
- User makes an edit
- the editor will emit a 'change' event
- the global EditorWatchdogManager will process it first
- the local EditorWatchdogManager will process it next
- Document-updater confirms an edit
- the local EditorWatchdogManager will process it first, it passes it on to
- the global EditorWatchdogManager will process it next
Time
====
The delay between edits and acks is measured using a monotonic clock:
`performance.now()`.
It is agnostic to system clock changes in either direction and timezone
changes do not affect it as well.
Roughly speaking, it is initialized with `0` when the `window` context is
created, before our JS app boots.
As per canIUse.com and MDN `performance.now()` is available to all supported
Browsers, including IE11.
See also: https://caniuse.com/?search=performance.now
See also: https://developer.mozilla.org/en-US/docs/Web/API/Performance/now
*/
// TIMEOUT specifies the timeout for edits into a single ShareJsDoc.
const TIMEOUT = 60 * 1000
// GLOBAL_TIMEOUT specifies the timeout for edits into any ShareJSDoc.
const GLOBAL_TIMEOUT = TIMEOUT
// REPORT_EVERY specifies how often we send events/report errors.
const REPORT_EVERY = 60 * 1000
const SCOPE_LOCAL = 'ShareJsDoc'
const SCOPE_GLOBAL = 'global'
class Reporter {
constructor(onTimeoutHandler) {
this._onTimeoutHandler = onTimeoutHandler
this._lastReport = undefined
this._queue = []
}
_getMetaPreferLocal() {
for (const meta of this._queue) {
if (meta.scope === SCOPE_LOCAL) {
return meta
}
}
return this._queue.pop()
}
onTimeout(meta) {
// Collect all 'meta's for this update.
// global arrive before local ones, but we are eager to report local ones.
this._queue.push(meta)
setTimeout(() => {
// Another handler processed the 'meta' entry already
if (!this._queue.length) return
const maybeLocalMeta = this._getMetaPreferLocal()
// Discard other, newly arrived 'meta's
this._queue.length = 0
const now = Date.now()
// Do not flood the server with losing-edits events
const reportedRecently = now - this._lastReport < REPORT_EVERY
if (!reportedRecently) {
this._lastReport = now
this._onTimeoutHandler(maybeLocalMeta)
}
})
}
}
export default class EditorWatchdogManager {
constructor({ parent, onTimeoutHandler }) {
this.scope = parent ? SCOPE_LOCAL : SCOPE_GLOBAL
this.timeout = parent ? TIMEOUT : GLOBAL_TIMEOUT
this.parent = parent
if (parent) {
this.reporter = parent.reporter
} else {
this.reporter = new Reporter(onTimeoutHandler)
}
this.lastAck = null
this.lastUnackedEdit = null
}
onAck() {
this.lastAck = performance.now()
// bubble up to globalEditorWatchdogManager
if (this.parent) this.parent.onAck()
}
onEdit() {
// Use timestamps to track the high-water mark of unacked edits
const now = performance.now()
// Discard the last unacked edit if there are now newer acks
if (this.lastAck > this.lastUnackedEdit) {
this.lastUnackedEdit = null
}
// Start tracking for this keypress if we aren't already tracking an
// unacked edit
if (!this.lastUnackedEdit) {
this.lastUnackedEdit = now
}
// Report an error if the last tracked edit hasn't been cleared by an
// ack from the server after a long time
const delay = now - this.lastUnackedEdit
if (delay > this.timeout) {
const timeOrigin = Date.now() - now
const scope = this.scope
const lastAck = new Date(this.lastAck ? timeOrigin + this.lastAck : 0)
const lastUnackedEdit = new Date(timeOrigin + this.lastUnackedEdit)
const meta = { scope, delay, lastAck, lastUnackedEdit }
this._log('timedOut', meta)
this.reporter.onTimeout(meta)
}
}
attachToEditor(editorName, editor) {
let onChange
if (editorName === 'CM') {
// CM is passing the CM instance as first parameter, then the change.
onChange = (editor, change) => {
// Ignore remote changes.
if (change.origin === 'remote') return
// sharejs only looks at DEL or INSERT change events.
// NOTE: Keep in sync with sharejs.
if (!(change.removed || change.text)) return
this.onEdit()
}
} else {
// ACE is passing the change object as first parameter.
onChange = change => {
// Ignore remote changes.
if (change.origin === 'remote') return
// sharejs only looks at DEL or INSERT change events.
// NOTE: Keep in sync with sharejs.
if (!(change.action === 'remove' || change.action === 'insert')) return
this.onEdit()
}
}
this._log('attach to editor', editorName)
editor.on('change', onChange)
const detachFromEditor = () => {
this._log('detach from editor', editorName)
editor.off('change', onChange)
}
return detachFromEditor
}
_log() {
sl_console.log(`[EditorWatchdogManager] ${this.scope}:`, ...arguments)
}
}
| overleaf/web/frontend/js/ide/connection/EditorWatchdogManager.js/0 | {
"file_path": "overleaf/web/frontend/js/ide/connection/EditorWatchdogManager.js",
"repo_id": "overleaf",
"token_count": 2411
} | 492 |
/* eslint-disable
max-len,
no-cond-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
* 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 'ace/ace'
import 'ace/ext-language_tools'
const { Range } = ace.require('ace/range')
var Helpers = {
getLastCommandFragment(lineUpToCursor) {
let index
if ((index = Helpers.getLastCommandFragmentIndex(lineUpToCursor)) > -1) {
return lineUpToCursor.slice(index)
} else {
return null
}
},
getLastCommandFragmentIndex(lineUpToCursor) {
// This is hack to let us skip over commands in arguments, and
// go to the command on the same 'level' as us. E.g.
// \includegraphics[width=\textwidth]{..
// should not match the \textwidth.
let m
const blankArguments = lineUpToCursor.replace(/\[([^\]]*)\]/g, args =>
Array(args.length + 1).join('.')
)
if ((m = blankArguments.match(/(\\[^\\]*)$/))) {
return m.index
} else {
return -1
}
},
getCommandNameFromFragment(commandFragment) {
return __guard__(
commandFragment != null ? commandFragment.match(/\\(\w+)\{/) : undefined,
x => x[1]
)
},
getContext(editor, pos) {
const upToCursorRange = new Range(pos.row, 0, pos.row, pos.column)
const lineUpToCursor = editor.getSession().getTextRange(upToCursorRange)
const commandFragment = Helpers.getLastCommandFragment(lineUpToCursor)
const commandName = Helpers.getCommandNameFromFragment(commandFragment)
const beyondCursorRange = new Range(pos.row, pos.column, pos.row, 99999)
const lineBeyondCursor = editor.getSession().getTextRange(beyondCursorRange)
return {
lineUpToCursor,
commandFragment,
commandName,
lineBeyondCursor,
}
},
}
export default Helpers
function __guard__(value, transform) {
return typeof value !== 'undefined' && value !== null
? transform(value)
: undefined
}
| overleaf/web/frontend/js/ide/editor/directives/aceEditor/auto-complete/Helpers.js/0 | {
"file_path": "overleaf/web/frontend/js/ide/editor/directives/aceEditor/auto-complete/Helpers.js",
"repo_id": "overleaf",
"token_count": 822
} | 493 |
import App from '../../../base'
App.controller('FileTreeController', function ($scope) {
$scope.openNewDocModal = () => {
window.dispatchEvent(
new CustomEvent('file-tree.start-creating', { detail: { mode: 'doc' } })
)
}
$scope.orderByFoldersFirst = function (entity) {
if ((entity != null ? entity.type : undefined) === 'folder') {
return '0'
}
return '1'
}
})
| overleaf/web/frontend/js/ide/file-tree/controllers/FileTreeController.js/0 | {
"file_path": "overleaf/web/frontend/js/ide/file-tree/controllers/FileTreeController.js",
"repo_id": "overleaf",
"token_count": 152
} | 494 |
import _ from 'lodash'
/* eslint-disable
max-len,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import App from '../../../base'
import ColorManager from '../../colors/ColorManager'
import displayNameForUser from '../util/displayNameForUser'
const historyLabelsListController = function ($scope, $element, $attrs) {
const ctrl = this
ctrl.isDragging = false
ctrl.versionsWithLabels = []
$scope.$watchCollection('$ctrl.labels', function (labels) {
if (labels) {
const groupedLabelsHash = _.groupBy(labels, 'version')
ctrl.versionsWithLabels = _.map(groupedLabelsHash, (labels, version) => {
return {
version: parseInt(version, 10),
labels,
}
})
}
})
ctrl.initHoveredRange = () => {
ctrl.hoveredHistoryRange = {
toV: ctrl.selectedHistoryRange.toV,
fromV: ctrl.selectedHistoryRange.fromV,
}
}
ctrl.resetHoveredRange = () => {
ctrl.hoveredHistoryRange = { toV: null, fromV: null }
}
ctrl.setHoveredRangeToV = toV => {
if (toV >= ctrl.hoveredHistoryRange.fromV) {
ctrl.hoveredHistoryRange.toV = toV
}
}
ctrl.setHoveredRangeFromV = fromV => {
if (fromV <= ctrl.hoveredHistoryRange.toV) {
ctrl.hoveredHistoryRange.fromV = fromV
}
}
ctrl.isVersionSelected = function (version) {
if (ctrl.rangeSelectionEnabled) {
return (
version <= ctrl.selectedHistoryRange.toV &&
version >= ctrl.selectedHistoryRange.fromV
)
} else {
return version === ctrl.selectedHistoryVersion
}
}
ctrl.isVersionHoverSelected = function (version) {
return (
ctrl.rangeSelectionEnabled &&
version <= ctrl.hoveredHistoryRange.toV &&
version >= ctrl.hoveredHistoryRange.fromV
)
}
ctrl.onDraggingStart = () => {
$scope.$applyAsync(() => {
ctrl.isDragging = true
ctrl.initHoveredRange()
})
}
ctrl.onDraggingStop = (isValidDrop, boundary) => {
$scope.$applyAsync(() => {
if (!isValidDrop) {
if (boundary === 'toV') {
ctrl.setRangeToV(ctrl.hoveredHistoryRange.toV)
} else if (boundary === 'fromV') {
ctrl.setRangeFromV(ctrl.hoveredHistoryRange.fromV)
}
}
ctrl.isDragging = false
ctrl.resetHoveredRange()
})
}
ctrl.onDrop = (boundary, versionWithLabel) => {
if (boundary === 'toV') {
$scope.$applyAsync(() => ctrl.setRangeToV(versionWithLabel.version))
} else if (boundary === 'fromV') {
$scope.$applyAsync(() => ctrl.setRangeFromV(versionWithLabel.version))
}
}
ctrl.onOver = (boundary, versionWithLabel) => {
if (boundary === 'toV') {
$scope.$applyAsync(() =>
ctrl.setHoveredRangeToV(versionWithLabel.version)
)
} else if (boundary === 'fromV') {
$scope.$applyAsync(() =>
ctrl.setHoveredRangeFromV(versionWithLabel.version)
)
}
}
ctrl.handleVersionSelect = versionWithLabel => {
if (ctrl.rangeSelectionEnabled) {
// TODO
ctrl.onRangeSelect({
selectedToV: versionWithLabel.version,
selectedFromV: versionWithLabel.version,
})
} else {
ctrl.onVersionSelect({ version: versionWithLabel.version })
}
}
ctrl.setRangeToV = version => {
if (version >= ctrl.selectedHistoryRange.fromV) {
ctrl.onRangeSelect({
selectedToV: version,
selectedFromV: ctrl.selectedHistoryRange.fromV,
})
}
}
ctrl.setRangeFromV = version => {
if (version <= ctrl.selectedHistoryRange.toV) {
ctrl.onRangeSelect({
selectedToV: ctrl.selectedHistoryRange.toV,
selectedFromV: version,
})
}
}
ctrl.buildUserView = label => {
const user = {
_id: label.user_id,
displayName: label.user_display_name,
}
return user
}
ctrl.displayName = displayNameForUser
ctrl.getUserCSSStyle = function (user, versionWithLabel) {
const curUserId =
(user != null ? user._id : undefined) ||
(user != null ? user.id : undefined)
const hue = ColorManager.getHueForUserId(curUserId) || 100
if (
ctrl.isVersionSelected(versionWithLabel.version) ||
ctrl.isVersionHoverSelected(versionWithLabel.version)
) {
return { color: '#FFF' }
} else {
return { color: `hsl(${hue}, 70%, 50%)` }
}
}
ctrl.$onInit = () => {
ctrl.resetHoveredRange()
}
}
export default App.component('historyLabelsList', {
bindings: {
labels: '<',
rangeSelectionEnabled: '<',
users: '<',
currentUser: '<',
isLoading: '<',
selectedHistoryVersion: '<?',
selectedHistoryRange: '<?',
onVersionSelect: '&',
onRangeSelect: '&',
onLabelDelete: '&',
},
controller: historyLabelsListController,
templateUrl: 'historyLabelsListTpl',
})
| overleaf/web/frontend/js/ide/history/components/historyLabelsList.js/0 | {
"file_path": "overleaf/web/frontend/js/ide/history/components/historyLabelsList.js",
"repo_id": "overleaf",
"token_count": 2078
} | 495 |
/* eslint-disable no-useless-escape */
import PropTypes from 'prop-types'
function WikiLink({ url, children, skipPlainRendering }) {
if (window.wikiEnabled) {
return (
<a href={url} target="_blank">
{children}
</a>
)
} else {
return <>{children}</>
}
}
WikiLink.propTypes = {
url: PropTypes.string.isRequired,
children: PropTypes.node.isRequired,
}
const rules = [
{
regexToMatch: /Misplaced alignment tab character \&/,
extraInfoURL:
'https://www.overleaf.com/learn/Errors/Misplaced_alignment_tab_character_%26',
humanReadableHintComponent: (
<>
You have placed an alignment tab character '&' in the wrong place. If
you want to align something, you must write it inside an align
environment such as \begin
{'{align}'} … \end
{'{align}'}, \begin
{'{tabular}'} … \end
{'{tabular}'}, etc. If you want to write an ampersand '&' in text, you
must write \& instead.
</>
),
humanReadableHint:
'You have placed an alignment tab character '&' in the wrong place. If you want to align something, you must write it inside an align environment such as \\begin{align} … \\end{align}, \\begin{tabular} … \\end{tabular}, etc. If you want to write an ampersand '&' in text, you must write \\& instead.',
},
{
regexToMatch: /Extra alignment tab has been changed to \\cr/,
extraInfoURL:
'https://www.overleaf.com/learn/Errors/Extra_alignment_tab_has_been_changed_to_%5Ccr',
humanReadableHintComponent: (
<>
You have written too many alignment tabs in a table, causing one of them
to be turned into a line break. Make sure you have specified the correct
number of columns in your{' '}
<WikiLink url="https://www.overleaf.com/learn/Tables">table</WikiLink>.
</>
),
humanReadableHint:
'You have written too many alignment tabs in a table, causing one of them to be turned into a line break. Make sure you have specified the correct number of columns in your <a href="https://www.overleaf.com/learn/Tables" target="_blank">table</a>.',
},
{
regexToMatch: /Display math should end with \$\$/,
extraInfoURL:
'https://www.overleaf.com/learn/Errors/Display_math_should_end_with_$$',
humanReadableHintComponent: (
<>
You have forgotten a $ sign at the end of 'display math' mode. When
writing in display math mode, you must always math write inside $$ … $$.
Check that the number of $s match around each math expression.
</>
),
humanReadableHint:
'You have forgotten a $ sign at the end of 'display math' mode. When writing in display math mode, you must always math write inside $$ … $$. Check that the number of $s match around each math expression.',
},
{
regexToMatch: /Missing [{$] inserted./,
extraInfoURL: 'https://www.overleaf.com/learn/Errors/Missing_$_inserted',
humanReadableHintComponent: (
<>
<p>
You need to enclose all mathematical expressions and symbols with
special markers. These special markers create a ‘math mode’.
</p>
<p>
Use <code>$...$</code> for inline math mode, and <code>\[...\]</code>
or one of the mathematical environments (e.g. equation) for display
math mode.
</p>
<p>
This applies to symbols such as subscripts ( <code>_</code> ),
integrals ( <code>\int</code> ), Greek letters ( <code>\alpha</code>,{' '}
<code>\beta</code>, <code>\delta</code> ) and modifiers{' '}
<code>{'(\\vec{x}'}</code>, <code>{'\\tilde{x}'})</code>.
</p>
</>
),
humanReadableHint:
'You need to enclose all mathematical expressions and symbols with special markers. These special markers create a ‘math mode’. Use $...$ for inline math mode, and \\[...\\] or one of the mathematical environments (e.g. equation) for display math mode. This applies to symbols such as subscripts ( _ ), integrals ( \\int ), Greek letters ( \\alpha, \\beta, \\delta ) and modifiers (\\vec{x}, \\tilde{x} ).',
},
{
regexToMatch: /(undefined )?[rR]eference(s)?.+(undefined)?/,
extraInfoURL:
'https://www.overleaf.com/learn/Errors/There_were_undefined_references',
humanReadableHintComponent: (
<>
You have referenced something which has not yet been labelled. If you
have labelled it already, make sure that what is written inside \ref
{'{...}'} is the same as what is written inside \label
{'{...}'}.
</>
),
humanReadableHint:
'You have referenced something which has not yet been labelled. If you have labelled it already, make sure that what is written inside \\ref{...} is the same as what is written inside \\label{...}.',
},
{
regexToMatch: /Citation .+ on page .+ undefined on input line .+/,
extraInfoURL:
'https://www.overleaf.com/learn/Errors/Citation_XXX_on_page_XXX_undefined_on_input_line_XXX',
humanReadableHintComponent: (
<>
You have cited something which is not included in your bibliography.
Make sure that the citation (\cite
{'{...}'}) has a corresponding key in your bibliography, and that both
are spelled the same way.
</>
),
humanReadableHint:
'You have cited something which is not included in your bibliography. Make sure that the citation (\\cite{...}) has a corresponding key in your bibliography, and that both are spelled the same way.',
},
{
regexToMatch: /(Label .+)? multiply[ -]defined( labels)?/,
extraInfoURL:
'https://www.overleaf.com/learn/Errors/There_were_multiply-defined_labels',
humanReadableHintComponent: (
<>
You have used the same label more than once. Check that each \label
{'{...}'} labels only one item.
</>
),
humanReadableHint:
'You have used the same label more than once. Check that each \\label{...} labels only one item.',
},
{
regexToMatch: /`!?h' float specifier changed to `!?ht'/,
extraInfoURL:
'https://www.overleaf.com/learn/Errors/%60!h%27_float_specifier_changed_to_%60!ht%27',
humanReadableHintComponent: (
<>
The float specifier 'h' is too strict of a demand for LaTeX to place
your float in a nice way here. Try relaxing it by using 'ht', or even
'htbp' if necessary. If you want to try keep the float here anyway,
check out the{' '}
<WikiLink url="https://www.overleaf.com/learn/Positioning_of_Figures">
float package
</WikiLink>
.
</>
),
humanReadableHint:
'The float specifier 'h' is too strict of a demand for LaTeX to place your float in a nice way here. Try relaxing it by using 'ht', or even 'htbp' if necessary. If you want to try keep the float here anyway, check out the <a href="https://www.overleaf.com/learn/Positioning_of_Figures" target="_blank">float package</a>.',
},
{
regexToMatch: /No positions in optional float specifier/,
extraInfoURL:
'https://www.overleaf.com/learn/Errors/No_positions_in_optional_float_specifier',
humanReadableHintComponent: (
<>
You have forgotten to include a float specifier, which tells LaTeX where
to position your figure. To fix this, either insert a float specifier
inside the square brackets (e.g. \begin
{'{figure}'}
[h]), or remove the square brackets (e.g. \begin
{'{figure}'}
). Find out more about float specifiers{' '}
<WikiLink url="https://www.overleaf.com/learn/Positioning_of_Figures">
here
</WikiLink>
.
</>
),
humanReadableHint:
'You have forgotten to include a float specifier, which tells LaTeX where to position your figure. To fix this, either insert a float specifier inside the square brackets (e.g. \\begin{figure}[h]), or remove the square brackets (e.g. \\begin{figure}). Find out more about float specifiers <a href="https://www.overleaf.com/learn/Positioning_of_Figures" target="_blank">here</a>.',
},
{
regexToMatch: /Undefined control sequence/,
extraInfoURL:
'https://www.overleaf.com/learn/Errors/Undefined_control_sequence',
humanReadableHintComponent: (
<>
The compiler is having trouble understanding a command you have used.
Check that the command is spelled correctly. If the command is part of a
package, make sure you have included the package in your preamble using
\usepackage
{'{...}'}.
</>
),
humanReadableHint:
'The compiler is having trouble understanding a command you have used. Check that the command is spelled correctly. If the command is part of a package, make sure you have included the package in your preamble using \\usepackage{...}.',
},
{
regexToMatch: /File .+ not found/,
extraInfoURL:
'https://www.overleaf.com/learn/Errors/File_XXX_not_found_on_input_line_XXX',
humanReadableHintComponent: (
<>
The compiler cannot find the file you want to include. Make sure that
you have{' '}
<WikiLink url="https://www.overleaf.com/learn/Including_images_in_ShareLaTeX">
uploaded the file
</WikiLink>{' '}
and{' '}
<WikiLink url="https://www.overleaf.com/learn/Errors/File_XXX_not_found_on_input_line_XXX.">
specified the file location correctly
</WikiLink>
.
</>
),
humanReadableHint:
'The compiler cannot find the file you want to include. Make sure that you have <a href="https://www.overleaf.com/learn/Including_images_in_ShareLaTeX" target="_blank">uploaded the file</a> and <a href="https://www.overleaf.com/learn/Errors/File_XXX_not_found_on_input_line_XXX." target="_blank">specified the file location correctly</a>.',
},
{
regexToMatch: /LaTeX Error: Unknown graphics extension: \..+/,
extraInfoURL:
'https://www.overleaf.com/learn/Errors/LaTeX_Error:_Unknown_graphics_extension:_.XXX',
humanReadableHintComponent: (
<>
The compiler does not recognise the file type of one of your images.
Make sure you are using a{' '}
<WikiLink url="https://www.overleaf.com/learn/Errors/LaTeX_Error:_Unknown_graphics_extension:_.gif.">
supported image format
</WikiLink>{' '}
for your choice of compiler, and check that there are no periods (.) in
the name of your image.
</>
),
humanReadableHint:
'The compiler does not recognise the file type of one of your images. Make sure you are using a <a href="https://www.overleaf.com/learn/Errors/LaTeX_Error:_Unknown_graphics_extension:_.gif." target="_blank">supported image format</a> for your choice of compiler, and check that there are no periods (.) in the name of your image.',
},
{
regexToMatch: /LaTeX Error: Unknown float option `H'/,
extraInfoURL:
'https://www.overleaf.com/learn/Errors/LaTeX_Error:_Unknown_float_option_%60H%27',
humanReadableHintComponent: (
<>
The compiler isn't recognizing the float option 'H'. Include \usepackage
{'{float}'} in your preamble to fix this.
</>
),
humanReadableHint:
'The compiler isn't recognizing the float option 'H'. Include \\usepackage{float} in your preamble to fix this.',
},
{
regexToMatch: /LaTeX Error: Unknown float option `q'/,
extraInfoURL:
'https://www.overleaf.com/learn/Errors/LaTeX_Error:_Unknown_float_option_%60q%27',
humanReadableHintComponent: (
<>
You have used a float specifier which the compiler does not understand.
You can learn more about the different float options available for
placing figures{' '}
<WikiLink url="https://www.overleaf.com/learn/Positioning_of_Figures">
here
</WikiLink>{' '}
.
</>
),
humanReadableHint:
'You have used a float specifier which the compiler does not understand. You can learn more about the different float options available for placing figures <a href="https://www.overleaf.com/learn/Positioning_of_Figures" target="_blank">here</a> .',
},
{
regexToMatch: /LaTeX Error: \\math.+ allowed only in math mode/,
extraInfoURL:
'https://www.overleaf.com/learn/Errors/LaTeX_Error:_%5Cmathrm_allowed_only_in_math_mode',
humanReadableHintComponent: (
<>
You have used a font command which is only available in math mode. To
use this command, you must be in maths mode (E.g. $ … $ or \begin
{'{math}'} … \end
{'{math}'}
). If you want to use it outside of math mode, use the text version
instead: \textrm, \textit, etc.
</>
),
humanReadableHint:
'You have used a font command which is only available in math mode. To use this command, you must be in maths mode (E.g. $ … $ or \\begin{math} … \\end{math}). If you want to use it outside of math mode, use the text version instead: \\textrm, \\textit, etc.',
},
{
ruleId: 'hint_mismatched_environment',
types: ['environment'],
regexToMatch: /Error: `([^']{2,})' expected, found `([^']{2,})'.*/,
newMessage: 'Error: environment does not match \\begin{$1} ... \\end{$2}',
humanReadableHintComponent: (
<>
You have used \begin
{'{...}'} without a corresponding \end
{'{...}'}.
</>
),
humanReadableHint:
'You have used \\begin{...} without a corresponding \\end{...}.',
},
{
ruleId: 'hint_mismatched_brackets',
types: ['environment'],
regexToMatch: /Error: `([^a-zA-Z0-9])' expected, found `([^a-zA-Z0-9])'.*/,
newMessage: "Error: brackets do not match, found '$2' instead of '$1'",
humanReadableHintComponent: (
<>You have used an open bracket without a corresponding close bracket.</>
),
humanReadableHint:
'You have used an open bracket without a corresponding close bracket.',
},
{
regexToMatch: /LaTeX Error: Can be used only in preamble/,
extraInfoURL:
'https://www.overleaf.com/learn/Errors/LaTeX_Error:_Can_be_used_only_in_preamble',
humanReadableHintComponent: (
<>
You have used a command in the main body of your document which should
be used in the preamble. Make sure that \documentclass[…]
{'{…}'} and all \usepackage
{'{…}'} commands are written before \begin
{'{document}'}.
</>
),
humanReadableHint:
'You have used a command in the main body of your document which should be used in the preamble. Make sure that \\documentclass[…]{…} and all \\usepackage{…} commands are written before \\begin{document}.',
},
{
regexToMatch: /Missing \\right inserted/,
extraInfoURL:
'https://www.overleaf.com/learn/Errors/Missing_%5Cright_insertede',
humanReadableHintComponent: (
<>
You have started an expression with a \left command, but have not
included a corresponding \right command. Make sure that your \left and
\right commands balance everywhere, or else try using \Biggl and \Biggr
commands instead as shown{' '}
<WikiLink url="https://www.overleaf.com/learn/Errors/Missing_%5Cright_inserted">
here
</WikiLink>
.
</>
),
humanReadableHint:
'You have started an expression with a \\left command, but have not included a corresponding \\right command. Make sure that your \\left and \\right commands balance everywhere, or else try using \\Biggl and \\Biggr commands instead as shown <a href="https://www.overleaf.com/learn/Errors/Missing_%5Cright_inserted" target="_blank">here</a>.',
},
{
regexToMatch: /Double superscript/,
extraInfoURL: 'https://www.overleaf.com/learn/Errors/Double_superscript',
humanReadableHintComponent: (
<>
You have written a double superscript incorrectly as a^b^c, or else you
have written a prime with a superscript. Remember to include {'{and}'}{' '}
when using multiple superscripts. Try a^
{'{b ^ c}'} instead.
</>
),
humanReadableHint:
'You have written a double superscript incorrectly as a^b^c, or else you have written a prime with a superscript. Remember to include {and} when using multiple superscripts. Try a^{b ^ c} instead.',
},
{
regexToMatch: /Double subscript/,
extraInfoURL: 'https://www.overleaf.com/learn/Errors/Double_subscript',
humanReadableHintComponent: (
<>
You have written a double subscript incorrectly as a_b_c. Remember to
include {'{and}'} when using multiple subscripts. Try a_
{'{b_c}'} instead.
</>
),
humanReadableHint:
'You have written a double subscript incorrectly as a_b_c. Remember to include {and} when using multiple subscripts. Try a_{b_c} instead.',
},
{
regexToMatch: /No \\author given/,
extraInfoURL: 'https://www.overleaf.com/learn/Errors/No_%5Cauthor_given',
humanReadableHintComponent: (
<>
You have used the \maketitle command, but have not specified any
\author. To fix this, include an author in your preamble using the
\author
{'{…}'} command.
</>
),
humanReadableHint:
'You have used the \\maketitle command, but have not specified any \\author. To fix this, include an author in your preamble using the \\author{…} command.',
},
{
regexToMatch: /LaTeX Error: Environment .+ undefined/,
extraInfoURL:
'https://www.overleaf.com/learn/Errors%2FLaTeX%20Error%3A%20Environment%20XXX%20undefined',
humanReadableHintComponent: (
<>
You have created an environment (using \begin
{'{…}'} and \end
{'{…}'} commands) which is not recognized. Make sure you have included
the required package for that environment in your preamble, and that the
environment is spelled correctly.
</>
),
humanReadableHint:
'You have created an environment (using \\begin{…} and \\end{…} commands) which is not recognized. Make sure you have included the required package for that environment in your preamble, and that the environment is spelled correctly.',
},
{
regexToMatch: /LaTeX Error: Something's wrong--perhaps a missing \\item/,
extraInfoURL:
'https://www.overleaf.com/learn/Errors/LaTeX_Error:_Something%27s_wrong--perhaps_a_missing_%5Citem',
humanReadableHintComponent: (
<>
There are no entries found in a list you have created. Make sure you
label list entries using the \item command, and that you have not used a
list inside a table.
</>
),
humanReadableHint:
'There are no entries found in a list you have created. Make sure you label list entries using the \\item command, and that you have not used a list inside a table.',
},
{
regexToMatch: /Misplaced \\noalign/,
extraInfoURL: 'https://www.overleaf.com/learn/Errors/Misplaced_%5Cnoalign',
humanReadableHintComponent: (
<>
You have used a \hline command in the wrong place, probably outside a
table. If the \hline command is written inside a table, try including \\
before it.
</>
),
humanReadableHint:
'You have used a \\hline command in the wrong place, probably outside a table. If the \\hline command is written inside a table, try including \\\\ before it.',
},
{
regexToMatch: /LaTeX Error: There's no line here to end/,
extraInfoURL:
'https://www.overleaf.com/learn/Errors/LaTeX_Error:_There%27s_no_line_here_to_end',
humanReadableHintComponent: (
<>
You have used a \\ or \newline command where LaTeX was not expecting
one. Make sure that you only use line breaks after blocks of text, and
be careful using linebreaks inside lists and other environments.\
</>
),
humanReadableHint:
'You have used a \\\\ or \\newline command where LaTeX was not expecting one. Make sure that you only use line breaks after blocks of text, and be careful using linebreaks inside lists and other environments.\\',
},
{
regexToMatch: /LaTeX Error: \\verb ended by end of line/,
extraInfoURL:
'https://www.overleaf.com/learn/Errors/LaTeX_Error:_%5Cverb_ended_by_end_of_line',
humanReadableHintComponent: (
<>
You have used a \verb command incorrectly. Try replacling the \verb
command with \begin
{'{verbatim}'}
…\end
{'{verbatim}'}
.\
</>
),
humanReadableHint:
'You have used a \\verb command incorrectly. Try replacling the \\verb command with \\begin{verbatim}…\\end{verbatim}.\\',
},
{
regexToMatch: /Illegal unit of measure (pt inserted)/,
extraInfoURL:
'https://www.overleaf.com/learn/Errors%2FIllegal%20unit%20of%20measure%20(pt%20inserted)',
humanReadableHintComponent: (
<>
You have written a length, but have not specified the appropriate units
(pt, mm, cm etc.). If you have not written a length, check that you have
not witten a linebreak \\ followed by square brackets […] anywhere.
</>
),
humanReadableHint:
'You have written a length, but have not specified the appropriate units (pt, mm, cm etc.). If you have not written a length, check that you have not witten a linebreak \\\\ followed by square brackets […] anywhere.',
},
{
regexToMatch: /Extra \\right/,
extraInfoURL: 'https://www.overleaf.com/learn/Errors/Extra_%5Cright',
humanReadableHintComponent: (
<>
You have written a \right command without a corresponding \left command.
Check that all \left and \right commands balance everywhere.
</>
),
humanReadableHint:
'You have written a \\right command without a corresponding \\left command. Check that all \\left and \\right commands balance everywhere.',
},
{
regexToMatch: /Missing \\begin{document}/,
extraInfoURL:
'https://www.overleaf.com/learn/Errors%2FLaTeX%20Error%3A%20Missing%20%5Cbegin%20document',
humanReadableHintComponent: (
<>
No \begin
{'{document}'} command was found. Make sure you have included \begin
{'{document}'} in your preamble, and that your main document is set
correctly.
</>
),
humanReadableHint:
'No \\begin{document} command was found. Make sure you have included \\begin{document} in your preamble, and that your main document is set correctly.',
},
{
ruleId: 'hint_mismatched_environment2',
types: ['environment'],
cascadesFrom: ['environment'],
regexToMatch: /Error: `\\end\{([^\}]+)\}' expected but found `\\end\{([^\}]+)\}'.*/,
newMessage: 'Error: environments do not match: \\begin{$1} ... \\end{$2}',
humanReadableHintComponent: (
<>
You have used \begin
{'{}'} without a corresponding \end
{'{}'}.
</>
),
humanReadableHint:
'You have used \\begin{} without a corresponding \\end{}.',
},
{
ruleId: 'hint_mismatched_environment3',
types: ['environment'],
cascadesFrom: ['environment'],
regexToMatch: /Warning: No matching \\end found for `\\begin\{([^\}]+)\}'.*/,
newMessage: 'Warning: No matching \\end found for \\begin{$1}',
humanReadableHintComponent: (
<>
You have used \begin
{'{}'} without a corresponding \end
{'{}'}.
</>
),
humanReadableHint:
'You have used \\begin{} without a corresponding \\end{}.',
},
{
ruleId: 'hint_mismatched_environment4',
types: ['environment'],
cascadesFrom: ['environment'],
regexToMatch: /Error: Found `\\end\{([^\}]+)\}' without corresponding \\begin.*/,
newMessage: 'Error: found \\end{$1} without a corresponding \\begin{$1}',
humanReadableHintComponent: (
<>
You have used \begin
{'{}'} without a corresponding \end
{'{}'}.
</>
),
humanReadableHint:
'You have used \\begin{} without a corresponding \\end{}.',
},
]
if (!window.wikiEnabled) {
rules.forEach(rule => {
rule.extraInfoURL = null
rule.humanReadableHint = stripHTMLFromString(rule.humanReadableHint)
})
}
function stripHTMLFromString(htmlStr) {
const tmp = document.createElement('DIV')
tmp.innerHTML = htmlStr
return tmp.textContent || tmp.innerText || ''
}
export default rules
| overleaf/web/frontend/js/ide/human-readable-logs/HumanReadableLogsRules.js/0 | {
"file_path": "overleaf/web/frontend/js/ide/human-readable-logs/HumanReadableLogsRules.js",
"repo_id": "overleaf",
"token_count": 9302
} | 496 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.