text stringlengths 1 2.83M | id stringlengths 16 152 | metadata dict | __index_level_0__ int64 0 949 |
|---|---|---|---|
---
title: PlayAudioStreamForPlayer
description: Pustanje 'audio stream-a' igracu.
tags: ["player"]
---
## Description
Pusta audio stream igracu. Audio fajlovi takodje rade (.mp3).
| Name | Description |
| -------------- | ------------------------------------------------------------------------------------------------------------- |
| playerid | ID igraca kome se pusta audio |
| url[] | Link koji se pusta. Pravilni formati su mp3 i ogg/vorbis. Link ka .pls fajlu (playlista) ce pustiti playlistu |
| Float:PosX | Pozicija X na kojoj se pusta audio. Default 0.0. Nema efekta osim ako je usepos podesen na 1. |
| Float:PosY | Pozicija Y na kojoj se pusta audio. Default 0.0. Nema efekta osim ako je usepos podesen na 1. |
| Float:PosZ | Pozicija Z na kojoj se pusta audio. Default 0.0. Nema efekta osim ako je usepos podesen na 1. |
| Float:distance | Razdaljina do koje se cuje audio. Nema efekta osim ako je usepos podesen na 1. |
| usepos | Koristi postavljenu poziciju i distancu. Default neaktivan (0). |
## Returns
1: Funkcija je uspesno izvrsena.
0: Funkcija nije uspela da se izvrsi. Zadati igrac ne postoji.
## Examples
```c
public OnPlayerCommandText(playerid, cmdtext[])
{
if (strcmp("/radio", cmdtext, true) == 0)
{
PlayAudioStreamForPlayer(playerid, "http://somafm.com/tags.pls");
return 1;
}
if (strcmp("/radiopos", cmdtext, true) == 0)
{
new Float:X, Float:Y, Float:Z, Float:Distance = 5.0;
GetPlayerPos(playerid, X, Y, Z);
PlayAudioStreamForPlayer(playerid, "http://somafm.com/tags.pls", X, Y, Z, Distance, 1);
return 1;
}
return 0;
}
```
## Related Functions
- [StopAudioStreamForPlayer](StopAudioStreamForPlayer.md): Zaustavlja audio stream za igraca.
- [PlayerPlaySound](PlayerPlaySound.md): Pustanje zvuka igracu.
| openmultiplayer/web/docs/translations/sr/scripting/functions/PlayAudioStreamForPlayer.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/sr/scripting/functions/PlayAudioStreamForPlayer.md",
"repo_id": "openmultiplayer",
"token_count": 1066
} | 423 |
---
title: OnPlayerClickMap
description: Callback นี้ถูกเรียกเมื่อผู้เล่นวาง เป้าหมาย/จุดหมาย บนแผนที่ในเมนู (โดยการคลิกขวา)
tags: ["player"]
---
:::warning
Callback นี้ถูกเพิ่มใน SA-MP 0.3d และจะไม่ทำงานในเวอร์ชั่นก่อนหน้านี้!
:::
## คำอธิบาย
Callback นี้ถูกเรียกเมื่อผู้เล่นวาง เป้าหมาย/จุดหมาย บนแผนที่ในเมนู (โดยการคลิกขวา)
| ชื่อ | คำอธิบาย |
| -------- | ----------------------------------------------------- |
| playerid | ไอดีของผู้เล่นที่วาง เป้าหมาย/จุดหมาย |
| Float:fX | พิกัด X ที่ผู้เล่นคลิก |
| Float:fY | พิกัด Y ที่ผู้เล่นคลิก |
| Float:fZ | พิกัด Z ที่ผู้เล่นคลิก (ไม่แม่นยำ - ดูบันทึกด้านล่าง) |
## ส่งคืน
1 - จะป้องกันไม่ให้ฟิลเตอร์สคริปต์อื่นถูกเรียกโดย Callback นี้
0 - บอกให้ Callback นี้ส่งต่อไปยังฟิลเตอร์สคริปต์ถัดไป
มันถูกเรียกในเกมโหมดก่อนเสมอ
## ตัวอย่าง
```c
public OnPlayerClickMap(playerid, Float:fX, Float:fY, Float:fZ)
{
SetPlayerPosFindZ(playerid, fX, fY, fZ);
return 1;
}
```
## บันทึก
:::tip
ค่า Z จะถูกส่งกลับเป็น 0 (ไม่ถูกต้อง) หากมันอยู่ไกลจากผู้เล่นเกินไป; ใช้ปลั๊กอิน MapAndreas เพื่อให้ได้พิกัด Z ได้แม่นยำขึ้น
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
| openmultiplayer/web/docs/translations/th/scripting/callbacks/OnPlayerClickMap.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/callbacks/OnPlayerClickMap.md",
"repo_id": "openmultiplayer",
"token_count": 1536
} | 424 |
---
title: OnPlayerStreamOut
description: This callback is called when a player is streamed out from some other player's client.
tags: ["player"]
---
## คำอธิบาย
This callback is called when a player is streamed out from some other player's client.
| Name | Description |
| ----------- | ----------------------------------------------- |
| playerid | The player who has been destreamed. |
| forplayerid | The player who has destreamed the other player. |
## ส่งคืน
มันถูกเรียกในฟิลเตอร์สคริปต์ก่อนเสมอ
## ตัวอย่าง
```c
public OnPlayerStreamOut(playerid, forplayerid)
{
new string[80];
format(string, sizeof(string), "Your computer has just unloaded player ID %d", playerid);
SendClientMessage(forplayerid, 0xFF0000FF, string);
return 1;
}
```
## บันทึก
:::tip
NPC สามารถเรียก Callback นี้ได้
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
| openmultiplayer/web/docs/translations/th/scripting/callbacks/OnPlayerStreamOut.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/callbacks/OnPlayerStreamOut.md",
"repo_id": "openmultiplayer",
"token_count": 501
} | 425 |
---
title: OnVehicleSpawn
description: This callback is called when a vehicle respawns.
tags: ["vehicle"]
---
:::warning
This callback is called **only** when vehicle **re**spawns! CreateVehicle and AddStaticVehicle(Ex) **won't** trigger this callback.
:::
## คำอธิบาย
This callback is called when a vehicle respawns.
| Name | Description |
| --------- | ----------------------------------- |
| vehicleid | The ID of the vehicle that spawned. |
## ส่งคืน
0 - Will prevent other filterscripts from receiving this callback.
1 - Indicates that this callback will be passed to the next filterscript.
มันถูกเรียกในฟิลเตอร์สคริปต์ก่อนเสมอ
## ตัวอย่าง
```c
public OnVehicleSpawn(vehicleid)
{
printf("Vehicle %i spawned!",vehicleid);
return 1;
}
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [SetVehicleToRespawn](../../scripting/functions/SetVehicleToRespawn.md): Respawn a vehicle.
- [CreateVehicle](../../scripting/functions/CreateVehicle.md): Create a vehicle.
| openmultiplayer/web/docs/translations/th/scripting/callbacks/OnVehicleSpawn.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/callbacks/OnVehicleSpawn.md",
"repo_id": "openmultiplayer",
"token_count": 466
} | 426 |
---
title: ApplyActorAnimation
description: Apply an animation to an actor.
tags: []
---
:::warning
ฟังก์ชั่นนี้ถูกเพิ่มใน SA-MP 0.3.7 และจะไม่ทำงานในเวอร์ชั่นก่อนหน้านี้!
:::
## คำอธิบาย
Apply an animation to an actor.
| Name | Description |
| ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| actorid | The ID of the actor to apply the animation to. |
| animlib[] | The animation library from which to apply an animation. |
| animname[] | The name of the animation to apply, within the specified library. |
| fDelta | The speed to play the animation (use 4.1). |
| loop | If set to 1, the animation will loop. If set to 0, the animation will play once. |
| lockx | If set to 0, the actor is returned to their old X coordinate once the animation is complete (for animations that move the actor such as walking). 1 will not return them to their old position. |
| locky | Same as above but for the Y axis. Should be kept the same as the previous parameter. |
| freeze | Setting this to 1 will freeze an actor at the end of the animation. 0 will not. |
| time | Timer in milliseconds. For a never-ending loop it should be 0. |
## ส่งคืน
1: The function executed successfully.
0: The function failed to execute. The actor specified does not exist.
## ตัวอย่าง
```c
new MyActor;
public OnGameModeInit()
{
MyActor = CreateActor(179, 316.1, -134.0, 999.6, 90.0); // Actor as salesperson in Ammunation
ApplyActorAnimation(MyActor, "DEALER", "shop_pay", 4.1, 0, 0, 0, 0, 0); // Pay anim
return 1;
}
```
## บันทึก
:::tip
You must preload the animation library for the player the actor will be applying the animation for, and not for the actor. Otherwise, the animation won't be applied to the actor until the function is executed again.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [ClearActorAnimations](../../scripting/functions/ClearActorAnimations.md): Clear any animations that are applied to an actor.
| openmultiplayer/web/docs/translations/th/scripting/functions/ApplyActorAnimation.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/ApplyActorAnimation.md",
"repo_id": "openmultiplayer",
"token_count": 1982
} | 427 |
---
title: CallRemoteFunction
description: Calls a public function in any script that is loaded.
tags: []
---
## คำอธิบาย
Calls a public function in any script that is loaded.
| Name | Description |
| -------------- | ------------------------------------------- |
| function[] | Public function's name. |
| format[] | Tag/format of each variable |
| {Float,\_}:... | 'Indefinite' number of arguments of any tag |
## ส่งคืน
The value that the last public function returned.
## ตัวอย่าง
```c
forward CallMe(number, const string[]);
public CallMe(number, const string[])
{
printf("CallMe called. Int: %i String: %s.", number, string);
return 1;
}
// Somewhere... in another file perhaps?
CallRemoteFunction("CallMe", "is", 69, "this is a string");
```
## บันทึก
:::warning
CallRemoteFunction crashes the server if it's passing an empty string.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [CallLocalFunction](../../scripting/functions/CallLocalFunction.md): Call a function in the script.
| openmultiplayer/web/docs/translations/th/scripting/functions/CallRemoteFunction.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/CallRemoteFunction.md",
"repo_id": "openmultiplayer",
"token_count": 475
} | 428 |
---
title: CreatePlayerObject
description: Creates an object which will be visible to only one player.
tags: ["player"]
---
## คำอธิบาย
Creates an object which will be visible to only one player.
| Name | Description |
| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| playerid | The ID of the player to create the object for. |
| modelid | The model to create. |
| Float:X | The X coordinate to create the object at. |
| Float:Y | The Y coordinate to create the object at. |
| Float:Z | The Z coordinate to create the object at. |
| Float:rX | The X rotation of the object. |
| Float:rY | The Y rotation of the object. |
| Float:rZ | The Z rotation of the object. |
| Float:DrawDistance | The distance from which objects will appear to players. 0.0 will cause an object to render at its default distance. Leaving this parameter out will cause objects to be rendered at their default distance. |
## ส่งคืน
The ID of the object that was created, or INVALID_OBJECT_ID if the object limit (MAX_OBJECTS) was reached.
## ตัวอย่าง
```c
new pObject[MAX_PLAYERS];
public OnPlayerConnect(playerid)
{
pObject[playerid] = CreatePlayerObject(playerid, 2587, 2001.195679, 1547.113892, 14.283400, 0, 0, 96);
// Or alternatively, using the DrawDistance parameter to show it from as far away as possible:
pObject[playerid] = CreatePlayerObject(playerid, 2587, 2001.195679, 1547.113892, 14.283400, 0, 0, 96, 300.0);
return 1;
}
public OnPlayerDisconnect(playerid, reason)
{
DestroyPlayerObject(playerid, pObject[playerid]);
return 1;
}
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [DestroyPlayerObject](../../scripting/functions/DestroyPlayerObject.md): Destroy a player object.
- [IsValidPlayerObject](../../scripting/functions/IsValidPlayerObject.md): Checks if a certain player object is vaild.
- [MovePlayerObject](../../scripting/functions/MovePlayerObject.md): Move a player object.
- [StopPlayerObject](../../scripting/functions/StopPlayerObject.md): Stop a player object from moving.
- [SetPlayerObjectPos](../../scripting/functions/SetPlayerObjectPos.md): Set the position of a player object.
- [SetPlayerObjectRot](../../scripting/functions/SetPlayerObjectRot.md): Set the rotation of a player object.
- [GetPlayerObjectPos](../../scripting/functions/GetPlayerObjectPos.md): Locate a player object.
- [GetPlayerObjectRot](../../scripting/functions/GetPlayerObjectRot.md): Check the rotation of a player object.
- [AttachPlayerObjectToPlayer](../../scripting/functions/AttachPlayerObjectToPlayer.md): Attach a player object to a player.
- [CreateObject](../../scripting/functions/CreateObject.md): Create an object.
- [DestroyObject](../../scripting/functions/DestroyObject.md): Destroy an object.
- [IsValidObject](../../scripting/functions/IsValidObject.md): Checks if a certain object is vaild.
- [MoveObject](../../scripting/functions/MoveObject.md): Move an object.
- [StopObject](../../scripting/functions/StopObject.md): Stop an object from moving.
- [SetObjectPos](../../scripting/functions/SetObjectPos.md): Set the position of an object.
- [SetObjectRot](../../scripting/functions/SetObjectRot.md): Set the rotation of an object.
- [GetObjectPos](../../scripting/functions/GetObjectPos.md): Locate an object.
- [GetObjectRot](../../scripting/functions/GetObjectRot.md): Check the rotation of an object.
- [AttachObjectToPlayer](../../scripting/functions/AttachObjectToPlayer.md): Attach an object to a player.
| openmultiplayer/web/docs/translations/th/scripting/functions/CreatePlayerObject.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/CreatePlayerObject.md",
"repo_id": "openmultiplayer",
"token_count": 3667
} | 429 |
---
title: DisableMenuRow
description: Disable a specific row in a menu for all players.
tags: ["menu"]
---
## คำอธิบาย
Disable a specific row in a menu for all players. It will be greyed-out and can't be selected by players.
| Name | Description |
| ----------- | ----------------------------------------------------------------------------------------------------------------- |
| Menu:menuid | The ID of the menu to disable a row of. Ensure this is valid, as an invalid menu ID will crash the entire server. |
| row | The ID of the row to disable (rows start at 0). |
## ส่งคืน
This function always returns 1, even if the function fails. If an invalid row is specified, nothing will happen. If an invalid menu ID is specified, the server will crash.
## ตัวอย่าง
```c
new Menu:WeaponMenu;
WeaponMenu = CreateMenu("Weapons", 1, 50.0, 180.0, 200.0, 200.0);
AddMenuItem(WeaponMenu, 0, "Rocket Launcher");
AddMenuItem(WeaponMenu, 0, "Flamethrower");
AddMenuItem(WeaponMenu, 0, "Minigun");
AddMenuItem(WeaponMenu, 0, "Grenades");
if (!strcmp(cmdtext, "/disablemenu", true))
{
DisableMenuRow(WeaponMenu, 2); //Disable the "Minigun" row
return 1;
}
```
## บันทึก
:::tip
Crashes when passed an invalid menu ID. This function disabled the specified menu row for all players. There is no function to disable a menu row for a specific player. You'd have to create two menus - one with a row disabled, and one without. Or one per player.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [CreateMenu](../../scripting/functions/CreateMenu.md): Create a menu.
- [DestroyMenu](../../scripting/functions/DestroyMenu.md): Destroy a menu.
- [AddMenuItem](../../scripting/functions/AddMenuItem.md): Add an item to a menu.
| openmultiplayer/web/docs/translations/th/scripting/functions/DisableMenuRow.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/DisableMenuRow.md",
"repo_id": "openmultiplayer",
"token_count": 766
} | 430 |
---
title: ForceClassSelection
description: Forces a player to go back to class selection.
tags: []
---
## คำอธิบาย
Forces a player to go back to class selection.
| Name | Description |
| -------- | ------------------------------------------- |
| playerid | The player to send back to class selection. |
## ส่งคืน
This function does not return any specific values.
## ตัวอย่าง
```c
if (!strcmp(cmdtext, "/class", true))
{
ForceClassSelection(playerid);
TogglePlayerSpectating(playerid, true);
TogglePlayerSpectating(playerid, false);
return 1;
}
```
## บันทึก
:::warning
This function does not perform a state change to PLAYER_STATE_WASTED when combined with TogglePlayerSpectating (see example below), as is listed here.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [AddPlayerClass](../functions/AddPlayerClass): Add a class.
- [SetPlayerSkin](../functions/SetPlayerSkin): Set a player's skin.
- [GetPlayerSkin](../functions/GetPlayerSkin): Get a player's current skin.
- [OnPlayerRequestClass](../callbacks/OnPlayerRequestClass): Called when a player changes class at class selection.
| openmultiplayer/web/docs/translations/th/scripting/functions/ForceClassSelection.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/ForceClassSelection.md",
"repo_id": "openmultiplayer",
"token_count": 451
} | 431 |
---
title: GetActorPoolSize
description: Gets the highest actorid created on the server.
tags: []
---
:::warning
ฟังก์ชั่นนี้ถูกเพิ่มใน SA-MP 0.3.7 และจะไม่ทำงานในเวอร์ชั่นก่อนหน้านี้!
:::
## คำอธิบาย
Gets the highest actorid created on the server.
| Name | Description |
| ---- | ----------- |
## ตัวอย่าง
```c
SetAllActorsHealth(Float:health)
{
for(new i = 0, j = GetActorPoolSize(); i <= j; i++)
{
if (IsValidActor(i))
{
SetActorHealth(i, health);
}
}
}
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [CreateActor](../functions/CreateActor): Create an actor (static NPC).
- [IsValidActor](../functions/isValidActor): Check if actor id is valid.
- [SetActorHealth](../functions/SetActorHealth): Set the health of an actor.
| openmultiplayer/web/docs/translations/th/scripting/functions/GetActorPoolSize.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/GetActorPoolSize.md",
"repo_id": "openmultiplayer",
"token_count": 460
} | 432 |
---
title: GetPVarNameAtIndex
description: Retrieve the name of a player's pVar via the index.
tags: ["pvar"]
---
## คำอธิบาย
Retrieve the name of a player's pVar via the index.
| Name | Description |
| ------------- | -------------------------------------------------------------- |
| playerid | The ID of the player whose player variable to get the name of. |
| index | The index of the player's pVar. |
| ret_varname[] | A string to store the pVar's name in, passed by reference. |
| ret_len | The max length of the returned string, use sizeof(). |
## ส่งคืน
This function does not return any specific values.
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- GetPVarType: Get the type of the player variable.
- GetPVarInt: Get the previously set integer from a player variable.
- GetPVarFloat: Get the previously set float from a player variable.
- GetPVarString: Get the previously set string from a player variable.
| openmultiplayer/web/docs/translations/th/scripting/functions/GetPVarNameAtIndex.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/GetPVarNameAtIndex.md",
"repo_id": "openmultiplayer",
"token_count": 438
} | 433 |
---
title: GetPlayerCameraUpVector
description: This function returns the vector, that points to the upside of the camera's view, or, in other words, to the middle top of your screen.
tags: ["player"]
---
## คำอธิบาย
This function returns the vector, that points to the upside of the camera's view, or, in other words, to the middle top of your screen.
| Name | Description |
| -------- | -------------------------------------------------------------- |
| playerid | The ID of the player you want to obtain the camera upvector 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.
## บันทึก
:::warning
This function was removed in SA-MP version 0.3b
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [GetPlayerCameraPos](../functions/GetPlayerCameraPos): Find out where the player's camera is.
- [GetPlayerCameraFrontVector](../functions/GetPlayerCameraFrontVector): Get the player's camera front vector
| openmultiplayer/web/docs/translations/th/scripting/functions/GetPlayerCameraUpVector.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/GetPlayerCameraUpVector.md",
"repo_id": "openmultiplayer",
"token_count": 450
} | 434 |
---
title: GetPlayerName
description: Get a player's name.
tags: ["player"]
---
## คำอธิบาย
Get a player's name.
| Name | Description |
| -------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| playerid | The ID of the player to get the name of. |
| name[] | An array into which to store the name, passed by reference. |
| len | The length of the string that should be stored. Recommended to be MAX_PLAYER_NAME + 1. The + 1 is necessary to account for the null terminator. |
## ส่งคืน
The player's name is stored in the specified array.
## ตัวอย่าง
```c
public OnPlayerConnect(playerid)
{
// Get the name of the player that connected and display a join message to other players
new name[MAX_PLAYER_NAME + 1];
GetPlayerName(playerid, name, sizeof(name));
new string[MAX_PLAYER_NAME + 23 + 1];
format(string, sizeof(string), "%s has joined the server.", name);
SendClientMessageToAll(0xC4C4C4FF, string);
return 1;
}
```
## บันทึก
:::tip
A player's name can be up to 24 characters long (as of 0.3d R2) by using SetPlayerName. This is defined in a_samp.inc as MAX_PLAYER_NAME. However, the client can only join with a nickname between 3 and 20 characters, otherwise the connection will be rejected and the player has to quit to choose a valid name.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- SetPlayerName: Set a player's name.
- GetPlayerIp: Get a player's IP.
- GetPlayerPing: Get the ping of a player.
- GetPlayerScore: Get the score of a player.
- GetPlayerVersion: Get a player's client-version.
| openmultiplayer/web/docs/translations/th/scripting/functions/GetPlayerName.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/GetPlayerName.md",
"repo_id": "openmultiplayer",
"token_count": 892
} | 435 |
---
title: GetPlayerTeam
description: Get the ID of the team the player is on.
tags: ["player"]
---
## คำอธิบาย
Get the ID of the team the player is on.
| Name | Description |
| -------- | ---------------------------------------- |
| playerid | The ID of the player to get the team of. |
## ส่งคืน
0-254: The player's team. (0 is a valid team)
255: Defined as NO_TEAM. The player is not on any team.
-1: The function failed to execute. Player is not connected.
## ตัวอย่าง
```c
public OnPlayerSpawn(playerid)
{
// Players who are in team 1 should spawn at Las Venturas airport.
if (GetPlayerTeam(playerid) == 1)
{
SetPlayerPos(playerid, 1667.8909, 1405.5618, 10.7801);
}
return 1;
}
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- SetPlayerTeam: Set a player's team.
- SetTeamCount: Set the number of teams available.
| openmultiplayer/web/docs/translations/th/scripting/functions/GetPlayerTeam.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/GetPlayerTeam.md",
"repo_id": "openmultiplayer",
"token_count": 402
} | 436 |
---
title: GetSVarsUpperIndex
description: Each SVar (server-variable) has its own unique identification number for lookup, this function returns the highest ID.
tags: []
---
## คำอธิบาย
Each SVar (server-variable) has its own unique identification number for lookup, this function returns the highest ID.
| Name | Description |
| ---- | ----------- |
## ตัวอย่าง
```c
// Store the upper index in the variable 'SVarUpperIndex' + 1
new SVarUpperIndex = GetSVarsUpperIndex() + 1;
// This sVarCount variable will store how many sVars are set as we count them.
new sVarCount;
for(new i=0; i != sVarUpperIndex; i++) // Loop through all sVar IDs under the upper index
{
// At first, we need to get SVar name
new sVarName[128];
GetSVarNameAtIndex(i, pVarName, sizeof(pVarName));
// If the var is set (type not 0), increment sVarCount.
if (GetSVarType(pVarName) != 0)
{
sVarCount ++;
}
}
new szString[66];
printf("There are %i server-variables set. Upper index (highest ID): %i.", sVarCount, SVarUpperIndex-1);
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- GetSVarNameAtIndex: Get the server variable's name from its index.
- GetSVarType: Get the type of the server variable.
| openmultiplayer/web/docs/translations/th/scripting/functions/GetSVarsUpperIndex.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/GetSVarsUpperIndex.md",
"repo_id": "openmultiplayer",
"token_count": 474
} | 437 |
---
title: GetVehicleParamsSirenState
description: Returns a vehicle's siren state (on/off).
tags: ["vehicle"]
---
:::warning
ฟังก์ชั่นนี้ถูกเพิ่มใน SA-MP 0.3.7 และจะไม่ทำงานในเวอร์ชั่นก่อนหน้านี้!
:::
## คำอธิบาย
Returns a vehicle's siren state (on/off).
| Name | Description |
| --------- | ------------------------------------------------ |
| vehicleid | The ID of the vehicle to get the siren state of. |
## ส่งคืน
-1: Vehicle siren hasn't been set yet (off)
0: Vehicle siren is off
1: Vehicle siren is on
## ตัวอย่าง
```c
new siren = GetVehicleParamsSirenState(vehicleid);
if (siren == 1)
{
// Siren is on, do something
}
else
{
// Siren is off, do something
}
```
## บันทึก
:::warning
Because a siren state of -1 or 0 means 'off', you cannot use a boolean conditional statement to check whether sirens are on. If you do 'if (sirenstate)', it will be true for anything NOT 0 (so -1 or 1). You should check that the siren state explicitly equals 1.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
| openmultiplayer/web/docs/translations/th/scripting/functions/GetVehicleParamsSirenState.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/GetVehicleParamsSirenState.md",
"repo_id": "openmultiplayer",
"token_count": 566
} | 438 |
---
title: IsActorStreamedIn
description: Checks if an actor is streamed in for a player.
tags: []
---
:::warning
ฟังก์ชั่นนี้ถูกเพิ่มใน SA-MP 0.3.7 และจะไม่ทำงานในเวอร์ชั่นก่อนหน้านี้!
:::
## คำอธิบาย
Checks if an actor is streamed in for a player.
| Name | Description |
| ----------- | --------------------- |
| actorid | The ID of the actor. |
| forplayerid | The ID of the player. |
## ส่งคืน
This function returns 1 if the actor is streamed in for the player, or 0 if it is not.
## ตัวอย่าง
```c
new MyActor;
public OnGameModeInit()
{
MyActor = CreateActor(...);
return 1;
}
public OnPlayerSpawn(playerid)
{
if (IsActorStreamedIn(MyActor, playerid))
{
// Do something
}
}
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [CreateActor](../../scripting/functions/CreateActor.md): Create an actor (static NPC).
- [IsPlayerStreamedIn](../../scripting/functions/IsPlayerStreamedIn.md): Checks if a player is streamed in for another player.
| openmultiplayer/web/docs/translations/th/scripting/functions/IsActorStreamedIn.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/IsActorStreamedIn.md",
"repo_id": "openmultiplayer",
"token_count": 530
} | 439 |
---
title: IsValidObject
description: Checks if an object with the ID provided exists.
tags: []
---
## คำอธิบาย
Checks if an object with the ID provided exists.
| Name | Description |
| -------- | ----------------------------------------------- |
| objectid | The ID of the object to check the existence of. |
## ส่งคืน
1: The object exists.
0: The object does not exist.
## ตัวอย่าง
```c
if (IsValidObject(objectid))
{
DestroyObject(objectid);
}
```
## บันทึก
:::warning
This is to check if an object exists, not if a model is valid.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [CreateObject](../../scripting/functions/CreateObject.md): Create an object.
- [DestroyObject](../../scripting/functions/DestroyObject.md): Destroy an object.
- [MoveObject](../../scripting/functions/MoveObject.md): Move an object.
- [StopObject](../../scripting/functions/StopObject.md): Stop an object from moving.
- [SetObjectPos](../../scripting/functions/SetObjectPos.md): Set the position of an object.
- [SetObjectRot](../../scripting/functions/SetObjectRot.md): Set the rotation of an object.
- [GetObjectPos](../../scripting/functions/GetObjectPos.md): Locate an object.
- [GetObjectRot](../../scripting/functions/GetObjectRot.md): Check the rotation of an object.
- [AttachObjectToPlayer](../../scripting/functions/AttachObjectToPlayer.md): Attach an object to a player.
- [CreatePlayerObject](../../scripting/functions/CreatePlayerObject.md): Create an object for only one player.
- [DestroyPlayerObject](../../scripting/functions/DestroyPlayerObject.md): Destroy a player object.
- [IsValidPlayerObject](../../scripting/functions/IsValidPlayerObject.md): Checks if a certain player object is vaild.
- [MovePlayerObject](../../scripting/functions/MovePlayerObject.md): Move a player object.
- [StopPlayerObject](../../scripting/functions/StopPlayerObject.md): Stop a player object from moving.
- [SetPlayerObjectPos](../../scripting/functions/SetPlayerObjectPos.md): Set the position of a player object.
- [SetPlayerObjectRot](../../scripting/functions/SetPlayerObjectRot.md): Set the rotation of a player object.
- [GetPlayerObjectPos](../../scripting/functions/GetPlayerObjectPos.md): Locate a player object.
- [GetPlayerObjectRot](../../scripting/functions/GetPlayerObjectRot.md): Check the rotation of a player object.
- [AttachPlayerObjectToPlayer](../../scripting/functions/AttachPlayerObjectToPlayer.md): Attach a player object to a player.
| openmultiplayer/web/docs/translations/th/scripting/functions/IsValidObject.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/IsValidObject.md",
"repo_id": "openmultiplayer",
"token_count": 846
} | 440 |
---
title: PlayerTextDrawLetterSize
description: Sets the width and height of the letters in a player-textdraw.
tags: ["player", "textdraw", "playertextdraw"]
---
## คำอธิบาย
Sets the width and height of the letters in a player-textdraw.
| Name | Description |
| -------- | -------------------------------------------------------------------- |
| playerid | The ID of the player whose player-textdraw to set the letter size of |
| text | The ID of the player-textdraw to change the letter size of |
| Float:x | Width of a char. |
| Float:y | Height of a char. |
## ส่งคืน
This function does not return any specific values.
## ตัวอย่าง
```c
MyTextDraw = CreatePlayerTextDraw(playerid, 100.0, 33.0,"Example TextDraw");
PlayerTextDrawLetterSize(playerid, MyTextDraw, 3.2 ,5.1);
```
## บันทึก
:::tip
When using this function purely for the benefit of affecting the textdraw box, multiply 'Y' by 0.135 to convert to TextDrawTextSize-like measurements
:::
:::tip
Fonts appear to look the best with an X to Y ratio of 1 to 4 (e.g. if x is 0.5 then y should be 2).
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- 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.
- 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/PlayerTextDrawLetterSize.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/PlayerTextDrawLetterSize.md",
"repo_id": "openmultiplayer",
"token_count": 883
} | 441 |
---
title: RemovePlayerMapIcon
description: Removes a map icon that was set earlier for a player using SetPlayerMapIcon.
tags: ["player"]
---
## คำอธิบาย
Removes a map icon that was set earlier for a player using SetPlayerMapIcon.
| Name | Description |
| -------- | ------------------------------------------------------------------------------- |
| playerid | The ID of the player whose icon to remove. |
| iconid | The ID of the icon to remove. This is the second parameter of SetPlayerMapIcon. |
## ส่งคืน
1: The function was executed successfully.
0: The function failed to execute.
## ตัวอย่าง
```c
SetPlayerMapIcon(playerid, 12, 2204.9468, 1986.2877, 16.7380, 52, 0);
// Later on
RemovePlayerMapIcon(playerid, 12);
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [SetPlayerMapIcon](/docs/scripting/functions/SetPlayerMapIcon): Create a mapicon for a player.
| openmultiplayer/web/docs/translations/th/scripting/functions/RemovePlayerMapIcon.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/RemovePlayerMapIcon.md",
"repo_id": "openmultiplayer",
"token_count": 440
} | 442 |
---
title: SetActorHealth
description: Set the health of an actor.
tags: []
---
:::warning
ฟังก์ชั่นนี้ถูกเพิ่มใน SA-MP 0.3.7 และจะไม่ทำงานในเวอร์ชั่นก่อนหน้านี้!
:::
## คำอธิบาย
Set the health of an actor.
| Name | Description |
| ------------ | ----------------------------------------- |
| actorid | The ID of the actor to set the health of. |
| Float:health | The value to set the actors's health to. |
## ส่งคืน
1 - success
0 - failure (i.e. actor is not created).
## ตัวอย่าง
```c
new MyActor;
public OnGameModeInit()
{
MyActor = CreateActor(179, 316.1, -134.0, 999.6, 90.0); // Actor as salesperson in Ammunation
SetActorHealth(MyActor, 100);
return 1;
}
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
| openmultiplayer/web/docs/translations/th/scripting/functions/SetActorHealth.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/SetActorHealth.md",
"repo_id": "openmultiplayer",
"token_count": 474
} | 443 |
---
title: SetPVarFloat
description: Set a float player variable's value.
tags: ["pvar"]
---
## คำอธิบาย
Set a float player variable's value.
| Name | Description |
| ----------- | ------------------------------------------------------- |
| playerid | The ID of the player whose player variable will be set. |
| varname | The name of the player variable. |
| float_value | The float you want to save in the player variable. |
## ส่งคืน
1: The function was executed successfully.
0: The function failed to execute. Either the player specified is not connected, or the variable name is null or over 40 characters.
## ตัวอย่าง
```c
forward SavePos(playerid);
public SavePos(playerid)
{
new Float:x,Float:y,Float:z;
GetPlayerPos(playerid,x,y,z); // Get the players position
SetPVarFloat(playerid,"xpos",x); // Save the float into a player variable
SetPVarFloat(playerid,"ypos",y); // Save the float into a player variable
SetPVarFloat(playerid,"zpos",z); // Save the float into a player variable
return 1;
}
```
## บันทึก
:::tip
Variables aren't reset until after OnPlayerDisconnect is called, so the values are still accessible in OnPlayerDisconnect.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- SetPVarInt: Set an integer for a player variable.
- GetPVarInt: Get the previously set integer from a player variable.
- SetPVarString: Set a string for a player variable.
- GetPVarString: Get the previously set string from a player variable.
- GetPVarFloat: Get the previously set float from a player variable.
- DeletePVar: Delete a player variable.
| openmultiplayer/web/docs/translations/th/scripting/functions/SetPVarFloat.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/SetPVarFloat.md",
"repo_id": "openmultiplayer",
"token_count": 634
} | 444 |
---
title: SetPlayerHoldingObject
description: Attaches an object to a bone.
tags: ["player"]
---
## คำอธิบาย
Attaches an object to a bone.
| Name | Description |
| -------- | -------------------------------------------------- |
| playerid | ID of the player you want to attach the object to. |
| modelid | The model you want to use. |
| bone | The bone you want to attach the object to. |
| fOffsetX | (optional) X axis offset for the object position. |
| fOffsetY | (optional) Y axis offset for the object position. |
| fOffsetZ | (optional) Z axis offset for the object position. |
| fRotX | (optional) X axis rotation of the object. |
| fRotY | (optional) Y axis rotation of the object. |
| fRotZ | (optional) Z axis rotation of the object. |
## ส่งคืน
1 on success, 0 on failure
## ตัวอย่าง
```c
public OnPlayerSpawn(playerid)
{
SetPlayerHoldingObject(playerid, 1609, 2); //Attach a turtle to the playerid's head!
return 1;
}
```
## บันทึก
:::tip
Only one object may be attached per player. This function is seperate from the CreateObject / CreatePlayerObject pools.
:::
:::warning
This function was removed in SA-MP 0.3c. check SetPlayerAttachedObject
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
| openmultiplayer/web/docs/translations/th/scripting/functions/SetPlayerHoldingObject.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/SetPlayerHoldingObject.md",
"repo_id": "openmultiplayer",
"token_count": 581
} | 445 |
---
title: SetPlayerSkin
description: Set the skin of a player.
tags: ["player"]
---
## คำอธิบาย
Set the skin of a player. A player's skin is their character model.
| Name | Description |
| -------- | ---------------------------------------- |
| playerid | The ID of the player to set the skin of. |
| skinid | The skin the player should use. |
## ส่งคืน
1: The function executed successfully.
0: The function failed to execute. This means the player specified does not exist.
Note that 'success' is reported even when skin ID is invalid (not 0-311, or 74), but the skin will be set to ID 0 (CJ).
## ตัวอย่าง
```c
public OnPlayerCommandText(playerid, cmdtext[])
{
if (strcmp(cmdtext, "/fireman", true) == 0)
{
// Set the player's skin to ID 277, which is a fireman.
SetPlayerSkin(playerid, 277);
return 1;
}
return 0;
}
stock SetPlayerSkinFix(playerid, skinid)
{
new
Float:tmpPos[4],
vehicleid = GetPlayerVehicleID(playerid),
seatid = GetPlayerVehicleSeat(playerid);
GetPlayerPos(playerid, tmpPos[0], tmpPos[1], tmpPos[2]);
GetPlayerFacingAngle(playerid, tmpPos[3]);
if (skinid < 0 || skinid > 299) return 0;
if (GetPlayerSpecialAction(playerid) == SPECIAL_ACTION_DUCK)
{
SetPlayerPos(playerid, tmpPos[0], tmpPos[1], tmpPos[2]);
SetPlayerFacingAngle(playerid, tmpPos[3]);
TogglePlayerControllable(playerid, 1); // preventing any freeze - optional
return SetPlayerSkin(playerid, skinid);
}
else if (IsPlayerInAnyVehicle(playerid))
{
new
tmp;
RemovePlayerFromVehicle(playerid);
SetPlayerPos(playerid, tmpPos[0], tmpPos[1], tmpPos[2]);
SetPlayerFacingAngle(playerid, tmpPos[3]);
TogglePlayerControllable(playerid, 1); // preventing any freeze - important - because of doing animations of exiting vehicle
tmp = SetPlayerSkin(playerid, skinid);
PutPlayerInVehicle(playerid, vehicleid, (seatid == 128) ? 0 : seatid);
return tmp;
}
else
{
return SetPlayerSkin(playerid, skinid);
}
}
```
## บันทึก
:::warning
Known Bug(s): If a player's skin is set when they are crouching, in a vehicle, or performing certain animations, they will become frozen or otherwise glitched. This can be fixed by using TogglePlayerControllable. Players can be detected as being crouched through GetPlayerSpecialAction (SPECIAL_ACTION_DUCK). Other players around the player may crash if he is in a vehicle or if he is entering/leaving a vehicle. Setting a player's skin when he is dead may crash players around him. Breaks sitting on bikes.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- GetPlayerSkin: Get a player's current skin.
- SetSpawnInfo: Set the spawn setting for a player.
| openmultiplayer/web/docs/translations/th/scripting/functions/SetPlayerSkin.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/SetPlayerSkin.md",
"repo_id": "openmultiplayer",
"token_count": 1116
} | 446 |
---
title: ShowPlayerDialog
description: Shows the player a synchronous (only one at a time) dialog box.
tags: ["player"]
---
## คำอธิบาย
Shows the player a synchronous (only one at a time) dialog box.
| Name | Description |
| --------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| playerid | The ID of the player to show the dialog to. |
| dialogid | An ID to assign this dialog to, so responses can be processed. Max dialogid is 32767. Using negative values will close any open dialog. |
| style | The style of the dialog. |
| caption[] | The title at the top of the dialog. The length of the caption can not exceed more than 64 characters before it starts to cut off. |
| info[] | The text to display in the main dialog. Use \n to start a new line and \t to tabulate. |
| button1[] | The text on the left button. |
| button2[] | The text on the right button. Leave it blank ( "" ) to hide it. |
## ส่งคืน
1: The function executed successfully.
0: The function failed to execute. This means the player is not connected.
## ตัวอย่าง
```c
// Define the dialog IDs either with an enum:
enum
{
DIALOG_LOGIN,
DIALOG_WELCOME,
DIALOG_WEAPONS
}
// Alternatively, using macros:
#define DIALOG_LOGIN 1
#define DIALOG_WELCOME 2
#define DIALOG_WEAPONS 3
// Enums are recommended, as you don't have to keep track of used IDs. However, enums use memory to store the defines, whereas defines are processed in the 'pre-processor' (compiling) stage.
// Example for DIALOG_STYLE_MSGBOX:
ShowPlayerDialog(playerid, DIALOG_WELCOME, DIALOG_STYLE_MSGBOX, "Notice", "You are connected to the server", "Close", "");
// Example for DIALOG_STYLE_INPUT:
ShowPlayerDialog(playerid, DIALOG_LOGIN, DIALOG_STYLE_INPUT, "Login", "Enter your password below:", "Login", "Cancel");
// Example for DIALOG_STYLE_LIST:
ShowPlayerDialog(playerid, DIALOG_WEAPONS, DIALOG_STYLE_LIST, "Weapons", "AK47\nM4\nSniper Rifle", "Option 1", "Option 2");
// Example for DIALOG_STYLE_PASSWORD:
ShowPlayerDialog(playerid, DIALOG_LOGIN, DIALOG_STYLE_PASSWORD, "Login", "Enter your password below:", "Login", "Cancel");
// Example for DIALOG_STYLE_TABLIST:
ShowPlayerDialog(playerid, DIALOG_WEAPONS, DIALOG_STYLE_TABLIST, "Buy Weapon", "Deagle\t$5000\t100\nSawnoff\t$5000\t100\nPistol\t$1000\t50", "Select", "Cancel");
// Example for DIALOG_STYLE_TABLIST_HEADERS:
ShowPlayerDialog(playerid, DIALOG_WEAPONS, DIALOG_STYLE_TABLIST_HEADERS, "Buy Weapon", "Weapon\tPrice\tAmmo\nDeagle\t$5000\t100\nSawnoff\t$5000\t100\nPistol\t$1000\t50", "Select", "Cancel");
```
## บันทึก
:::tip
It is recommended to use enumerations (see above) or definitions (#define) to determine which IDs dialogs have, to avoid confusion in the future. You should never use literal numbers for IDs - it gets confusing.
:::
:::tip
Use color embedding for multiple colors in the text. Using -1 as dialogid closes all dialogs currently shown on the client's screen.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- TextDrawShowForPlayer: Show a textdraw for a certain player.
- OnDialogResponse: Called when a player responds to a dialog.
| openmultiplayer/web/docs/translations/th/scripting/functions/ShowPlayerDialog.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/ShowPlayerDialog.md",
"repo_id": "openmultiplayer",
"token_count": 1687
} | 447 |
---
title: TextDrawFont
description: Changes the text font.
tags: ["textdraw"]
---
## คำอธิบาย
Changes the text font.
| Name | Description |
| ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| text | The TextDraw to change |
| font | There are four font styles as shown below. Font value 4 specifies that this is a txd sprite; 5 specifies that this textdraw can display preview models. A font value greater than 5 does not display, and anything greater than 16 crashes the client. |
Available Styles:

Available Fonts:

## ส่งคืน
This function does not return any specific values.
## ตัวอย่าง
```c
new Text:MyTextdraw;
public OnGameModeInit()
{
MyTextdraw= TextDrawCreate(320.0, 425.0, "This is an example textdraw");
TextDrawFont(MyTextdraw, 2);
return 1;
}
```
## บันทึก
:::tip
If you want to change the font of a textdraw that is already shown, you don't have to recreate it. Simply use TextDrawShowForPlayer/TextDrawShowForAll after modifying the textdraw and the change will be visible.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [TextDrawCreate](../functions/TextDrawCreate.md): Create a textdraw.
- [TextDrawDestroy](../functions/TextDrawDestroy.md): Destroy a textdraw.
- [TextDrawColor](../functions/TextDrawColor.md): Set the color of the text in a textdraw.
- [TextDrawBoxColor](../functions/TextDrawBoxColor.md): Set the color of the box in a textdraw.
- [TextDrawBackgroundColor](../functions/TextDrawBackgroundColor.md): Set the background color of a textdraw.
- [TextDrawAlignment](../functions/TextDrawAlignment.md): Set the alignment of a textdraw.
- [TextDrawLetterSize](../functions/TextDrawLetterSize.md): Set the letter size of the text in a textdraw.
- [TextDrawTextSize](../functions/TextDrawTextSize.md): Set the size of a textdraw box.
- [TextDrawSetOutline](../functions/TextDrawSetOutline.md): Choose whether the text has an outline.
- [TextDrawSetShadow](../functions/TextDrawSetShadow.md): Toggle shadows on a textdraw.
- [TextDrawSetProportional](../functions/TextDrawSetProportional.md): Scale the text spacing in a textdraw to a proportional ratio.
- [TextDrawUseBox](../functions/TextDrawUseBox.md): Toggle if the textdraw has a box or not.
- [TextDrawSetString](../functions/TextDrawSetString.md): Set the text in an existing textdraw.
- [TextDrawShowForPlayer](../functions/TextDrawShowForPlayer.md): Show a textdraw for a certain player.
- [TextDrawHideForPlayer](../functions/TextDrawHideForPlayer.md): Hide a textdraw for a certain player.
- [TextDrawShowForAll](../functions/TextDrawShowForAll.md): Show a textdraw for all players.
- [TextDrawHideForAll](../functions/TextDrawHideForAll.md): Hide a textdraw for all players.
| openmultiplayer/web/docs/translations/th/scripting/functions/TextDrawFont.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/TextDrawFont.md",
"repo_id": "openmultiplayer",
"token_count": 1386
} | 448 |
---
title: tickcount
description: This function can be used as a replacement for GetTickCount, as it returns the number of milliseconds since the start-up of the server.
tags: []
---
:::warning
This function starts with lowercase letter.
:::
## คำอธิบาย
This function can be used as a replacement for GetTickCount, as it returns the number of milliseconds since the start-up of the server.
| Name | Description |
| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| &granularity=0 | Upon return, this value contains the number of ticks that the internal system time will tick per second. This value therefore indicates the accuracy of the return value of this function. |
## ส่งคืน
The number of milliseconds since start-up of the system. For a 32-bit cell, this count overflows after approximately 24 days of continuous operation.
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [GetTickCount](../functions/GetTickCount.md): Get the uptime of the actual server.
| openmultiplayer/web/docs/translations/th/scripting/functions/Tickcount.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/Tickcount.md",
"repo_id": "openmultiplayer",
"token_count": 494
} | 449 |
---
title: db_query
description: This function is used to execute an SQL query on an opened SQLite database.
tags: ["sqlite"]
---
:::warning
This function starts with lowercase letter.
:::
## คำอธิบาย
This function is used to execute an SQL query on an opened SQLite database.
| Name | Description |
| ------- | ----------------------------- |
| DB:db | The database handle to query. |
| query[] | The query to execute. |
## ส่งคืน
The query result index (starting at 1).
## ตัวอย่าง
```c
new DB:db_handle;
// ...
public OnGameModeInit()
{
// Create a connection to the database
if ((db_handle = db_open("example.db")) == DB:0)
{
// Error
print("Failed to open a connection to \"example.db\".");
SendRconCommand("exit");
}
else
{
// Success
// Creates a "player spawn log" table, if it doesn't exists, and frees the result
db_free_result(db_query(db_handle, "CREATE TABLE IF NOT EXISTS `spawn_log`(`ID` INTEGER PRIMARY KEY AUTOINCREMENT,`PlayerID` INTEGER NOT NULL,`PlayerName` VARCHAR(24) NOT NULL)"));
print("Successfully created a connection to \"example.db\".");
}
// ...
return 1;
}
public OnGameModeExit()
{
// If there is a database connection, close it
if (db_handle) db_close(db_handle);
// ...
return 1;
}
public OnPlayerSpawn(playerid)
{
// Declare "query" and "p_name"
static query[98], p_name[MAX_PLAYER_NAME+1];
// Stores the name of the player to "p_name"
GetPlayerName(playerid, p_name, sizeof p_name);
// Formats "query"
format(query, sizeof query, "INSERT INTO `spawn_log` (`PlayerID`,`PlayerName`) VALUES (%d,'%s')", playerid, p_name);
// Inserts something into "spawn_log" and frees the result
db_free_result(db_query(db_handle, query));
// ...
return 1;
}
// Example function
GetNameBySpawnID(spawn_id)
{
// Declare "p_name"
new p_name[MAX_PLAYER_NAME+1];
// Declare "query" and "db_result"
static query[60], DBResult:db_result;
// Formats "query"
format(query, sizeof query, "SELECT `PlayerName` FROM `spawn_log` WHERE `ID`=%d", spawn_id);
// Selects the player name by using "spawn_id"
db_result = db_query(db_handle, query);
// If there is any valid entry
if (db_num_rows(db_result))
{
// Store data from "PlayerName" into "p_name"
db_get_field(db_result, 0, p_name, sizeof p_name);
}
// Frees the result
db_free_result(db_result);
// Returns "p_name"
return p_name;
}
```
## บันทึก
:::warning
Always free the result by using db_free_result!
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- db_open: Open a connection to an SQLite database
- db_close: Close the connection to an SQLite database
- db_query: Query an SQLite database
- db_free_result: Free result memory from a db_query
- db_num_rows: Get the number of rows in a result
- db_next_row: Move to the next row
- db_num_fields: Get the number of fields in a result
- db_field_name: Returns the name of a field at a particular index
- db_get_field: Get content of field with specified ID from current result row
- db_get_field_assoc: Get content of field with specified name from current result row
- db_get_field_int: Get content of field as an integer with specified ID from current result row
- db_get_field_assoc_int: Get content of field as an integer with specified name from current result row
- db_get_field_float: Get content of field as a float with specified ID from current result row
- db_get_field_assoc_float: Get content of field as a float with specified name from current result row
- db_get_mem_handle: Get memory handle for an SQLite database that was opened with db_open.
- db_get_result_mem_handle: Get memory handle for an SQLite query that was executed with db_query.
- db_debug_openfiles
- db_debug_openresults
| openmultiplayer/web/docs/translations/th/scripting/functions/db_query.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/db_query.md",
"repo_id": "openmultiplayer",
"token_count": 1473
} | 450 |
---
title: floatlog
description: This function allows you to get the logarithm of a float value.
tags: []
---
:::warning
This function starts with lowercase letter.
:::
## คำอธิบาย
This function allows you to get the logarithm of a float value.
| Name | Description |
| ----------- | ---------------------------------------- |
| Float:value | The value of which to get the logarithm. |
| Float:base | The logarithm base. |
## ส่งคืน
The logarithm as a float value.
## ตัวอย่าง
```c
public OnGameModeInit()
{
printf("The logarithm of 15.0 with the base 10.0 is %f", floatlog( 15.0, 10.0 ));
return 1;
}
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [floatsqroot](../functions/floatsqroot): Calculate the square root of a floating point value.
- [floatpower](../functions/floatpower): Raises given value to a power of exponent.
| openmultiplayer/web/docs/translations/th/scripting/functions/floatlog.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/floatlog.md",
"repo_id": "openmultiplayer",
"token_count": 411
} | 451 |
---
title: ftemp
description: Creates a file in the "tmp", "temp" or root directory with random name for reading and writing.
tags: []
---
:::warning
This function starts with lowercase letter.
:::
## คำอธิบาย
Creates a file in the "tmp", "temp" or root directory with random name for reading and writing. The file is deleted after fclose() is used on the file.
| Name | Description |
| ---- | ----------- |
## ตัวอย่าง
```c
// Create a temporary file stream
new File:t_handle = ftemp(),
// Declare "handle"
File:handle,
// Declare "g_char"
g_char;
// Check, if temporary file stream is open
if (t_handle)
{
// Success
// Open "file.txt" in "read only" mode and check, if the file is open
if (handle = fopen("file.txt", io_read))
{
// Get all the characters from "file.txt"
while((g_char = fgetchar(handle, 0, false)) != EOF)
{
// Write character in lowercase into the temporary file stream
fputchar(t_handle, tolower(g_char), false);
}
// Close "file.txt"
fclose(handle);
// Set the file pointer of the temporary file stream to the first byte
fseek(t_handle, _, seek_begin);
// Open "file1.txt" in "write only" mode, and check, if the file is open
if (handle = fopen("file1.txt", io_write))
{
// Success
// Get all the characters from the temporary file stream
while((g_char = fgetchar(t_handle, 0, false)) != EOF)
{
// Write character into "file1.txt"
fputchar(handle, g_char, false);
}
// Close "file1.txt"
fclose(handle);
// Set the file pointer of the temporary file stream to the first byte
fseek(t_handle, _, seek_begin);
}
else
{
// Error
print("Failed to open file \"file1.txt\".");
}
// Open "file2.txt" in "write only" mode, and check, if the file is open
if (handle = fopen("file2.txt", io_write))
{
// Success
// Get all the characters from the temporary file stream
while((g_char = fgetchar(t_handle, 0, false)) != EOF)
{
// Write character into "file2.txt"
fputchar(handle, g_char, false);
}
// Close "file2.txt"
fclose(handle);
}
else
{
// Error
print("Failed to open file \"file2.txt\".");
}
}
else
{
// Error
print("Failed to open file \"file.txt\".");
}
// Close the temporary file stream
fclose(t_handle);
}
else
{
// Error
print("Failed to create a temporary file stream.");
}
```
## บันทึก
:::warning
This function can crash the server when the right directory isn't created.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [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/ftemp.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/ftemp.md",
"repo_id": "openmultiplayer",
"token_count": 1668
} | 452 |
---
title: random
description: Get a pseudo-random number.
tags: []
---
:::warning
This function starts with lowercase letter.
:::
## คำอธิบาย
Get a pseudo-random number.
| Name | Description |
| ---- | -------------------------------------------------------------------------- |
| max | The range of values (from 0 to this value minus one) that can be returned. |
## ส่งคืน
A random number ranging from 0 to max-1.
## ตัวอย่าง
```c
new value = random(5);
// 'value' might be 0, 1, 2, 3 or 4. 5 possible values.
new Float:RandomSpawn[][4] =
{
// Positions, (X, Y, Z and Facing Angle)
{-2796.9854, 1224.8180, 20.5429, 192.0335},
{-2454.2170, 503.8759, 30.0790, 267.2932},
{-2669.7322, -6.0874, 6.1328, 89.8853}
};
public OnPlayerSpawn(playerid)
{
new rand = random(sizeof(RandomSpawn));
// SetPlayerPos to the random spawn data
SetPlayerPos(playerid, RandomSpawn[rand][0], RandomSpawn[rand][1],RandomSpawn[rand][2]);
// SetPlayerFacingAngle to the random facing angle data
SetPlayerFacingAngle(playerid, RandomSpawn[rand][3]);
return 1;
}
```
## บันทึก
:::tip
Using a value smaller than 1 gives weird values.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
| openmultiplayer/web/docs/translations/th/scripting/functions/random.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/random.md",
"repo_id": "openmultiplayer",
"token_count": 585
} | 453 |
---
title: tolower
description: This function changes a single character to lowercase.
tags: []
---
:::warning
This function starts with lowercase letter.
:::
## คำอธิบาย
This function changes a single character to lowercase.
| Name | Description |
| ---- | ------------------------------------- |
| c | The character to change to lowercase. |
## ส่งคืน
The ASCII value of the character provided as lowercase.
## ตัวอย่าง
```c
public OnPlayerText(playerid, text[])
{
text[0] = tolower(text[0]);
//This sets the first character to lowercase.
return 1;
}
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [toupper](../functions/toupper.md)
| openmultiplayer/web/docs/translations/th/scripting/functions/tolower.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/tolower.md",
"repo_id": "openmultiplayer",
"token_count": 315
} | 454 |
---
title: Bullet Hit Types
---
:::info
To be used with [OnPlayerWeaponShot](../callbacks/OnPlayerWeaponShot).
:::
---
| Name | Value |
| ----------------------------- | ----- |
| BULLET_HIT_TYPE_NONE | 0 |
| BULLET_HIT_TYPE_PLAYER | 1 |
| BULLET_HIT_TYPE_VEHICLE | 2 |
| BULLET_HIT_TYPE_OBJECT | 3 |
| BULLET_HIT_TYPE_PLAYER_OBJECT | 4 |
---
:::caution
BULLET_HIT_TYPE_PLAYER is also called for NPCs. Actors are ignored by this callback and detects as BULLET_HIT_TYPE_NONE.
:::
| openmultiplayer/web/docs/translations/th/scripting/resources/bullethittypes.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/resources/bullethittypes.md",
"repo_id": "openmultiplayer",
"token_count": 269
} | 455 |
---
title: Glossary
description: Glossary of terms
tags: []
sidebar_label: Glossary
---
| Word | Meaning |
| ------------- | ------------------------------------------------------------------------------------------------------- |
| PAWN | The scripting language used to make SA:MP scripts |
| Gamemodes | The main script that runs on a server |
| Filterscripts | Scripts that run alongside gamemodes |
| Plugins | Extra functions/capabilites added through a .dll (Windows) or .so (Linux) file |
| Include | Pieces of script placed in .inc files to be included in Filterscripts/Gamemodes using `#include <name>` |
| Pawno | The script editor most people use for PAWN |
| Masterlist | The server SA:MP stores its data on such as the Internet list |
| Deathmatch | A contest where players try to kill each other to win |
| Roleplay | A gamemode type where players acting like in real life |
| Reallife | A gamemode type which is based on real life but players do not need to act like in real life |
| openmultiplayer/web/docs/translations/th/scripting/resources/glossary.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/resources/glossary.md",
"repo_id": "openmultiplayer",
"token_count": 830
} | 456 |
---
title: Player States
description: A list of all the player states to be used with the GetPlayerState function or OnPlayerStateChange callback.
tags: ["player"]
sidebar_label: Player States
---
This page compiles the list of all the player states to be used with the [GetPlayerState](../functions/GetPlayerState.md) function or [OnPlayerStateChange](../callbacks/OnPlayerStateChange.md) callback. Both pages contain examples on how to use the values below.
## States
| ID | Macro | Description |
| --- | ------------------------------------ | ------------------------------------ |
| 0 | PLAYER_STATE_NONE | Empty (while initializing) |
| 1 | PLAYER_STATE_ONFOOT | Player is on foot |
| 2 | PLAYER_STATE_DRIVER | Player is the driver of a vehicle |
| 3 | PLAYER_STATE_PASSENGER | Player is passenger of a vehicle |
| 4 | PLAYER_STATE_EXIT_VEHICLE | Player exits a vehicle |
| 5 | PLAYER_STATE_ENTER_VEHICLE_DRIVER | Player enters a vehicle as driver |
| 6 | PLAYER_STATE_ENTER_VEHICLE_PASSENGER | Player enters a vehicle as passenger |
| 7 | PLAYER_STATE_WASTED | Player is dead or on class selection |
| 8 | PLAYER_STATE_SPAWNED | Player is spawned |
| 9 | PLAYER_STATE_SPECTATING | Player is spectating |
| openmultiplayer/web/docs/translations/th/scripting/resources/playerstates.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/resources/playerstates.md",
"repo_id": "openmultiplayer",
"token_count": 638
} | 457 |
---
title: Vehicle Health
description: Vehicle Health Values
---
| Health | Engine Status |
| ------- | ------------------------------------ |
| > 650 | Undamaged |
| 650-550 | White Smoke |
| 550-390 | Grey Smoke |
| 390-250 | Black Smoke |
| < 250 | On fire (will explode seconds later) |
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [SetVehicleHealth](../functions/SetVehicleHealth): Set a vehicle's health.
- [GetVehicleHealth](../functions/GetVehicleHealth): Get a vehicle's health.
| openmultiplayer/web/docs/translations/th/scripting/resources/vehiclehealth.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/resources/vehiclehealth.md",
"repo_id": "openmultiplayer",
"token_count": 312
} | 458 |
---
title: OnIncomingConnection
description: Bu callback bir IP adresi sunucuya erişim sağlamaya çalıştığında tetiklenir.
tags: []
---
## Açıklama
Bu callback bir IP adresi sunucuya erişim sağlamaya çalıştığında tetiklenir. BlockIpAddress kullanarak gelen bağlantıları engelleyebilirsiniz.
| Name | Description |
| ------------ | --------------------------------------------- |
| playerid | Bağlantı kurmaya çalışan oyuncunun ID'si. |
| ip_address[] | Bağlantı kurmaya çalışan oyuncunun IP adresi. |
| port | Kurulmaya çalışılan bağlantının portu. |
## Çalışınca Vereceği Sonuçlar
1 - Diğer filterscriptlerin bu callbacki çalıştırmasını engeller.
0 - Diğer filterscriptler içinde aranması için pas geçilir.
Her zaman öncelikle filterscriptlerde çağrılır.
## Örnekler
```c
public OnIncomingConnection(playerid, ip_address[], port)
{
printf("Incoming connection for player ID %i [IP/port: %s:%i]", playerid, ip_address, port);
return 1;
}
```
## Bağlantılı Fonksiyonlar
- [BlockIpAddress](../functions/BlockIpAddress.md): Belli bir zaman için bir IP adresinin sunucuya girmesini engeller.
- [UnBlockIpAddress](../functions/UnBlockIpAddress.md): Daha önce engellenmiş bir IP adresinin engelini kaldırır.
| openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnIncomingConnection.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnIncomingConnection.md",
"repo_id": "openmultiplayer",
"token_count": 580
} | 459 |
---
title: OnPlayerExitedMenu
description: Oyuncu bir menüden çıktığında çağrılır.
tags: ["player", "menu"]
---
## Açıklama
Oyuncu bir menüden çıktığında çağrılır.
| İsim | Açıklama |
| -------- | ----------------------------------------- |
| playerid | Menüden çıkan oyuncunun ID'si |
## Çalışınca Vereceği Sonuçlar
Her zaman öncelikle oyun modunda çağrılır.
## Örnekler
```c
public OnPlayerExitedMenu(playerid)
{
TogglePlayerControllable(playerid,1); // oyuncuyu menüden çıktığında unfreeze durumuna getirir
return 1;
}
```
## Bağlantılı Fonksiyonlar
- [CreateMenu](../functions/CreateMenu): Menü oluşturur.
- [DestroyMenu](../functions/DestroyMenu): Menü siler.
| openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnPlayerExitedMenu.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnPlayerExitedMenu.md",
"repo_id": "openmultiplayer",
"token_count": 352
} | 460 |
---
title: OnPlayerStateChange
description: Bu fonksiyon, bir oyuncu durumunu değiştirdiğinde çağrılır.
tags: ["player"]
---
## Açıklama
Bu fonksiyon, bir oyuncu durumunu değiştirdiğinde çağrılır. Örneğin, bir oyuncu bir aracın sürücüsündeyken yaya olarak değiştğinde çağrılır.
| Parametre | Açıklama |
| --------- | ---------------------------------------- |
| playerid | Durumu değiştirilen oyuncunun ID'si. |
| newstate | Oyuncunun yeni durumu. |
| oldstate | Oyuncunun önceki durumu. |
Mevcut tüm oyuncu durumlarının listesi için [Oyuncu Durumları](../resources/playerstates)'na bakın.
## Çalışınca Vereceği Sonuçlar
Filtercsript komutlarında her zaman ilk olarak çağrılır.
## Örnekler
```c
public OnPlayerStateChange(playerid, PLAYER_STATE:newstate, PLAYER_STATE:oldstate)
{
if (oldstate == PLAYER_STATE_ONFOOT && newstate == PLAYER_STATE_DRIVER) // Oyuncu eğer araca şoför olarak bindiyse...
{
new vehicleid = GetPlayerVehicleID(playerid);
AddVehicleComponent(vehicleid, 1010); // Araca nitro ekle.
}
return 1;
}
```
## Notlar
<TipNPCCallbacks />
## Bağlantılı Fonksiyonlar
- [GetPlayerState](../functions/GetPlayerState): Oyuncunun mevcut durumunu kontrol etme.
- [GetPlayerSpecialAction](../functions/GetPlayerSpecialAction): Oyuncunun mevcut özel eylemini kontrol edin.
- [SetPlayerSpecialAction](../functions/SetPlayerSpecialAction): Oyuncunun özel eylemini ayarlama.
| openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnPlayerStateChange.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnPlayerStateChange.md",
"repo_id": "openmultiplayer",
"token_count": 691
} | 461 |
---
title: OnVehicleSirenStateChange
description: Bu callback bir aracın siren durumu değiştiğinde çağrılır.
tags: ["vehicle"]
---
<VersionWarnTR name='callback' version='SA-MP 0.3.7' />
## Açıklama
Bu callback bir aracın siren durumu değiştiğinde çağrılır.
| İsim | Açıklama |
| --------- | --------------------------------------------------- |
| playerid | Siren durumunu değiştiren oyuncu ID'si (sürücü). |
| vehicleid | Siren durumu değiştirilen araç ID'si. |
| newstate | 0 ise siren kapalı, 1 ise açık durumda. |
## Çalışınca Vereceği Sonuçlar
1 - Oyun modunda bu callbackin kullanılmasını önler.
0 - Bu callbackin oyun modunda pas geçileceğini gösterir.
Her zaman ilk filterscriptslerde çağrılır.
## Örnekler
```c
public OnVehicleSirenStateChange(playerid, vehicleid, newstate)
{
if (newstate)
{
GameTextForPlayer(playerid, "~W~Siren ~G~acik", 1000, 3);
}
else
{
GameTextForPlayer(playerid, "~W~Siren ~r~kapali", 1000, 3);
}
return 1;
}
```
## Notlar
:::tip
Bu callback sadece bir aracın siren durumu değiştirildiğinde kullanılır, alternatif (H'ye basılı tutma) sirende kullanılmaz.
:::
## Bağlantılı Fonksiyonlar
- [GetVehicleParamsSirenState](../functions/GetVehicleParamsSirenState): Bir aracın siren durumunu kontrol eder.
| openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnVehicleSirenStateChange.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnVehicleSirenStateChange.md",
"repo_id": "openmultiplayer",
"token_count": 669
} | 462 |
---
title: AllowInteriorWeapons
description: Interior içinde silah kullanımını kısıtlamanızı sağlar.
tags: []
---
## Açıklama
Bu fonksiyonla interior içlerinde silah kullanıp kullanılamayacağını belirlersiniz.
| İsim | Açıklama |
| ----------------------------------- | ------------------------------------------------------------------------------------------------------ |
| allow | izni vermek için 1, kapatmak için 0 (default olarak 1 gelir) |
## Çalışınca Vereceği Sonuçlar
Bu fonksiyon geliştiriciye dönüt vermez.
## Örnekler
```c
public OnGameModeInit()
{
// Bu kod interior içinde silah kullanımına izin verir
AllowInteriorWeapons(1);
return 1;
}
```
## Notlar
:::warning
Bu fonksiyon şu anki SA:MP sürümünde çalışmamakta!
:::
## Bağlantılı Fonksiyonlar
- [SetPlayerInterior](SetPlayerInterior.md): Oyuncunun interiorunu değiştirin.
- [GetPlayerInterior](SetPlayerInterior.md): Oyuncunun interiorunu öğrenin.
- [OnPlayerInteriorChange](../callbacks/OnPlayerInteriorChange.md): Bu callback oyuncunun interioru değiştiğinde çağrılır.
| openmultiplayer/web/docs/translations/tr/scripting/functions/AllowInteriorWeapons.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/tr/scripting/functions/AllowInteriorWeapons.md",
"repo_id": "openmultiplayer",
"token_count": 630
} | 463 |
---
title: CancelSelectTextDraw
description: Fare seçim modunu iptal edin.
tags: ["textdraw"]
---
## Açıklama
Fare seçim modunu iptal edin. Fareniz ekrandan gider.
| Parametre | Açılama |
| --------- | ------------------------------------------------------------------- |
| playerid | Fare seçim modu iptal edilecek oyuncunun ID'si. |
## Çalışınca Vereceği Sonuçlar
Bu fonksiyon herhangi bir değer döndürmez.
## Örnekler
```c
public OnPlayerCommandText(playerid, cmdtext[])
{
if (!strcmp(cmdtext, "/cancelselect", true))
{
CancelSelectTextDraw(playerid);
SendClientMessage(playerid, 0xFFFFFFFF, "SERVER: TextDraw seçimi iptal edildi!");
return 1;
}
return 0;
}
```
## Notlar
:::warning
\*Bu fonksiyon OnPlayerClickTextDraw'ı ile INVALID_TEXT_DRAW(65535) çağırır. Bu işlevi OnPlayerClickTextDraw içinde bu duruma yakalanmadan kullanmak, istemcilerin sonsuz bir döngüye girmesine neden olur.
:::
## Bağlantılı Fonksiyonlar
- [SelectTextDraw](SelectTextDraw): Oyuncunun bir TextDraw seçmesi için faresini etkinleştirme.
- [TextDrawSetSelectable](TextDrawSetSelectable): Bir TextDraw'ın seçilebilirliğini düzenleme.
- [OnPlayerClickTextDraw](../callbacks/OnPlayerClickTextDraw): Bu fonksiyon, bir oyuncu bir TextDraw'a tıkladığında çağrılır.
| openmultiplayer/web/docs/translations/tr/scripting/functions/CancelSelectTextDraw.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/tr/scripting/functions/CancelSelectTextDraw.md",
"repo_id": "openmultiplayer",
"token_count": 615
} | 464 |
---
title: GetActorPos
description: Aktörün koordinat değerlerini kontrol etme.
tags: ["actor"]
---
<VersionWarnTR version='SA-MP 0.3.7' />
## Açıklama
Aktörün koordinat değerlerini kontrol etme.
| Parametre | Description |
| ------- | --------------------------------------------------------------------------------------- |
| actorid | Koordinat değerleri kontrol edilecek aktörün ID'si. |
| X | Aktör'e ait olan X koordinatının saklanması için gerekli değişken. |
| Y | Aktör'e ait olan Y koordinatının saklanması için gerekli değişken. |
| Z | Aktör'e ait olan Z koordinatının saklanması için gerekli değişken. |
## Çalışınca Vereceği Sonuçlar
1: Fonksiyon çalıştı.
0: Fonksiyon geçersiz aktör ID'si girildiği için çalışmadı.
Aktörün XYZ değeri oluşturulan değişkenlerde saklanır.
## Örnekler
```c
new Float:x, Float:y, Float:z; // Herhangi bir yere aktörün koordinat değerlerinin saklanacağı değişkenleri tanıtıyoruz.
GetActorPos(actorid, x, y, z);
```
## Bağlantılı Fonksiyonlar
- [SetActorPos](SetActorPos): Aktörün koordinat değerlerini değiştirme.
| openmultiplayer/web/docs/translations/tr/scripting/functions/GetActorPos.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/tr/scripting/functions/GetActorPos.md",
"repo_id": "openmultiplayer",
"token_count": 700
} | 465 |
# PAWN

### gömülü betik dili
##### Şubat 2006
---
##### ITB CompuPhase
##### ii
---
“Java”, Sun Microsystems, Inc. şirketinin ticari markasıdır.
“Microsoft” ve “Microsoft Windows”, Microsoft Corporation'ın tescilli ticari markalarıdır.
“Linux”, Linus Torvalds'ın tescilli ticari markasıdır.
“CompuPhase”, ITB CompuPhase'nin tescilli ticari markasıdır.
“Unicode”, Unicode, Inc.'in tescilli ticari markasıdır.
Telif Hakkı c 1997–2006, ITB CompuPhase
Eerste Industriestraat 19–21, 1401VL Bussum Hollanda
telefon: (+31)-(0)35 6939 261
e-posta: info@compuphase.com, http://www.compuphase.com
Bu kılavuzdaki bilgiler ve ilişkili yazılım "olduğu gibi" sağlanmıştır. Yazılımın ve kılavuzun doğru olduğuna dair açık veya örtülü herhangi bir garanti bulunmamaktadır.
Kılavuz ve yazılıma yönelik düzeltme ve eklemeler için talepler, yukarıdaki adrese ITB CompuPhase'e yönlendirilebilir.
TEX ile "Computer Modern" ve "Palatino" yazı tipleri kullanılarak 11 punto temel boyutta düzenlenmiştir.
---
# İçindekiler
---
[Önsöz](01-Foreword.md) - Sayfa 3-5
[Öğretici giriş](02-A-tutorial-introduction.md) - Sayfa 5-62
[Veri ve deklarasyonlar](03-Data-and-declarations.md) - Sayfa 62-70
[Fonksiyonlar](04-Functions.md) - Sayfa 70-93
[Ön işlemci](05-The-preprocessor.md) - Sayfa 93-97
[Genel sözdizimi](06-General-syntax.md) - Sayfa 97-104
[Operatörler ve ifadeler](07-Operators-and-expressions.md) - Sayfa 104-112
[İfadeler](08-Statements.md) - Sayfa 112-117
[Doğrudanifadeler](09-Directives.md) - Sayfa 117-124
[Taslak fonksiyon kütüphanesi](10-Proposed-function-library.md) - Sayfa 124-134
[Tuzaklar: C'den farklılıklar](11-Pitfalls-differences-from-C.md) - Sayfa 134-137
[Çeşitli ipuçları](12-Assorted-tips.md) - Sayfa 137-148
[Ekler](13-Appendices.md) - Sayfa 148-183
∟ [Hata ve uyarı mesajları](12-Appendices.md#error-and-warning-messages) - Sayfa 148-168
∟ [Derleyici](13-Appendices.md#the-compiler) - Sayfa 168-174
∟ [Gerekçe](13-Appendices.md#rationale) - Sayfa 174-181
∟ [Lisans](13-Appendices.md#license) - Sayfa 181-183
| openmultiplayer/web/docs/translations/tr/scripting/language/reference/00-Contents.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/tr/scripting/language/reference/00-Contents.md",
"repo_id": "openmultiplayer",
"token_count": 1010
} | 466 |
---
title: OnNPCDisconnect
description: 当NPC与服务器断开连接时,会调用此回调。
tags: []
---
## 描述
当 NPC 与服务器断开连接时,会调用此回调。
| 参数名 | 描述 |
| -------- | -------------------------- |
| reason[] | NPC 与服务器断开连接的原因 |
## 案例
```c
public OnNPCDisconnect(reason[])
{
printf("已断开与服务器的连接 %s", reason);
}
```
## 相关回调
- [OnNPCConnect](../callbacks/OnNPCConnect): 当 NPC 成功连接到服务器时调用。
- [OnPlayerDisconnect](../callbacks/OnPlayerDisconnect): 在玩家离开服务器时调用。
- [OnPlayerConnect](../callbacks/OnPlayerConnect): 当玩家连接到服务器时调用。
| openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnNPCDisconnect.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnNPCDisconnect.md",
"repo_id": "openmultiplayer",
"token_count": 410
} | 467 |
---
title: OnPlayerEditObject
description: 当玩家编辑完一个物体(EditObject/EditPlayerObject)时,会调用该回调。
tags: ["player"]
---
## 描述
当玩家编辑完一个物体(EditObject/EditPlayerObject)时,会调用该回调。
| 参数名 | 描述 |
| ------------ | ---------------------------------------------------- |
| playerid | 编辑物体的玩家的 ID |
| playerobject | 如果它是全局物体,则为 0;如果它是玩家物体,则为 1。 |
| objectid | 已编辑物体的 ID |
| EDIT_RESPONSE:response | [响应类型](../resources/objecteditionresponsetypes) |
| Float:fX | 已编辑物体的 X 偏移量 |
| Float:fY | 已编辑物体的 Y 偏移量 |
| Float:fZ | 已编辑物体的 Z 偏移量 |
| Float:fRotX | 已编辑物体的 X 向旋转 |
| Float:fRotY | 已编辑物体的 Y 向旋转 |
| Float:fRotZ | 已编辑物体的 Z 向旋转 |
## 返回值
1 - 将阻止其他脚本接收此回调。
0 - 指示此回调将传递给下一个脚本。
它在过滤脚本中总是先被调用。
## 案例
```c
public OnPlayerEditObject(playerid, playerobject, objectid, EDIT_RESPONSE:response, Float:fX, Float:fY, Float:fZ, Float:fRotX, Float:fRotY, Float:fRotZ)
{
new
Float: oldX,
Float: oldY,
Float: oldZ,
Float: oldRotX,
Float: oldRotY,
Float: oldRotZ;
GetObjectPos(objectid, oldX, oldY, oldZ);
GetObjectRot(objectid, oldRotX, oldRotY, oldRotZ);
if (!playerobject) // 如果这是全局物体,请同步其他玩家的位置
{
if (!IsValidObject(objectid))
{
return 1;
}
SetObjectPos(objectid, fX, fY, fZ);
SetObjectRot(objectid, fRotX, fRotY, fRotZ);
}
switch (response)
{
case EDIT_RESPONSE_FINAL:
{
// 玩家点击了保存图标
// 在此执行任何操作以保存更新的物体位置(和旋转)
}
case EDIT_RESPONSE_CANCEL:
{
// 玩家取消了比赛,所以把物体放回原来的位置
if (!playerobject) // 物体不是玩家物体
{
SetObjectPos(objectid, oldX, oldY, oldZ);
SetObjectRot(objectid, oldRotX, oldRotY, oldRotZ);
}
else
{
SetPlayerObjectPos(playerid, objectid, oldX, oldY, oldZ);
SetPlayerObjectRot(playerid, objectid, oldRotX, oldRotY, oldRotZ);
}
}
}
return 1;
}
```
## 要点
:::warning
使用‘EDIT_RESPONSE_UPDATE’时,请注意,在释放正在进行的编辑时不会调用此回调,从而导致‘EDIT_RESPONSE_UPDATE’的最后更新与物体当前位置不同步。
:::
## 相关函数
- [EditObject](../functions/EditObject): 编辑物体。
- [CreateObject](../functions/CreateObject): 创建一个物体。
- [DestroyObject](../functions/DestroyObject): 摧毁一个物体。
- [MoveObject](../functions/MoveObject): 移动物体。
| openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnPlayerEditObject.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnPlayerEditObject.md",
"repo_id": "openmultiplayer",
"token_count": 2058
} | 468 |
---
title: OnPlayerRequestDownload
description: 当玩家请求自定义模型下载时,这个回调函数被调用。
tags: ["player"]
---
<VersionWarnCN name='回调' version='SA-MP 0.3.DL R1' />
## 描述
当玩家请求自定义模型下载时,这个回调函数被调用。
| 参数名 | 描述 |
| -------- | ----------------------------- |
| playerid | 请求自定义模型下载的玩家 ID。 |
| type | 请求的类型(见下文)。 |
| crc | 自定义模型文件的 CRC 校验和。 |
## 返回值
0 - 拒绝下载请求
1 - 接收下载请求
## 案例
```c
#define DOWNLOAD_REQUEST_EMPTY (0)
#define DOWNLOAD_REQUEST_MODEL_FILE (1)
#define DOWNLOAD_REQUEST_TEXTURE_FILE (2)
new baseurl[] = "https://files.sa-mp.com/server";
public OnPlayerRequestDownload(playerid, type, crc)
{
new fullurl[256+1];
new dlfilename[64+1];
new foundfilename=0;
if (!IsPlayerConnected(playerid)) return 0;
if (type == DOWNLOAD_REQUEST_TEXTURE_FILE) {
foundfilename = FindTextureFileNameFromCRC(crc,dlfilename,64);
}
else if (type == DOWNLOAD_REQUEST_MODEL_FILE) {
foundfilename = FindModelFileNameFromCRC(crc,dlfilename,64);
}
if (foundfilename) {
format(fullurl,256,"%s/%s",baseurl,dlfilename);
RedirectDownload(playerid,fullurl);
}
return 0;
}
```
## 相关函数
- [OnPlayerFinishedDownloading](OnPlayerFinishedDownloading): 当玩家下载完自定义模型时调用。
| openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnPlayerRequestDownload.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnPlayerRequestDownload.md",
"repo_id": "openmultiplayer",
"token_count": 801
} | 469 |
---
title: OnUnoccupiedVehicleUpdate
description: 当玩家的客户端更新/同步他们没有驾驶的车辆的位置时,这个回调被调用。
tags: ["vehicle"]
---
## 描述
当玩家的客户端更新/同步他们没有驾驶的车辆的位置时,这个回调被调用。这可能发生在车外,或当玩家是某个无人驾驶的车辆的乘客时。
| 参数名 | 描述 |
| -------------- | ---------------------------------------------------------------------------------------------------------------------- |
| vehicleid | 更新了位置的车辆载具 ID。 |
| playerid | 发送车辆位置同步更新的玩家的 ID。 |
| passenger_seat | 如果玩家是乘客,则为其座位的 ID。0=不在车上,1=前排乘客,2=后左,3=后右,4+用于有很多乘客座位的大客车/公共汽车等车辆。 |
| new_x | 车辆新的 X 轴坐标。 |
| new_y | 车辆新的 Y 轴坐标。 |
| new_z | 车辆新的 Z 轴坐标。 |
| vel_x | 车辆新的 X 轴速度。略。 |
| vel_y | 车辆新的 Y 轴速度。略。 |
| vel_z | 车辆新的 Z 轴速度。略。 |
## 返回值
它总是在过滤脚本中先被调用,所以返回 0 也会阻止其他过滤脚本看到它。
## 案例
```c
public OnUnoccupiedVehicleUpdate(vehicleid, playerid, passenger_seat, Float:new_x, Float:new_y, Float:new_z, Float:vel_x, Float:vel_y, Float:vel_z)
{
// 检查它是否移动了很远。
if (GetVehicleDistanceFromPoint(vehicleid, new_x, new_y, new_z) > 50.0)
{
// 拒绝更新
return 0;
}
return 1;
}
```
## 要点
:::warning
这个回调函数每秒钟被频繁地调用。
您应该避免在这个回调中实现密集的计算或密集的文件写/读操作。
GetVehiclePos 函数将返回在此更新之前车辆的旧坐标。
:::
## 相关回调
| openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnUnoccupiedVehicleUpdate.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnUnoccupiedVehicleUpdate.md",
"repo_id": "openmultiplayer",
"token_count": 1658
} | 470 |
---
title: AddStaticPickup
description: 该函数用于给游戏添加一个“静态”拾取器。
tags: []
---
## 描述
该函数用于给游戏添加一个“静态”拾取器。拾取器支持武器、生命值、护甲等,无需编写脚本即可生效(武器/生命值/护甲将自动提供)。
| 参数名 | 说明 |
| -------------------------------- | --------------------------------------------------------- |
| [model](../resources/pickupids) | 拾取器的模型。 |
| [type](../resources/pickuptypes) | 拾取器的类型。决定了拾取器在被拾起时如何响应。 |
| Float:X | 在哪个 X 轴坐标创建。 |
| Float:Y | 在哪个 Y 轴坐标创建。 |
| Float:Z | 在哪个 Z 轴坐标创建。 |
| virtualworld | 要显示拾取器的虚拟世界 ID。使用 -1 表示在所有世界中显示。 |
## 返回值
如果创建成功,则为 1。
如果创建失败,则为 0。
## 案例
```c
public OnGameModeInit()
{
// 创建一个护甲拾取器
AddStaticPickup(1242, 2, 1503.3359, 1432.3585, 10.1191, 0);
// 创建一个生命值拾取器,就在护甲边上
AddStaticPickup(1240, 2, 1506.3359, 1432.3585, 10.1191, 0);
return 1;
}
```
## 要点
:::tip
该函数不返回您可以在 OnPlayerPickUpPickup 中使用的拾取 ID。
如果您想分配 ID,请使用 CreatePickup。
:::
## 相关函数
- [CreatePickup](CreatePickup): 创建一个拾取器。
- [DestroyPickup](DestroyPickup): 销毁一个拾取器。
- [OnPlayerPickUpPickup](../callbacks/OnPlayerPickUpPickup): 当某个玩家拾起一个拾取器时调用。
| openmultiplayer/web/docs/translations/zh-cn/scripting/functions/AddStaticPickup.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/functions/AddStaticPickup.md",
"repo_id": "openmultiplayer",
"token_count": 1271
} | 471 |
---
title: ClearAnimations
description: 清除指定玩家的所有动画(它也取消所有当前任务,如喷气背包、跳伞、进入载具、驾驶(将玩家从载具中移除)、游泳等。
tags: []
---
## 描述
清除指定玩家的所有动画(它也取消所有当前任务,如喷气背包、跳伞、进入载具、驾驶(将玩家从载具中移除)、游泳等。
| 参数名 | 说明 |
| --------- | ------------------------------------------------------------ |
| playerid | 要清除动画的玩家的 ID。 |
| forcesync | 设为 1,强迫 playerid 与流半径内的其他玩家同步动画(可选)。 |
## 返回值
这个函数总是返回 1,即使指定的玩家没有连接。
## 案例
```c
public OnPlayerCommandText(playerid, cmdtext[])
{
if (!strcmp(cmdtext, "/animclear", true))
{
ClearAnimations(playerid);
return 1;
}
return 0;
}
```
## 要点
:::tip
如果在 ApplyAnimation 中给冻结参数传入 1,那么当动画结束后,ClearAnimations 不会有任何效果。
:::
:::tip
与其他一些将玩家从载具中移除的方法不同,这也会将载具的速度重置为零,使载具瞬间停止前进。玩家将出现在他载具的座位上的位置相同的上方。
:::
## 相关函数
- [ApplyAnimation](ApplyAnimation): 将动画应用于玩家。
| openmultiplayer/web/docs/translations/zh-cn/scripting/functions/ClearAnimations.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/functions/ClearAnimations.md",
"repo_id": "openmultiplayer",
"token_count": 906
} | 472 |
---
title: SetCameraBehindPlayer
description: 使用SetPlayerCameraPos等函数后,将视角重置到玩家的后面。
tags: ["player", "camera"]
---
## 描述
使用 SetPlayerCameraPos 等函数后,将视角重置到玩家的后面。
| 参数名 | 说明 |
| -------- | --------------------- |
| playerid | 要重置视角的玩家 ID。 |
## 返回值
1:函数执行成功。
0:函数执行失败。 这意味着指定的玩家不存在。
## 案例
```c
SetCameraBehindPlayer(playerid);
```
## 相关函数
- [SetPlayerCameraPos](SetPlayerCameraPos): 设置玩家的视角位置。
- [SetPlayerCameraLookAt](SetPlayerCameraLookAt): 设置玩家的视角所看的方向。
| openmultiplayer/web/docs/translations/zh-cn/scripting/functions/SetCameraBehindPlayer.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/functions/SetCameraBehindPlayer.md",
"repo_id": "openmultiplayer",
"token_count": 386
} | 473 |
---
title: "远程控制 (RCON)"
description: 远程服务器管理.
---
远程控制台是一个命令提示符,您可以在其中使用 RCON 命令,而无需进入游戏和服务器。 从 0.3b 开始,远程控制台已从服务器详细信息中删除。 从现在开始,您将必须使用另一种方式来访问远程 RCON,如下所述。
1. 打开一个文本编辑器 (记事本即可).
2. 在其中写入: `rcon.exe IP PORT RCON-PASS` (将 IP/PORT/RCON-PASS 替换为您的服务器信息)
3. 保存该文件为 `rcon.bat`
4. 将该文件放入与 `rcon.exe` 同级目录.
5. 运行 `rcon.bat`
6. 如果参数无误,您将能够连接到您的服务器,可以输入任意 RCON 命令管理您的服务器.

注意:不需要在服务器控制台的命令前输入`/rcon`,否则命令将不起作用。 例如,如果您想重置服务器,只需键入“gmx”并回车即可。
| openmultiplayer/web/docs/translations/zh-cn/server/RemoteConsole.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/zh-cn/server/RemoteConsole.md",
"repo_id": "openmultiplayer",
"token_count": 659
} | 474 |
---
title: How can I join the team?
date: "2021-08-29T01:24:09"
author: Potassium
---
➖ KAKO SE MOGU PRIDRUŽITI TIMU?
Ovo pitanje nam se PUNO postavlja, pa smo mislili da bismo trebali napraviti post o tome!
Prvo, veliko Vam hvala svima na zainteresovanju za doprinos!
Kao što znate, svi smo mi "SA-MP veterani", igrači, koji su se okupili da održimo svijet SA multiplayera živim. Mi smo strastveni oko toga da je projekat ZA igrače i BY igrače, i to je razlog zašto će na kraju biti open-source.
RAZVOJ:
Trenutno radimo na završnim detaljima beta izdanja, a kada ono bude uživo, bili bismo veoma zahvalni i dobrodošli bismo doprinos zajednice! Trebat će nam pomoć u testiranju funkcionalnosti i rubnih slučajeva, i naravno u potrazi za greškama i drugim problemima na kojima je potrebno raditi.
Beta test će biti izuzetno važan dio razvojnog puta, i voljeli bismo da svi budu uključeni, stoga vas molimo da ostavite sa nama za najavu beta testa, za koji obećavamo da će biti vrlo, jako brzo!
REGIONALNI KOORDINATORI:
Govorite li engleski I drugi jezik, oboje tečno? Voljeli bismo vašu pomoć da prevedemo naše Wiki stranice, naše postove na blogu i objave na društvenim mrežama, te da pomognemo u moderiranju jezičnih odjeljaka našeg Discorda i našeg foruma.
Prijave za ova radna mjesta su trenutno zatvorene dok radimo neke promjene, ali će uskoro biti ponovo otvorene!
DRUGI NAČINI POMOĆI:
- PODIJELITE naše objave na društvenim mrežama
- POZOVITE druge SA igrače u naš Discord (discord.gg/samp)
- UKLJUČUJ SE u našu zajednicu na Discordu
- POMOZI drugim igračima na Discordu (skriptiranje, tehnika, bilo šta!)
| openmultiplayer/web/frontend/content/bs/blog/how-to-join-the-team.mdx/0 | {
"file_path": "openmultiplayer/web/frontend/content/bs/blog/how-to-join-the-team.mdx",
"repo_id": "openmultiplayer",
"token_count": 737
} | 475 |
# FAQ (Preguntas frecuentes)
<hr />
## ¿Qué es open.mp?
open.mp (Open Multiplayer, OMP) es un mod multijugador sustituto para San Andreas, iniciado como respuesta al desafortunado aumento de problemas en actualizaciones y la administración de SA:MP. El lanzamiento inicial será un reemplazo directo del software para el servidor solamente. Los clientes SA:MP ya existentes podrán conectarse a este servidor. En el futuro, un nuevo cliente para open.mp estará disponible, permitiendo lanzar más actualizaciones interesantes.
<hr />
## ¿Es un fork/una bifurcación?
No. Esta es una reescritura completa, tomando ventaja de décadas de conocimiento y experiencia. Han habido intentos de bifurcarse de SA:MP antes, pero creemos que estos tenian dos graves problemas:
- Estaban basados en código filtrado de SA:MP. Los autores de estos mods no tenían derechos legales para poder usar este código, y por eso siempre tuvieron una desventaja, tanto moral como legal. Nos rehusamos directamente a usar este código. Esto desacelera un poco la velocidad de desarollo, pero es un movimiento clave a la larga.
- Intentaron reinventar mucho a la vez. Ya sea reemplazando el motor de scripting, o sacando características mientras añadían otras, o cambiando las cosas de maneras no compatibles. Esto impedía a servidores existentes con scripts largos y una base de jugadores muy grande mudarse, ya que tendrian que reescribir poco, si es que no todo, su código - un trabajo extraordinariamente grande. Nuestra intención es ir añadiendo características y cambiando las cosas, con el tiempo, pero tambien estamos concentrados en soportar servidores existentes, permitiéndoles usar nuestro código sin tener que cambiar el suyo.
<hr />
## ¿Por qué hacen esto?
A pesar de numerosos intentos por impulsar el desarollo de SA:MP hacia adelante oficialmente, en la forma de sugerencias, peticiones repetidas, y ofertas de ayuda de miembros del mismo equipo de beta-testing; junto a una comunidad pidiendo a gritos algo nuevo; no se veía nada de progreso. Esto siempre se percibía simplemente como una falta de interés por parte del líder del mod, lo cual no es un problema en si, pero no había ninguna señal de continuación. En vez de permitir que los demás pudieran contribuir al desarrollo del mod, el fundador simplemente quería traerse todo abajo con él mismo, mientras aparentemente mantenía las cosas cuando podía con un mínimo esfuerzo. Algunos decían que esto era por razones de ganancias pasivas, pero no hay evidencia de eso. A pesar del interés inmenso y una fuerte comunidad, él pensaba que al mod le quedaban solo 1-2 años de vida, y la comunidad que trabajaba tan duro para hacer SA:MP lo que es hoy en día, no se merecía una continuación.
<br />
Nosotros no estamos de acuerdo.
<hr />
## ¿Cuáles son sus opiniones acerca de Kalcor/SA:MP o lo que fuese?
Amamos SA:MP, es por eso que estamos aquí en primer lugar y, debemos el crear eso a Kalcor. Él ha realizado muchísimo para el mod y esa contribución no debería ser olvidada o ignorada. La acciones que desembocaron en open.mp se tomaron bajo el motivo de que no compartimos severas decisiones y, sin importar los intentos reiterados de guiar el mod en una diferente dirección, ninguna solución ha sido vista venir. Por ésto fuimos forzados a tomar la decisión de intentar continuar SA:MP en espíritu sin Kalcor. Esto no es una acción tomada en contra de él personalmente, y no debería ser vista como un ataque a él, personalmente. No toleraremos que se insulte a nadie, sin importar la problemática, si formas parte de open.mp, podrías tener un debate razonable sin recurrir a ataques ad-hominem.
<hr />
## ¿No es esto simplemente dividir a la comunidad?
Esa no es nuestra intención. Lo ideal es que no se requiera ninguna división, pero separar un poco y guardar esa parte es mejor que mirar cómo se marchita todo. De hecho, desde que se anunció este mod, una gran cantidad de comunidades que no están en inglés se han vuelto a comprometer con la comunidad inglesa. Estas comunidades fueron empujadas lentamente, por lo que su reincorporación en realidad está uniendo a una comunidad dividida. Un gran número de personas han sido excluidas de los foros oficiales de SA:MP (y en algunos casos, se ha purgado todo su historial de publicaciones), pero el mismo Kalcor ha señalado que los foros oficiales no son SA:MP, solo una parte de SA:MP Muchos jugadores y propietarios de servidores nunca han publicado, o incluso se han unido a esos foros; así que hablar con estas personas de nuevo es unificar aún más partes de la comunidad.
<hr />
## Ya que es "Open" (abierto) Multiplayer, ¿será open-source (código abierto)?
Eventualmente ese es el plan, sí. Por ahora estamos intentando hacer el desarollo "abierto" en términos de comunicación y transparencia (que en sí, ya es una mejora), y se moverá hacia hacer el código abierto una vez las cosas estén bien planeadas.
<hr />
## ¿Cuándo saldrá open.mp?
Esta es la típica pregunta, desafortunadamente tiene la típica respuesta: cuando esté listo. Simplemente no hay manera de saber cuánto tiempo tomará un proyecto como este. Ha estado funcionando silenciosamente por un tiempo, y ya ha visto algunas fluctuaciones en el nivel de actividad, dependiendo de cuán ocupadas estén las personas que lo desarrollan. Pero ten la seguridad de que está en camino y progresando rápidamente gracias a algunas decisiones de diseño fundamentales.
<hr />
## ¿Cómo puedo ayudar?
Permanece atento al foro. Tenemos un tema exactamente para esto, y tenemos la intención de mantenerlo actualizado mientras tengamos cosas que enseñar. Aunque el proyecto fue revelado mucho antes de lo esperado, estamos en un muy bien camino para un lanzamiento inicial, pero eso no significa que más ayuda no sea enormemente apreciada. Gracias de antemano por tener interés, y creer en el proyecto:
<br />
[Tema "How to help" (como ayudar) (en inglés)](https://forum.open.mp/showthread.php?tid=99)
<hr />
## ¿Qué es burgershot.gg?
burgershot.gg es un foro de gaming, nada más. Un montón de gente está involucrada en ambos, y algo del desarollo y actualizaciones sobre OMP están siendo publicados ahí, pero son dos proyectos independientes. No son los foros OMP, y tampoco es OMP propiedad de burgershot. Una vez que tengamos un sitio para OMP completo y andando, los dos podrán ser separados el uno del otro (muy así como SA:MP estuvo alguna vez hospedado en GTAForums antes de que tuvieran su propio sitio).
<hr />
## ¿Qué hay de OpenMP?
El proyecto "Open Multi-Processing" (Multi-procesamiento abierto) es "OpenMP", nosotros somos "open.mp". Hay mucha diferencia.
| openmultiplayer/web/frontend/content/es/faq.mdx/0 | {
"file_path": "openmultiplayer/web/frontend/content/es/faq.mdx",
"repo_id": "openmultiplayer",
"token_count": 2394
} | 476 |
<h1>FAQ</h1>
<hr />
<h2>O que é open.mp?</h2>
open.mp (Open Multiplayer, OMP) é um mod multiplayer substituto para San Andreas, iniciado em
resposta ao infeliz aumento de problemas com atualizações e gerenciamento do SA:MP. O lançamento
inicial vai ser uma substituição fácil para o software de servidor apenas. Clientes SA:MP serão
capazes de conectar neste servidor. No futuro, um novo cliente open.mp vai ser disponibilizado,
permitindo o lançamento de atualizações mais interessantes.
<hr />
<h2>Isso é uma cópia/reaproveitamento de código?</h2>
Não. Este projeto foi totalmente reescrito, tendo a vantagem de décadas de conhecimento e
experiências. Houveram tentativas de reaproveitar o código do SA:MP antes, mas acreditamos que tais
tentativas tinham dois grandes problemas:
<ol>
<li>
Elas foram baseadas em um código fonte vazado do SA:MP. Os autores dessas modificações não
tinham nenhum direito legal sobre este código, e assim sempre estiveram com uma desvantagem,
tanto moral como legal. Nós nos recusamos a usar este código. Isto deixa o desenvolvimento
um pouco mais lento, mas é a escolha certa a se fazer.
</li>
<li>
Elas tentaram reinventar muito de uma vez. Ou por substituindo todo o motor de
desenvolvimento, ou removendo e adicionando características, ou apenas por melhorar coisas
de maneira incompativel. Isto impede que servidores com imensas bases de código e base de
jogadores pudessem se mudar, já que teriam que reescrever alguns, se não todos, os seus
códigos - um trabalho muito exaustivo. Nós temos a intenção de adicionar características, e
melhorar as coisas com o passar do tempo, mas estamos também focados em dar suporte a
servidores existentes, permitindo que eles usem nosso código sem alterar o deles.
</li>
</ol>
<hr />
<h2>Por que vocês estão fazendo isso?</h2>
Mesmo após numerosas tentativas de empurrar o desenvolvimento do SA:MP oficialmente, na forma de
sugestões, vários pedidos, e ofertas de ajuda por parte da equipe de testadores de versões beta; uma
comunidade literalmente implorando por qualquer atualização que seja; nenhum progresso foi visto.
Isto foi percebido pela falta de interesse do fundador, o que não é um problema, mas não havia
nenhuma linha de sucessão. Em vez de entregar o desenvolvimento nas mãos de alguém interessado em
continuar a trabalhar na modificação, o fundador simplesmente escolheu trazer tudo abaixo consigo
mesmo. Alguns clamam que isto foi por razões de ganância passiva, mas não há evidências disso.
Apesar do enorme interesse e de uma comunidade forte e familiar, ele acreditava que restavam apenas
1-2 anos na modificação e que a comunidade que havia trabalhado tanto para fazer o SA:MP o que é
hoje, não merecia uma continuação.
<br />
Nós discordamos.
<hr />
<h2>Quais suas opiniões sobre o Kalcor ou SA:MP?</h2>
Nós amamos o SA:MP, e é por isso que estamos aqui em primeiro lugar - e nós devemos isso ao Kalcor.
Ele fez muito pelo mod ao longo dos anos, e essa contribuição não deve ser esquecida ou ignorada. As
ações que levaram ao open.mp foram tomadas porque discordamos de várias decisões recentes, e apesar
das tentativas de guiar o mod em uma direção diferente, nenhuma solução foi vista como próxima.
Assim, fomos forçados a tomar a infeliz decisão de tentar continuar o SA:MP em espírito sem o
Kalcor. Esta não é uma ação tomada contra ele pessoalmente, e não deve ser vista como um ataque
contra o mesmo. Não vamos tolerar insultos contra ninguém - independentemente de onde eles estejam
em questão do open.mp; deveríamos ser capazes de ter um debate razoável sem recorrer a ataques à
pessoa.
<hr />
<h2>Isto não está apenas dividindo a comunidade?</h2>
Essa não é a nossa intenção. Idealmente, isso não é necessário, mas dividir uma parte e salvar ela é
melhor do que ver a coisa toda desaparecer. De fato, desde que esse mod foi anunciado, um grande
número de comunidades de fora se juntaram novamente com a comunidade inglesa. Essas comunidades
foram lentamente empurradas para fora, então a reinclusão delas está trazendo de volta uma
comunidade que antes foi dividida. Um grande número de pessoas foram banidas do fórum oficial do
SA:MP (e em alguns casos, tiveram todas as suas postagens removidas), mas o próprio Kalcor apontou
que o fórum oficial não é o SA:MP em si, mas, apenas uma parte dele. Muitos jogadores e donos de
servidores nunca postaram ou participaram do fórum; então falar com essas pessoas irá unir a
comunidade ainda mais.
<hr />
<h2>Já que isto é "Open" Multiplayer, este projeto será de código aberto?</h2>
Eventualmente esse é o plano, sim. Por enquanto, estamos tentando tornar o desenvolvimento aberto em
termos de comunicação e transparência (o que, em si mesmo, é uma melhoria), e avançaremos para o
código aberto quando pudermos, uma vez que tudo esteja resolvido.
<hr />
<h2>Quando o open.mp será lançado?</h2>
Esta é uma a questão antiga e, infelizmente, temos a seguinte resposta para ela: quando estiver
pronto. Simplesmente não há como saber quanto tempo um projeto como esse levará. Ele já está
funcionando silenciosamente há algum tempo e já viu algumas mudanças no nível de atividade,
dependendo de como as pessoas estão ocupadas. Mas é certeza que tudo está indo bem, e progredindo
rapidamente graças a algumas decisões fundamentais de design (em breve falaremos sobre a
arquitetura).
<hr />
<h2>Como eu posso ajudar?</h2>
Fique de olho nos fóruns. Temos um tópico exatamente para isso e vamos mantê-lo atualizado à medida
que mais trabalhos se tornarem disponíveis. Embora o projeto tenha sido revelado um pouco antes do
planejado, já estamos a caminho de um lançamento inicial, mas isso não significa que mais ajuda não
seja apreciada. Agradeço antecipadamente por se interessar e por acreditar no projeto:
<br />
<a href="https://forum.open.mp/showthread.php?tid=99">
<u>"Tópico sobre como ajudar"</u>
</a>
<hr />
<h2>O que é burgershot.gg?</h2>
O burgershot.gg é um fórum de jogos, nada mais. Muitas pessoas estão envolvidas em ambos, e algumas
atualizações e desenvolvimento do OMP são postadas lá, mas são dois projetos independentes. Eles não
são os fóruns do OMP, nem o OMP é uma propriedade do burgershot. Uma vez que o site completo do OMP
esteja em funcionamento, os dois podem ser desconectados um do outro (assim como o SA:MP já foi
hospedado pelo GTAForums antes de seu próprio site estar ativo).
<hr />
<h2>E sobre o OpenMP?</h2>
O projeto Open Multi-Processing é chamado "OpenMP", nós somos "open.mp". Totalmente diferente.
| openmultiplayer/web/frontend/content/pt-BR/faq.mdx/0 | {
"file_path": "openmultiplayer/web/frontend/content/pt-BR/faq.mdx",
"repo_id": "openmultiplayer",
"token_count": 2608
} | 477 |
---
title: Forum and Wiki offline
description: Wondering why the SA-MP Forum and Wiki are offline? Read this for information and next steps.
---
# Чому форум та вікі недоступні?
25 вересня 2020 року термін дії сертифіката для forum.sa-mp.com та wiki.sa-mp.com закінчився. Багато користувачів звернули увагу на це й підняли проблему на Discord.
Хоча сайт все ще був доступний в обхід безпеки HTTPS, було очевидно, що щось більше не в порядку.
Наступного дня користувачі виявили, що обидва сайти повністю офлайн, а в браузері відображаються помилки бази даних.

Тепер ця помилка є досить поширеною, вона зазвичай вказує на резервну копію бази даних. Але з огляду на інцидент із сертифікатом SSL, це здавалося свідченням чогось іншого.
Пізніше того ж дня обидва сайти були повністю офлайн, навіть не відповідаючи сторінкою з помилкою.

## Що це значить?
У спільноті SA-MP багато припущень, але офіційного повідомлення про те, що сталося, немає. Однак, як ми дізналися в минулому, найкраще припустити найгірше.
Форум та вікі, ймовірно, не повернуться. Було б чудово помилитися з цього приводу.
## Альтернативи
Наразі вміст вікі все ще доступний за допомогою збережених копій на [Archive.org](http://web-old.archive.org/web/20200314132548/https://wiki.sa-mp.com/wiki/Main_Page).
Очевидно, це не найкраще довгострокове рішення. Завантаження цих сторінок займає багато часу, і це підкреслює службу Archive.org (яка вже недофінансована і є дуже важливою частиною історії Інтернету).
[Наша версія вікі SA-MP](/docs) є чудовою сучасною альтернативою. Він використовує Markdown і розміщується за допомогою GitHub та Vercel. Ми закликаємо користувачів максимально сприяти передачі всіх наявних сторінок вікі до нової. Дізнатися більше можна тут: https://github.com/openmultiplayer/wiki/issues/27
| openmultiplayer/web/frontend/content/uk/missing-sites.mdx/0 | {
"file_path": "openmultiplayer/web/frontend/content/uk/missing-sites.mdx",
"repo_id": "openmultiplayer",
"token_count": 1808
} | 478 |
/// <reference types="next" />
/// <reference types="next/types/global" />
/// <reference types="next/image-types/global" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information.
| openmultiplayer/web/frontend/next-env.d.ts/0 | {
"file_path": "openmultiplayer/web/frontend/next-env.d.ts",
"repo_id": "openmultiplayer",
"token_count": 71
} | 479 |
import { Box } from "@chakra-ui/layout";
import { FC } from "react";
/**
* Provides a generic page wrapper that sets the correct max width.
*/
const Measured: FC = ({ children }) => {
return (
<Box maxWidth="48em" mx="auto" p="0.5em" height="100%">
{children}
</Box>
);
};
export default Measured;
| openmultiplayer/web/frontend/src/components/generic/Measured.tsx/0 | {
"file_path": "openmultiplayer/web/frontend/src/components/generic/Measured.tsx",
"repo_id": "openmultiplayer",
"token_count": 115
} | 480 |
import { Box, HStack, Stack, VStack, Text, useColorModeValue, Link } from "@chakra-ui/react";
import { ExternalLinkIcon } from "@chakra-ui/icons";
import Image from "next/image";
import NextLink from "next/link";
import cardStyles from "../../styles/Card.module.css";
import React, { VFC } from "react";
type CardProps = {
heading: string;
bodyText: string;
buttonLink: string;
buttonText: string;
img: string;
imgAlt: string;
};
const Card: VFC<CardProps> = ({
heading,
bodyText,
buttonLink,
buttonText,
img,
imgAlt,
}) => {
return (
<Box
maxW="60em"
className={cardStyles.card}
bgGradient={useColorModeValue('linear(to-r, #f7f7f7, rgba(247, 247, 247, 0))', 'linear(to-r, gray.800, gray.700)')}
border={useColorModeValue('1px solid rgba(134, 119, 206, 0.185)', '1px solid rgba(134, 119, 206, 0.15)')}
boxShadow={useColorModeValue('0px 0px 40px 8px rgba(134, 119, 206, 0.05)', '')}
px={{ base: "1em", md: "4em" }}
py={{ base: "3em", md: "4em" }}
>
<HStack
spacing="2em"
justify={{ base: "center", md: "space-between" }}
wrap="wrap-reverse"
gridGap={{ base: "1em", md: "6em" }}
>
<Stack
maxW={{ base: "34em", md: "20em" }}
textAlign={{ base: "center", md: "left" }}
align="left"
spacing="1em"
mt={{ base: "1em", md: "0" }}
>
<VStack align="left" spacing="0.6em">
<Text fontWeight="700" fontSize="xl">
{heading}
</Text>
<Text color={useColorModeValue('#505050', 'gray.500')}>{bodyText}</Text>
</VStack>
<NextLink href={buttonLink} passHref>
<HStack
align="center"
spacing="0.2em"
justify={{ base: "center", md: "left" }}
>
<Link
href={buttonLink}
style={{
color: "#9083D2",
fontSize: "md",
fontWeight: 700,
}}
>
{buttonText}
</Link>
<ExternalLinkIcon w={4} h={4} color="#9083D2" />
</HStack>
</NextLink>
</Stack>
<Box>
<Image
src={img}
alt={imgAlt}
width="180"
height="160"
quality="100"
/>
</Box>
</HStack>
</Box>
);
};
export default Card;
| openmultiplayer/web/frontend/src/components/site/Card.tsx/0 | {
"file_path": "openmultiplayer/web/frontend/src/components/site/Card.tsx",
"repo_id": "openmultiplayer",
"token_count": 1321
} | 481 |
import Admonition from "../../../Admonition";
export default function NoteLowercase({ name = "function" }) {
return (
<Admonition type="warning">
<p>{name} ini diawali dengan huruf kecil.</p>
</Admonition>
);
}
| openmultiplayer/web/frontend/src/components/templates/translations/id/lowercase-note.tsx/0 | {
"file_path": "openmultiplayer/web/frontend/src/components/templates/translations/id/lowercase-note.tsx",
"repo_id": "openmultiplayer",
"token_count": 87
} | 482 |
export default function BabelPluginMdxBrowser() {
return {
visitor: {
// remove all imports, we will add these to scope manually
ImportDeclaration(path: any) {
path.remove();
},
// the `makeShortcode` template is nice for error handling but we
// don't need it here as we are manually injecting dependencies
VariableDeclaration(path: any) {
// this removes the `makeShortcode` function
if (path.node.declarations[0].id.name === "makeShortcode") {
path.remove();
}
// this removes any variable that is set using the `makeShortcode` function
if (
path.node &&
path.node.declarations &&
path.node.declarations[0] &&
path.node.declarations[0].init &&
path.node.declarations[0].init.callee &&
path.node.declarations[0].init.callee.name === "makeShortcode"
) {
path.remove();
}
},
},
};
}
| openmultiplayer/web/frontend/src/mdx-helpers/babel-plugin-mdx-browser.ts/0 | {
"file_path": "openmultiplayer/web/frontend/src/mdx-helpers/babel-plugin-mdx-browser.ts",
"repo_id": "openmultiplayer",
"token_count": 411
} | 483 |
import { GetStaticPropsContext, GetStaticPropsResult } from "next";
import Link from "next/link";
import { NextSeo } from "next-seo";
import { useColorModeValue } from "@chakra-ui/react";
import { orderBy } from "lodash/fp";
import format from "date-fns/format";
import parseISO from "date-fns/parseISO";
import matter from "gray-matter";
import { Content } from "src/types/content";
import { getContentPathsForLocale, readLocaleContent } from "src/utils/content";
type Props = {
posts: Content[];
};
const Posts = ({ list }: { list: Content[] }) => {
const borderColor = useColorModeValue('var(--chakra-colors-gray-300)', 'var(--chakra-colors-gray-700)');
return (
<>
{list.map((post: Content) => {
try {
return (
<article key={post.slug} style={{
border: `1px solid ${borderColor}`,
borderRadius: "5px",
padding: "0.5rem",
marginTop: "2rem",
}}>
<h2 style={{
margin: '0',
marginLeft: "5px"
}}>
<Link href={`/blog/${post.slug}`}>
<a>{post.title}</a>
</Link>
</h2>
<p style={{
margin: '0',
marginLeft: "5px"
}}>
<time>{format(parseISO(post.date!), "yyyy-MM-dd")}</time> by{" "}
{post.author}
</p>
</article>
);
} catch (e) {
console.error("Failed to generate post", post.title, "Error:", e.message);
}
})}
</>
);
}
const NoContent = () => <h3>There are currently no posts.</h3>;
const PostList = ({ list }: { list: Content[] }) =>
list ? <Posts list={list} /> : <NoContent />;
const Page = ({ posts }: Props) => (
<>
<NextSeo
title="Blog"
description="The official open.mp development and community blog."
/>
<section className="measure-wide center pb4">
<h1>Development Blog</h1>
<PostList list={posts} />
</section>
</>
);
export async function getStaticProps(
context: GetStaticPropsContext<{ slug: string[] }>
): Promise<GetStaticPropsResult<Props>> {
const paths = getContentPathsForLocale("blog", "en");
// read each post and extract the metadata from frontmatter. This is then used
// in the page to generate the post list with titles, dates, authors, etc.
const posts: Content[] = await Promise.all(
paths.map(async (v: string) => {
const name = v.slice(1, v.length);
const { source } = await readLocaleContent(name, context.locale || "en");
const { data } = matter(source);
data.slug = name.split("/")[1]; // get the slug from the name minus blog/
return data as Content;
})
);
return {
props: {
posts: orderBy("date", "desc")(posts) as Content[],
},
};
}
export default Page;
| openmultiplayer/web/frontend/src/pages/blog/index.tsx/0 | {
"file_path": "openmultiplayer/web/frontend/src/pages/blog/index.tsx",
"repo_id": "openmultiplayer",
"token_count": 1300
} | 484 |
import { Global } from "@emotion/react";
const Fonts = () => {
return (
<Global
styles={`
@font-face {
font-family: "nimbus-sans";
src: url("/fonts/nimbus-sans_400.woff2") format("woff2"),
url("/fonts/nimbus-sans_400.woff") format("woff"),
url("/fonts/nimbus-sans_400.opentype") format("opentype");
font-display: auto;
font-style: normal;
font-weight: 400;
}
@font-face {
font-family: "nimbus-sans";
src: url("/fonts/nimbus-sans_900.woff2") format("woff2"),
url("/fonts/nimbus-sans_900.woff") format("woff"),
url("/fonts/nimbus-sans_900.opentype") format("opentype");
font-display: auto;
font-style: normal;
font-weight: 900;
}
@font-face {
font-family: "signo";
src: url("/fonts/signo_700.woff2") format("woff2"),
url("/fonts/signo_700.woff") format("woff"),
url("/fonts/signo_700.opentype") format("opentype");
font-display: auto;
font-style: normal;
font-weight: 700;
}
@font-face {
font-family: "signo";
src: url("/fonts/signo_400.woff2") format("woff2"),
url("/fonts/signo_400.woff") format("woff"),
url("/fonts/signo_400.opentype") format("opentype");
font-display: auto;
font-style: normal;
font-weight: 400;
}
@font-face {
font-family: "english-grotesque";
src: url("/fonts/english-grotesque_700.woff2") format("woff2"),
url("/fonts/english-grotesque_700.woff") format("woff"),
url("/fonts/english-grotesque_700.opentype") format("opentype");
font-display: auto;
font-style: normal;
font-weight: 700;
}
@font-face {
font-family: "english-grotesque";
src: url("/fonts/english-grotesque_300.woff2") format("woff2"),
url("/fonts/english-grotesque_300.woff") format("woff"),
url("/fonts/english-grotesque_300.opentype") format("opentype");
font-display: auto;
font-style: normal;
font-weight: 300;
}
`}
/>
);
};
export default Fonts;
| openmultiplayer/web/frontend/src/styles/Fonts.tsx/0 | {
"file_path": "openmultiplayer/web/frontend/src/styles/Fonts.tsx",
"repo_id": "openmultiplayer",
"token_count": 1386
} | 485 |
// Content acquisition helper APIs for retrieving Markdown text from various
// sources. The helpers here wrap various fallbacks and different extensions
// and list files/locales.
import { statSync, readFileSync, readdirSync } from "fs";
import { join, resolve } from "path";
import getConfig from "next/config";
import {
PHASE_DEVELOPMENT_SERVER,
PHASE_PRODUCTION_BUILD,
} from "next/constants";
import glob from "glob";
import { flow, map, join as ldjoin, filter } from "lodash/fp";
import { RawContent } from "src/types/content";
// relative to the `frontend/` directory, the app's working directory.
const CONTENT_PATH = "content";
// Gets a list of all content. English is the default and all other languages
// will be a subset of the English content so it's essentially the master copy.
// Because of this, the "en" directory is where to source the list of content.
//
// It returns essentially a matrix of all combinations of all locales and all
// content pages. The result is a flattened list.
export const getContentPaths = (subdir = ""): string[] => {
const contents = getContentPathsForLocale(subdir);
return getAllContentLocales()
.map((locale: string) => contents.map((content) => `/${locale}${content}`))
.flat();
};
// Gets a list of all content for a specific language
export const getContentPathsForLocale = (
subdir = "",
locale = "en"
) =>
glob
.sync(join(CONTENT_PATH, locale, subdir, "**", "*.mdx"))
.map(
(path: string) =>
path.substring(
("content/" + locale).length, // strip off "content/en/"
path.indexOf(".mdx") // strip off ".mdx"
) // result: only the path bit, relative to locale directory without ext
)
.filter((path: string) => path !== "/index"); // ignore index page, this is automatic
// Get all possible locales by simply listing the content directory. Each
// subdirectory in here is a locale. There should be no other files or
// directories in here.
export const getAllContentLocales = () =>
readdirSync(CONTENT_PATH).filter((path: string) => !path.startsWith(".")); // ignore dotfiles
// A helper for checking if a file exists because it's easier than exceptions.
export const exists = (path: string): boolean => {
try {
statSync(path);
return true;
} catch {
return false;
}
};
// Reads a markdown content file from the local filesystem. Only works at build
// time. Will not work in production on Vercel at request-time.
export const readMdFromLocal = async (
path: string
): Promise<string | undefined> => {
const path_mdx = path + ".mdx";
const path_md = path + ".md";
if (exists(path_mdx)) {
return readFileSync(path_mdx).toString();
}
if (exists(path_md)) {
return readFileSync(path_md).toString();
}
return undefined;
};
// Reads a markdown content file from the API. This is suitable for runtime use
// and is used to build docs pages at request-time.
export const readMdFromAPI = async (
path: string
): Promise<string | undefined> => {
const path_mdx = path + ".mdx";
const path_md = path + ".md";
let response: string | undefined;
// TODO: Perform the md/mdx differentiation on the API, instead of here.
response = await rawAPI(path_md);
if (response) {
return response;
}
response = await rawAPI(path_mdx);
if (response) {
return response;
}
return undefined;
};
// Fetches content directly from GitHub's raw content CDN.
const rawAPI = async (path: string): Promise<string | undefined> => {
const response = await fetch("https://api.open.mp/docs/" + path);
if (response.status === 200) {
return await response.text();
}
return undefined;
};
// Reads "content" (not docs) based on the given name and locale. It first
// attempts the given locale and if that isn't found, it attempts the "en"
// version. If the English version is used as a fallback, `fallback` is `true`.
export const readLocaleContent = async (
name: string,
locale: string
): Promise<RawContent> => {
let source = await readMdFromLocal(resolve("content", locale, name));
if (source !== undefined) {
return { source, fallback: false };
}
source = await readMdFromLocal(resolve("content", "en", name));
if (source !== undefined) {
return { source, fallback: true };
}
throw new Error(`Not found (${name} - ${locale})`);
};
const readLocaleDocsDevMode = async (
name: string,
locale?: string
): Promise<RawContent> => {
// The path may not be a file, it may be a directory. If so, generate a page
// for this directory that lists all its children as well as any content in
// a special file named `_.md`.
const dir = "../docs/" + name;
if (exists(dir) && statSync(dir).isDirectory()) {
const list = readdirSync(dir);
// Attempt to read a file named _.md from the directory
let source = await readMdFromLocal(dir + "/_");
if (source === undefined) {
source = "# " + name + "\n\n";
}
// Generate some content for this category page. A heading, some content
// from the index.md if it exists and a list of pages inside it.
const additional = flow(
filter((v: string) => v !== "_.md"), // filter out the special index page
map((v: string) => v.replace(".md", "")), // remove the file extension
map((v: string) => `- [${v}](${"/docs/" + name + "/" + v})`), // generate a ul element
ldjoin("\n")
)(list);
return {
source: source + additional,
fallback: false,
};
}
if (name === "") {
name = "index";
}
//
// Local Filesystem Docs Content
//
let withLocale = "../docs/" + name;
if (locale && locale != "en") {
withLocale = `../docs/translations/${locale}/${name}`;
}
let source = await readMdFromLocal(withLocale);
if (source !== undefined) {
return { source, fallback: false };
}
const fallbackPath = "../docs/" + name;
source = await readMdFromLocal(fallbackPath);
if (source !== undefined) {
return { source, fallback: true };
}
throw new Error(`Not found locally (${name}) check ../docs for the file.`);
};
// Reads docs with the given name and locale. Attempts the locale version first
// (if not English) and falls back to the English if not found.
export const readLocaleDocs = async (
name: string,
locale?: string
): Promise<RawContent> => {
// If dev mode (`npm run dev`) or a production build (`npm run build`) and the
// then site is not on Vercel, read docs from the local filesystem.
const { serverRuntimeConfig } = getConfig();
if (
(serverRuntimeConfig.phase === PHASE_DEVELOPMENT_SERVER ||
serverRuntimeConfig.phase === PHASE_PRODUCTION_BUILD) &&
process.env.VERCEL !== "1"
) {
// If you want to simulate how the production site fetches content, comment
// out the line below so local files aren't used to render docs pages.
return await readLocaleDocsDevMode(name, locale);
}
// Otherwise, this is being run in production and is happening at request-time
// so use the API to get the content.
// Only attempt to find translated copies on the API. These aren't built
// statically at build-time because the traffic is lower than the English
// (default) pages so it's fine to sacrifice a bit of performance here.
let withLocale = name;
if (locale && locale != "en") {
withLocale = `translations/${locale}/${name}`;
}
let source = await readMdFromAPI(withLocale);
if (source !== undefined) {
return { source, fallback: false };
}
//Next, try the English version as a fallback.
source = await readMdFromAPI(name);
if (source !== undefined) {
return { source, fallback: true };
}
// Finally, try the API for the directory listing or the raw file. This is
// usually hit for when a category page is request for a non-en locale.
// In dev mode, this is never hit because the local files are found but in
// prod, those local files aren't available.
source = await rawAPI(name);
if (source !== undefined) {
// Little hack because of how the API server's filesystem router works. If
// you hit a directory, it gives you a <pre> list of <a> tags linking to
// the pages. So we want to remove the tags and the `.md` extensions.
if (source.startsWith("<pre>")) {
source = source
.replace("<pre>", "<ul>") // unordered list
.replace("</pre>", "</ul>")
.replace(/<a href="/g, `<li><a href="/docs/${name}/`) // turn links into list items
.replace(/<\/a>/g, "</a></li>")
.replace(/.md/g, ""); // remove file extensions
}
return { source, fallback: true };
}
throw new Error(`Not found (${name})`);
};
// Gets the url for the corresponding docs page name and locale on Github.
export const getDocsGithubUrl = (name: string, exists: boolean, locale ?: string) => {
const translation = locale === 'en' ? '' : `translations/${locale}/`;
const mode = exists ? "edit" : "new";
// TODO: are there ways for a new file to fill its content/title?
return `https://github.com/openmultiplayer/web/${mode}/master/docs/${translation}${name}.md`;
}; | openmultiplayer/web/frontend/src/utils/content.ts/0 | {
"file_path": "openmultiplayer/web/frontend/src/utils/content.ts",
"repo_id": "openmultiplayer",
"token_count": 2929
} | 486 |
/*
Warnings:
- The migration will add a unique constraint covering the columns `[email]` on the table `User`. If there are existing duplicate values, the migration will fail.
- Added the required column `authMethod` to the `User` table without a default value. This is not possible if the table is not empty.
- Added the required column `updatedAt` to the `User` table without a default value. This is not possible if the table is not empty.
*/
-- CreateEnum
CREATE TYPE "AuthMethod" AS ENUM ('GITHUB', 'DISCORD');
-- AlterTable
ALTER TABLE "User" ADD COLUMN "authMethod" "AuthMethod" NOT NULL,
ADD COLUMN "admin" BOOLEAN NOT NULL DEFAULT false,
ADD COLUMN "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
ADD COLUMN "updatedAt" TIMESTAMP(3) NOT NULL;
-- CreateTable
CREATE TABLE "GitHub" (
"userId" TEXT NOT NULL,
"accountId" TEXT NOT NULL,
"username" TEXT NOT NULL,
"email" TEXT NOT NULL,
PRIMARY KEY ("userId")
);
-- CreateTable
CREATE TABLE "Discord" (
"userId" TEXT NOT NULL,
"accountId" TEXT NOT NULL,
"username" TEXT NOT NULL,
"email" TEXT NOT NULL,
PRIMARY KEY ("userId")
);
-- CreateIndex
CREATE UNIQUE INDEX "GitHub.accountId_unique" ON "GitHub"("accountId");
-- CreateIndex
CREATE UNIQUE INDEX "GitHub.username_unique" ON "GitHub"("username");
-- CreateIndex
CREATE UNIQUE INDEX "GitHub.email_unique" ON "GitHub"("email");
-- CreateIndex
CREATE UNIQUE INDEX "GitHub_userId_unique" ON "GitHub"("userId");
-- CreateIndex
CREATE UNIQUE INDEX "Discord.accountId_unique" ON "Discord"("accountId");
-- CreateIndex
CREATE UNIQUE INDEX "Discord.username_unique" ON "Discord"("username");
-- CreateIndex
CREATE UNIQUE INDEX "Discord.email_unique" ON "Discord"("email");
-- CreateIndex
CREATE UNIQUE INDEX "Discord_userId_unique" ON "Discord"("userId");
-- CreateIndex
CREATE UNIQUE INDEX "User.email_unique" ON "User"("email");
-- AddForeignKey
ALTER TABLE "GitHub" ADD FOREIGN KEY("userId")REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Discord" ADD FOREIGN KEY("userId")REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
| openmultiplayer/web/prisma/migrations/20201221195142_auth/migration.sql/0 | {
"file_path": "openmultiplayer/web/prisma/migrations/20201221195142_auth/migration.sql",
"repo_id": "openmultiplayer",
"token_count": 761
} | 487 |
.git
.npmrc
modules/*/Makefile
**/node_modules
copybara
data
public/js
public/minjs
public/stylesheets
public/manifest.json
build.tar
.sentryclirc
.sentryclirc.enc
| overleaf/web/.dockerignore/0 | {
"file_path": "overleaf/web/.dockerignore",
"repo_id": "overleaf",
"token_count": 69
} | 488 |
⚠️ This repository has been migrated into [`overleaf/overleaf`](https://github.com/overleaf/overleaf). See the [monorepo announcement](https://github.com/overleaf/overleaf/issues/923) for more info. ⚠️
---
overleaf/web
==============
overleaf/web is the front-end web service of the open-source web-based collaborative LaTeX editor,
[Overleaf](https://www.overleaf.com).
It serves all the HTML pages, CSS and javascript to the client. overleaf/web also contains
a lot of logic around creating and editing projects, and account management.
The rest of the Overleaf stack, along with information about contributing can be found in the
[overleaf/overleaf](https://github.com/overleaf/overleaf) repository.
Build process
----------------
overleaf/web uses [Grunt](http://gruntjs.com/) to build its front-end related assets.
Image processing tasks are commented out in the gruntfile and the needed packages aren't presently in the project's `package.json`. If the images need to be processed again (minified and sprited), start by fetching the packages (`npm install grunt-contrib-imagemin grunt-sprity`), then *decomment* the tasks in `Gruntfile.coffee`. After this, the tasks can be called (explicitly, via `grunt imagemin` and `grunt sprity`).
New Docker-based build process
------------------------------
Note that the Grunt workflow from above should still work, but we are transitioning to a
Docker based testing workflow, which is documented below:
### Running the app
The app runs natively using npm and Node on the local system:
```
$ npm install
$ npm run start
```
*Ideally the app would run in Docker like the tests below, but with host networking not supported in OS X, we need to run it natively until all services are Dockerised.*
### Running Tests
To run all tests run:
```
make test
```
To run both unit and acceptance tests for a module run:
```
make test_module MODULE=overleaf-integration
```
### Unit Tests
The test suites run in Docker.
Unit tests can be run in the `test_unit` container defined in `docker-compose.tests.yml`.
The makefile contains a short cut to run these:
```
make test_unit
```
During development it is often useful to only run a subset of tests, which can be configured with arguments to the mocha CLI:
```
make test_unit MOCHA_GREP='AuthorizationManager'
```
To run only the unit tests for a single module do:
```
make test_unit_module MODULE=overleaf-integration
```
Module tests can also use a MOCHA_GREP argument:
```
make test_unit_module MODULE=overleaf-integration MOCHA_GREP=SSO
```
### Acceptance Tests
Acceptance tests are run against a live service, which runs in the `acceptance_test` container defined in `docker-compose.tests.yml`.
To run the tests out-of-the-box, the makefile defines:
```
make test_acceptance
```
However, during development it is often useful to leave the service running for rapid iteration on the acceptance tests. This can be done with:
```
make test_acceptance_app_start_service
make test_acceptance_app_run # Run as many times as needed during development
make test_acceptance_app_stop_service
```
`make test_acceptance` just runs these three commands in sequence and then runs `make test_acceptance_modules` which performs the tests for each module in the `modules` directory. (Note that there is not currently an equivalent to the `-start` / `-run` x _n_ / `-stop` series for modules.)
During development it is often useful to only run a subset of tests, which can be configured with arguments to the mocha CLI:
```
make test_acceptance_run MOCHA_GREP='AuthorizationManager'
```
To run only the acceptance tests for a single module do:
```
make test_acceptance_module MODULE=overleaf-integration
```
Module tests can also use a MOCHA_GREP argument:
```
make test_acceptance_module MODULE=overleaf-integration MOCHA_GREP=SSO
```
Routes
------
Run `bin/routes` to print out all routes in the project.
License and Credits
-------------------
This project is licensed under the [AGPLv3 license](http://www.gnu.org/licenses/agpl-3.0.html)
### Stylesheets
Overleaf is based on [Bootstrap](http://getbootstrap.com/), which is licensed under the
[MIT license](http://opensource.org/licenses/MIT).
All modifications (`*.less` files in `public/stylesheets`) are also licensed
under the MIT license.
### Artwork
#### Silk icon set 1.3
We gratefully acknowledge [Mark James](http://www.famfamfam.com/lab/icons/silk/) for
releasing his Silk icon set under the Creative Commons Attribution 2.5 license. Some
of these icons are used within Overleaf inside the `public/img/silk` and
`public/brand/icons` directories.
#### IconShock icons
We gratefully acknowledge [IconShock](http://www.iconshock.com) for use of the icons
in the `public/img/iconshock` directory found via
[findicons.com](http://findicons.com/icon/498089/height?id=526085#)
| overleaf/web/README.md/0 | {
"file_path": "overleaf/web/README.md",
"repo_id": "overleaf",
"token_count": 1382
} | 489 |
module.exports = {
INVITE: 'invite',
TOKEN: 'token',
OWNER: 'owner',
}
| overleaf/web/app/src/Features/Authorization/Sources.js/0 | {
"file_path": "overleaf/web/app/src/Features/Authorization/Sources.js",
"repo_id": "overleaf",
"token_count": 34
} | 490 |
/* 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
*/
let ClsiFormatChecker
const _ = require('lodash')
const async = require('async')
const settings = require('@overleaf/settings')
module.exports = ClsiFormatChecker = {
checkRecoursesForProblems(resources, callback) {
const jobs = {
conflictedPaths(cb) {
return ClsiFormatChecker._checkForConflictingPaths(resources, cb)
},
sizeCheck(cb) {
return ClsiFormatChecker._checkDocsAreUnderSizeLimit(resources, cb)
},
}
return async.series(jobs, function (err, problems) {
if (err != null) {
return callback(err)
}
problems = _.omitBy(problems, _.isEmpty)
if (_.isEmpty(problems)) {
return callback()
} else {
return callback(null, problems)
}
})
},
_checkForConflictingPaths(resources, callback) {
const paths = resources.map(resource => resource.path)
const conflicts = _.filter(paths, function (path) {
const matchingPaths = _.filter(
paths,
checkPath => checkPath.indexOf(path + '/') !== -1
)
return matchingPaths.length > 0
})
const conflictObjects = conflicts.map(conflict => ({ path: conflict }))
return callback(null, conflictObjects)
},
_checkDocsAreUnderSizeLimit(resources, callback) {
const sizeLimit = 1000 * 1000 * settings.compileBodySizeLimitMb
let totalSize = 0
let sizedResources = resources.map(function (resource) {
const result = { path: resource.path }
if (resource.content != null) {
result.size = resource.content.replace(/\n/g, '').length
result.kbSize = Math.ceil(result.size / 1000)
} else {
result.size = 0
}
totalSize += result.size
return result
})
const tooLarge = totalSize > sizeLimit
if (!tooLarge) {
return callback()
} else {
sizedResources = _.sortBy(sizedResources, 'size').reverse().slice(0, 10)
return callback(null, { resources: sizedResources, totalSize })
}
},
}
| overleaf/web/app/src/Features/Compile/ClsiFormatChecker.js/0 | {
"file_path": "overleaf/web/app/src/Features/Compile/ClsiFormatChecker.js",
"repo_id": "overleaf",
"token_count": 886
} | 491 |
/* eslint-disable
camelcase,
node/handle-callback-err,
max-len,
no-dupe-keys,
no-unused-vars,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
const logger = require('logger-sharelatex')
const OError = require('@overleaf/o-error')
const Metrics = require('@overleaf/metrics')
const ProjectEntityUpdateHandler = require('../Project/ProjectEntityUpdateHandler')
const ProjectOptionsHandler = require('../Project/ProjectOptionsHandler')
const ProjectDetailsHandler = require('../Project/ProjectDetailsHandler')
const ProjectDeleter = require('../Project/ProjectDeleter')
const DocumentUpdaterHandler = require('../DocumentUpdater/DocumentUpdaterHandler')
const EditorRealTimeController = require('./EditorRealTimeController')
const async = require('async')
const PublicAccessLevels = require('../Authorization/PublicAccessLevels')
const _ = require('underscore')
const { promisifyAll } = require('../../util/promises')
const EditorController = {
addDoc(project_id, folder_id, docName, docLines, source, user_id, callback) {
if (callback == null) {
callback = function (error, doc) {}
}
return EditorController.addDocWithRanges(
project_id,
folder_id,
docName,
docLines,
{},
source,
user_id,
callback
)
},
addDocWithRanges(
project_id,
folder_id,
docName,
docLines,
docRanges,
source,
user_id,
callback
) {
if (callback == null) {
callback = function (error, doc) {}
}
docName = docName.trim()
Metrics.inc('editor.add-doc')
return ProjectEntityUpdateHandler.addDocWithRanges(
project_id,
folder_id,
docName,
docLines,
docRanges,
user_id,
(err, doc, folder_id) => {
if (err != null) {
OError.tag(err, 'error adding doc without lock', {
project_id,
docName,
})
return callback(err)
}
EditorRealTimeController.emitToRoom(
project_id,
'reciveNewDoc',
folder_id,
doc,
source,
user_id
)
return callback(err, doc)
}
)
},
addFile(
project_id,
folder_id,
fileName,
fsPath,
linkedFileData,
source,
user_id,
callback
) {
if (callback == null) {
callback = function (error, file) {}
}
fileName = fileName.trim()
Metrics.inc('editor.add-file')
return ProjectEntityUpdateHandler.addFile(
project_id,
folder_id,
fileName,
fsPath,
linkedFileData,
user_id,
(err, fileRef, folder_id) => {
if (err != null) {
OError.tag(err, 'error adding file without lock', {
project_id,
folder_id,
fileName,
})
return callback(err)
}
EditorRealTimeController.emitToRoom(
project_id,
'reciveNewFile',
folder_id,
fileRef,
source,
linkedFileData,
user_id
)
return callback(err, fileRef)
}
)
},
upsertDoc(
project_id,
folder_id,
docName,
docLines,
source,
user_id,
callback
) {
if (callback == null) {
callback = function (err) {}
}
return ProjectEntityUpdateHandler.upsertDoc(
project_id,
folder_id,
docName,
docLines,
source,
user_id,
function (err, doc, didAddNewDoc) {
if (didAddNewDoc) {
EditorRealTimeController.emitToRoom(
project_id,
'reciveNewDoc',
folder_id,
doc,
source,
user_id
)
}
return callback(err, doc)
}
)
},
upsertFile(
project_id,
folder_id,
fileName,
fsPath,
linkedFileData,
source,
user_id,
callback
) {
if (callback == null) {
callback = function (err, file) {}
}
return ProjectEntityUpdateHandler.upsertFile(
project_id,
folder_id,
fileName,
fsPath,
linkedFileData,
user_id,
function (err, newFile, didAddFile, existingFile) {
if (err != null) {
return callback(err)
}
if (!didAddFile) {
// replacement, so remove the existing file from the client
EditorRealTimeController.emitToRoom(
project_id,
'removeEntity',
existingFile._id,
source
)
}
// now add the new file on the client
EditorRealTimeController.emitToRoom(
project_id,
'reciveNewFile',
folder_id,
newFile,
source,
linkedFileData,
user_id
)
return callback(null, newFile)
}
)
},
upsertDocWithPath(
project_id,
elementPath,
docLines,
source,
user_id,
callback
) {
return ProjectEntityUpdateHandler.upsertDocWithPath(
project_id,
elementPath,
docLines,
source,
user_id,
function (err, doc, didAddNewDoc, newFolders, lastFolder) {
if (err != null) {
return callback(err)
}
return EditorController._notifyProjectUsersOfNewFolders(
project_id,
newFolders,
function (err) {
if (err != null) {
return callback(err)
}
if (didAddNewDoc) {
EditorRealTimeController.emitToRoom(
project_id,
'reciveNewDoc',
lastFolder._id,
doc,
source,
user_id
)
}
return callback()
}
)
}
)
},
upsertFileWithPath(
project_id,
elementPath,
fsPath,
linkedFileData,
source,
user_id,
callback
) {
return ProjectEntityUpdateHandler.upsertFileWithPath(
project_id,
elementPath,
fsPath,
linkedFileData,
user_id,
function (
err,
newFile,
didAddFile,
existingFile,
newFolders,
lastFolder
) {
if (err != null) {
return callback(err)
}
return EditorController._notifyProjectUsersOfNewFolders(
project_id,
newFolders,
function (err) {
if (err != null) {
return callback(err)
}
if (!didAddFile) {
// replacement, so remove the existing file from the client
EditorRealTimeController.emitToRoom(
project_id,
'removeEntity',
existingFile._id,
source
)
}
// now add the new file on the client
EditorRealTimeController.emitToRoom(
project_id,
'reciveNewFile',
lastFolder._id,
newFile,
source,
linkedFileData,
user_id
)
return callback()
}
)
}
)
},
addFolder(project_id, folder_id, folderName, source, userId, callback) {
if (callback == null) {
callback = function (error, folder) {}
}
folderName = folderName.trim()
Metrics.inc('editor.add-folder')
return ProjectEntityUpdateHandler.addFolder(
project_id,
folder_id,
folderName,
(err, folder, folder_id) => {
if (err != null) {
OError.tag(err, 'could not add folder', {
project_id,
folder_id,
folderName,
source,
})
return callback(err)
}
return EditorController._notifyProjectUsersOfNewFolder(
project_id,
folder_id,
folder,
userId,
function (err) {
if (err != null) {
return callback(err)
}
return callback(null, folder)
}
)
}
)
},
mkdirp(project_id, path, callback) {
if (callback == null) {
callback = function (error, newFolders, lastFolder) {}
}
logger.log({ project_id, path }, "making directories if they don't exist")
return ProjectEntityUpdateHandler.mkdirp(
project_id,
path,
(err, newFolders, lastFolder) => {
if (err != null) {
OError.tag(err, 'could not mkdirp', {
project_id,
path,
})
return callback(err)
}
return EditorController._notifyProjectUsersOfNewFolders(
project_id,
newFolders,
function (err) {
if (err != null) {
return callback(err)
}
return callback(null, newFolders, lastFolder)
}
)
}
)
},
deleteEntity(project_id, entity_id, entityType, source, userId, callback) {
if (callback == null) {
callback = function (error) {}
}
Metrics.inc('editor.delete-entity')
return ProjectEntityUpdateHandler.deleteEntity(
project_id,
entity_id,
entityType,
userId,
function (err) {
if (err != null) {
OError.tag(err, 'could not delete entity', {
project_id,
entity_id,
entityType,
})
return callback(err)
}
logger.log(
{ project_id, entity_id, entityType },
'telling users entity has been deleted'
)
EditorRealTimeController.emitToRoom(
project_id,
'removeEntity',
entity_id,
source
)
return callback()
}
)
},
deleteEntityWithPath(project_id, path, source, user_id, callback) {
return ProjectEntityUpdateHandler.deleteEntityWithPath(
project_id,
path,
user_id,
function (err, entity_id) {
if (err != null) {
return callback(err)
}
EditorRealTimeController.emitToRoom(
project_id,
'removeEntity',
entity_id,
source
)
return callback(null, entity_id)
}
)
},
updateProjectDescription(project_id, description, callback) {
if (callback == null) {
callback = function () {}
}
logger.log({ project_id, description }, 'updating project description')
return ProjectDetailsHandler.setProjectDescription(
project_id,
description,
function (err) {
if (err != null) {
OError.tag(
err,
'something went wrong setting the project description',
{
project_id,
description,
}
)
return callback(err)
}
EditorRealTimeController.emitToRoom(
project_id,
'projectDescriptionUpdated',
description
)
return callback()
}
)
},
deleteProject(project_id, callback) {
Metrics.inc('editor.delete-project')
return ProjectDeleter.deleteProject(project_id, callback)
},
renameEntity(project_id, entity_id, entityType, newName, userId, callback) {
if (callback == null) {
callback = function (error) {}
}
Metrics.inc('editor.rename-entity')
return ProjectEntityUpdateHandler.renameEntity(
project_id,
entity_id,
entityType,
newName,
userId,
function (err) {
if (err != null) {
OError.tag(err, 'error renaming entity', {
project_id,
entity_id,
entityType,
newName,
})
return callback(err)
}
if (newName.length > 0) {
EditorRealTimeController.emitToRoom(
project_id,
'reciveEntityRename',
entity_id,
newName
)
}
return callback()
}
)
},
moveEntity(project_id, entity_id, folder_id, entityType, userId, callback) {
if (callback == null) {
callback = function (error) {}
}
Metrics.inc('editor.move-entity')
return ProjectEntityUpdateHandler.moveEntity(
project_id,
entity_id,
folder_id,
entityType,
userId,
function (err) {
if (err != null) {
OError.tag(err, 'error moving entity', {
project_id,
entity_id,
folder_id,
})
return callback(err)
}
EditorRealTimeController.emitToRoom(
project_id,
'reciveEntityMove',
entity_id,
folder_id
)
return callback()
}
)
},
renameProject(project_id, newName, callback) {
if (callback == null) {
callback = function (err) {}
}
return ProjectDetailsHandler.renameProject(
project_id,
newName,
function (err) {
if (err != null) {
OError.tag(err, 'error renaming project', {
project_id,
newName,
})
return callback(err)
}
EditorRealTimeController.emitToRoom(
project_id,
'projectNameUpdated',
newName
)
return callback()
}
)
},
setCompiler(project_id, compiler, callback) {
if (callback == null) {
callback = function (err) {}
}
return ProjectOptionsHandler.setCompiler(
project_id,
compiler,
function (err) {
if (err != null) {
return callback(err)
}
EditorRealTimeController.emitToRoom(
project_id,
'compilerUpdated',
compiler
)
return callback()
}
)
},
setImageName(project_id, imageName, callback) {
if (callback == null) {
callback = function (err) {}
}
return ProjectOptionsHandler.setImageName(
project_id,
imageName,
function (err) {
if (err != null) {
return callback(err)
}
EditorRealTimeController.emitToRoom(
project_id,
'imageNameUpdated',
imageName
)
return callback()
}
)
},
setSpellCheckLanguage(project_id, languageCode, callback) {
if (callback == null) {
callback = function (err) {}
}
return ProjectOptionsHandler.setSpellCheckLanguage(
project_id,
languageCode,
function (err) {
if (err != null) {
return callback(err)
}
EditorRealTimeController.emitToRoom(
project_id,
'spellCheckLanguageUpdated',
languageCode
)
return callback()
}
)
},
setPublicAccessLevel(project_id, newAccessLevel, callback) {
if (callback == null) {
callback = function (err) {}
}
return ProjectDetailsHandler.setPublicAccessLevel(
project_id,
newAccessLevel,
function (err) {
if (err != null) {
return callback(err)
}
EditorRealTimeController.emitToRoom(
project_id,
'project:publicAccessLevel:changed',
{ newAccessLevel }
)
if (newAccessLevel === PublicAccessLevels.TOKEN_BASED) {
return ProjectDetailsHandler.ensureTokensArePresent(
project_id,
function (err, tokens) {
if (err != null) {
return callback(err)
}
EditorRealTimeController.emitToRoom(
project_id,
'project:tokens:changed',
{ tokens }
)
return callback()
}
)
} else {
return callback()
}
}
)
},
setRootDoc(project_id, newRootDocID, callback) {
if (callback == null) {
callback = function (err) {}
}
return ProjectEntityUpdateHandler.setRootDoc(
project_id,
newRootDocID,
function (err) {
if (err != null) {
return callback(err)
}
EditorRealTimeController.emitToRoom(
project_id,
'rootDocUpdated',
newRootDocID
)
return callback()
}
)
},
_notifyProjectUsersOfNewFolders(project_id, folders, callback) {
if (callback == null) {
callback = function (error) {}
}
return async.eachSeries(
folders,
(folder, cb) =>
EditorController._notifyProjectUsersOfNewFolder(
project_id,
folder.parentFolder_id,
folder,
null,
cb
),
callback
)
},
_notifyProjectUsersOfNewFolder(
project_id,
folder_id,
folder,
userId,
callback
) {
if (callback == null) {
callback = function (error) {}
}
EditorRealTimeController.emitToRoom(
project_id,
'reciveNewFolder',
folder_id,
folder,
userId
)
return callback()
},
}
EditorController.promises = promisifyAll(EditorController)
module.exports = EditorController
| overleaf/web/app/src/Features/Editor/EditorController.js/0 | {
"file_path": "overleaf/web/app/src/Features/Editor/EditorController.js",
"repo_id": "overleaf",
"token_count": 8491
} | 492 |
/* eslint-disable
camelcase,
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 ExportsHandler = require('./ExportsHandler')
const SessionManager = require('../Authentication/SessionManager')
const logger = require('logger-sharelatex')
module.exports = {
exportProject(req, res, next) {
const { project_id, brand_variation_id } = req.params
const user_id = SessionManager.getLoggedInUserId(req.session)
const export_params = {
project_id,
brand_variation_id,
user_id,
}
if (req.body) {
if (req.body.firstName) {
export_params.first_name = req.body.firstName.trim()
}
if (req.body.lastName) {
export_params.last_name = req.body.lastName.trim()
}
// additional parameters for gallery exports
if (req.body.title) {
export_params.title = req.body.title.trim()
}
if (req.body.description) {
export_params.description = req.body.description.trim()
}
if (req.body.author) {
export_params.author = req.body.author.trim()
}
if (req.body.license) {
export_params.license = req.body.license.trim()
}
if (req.body.showSource != null) {
export_params.show_source = req.body.showSource
}
}
return ExportsHandler.exportProject(
export_params,
function (err, export_data) {
if (err != null) {
if (err.forwardResponse != null) {
logger.log(
{ responseError: err.forwardResponse },
'forwarding response'
)
const statusCode = err.forwardResponse.status || 500
return res.status(statusCode).json(err.forwardResponse)
} else {
return next(err)
}
}
logger.log(
{
user_id,
project_id,
brand_variation_id,
export_v1_id: export_data.v1_id,
},
'exported project'
)
return res.json({
export_v1_id: export_data.v1_id,
message: export_data.message,
})
}
)
},
exportStatus(req, res) {
const { export_id } = req.params
return ExportsHandler.fetchExport(export_id, function (err, export_json) {
let json
if (err != null) {
json = {
status_summary: 'failed',
status_detail: err.toString,
}
res.json({ export_json: json })
return err
}
const parsed_export = JSON.parse(export_json)
json = {
status_summary: parsed_export.status_summary,
status_detail: parsed_export.status_detail,
partner_submission_id: parsed_export.partner_submission_id,
v2_user_email: parsed_export.v2_user_email,
v2_user_first_name: parsed_export.v2_user_first_name,
v2_user_last_name: parsed_export.v2_user_last_name,
title: parsed_export.title,
token: parsed_export.token,
}
return res.json({ export_json: json })
})
},
exportDownload(req, res, next) {
const { type, export_id } = req.params
SessionManager.getLoggedInUserId(req.session)
return ExportsHandler.fetchDownload(
export_id,
type,
function (err, export_file_url) {
if (err != null) {
return next(err)
}
return res.redirect(export_file_url)
}
)
},
}
| overleaf/web/app/src/Features/Exports/ExportsController.js/0 | {
"file_path": "overleaf/web/app/src/Features/Exports/ExportsController.js",
"repo_id": "overleaf",
"token_count": 1663
} | 493 |
const { callbackify } = require('util')
const request = require('request-promise-native')
const settings = require('@overleaf/settings')
const OError = require('@overleaf/o-error')
const UserGetter = require('../User/UserGetter')
module.exports = {
initializeProject: callbackify(initializeProject),
flushProject: callbackify(flushProject),
resyncProject: callbackify(resyncProject),
deleteProject: callbackify(deleteProject),
injectUserDetails: callbackify(injectUserDetails),
promises: {
initializeProject,
flushProject,
resyncProject,
deleteProject,
injectUserDetails,
},
}
async function initializeProject() {
if (
!(
settings.apis.project_history &&
settings.apis.project_history.initializeHistoryForNewProjects
)
) {
return
}
try {
const body = await request.post({
url: `${settings.apis.project_history.url}/project`,
})
const project = JSON.parse(body)
const overleafId = project && project.project && project.project.id
if (!overleafId) {
throw new Error('project-history did not provide an id', project)
}
return { overleaf_id: overleafId }
} catch (err) {
throw OError.tag(err, 'failed to initialize project history')
}
}
async function flushProject(projectId) {
try {
await request.post({
url: `${settings.apis.project_history.url}/project/${projectId}/flush`,
})
} catch (err) {
throw OError.tag(err, 'failed to flush project to project history', {
projectId,
})
}
}
async function resyncProject(projectId) {
try {
await request.post({
url: `${settings.apis.project_history.url}/project/${projectId}/resync`,
})
} catch (err) {
throw OError.tag(err, 'failed to resync project history', { projectId })
}
}
async function deleteProject(projectId, historyId) {
try {
const tasks = [
request.delete(
`${settings.apis.project_history.url}/project/${projectId}`
),
]
if (historyId != null) {
tasks.push(
request.delete({
url: `${settings.apis.v1_history.url}/projects/${historyId}`,
auth: {
user: settings.apis.v1_history.user,
pass: settings.apis.v1_history.pass,
},
})
)
}
await Promise.all(tasks)
} catch (err) {
throw OError.tag(err, 'failed to clear project history', {
projectId,
historyId,
})
}
}
async function injectUserDetails(data) {
// data can be either:
// {
// diff: [{
// i: "foo",
// meta: {
// users: ["user_id", v1_user_id, ...]
// ...
// }
// }, ...]
// }
// or
// {
// updates: [{
// pathnames: ["main.tex"]
// meta: {
// users: ["user_id", v1_user_id, ...]
// ...
// },
// ...
// }, ...]
// }
// Either way, the top level key points to an array of objects with a meta.users property
// that we need to replace user_ids with populated user objects.
// Note that some entries in the users arrays may be v1 ids returned by the v1 history
// service. v1 ids will be `numbers`
let userIds = new Set()
let v1UserIds = new Set()
const entries = Array.isArray(data.diff)
? data.diff
: Array.isArray(data.updates)
? data.updates
: []
for (const entry of entries) {
for (const user of (entry.meta && entry.meta.users) || []) {
if (typeof user === 'string') {
userIds.add(user)
} else if (typeof user === 'number') {
v1UserIds.add(user)
}
}
}
userIds = Array.from(userIds)
v1UserIds = Array.from(v1UserIds)
const projection = { first_name: 1, last_name: 1, email: 1 }
const usersArray = await UserGetter.promises.getUsers(userIds, projection)
const users = {}
for (const user of usersArray) {
users[user._id.toString()] = _userView(user)
}
projection.overleaf = 1
const v1IdentifiedUsersArray = await UserGetter.promises.getUsersByV1Ids(
v1UserIds,
projection
)
for (const user of v1IdentifiedUsersArray) {
users[user.overleaf.id] = _userView(user)
}
for (const entry of entries) {
if (entry.meta != null) {
entry.meta.users = ((entry.meta && entry.meta.users) || []).map(user => {
if (typeof user === 'string' || typeof user === 'number') {
return users[user]
} else {
return user
}
})
}
}
return data
}
function _userView(user) {
const { _id, first_name: firstName, last_name: lastName, email } = user
return { first_name: firstName, last_name: lastName, email, id: _id }
}
| overleaf/web/app/src/Features/History/HistoryManager.js/0 | {
"file_path": "overleaf/web/app/src/Features/History/HistoryManager.js",
"repo_id": "overleaf",
"token_count": 1824
} | 494 |
/* eslint-disable
camelcase,
node/handle-callback-err,
max-len,
no-unused-vars,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
let UrlAgent
const request = require('request')
const _ = require('underscore')
const urlValidator = require('valid-url')
const { InvalidUrlError, UrlFetchFailedError } = require('./LinkedFilesErrors')
const LinkedFilesHandler = require('./LinkedFilesHandler')
const UrlHelper = require('../Helpers/UrlHelper')
module.exports = UrlAgent = {
createLinkedFile(
project_id,
linkedFileData,
name,
parent_folder_id,
user_id,
callback
) {
linkedFileData = this._sanitizeData(linkedFileData)
return this._getUrlStream(
project_id,
linkedFileData,
user_id,
function (err, readStream) {
if (err != null) {
return callback(err)
}
readStream.on('error', callback)
return readStream.on('response', function (response) {
if (response.statusCode >= 200 && response.statusCode < 300) {
readStream.resume()
return LinkedFilesHandler.importFromStream(
project_id,
readStream,
linkedFileData,
name,
parent_folder_id,
user_id,
function (err, file) {
if (err != null) {
return callback(err)
}
return callback(null, file._id)
}
) // Created
} else {
const error = new UrlFetchFailedError(
`url fetch failed: ${linkedFileData.url}`
)
error.statusCode = response.statusCode
return callback(error)
}
})
}
)
},
refreshLinkedFile(
project_id,
linkedFileData,
name,
parent_folder_id,
user_id,
callback
) {
return this.createLinkedFile(
project_id,
linkedFileData,
name,
parent_folder_id,
user_id,
callback
)
},
_sanitizeData(data) {
return {
provider: data.provider,
url: UrlHelper.prependHttpIfNeeded(data.url),
}
},
_getUrlStream(project_id, data, current_user_id, callback) {
if (callback == null) {
callback = function (error, fsPath) {}
}
callback = _.once(callback)
let { url } = data
if (!urlValidator.isWebUri(url)) {
return callback(new InvalidUrlError(`invalid url: ${url}`))
}
url = UrlHelper.wrapUrlWithProxy(url)
const readStream = request.get(url)
readStream.pause()
return callback(null, readStream)
},
}
| overleaf/web/app/src/Features/LinkedFiles/UrlAgent.js/0 | {
"file_path": "overleaf/web/app/src/Features/LinkedFiles/UrlAgent.js",
"repo_id": "overleaf",
"token_count": 1289
} | 495 |
const _ = require('lodash')
const Path = require('path')
const OError = require('@overleaf/o-error')
const fs = require('fs')
const crypto = require('crypto')
const async = require('async')
const logger = require('logger-sharelatex')
const { ObjectId } = require('mongodb')
const ProjectDeleter = require('./ProjectDeleter')
const ProjectDuplicator = require('./ProjectDuplicator')
const ProjectCreationHandler = require('./ProjectCreationHandler')
const EditorController = require('../Editor/EditorController')
const ProjectHelper = require('./ProjectHelper')
const metrics = require('@overleaf/metrics')
const { User } = require('../../models/User')
const TagsHandler = require('../Tags/TagsHandler')
const SubscriptionLocator = require('../Subscription/SubscriptionLocator')
const NotificationsHandler = require('../Notifications/NotificationsHandler')
const LimitationsManager = require('../Subscription/LimitationsManager')
const Settings = require('@overleaf/settings')
const AuthorizationManager = require('../Authorization/AuthorizationManager')
const InactiveProjectManager = require('../InactiveData/InactiveProjectManager')
const ProjectUpdateHandler = require('./ProjectUpdateHandler')
const ProjectGetter = require('./ProjectGetter')
const PrivilegeLevels = require('../Authorization/PrivilegeLevels')
const SessionManager = require('../Authentication/SessionManager')
const Sources = require('../Authorization/Sources')
const TokenAccessHandler = require('../TokenAccess/TokenAccessHandler')
const CollaboratorsGetter = require('../Collaborators/CollaboratorsGetter')
const ProjectEntityHandler = require('./ProjectEntityHandler')
const TpdsProjectFlusher = require('../ThirdPartyDataStore/TpdsProjectFlusher')
const UserGetter = require('../User/UserGetter')
const NotificationsBuilder = require('../Notifications/NotificationsBuilder')
const { V1ConnectionError } = require('../Errors/Errors')
const Features = require('../../infrastructure/Features')
const BrandVariationsHandler = require('../BrandVariations/BrandVariationsHandler')
const UserController = require('../User/UserController')
const AnalyticsManager = require('../Analytics/AnalyticsManager')
const Modules = require('../../infrastructure/Modules')
const SplitTestHandler = require('../SplitTests/SplitTestHandler')
const { getNewLogsUIVariantForUser } = require('../Helpers/NewLogsUI')
const _ssoAvailable = (affiliation, session, linkedInstitutionIds) => {
if (!affiliation.institution) return false
// institution.confirmed is for the domain being confirmed, not the email
// Do not show SSO UI for unconfirmed domains
if (!affiliation.institution.confirmed) return false
// Could have multiple emails at the same institution, and if any are
// linked to the institution then do not show notification for others
if (
linkedInstitutionIds.indexOf(affiliation.institution.id.toString()) === -1
) {
if (affiliation.institution.ssoEnabled) return true
if (affiliation.institution.ssoBeta && session.samlBeta) return true
return false
}
return false
}
const ProjectController = {
_isInPercentageRollout(rolloutName, objectId, percentage) {
if (Settings.bypassPercentageRollouts === true) {
return true
}
const data = `${rolloutName}:${objectId.toString()}`
const md5hash = crypto.createHash('md5').update(data).digest('hex')
const counter = parseInt(md5hash.slice(26, 32), 16)
return counter % 100 < percentage
},
updateProjectSettings(req, res, next) {
const projectId = req.params.Project_id
const jobs = []
if (req.body.compiler != null) {
jobs.push(callback =>
EditorController.setCompiler(projectId, req.body.compiler, callback)
)
}
if (req.body.imageName != null) {
jobs.push(callback =>
EditorController.setImageName(projectId, req.body.imageName, callback)
)
}
if (req.body.name != null) {
jobs.push(callback =>
EditorController.renameProject(projectId, req.body.name, callback)
)
}
if (req.body.spellCheckLanguage != null) {
jobs.push(callback =>
EditorController.setSpellCheckLanguage(
projectId,
req.body.spellCheckLanguage,
callback
)
)
}
if (req.body.rootDocId != null) {
jobs.push(callback =>
EditorController.setRootDoc(projectId, req.body.rootDocId, callback)
)
}
async.series(jobs, error => {
if (error != null) {
return next(error)
}
res.sendStatus(204)
})
},
updateProjectAdminSettings(req, res, next) {
const projectId = req.params.Project_id
const jobs = []
if (req.body.publicAccessLevel != null) {
jobs.push(callback =>
EditorController.setPublicAccessLevel(
projectId,
req.body.publicAccessLevel,
callback
)
)
}
async.series(jobs, error => {
if (error != null) {
return next(error)
}
res.sendStatus(204)
})
},
deleteProject(req, res) {
const projectId = req.params.Project_id
const user = SessionManager.getSessionUser(req.session)
const cb = err => {
if (err != null) {
res.sendStatus(500)
} else {
res.sendStatus(200)
}
}
ProjectDeleter.deleteProject(
projectId,
{ deleterUser: user, ipAddress: req.ip },
cb
)
},
archiveProject(req, res, next) {
const projectId = req.params.Project_id
const userId = SessionManager.getLoggedInUserId(req.session)
ProjectDeleter.archiveProject(projectId, userId, function (err) {
if (err != null) {
return next(err)
} else {
return res.sendStatus(200)
}
})
},
unarchiveProject(req, res, next) {
const projectId = req.params.Project_id
const userId = SessionManager.getLoggedInUserId(req.session)
ProjectDeleter.unarchiveProject(projectId, userId, function (err) {
if (err != null) {
return next(err)
} else {
return res.sendStatus(200)
}
})
},
trashProject(req, res, next) {
const projectId = req.params.project_id
const userId = SessionManager.getLoggedInUserId(req.session)
ProjectDeleter.trashProject(projectId, userId, function (err) {
if (err != null) {
return next(err)
} else {
return res.sendStatus(200)
}
})
},
untrashProject(req, res, next) {
const projectId = req.params.project_id
const userId = SessionManager.getLoggedInUserId(req.session)
ProjectDeleter.untrashProject(projectId, userId, function (err) {
if (err != null) {
return next(err)
} else {
return res.sendStatus(200)
}
})
},
expireDeletedProjectsAfterDuration(req, res) {
ProjectDeleter.expireDeletedProjectsAfterDuration(err => {
if (err != null) {
res.sendStatus(500)
} else {
res.sendStatus(200)
}
})
},
expireDeletedProject(req, res, next) {
const { projectId } = req.params
ProjectDeleter.expireDeletedProject(projectId, err => {
if (err != null) {
next(err)
} else {
res.sendStatus(200)
}
})
},
restoreProject(req, res) {
const projectId = req.params.Project_id
ProjectDeleter.restoreProject(projectId, err => {
if (err != null) {
res.sendStatus(500)
} else {
res.sendStatus(200)
}
})
},
cloneProject(req, res, next) {
res.setTimeout(5 * 60 * 1000) // allow extra time for the copy to complete
metrics.inc('cloned-project')
const projectId = req.params.Project_id
const { projectName } = req.body
logger.log({ projectId, projectName }, 'cloning project')
if (!SessionManager.isUserLoggedIn(req.session)) {
return res.send({ redir: '/register' })
}
const currentUser = SessionManager.getSessionUser(req.session)
const { first_name: firstName, last_name: lastName, email } = currentUser
ProjectDuplicator.duplicate(
currentUser,
projectId,
projectName,
(err, project) => {
if (err != null) {
OError.tag(err, 'error cloning project', {
projectId,
userId: currentUser._id,
})
return next(err)
}
res.send({
name: project.name,
project_id: project._id,
owner_ref: project.owner_ref,
owner: {
first_name: firstName,
last_name: lastName,
email,
_id: currentUser._id,
},
})
}
)
},
newProject(req, res, next) {
const currentUser = SessionManager.getSessionUser(req.session)
const {
first_name: firstName,
last_name: lastName,
email,
_id: userId,
} = currentUser
const projectName =
req.body.projectName != null ? req.body.projectName.trim() : undefined
const { template } = req.body
async.waterfall(
[
cb => {
if (template === 'example') {
ProjectCreationHandler.createExampleProject(userId, projectName, cb)
} else {
ProjectCreationHandler.createBasicProject(userId, projectName, cb)
}
},
],
(err, project) => {
if (err != null) {
return next(err)
}
res.send({
project_id: project._id,
owner_ref: project.owner_ref,
owner: {
first_name: firstName,
last_name: lastName,
email,
_id: userId,
},
})
}
)
},
renameProject(req, res, next) {
const projectId = req.params.Project_id
const newName = req.body.newProjectName
EditorController.renameProject(projectId, newName, err => {
if (err != null) {
return next(err)
}
res.sendStatus(200)
})
},
userProjectsJson(req, res, next) {
const userId = SessionManager.getLoggedInUserId(req.session)
ProjectGetter.findAllUsersProjects(
userId,
'name lastUpdated publicAccesLevel archived trashed owner_ref tokens',
(err, projects) => {
if (err != null) {
return next(err)
}
// _buildProjectList already converts archived/trashed to booleans so isArchivedOrTrashed should not be used here
projects = ProjectController._buildProjectList(projects, userId)
.filter(p => !(p.archived || p.trashed))
.map(p => ({ _id: p.id, name: p.name, accessLevel: p.accessLevel }))
res.json({ projects })
}
)
},
projectEntitiesJson(req, res, next) {
const projectId = req.params.Project_id
ProjectGetter.getProject(projectId, (err, project) => {
if (err != null) {
return next(err)
}
ProjectEntityHandler.getAllEntitiesFromProject(
project,
(err, docs, files) => {
if (err != null) {
return next(err)
}
const entities = docs
.concat(files)
// Sort by path ascending
.sort((a, b) => (a.path > b.path ? 1 : a.path < b.path ? -1 : 0))
.map(e => ({
path: e.path,
type: e.doc != null ? 'doc' : 'file',
}))
res.json({ project_id: projectId, entities })
}
)
})
},
projectListPage(req, res, next) {
const timer = new metrics.Timer('project-list')
const userId = SessionManager.getLoggedInUserId(req.session)
const currentUser = SessionManager.getSessionUser(req.session)
async.parallel(
{
tags(cb) {
TagsHandler.getAllTags(userId, cb)
},
notifications(cb) {
NotificationsHandler.getUserNotifications(userId, cb)
},
projects(cb) {
ProjectGetter.findAllUsersProjects(
userId,
'name lastUpdated lastUpdatedBy publicAccesLevel archived trashed owner_ref tokens',
cb
)
},
hasSubscription(cb) {
LimitationsManager.hasPaidSubscription(
currentUser,
(error, hasPaidSubscription) => {
if (error != null && error instanceof V1ConnectionError) {
return cb(null, true)
}
cb(error, hasPaidSubscription)
}
)
},
user(cb) {
User.findById(
userId,
'emails featureSwitches overleaf awareOfV2 features lastLoginIp',
cb
)
},
userEmailsData(cb) {
const result = { list: [], allInReconfirmNotificationPeriods: [] }
UserGetter.getUserFullEmails(userId, (error, fullEmails) => {
if (error && error instanceof V1ConnectionError) {
return cb(null, result)
}
if (!Features.hasFeature('affiliations')) {
result.list = fullEmails
return cb(null, result)
}
Modules.hooks.fire(
'allInReconfirmNotificationPeriodsForUser',
fullEmails,
(error, results) => {
// Module.hooks.fire accepts multiple methods
// and does async.series
const allInReconfirmNotificationPeriods =
(results && results[0]) || []
return cb(null, {
list: fullEmails,
allInReconfirmNotificationPeriods,
})
}
)
})
},
},
(err, results) => {
if (err != null) {
OError.tag(err, 'error getting data for project list page')
return next(err)
}
const { notifications, user, userEmailsData } = results
const userEmails = userEmailsData.list || []
const userAffiliations = userEmails
.filter(emailData => !!emailData.affiliation)
.map(emailData => {
const result = emailData.affiliation
result.email = emailData.email
return result
})
const { allInReconfirmNotificationPeriods } = userEmailsData
// Handle case of deleted user
if (user == null) {
UserController.logout(req, res, next)
return
}
const tags = results.tags
const notificationsInstitution = []
for (const notification of notifications) {
notification.html = req.i18n.translate(
notification.templateKey,
notification.messageOpts
)
}
// Institution SSO Notifications
let reconfirmedViaSAML
if (Features.hasFeature('saml')) {
reconfirmedViaSAML = _.get(req.session, ['saml', 'reconfirmed'])
const samlSession = req.session.saml
// Notification: SSO Available
const linkedInstitutionIds = []
user.emails.forEach(email => {
if (email.samlProviderId) {
linkedInstitutionIds.push(email.samlProviderId)
}
})
if (Array.isArray(userAffiliations)) {
userAffiliations.forEach(affiliation => {
if (
_ssoAvailable(affiliation, req.session, linkedInstitutionIds)
) {
notificationsInstitution.push({
email: affiliation.email,
institutionId: affiliation.institution.id,
institutionName: affiliation.institution.name,
templateKey: 'notification_institution_sso_available',
})
}
})
}
if (samlSession) {
// Notification: After SSO Linked
if (samlSession.linked) {
notificationsInstitution.push({
email: samlSession.institutionEmail,
institutionName: samlSession.linked.universityName,
templateKey: 'notification_institution_sso_linked',
})
}
// Notification: After SSO Linked or Logging in
// The requested email does not match primary email returned from
// the institution
if (
samlSession.requestedEmail &&
samlSession.emailNonCanonical &&
!samlSession.error
) {
notificationsInstitution.push({
institutionEmail: samlSession.emailNonCanonical,
requestedEmail: samlSession.requestedEmail,
templateKey: 'notification_institution_sso_non_canonical',
})
}
// Notification: Tried to register, but account already existed
// registerIntercept is set before the institution callback.
// institutionEmail is set after institution callback.
// Check for both in case SSO flow was abandoned
if (
samlSession.registerIntercept &&
samlSession.institutionEmail &&
!samlSession.error
) {
notificationsInstitution.push({
email: samlSession.institutionEmail,
templateKey: 'notification_institution_sso_already_registered',
})
}
// Notification: When there is a session error
if (samlSession.error) {
notificationsInstitution.push({
templateKey: 'notification_institution_sso_error',
error: samlSession.error,
})
}
}
delete req.session.saml
}
const portalTemplates = ProjectController._buildPortalTemplatesList(
userAffiliations
)
const projects = ProjectController._buildProjectList(
results.projects,
userId
)
// in v2 add notifications for matching university IPs
if (Settings.overleaf != null && req.ip !== user.lastLoginIp) {
NotificationsBuilder.ipMatcherAffiliation(user._id).create(req.ip)
}
ProjectController._injectProjectUsers(projects, (error, projects) => {
if (error != null) {
return next(error)
}
const viewModel = {
title: 'your_projects',
priority_title: true,
projects,
tags,
notifications: notifications || [],
notificationsInstitution,
allInReconfirmNotificationPeriods,
portalTemplates,
user,
userAffiliations,
userEmails,
hasSubscription: results.hasSubscription,
reconfirmedViaSAML,
zipFileSizeLimit: Settings.maxUploadSize,
isOverleaf: !!Settings.overleaf,
}
const paidUser =
(user.features != null ? user.features.github : undefined) &&
(user.features != null ? user.features.dropbox : undefined) // use a heuristic for paid account
const freeUserProportion = 0.1
const sampleFreeUser =
parseInt(user._id.toString().slice(-2), 16) <
freeUserProportion * 255
const showFrontWidget = paidUser || sampleFreeUser
if (showFrontWidget) {
viewModel.frontChatWidgetRoomId =
Settings.overleaf != null
? Settings.overleaf.front_chat_widget_room_id
: undefined
}
res.render('project/list', viewModel)
timer.done()
})
}
)
},
loadEditor(req, res, next) {
const timer = new metrics.Timer('load-editor')
if (!Settings.editorIsOpen) {
return res.render('general/closed', { title: 'updating_site' })
}
let anonymous, userId, sessionUser
if (SessionManager.isUserLoggedIn(req.session)) {
sessionUser = SessionManager.getSessionUser(req.session)
userId = SessionManager.getLoggedInUserId(req.session)
anonymous = false
} else {
sessionUser = null
anonymous = true
userId = null
}
const projectId = req.params.Project_id
async.auto(
{
project(cb) {
ProjectGetter.getProject(
projectId,
{
name: 1,
lastUpdated: 1,
track_changes: 1,
owner_ref: 1,
brandVariationId: 1,
overleaf: 1,
tokens: 1,
},
(err, project) => {
if (err != null) {
return cb(err)
}
cb(null, project)
}
)
},
user(cb) {
if (userId == null) {
cb(null, defaultSettingsForAnonymousUser(userId))
} else {
User.findById(
userId,
'email first_name last_name referal_id signUpDate featureSwitches features refProviders alphaProgram betaProgram isAdmin ace',
(err, user) => {
// Handle case of deleted user
if (user == null) {
UserController.logout(req, res, next)
return
}
logger.log({ projectId, userId }, 'got user')
cb(err, user)
}
)
}
},
subscription(cb) {
if (userId == null) {
return cb()
}
SubscriptionLocator.getUsersSubscription(userId, cb)
},
activate(cb) {
InactiveProjectManager.reactivateProjectIfRequired(projectId, cb)
},
markAsOpened(cb) {
// don't need to wait for this to complete
ProjectUpdateHandler.markAsOpened(projectId, () => {})
cb()
},
isTokenMember(cb) {
if (userId == null) {
return cb()
}
CollaboratorsGetter.userIsTokenMember(userId, projectId, cb)
},
brandVariation: [
'project',
(cb, results) => {
if (
(results.project != null
? results.project.brandVariationId
: undefined) == null
) {
return cb()
}
BrandVariationsHandler.getBrandVariationById(
results.project.brandVariationId,
(error, brandVariationDetails) => cb(error, brandVariationDetails)
)
},
],
flushToTpds: cb => {
TpdsProjectFlusher.flushProjectToTpdsIfNeeded(projectId, cb)
},
pdfCachingFeatureFlag(cb) {
if (!Settings.enablePdfCaching) return cb(null, '')
if (!userId) return cb(null, 'enable-caching-only')
SplitTestHandler.getTestSegmentation(
userId,
'pdf_caching_full',
(err, segmentation) => {
if (err) {
// Do not fail loading the editor.
return cb(null, '')
}
cb(null, (segmentation && segmentation.variant) || '')
}
)
},
},
(err, results) => {
if (err != null) {
OError.tag(err, 'error getting details for project page')
return next(err)
}
const { project } = results
const { user } = results
const { subscription } = results
const { brandVariation } = results
const { pdfCachingFeatureFlag } = results
const anonRequestToken = TokenAccessHandler.getRequestToken(
req,
projectId
)
const { isTokenMember } = results
const allowedImageNames = ProjectHelper.getAllowedImagesForUser(
sessionUser
)
AuthorizationManager.getPrivilegeLevelForProject(
userId,
projectId,
anonRequestToken,
(error, privilegeLevel) => {
let allowedFreeTrial = true
if (error != null) {
return next(error)
}
if (
privilegeLevel == null ||
privilegeLevel === PrivilegeLevels.NONE
) {
return res.sendStatus(401)
}
if (subscription != null) {
allowedFreeTrial = false
}
let wsUrl = Settings.wsUrl
let metricName = 'load-editor-ws'
if (user.betaProgram && Settings.wsUrlBeta !== undefined) {
wsUrl = Settings.wsUrlBeta
metricName += '-beta'
} else if (
Settings.wsUrlV2 &&
Settings.wsUrlV2Percentage > 0 &&
(ObjectId(projectId).getTimestamp() / 1000) % 100 <
Settings.wsUrlV2Percentage
) {
wsUrl = Settings.wsUrlV2
metricName += '-v2'
}
if (req.query && req.query.ws === 'fallback') {
// `?ws=fallback` will connect to the bare origin, and ignore
// the custom wsUrl. Hence it must load the client side
// javascript from there too.
// Not resetting it here would possibly load a socket.io v2
// client and connect to a v0 endpoint.
wsUrl = undefined
metricName += '-fallback'
}
metrics.inc(metricName)
if (userId) {
AnalyticsManager.recordEvent(userId, 'project-opened', {
projectId: project._id,
})
}
const logsUIVariant = getNewLogsUIVariantForUser(user)
function shouldDisplayFeature(name, variantFlag) {
if (req.query && req.query[name]) {
return req.query[name] === 'true'
} else {
return variantFlag === true
}
}
function partOfPdfCachingRollout(flag) {
if (!Settings.enablePdfCaching) {
// The feature is disabled globally.
return false
}
const canSeeFeaturePreview = pdfCachingFeatureFlag.includes(flag)
if (!canSeeFeaturePreview) {
// The user is not in the target group.
return false
}
// Optionally let the user opt-out.
// The will opt-out of both caching and metrics collection,
// as if this editing session never happened.
return shouldDisplayFeature('enable_pdf_caching', true)
}
res.render('project/editor', {
title: project.name,
priority_title: true,
bodyClasses: ['editor'],
project_id: project._id,
user: {
id: userId,
email: user.email,
first_name: user.first_name,
last_name: user.last_name,
referal_id: user.referal_id,
signUpDate: user.signUpDate,
allowedFreeTrial: allowedFreeTrial,
featureSwitches: user.featureSwitches,
features: user.features,
refProviders: _.mapValues(user.refProviders, Boolean),
alphaProgram: user.alphaProgram,
betaProgram: user.betaProgram,
isAdmin: user.isAdmin,
},
userSettings: {
mode: user.ace.mode,
editorTheme: user.ace.theme,
fontSize: user.ace.fontSize,
autoComplete: user.ace.autoComplete,
autoPairDelimiters: user.ace.autoPairDelimiters,
pdfViewer: user.ace.pdfViewer,
syntaxValidation: user.ace.syntaxValidation,
fontFamily: user.ace.fontFamily || 'lucida',
lineHeight: user.ace.lineHeight || 'normal',
overallTheme: user.ace.overallTheme,
},
privilegeLevel,
anonymous,
anonymousAccessToken: anonymous ? anonRequestToken : null,
isTokenMember,
isRestrictedTokenMember: AuthorizationManager.isRestrictedUser(
userId,
privilegeLevel,
isTokenMember
),
languages: Settings.languages,
editorThemes: THEME_LIST,
maxDocLength: Settings.max_doc_length,
useV2History:
project.overleaf &&
project.overleaf.history &&
Boolean(project.overleaf.history.display),
brandVariation,
allowedImageNames,
gitBridgePublicBaseUrl: Settings.gitBridgePublicBaseUrl,
wsUrl,
showSupport: Features.hasFeature('support'),
showNewLogsUI: shouldDisplayFeature(
'new_logs_ui',
logsUIVariant.newLogsUI
),
logsUISubvariant: logsUIVariant.subvariant,
showNewNavigationUI: shouldDisplayFeature(
'new_navigation_ui',
true
),
showNewFileViewUI: shouldDisplayFeature(
'new_file_view',
user.alphaProgram || user.betaProgram
),
showSymbolPalette: shouldDisplayFeature(
'symbol_palette',
user.alphaProgram || user.betaProgram
),
trackPdfDownload: partOfPdfCachingRollout('collect-metrics'),
enablePdfCaching: partOfPdfCachingRollout('enable-caching'),
resetServiceWorker: Boolean(Settings.resetServiceWorker),
})
timer.done()
}
)
}
)
},
_buildProjectList(allProjects, userId) {
let project
const {
owned,
readAndWrite,
readOnly,
tokenReadAndWrite,
tokenReadOnly,
} = allProjects
const projects = []
for (project of owned) {
projects.push(
ProjectController._buildProjectViewModel(
project,
'owner',
Sources.OWNER,
userId
)
)
}
// Invite-access
for (project of readAndWrite) {
projects.push(
ProjectController._buildProjectViewModel(
project,
'readWrite',
Sources.INVITE,
userId
)
)
}
for (project of readOnly) {
projects.push(
ProjectController._buildProjectViewModel(
project,
'readOnly',
Sources.INVITE,
userId
)
)
}
// Token-access
// Only add these projects if they're not already present, this gives us cascading access
// from 'owner' => 'token-read-only'
for (project of tokenReadAndWrite) {
if (
projects.filter(p => p.id.toString() === project._id.toString())
.length === 0
) {
projects.push(
ProjectController._buildProjectViewModel(
project,
'readAndWrite',
Sources.TOKEN,
userId
)
)
}
}
for (project of tokenReadOnly) {
if (
projects.filter(p => p.id.toString() === project._id.toString())
.length === 0
) {
projects.push(
ProjectController._buildProjectViewModel(
project,
'readOnly',
Sources.TOKEN,
userId
)
)
}
}
return projects
},
_buildProjectViewModel(project, accessLevel, source, userId) {
const archived = ProjectHelper.isArchived(project, userId)
// If a project is simultaneously trashed and archived, we will consider it archived but not trashed.
const trashed = ProjectHelper.isTrashed(project, userId) && !archived
TokenAccessHandler.protectTokens(project, accessLevel)
const model = {
id: project._id,
name: project.name,
lastUpdated: project.lastUpdated,
lastUpdatedBy: project.lastUpdatedBy,
publicAccessLevel: project.publicAccesLevel,
accessLevel,
source,
archived,
trashed,
owner_ref: project.owner_ref,
isV1Project: false,
}
if (accessLevel === PrivilegeLevels.READ_ONLY && source === Sources.TOKEN) {
model.owner_ref = null
model.lastUpdatedBy = null
}
return model
},
_injectProjectUsers(projects, callback) {
const users = {}
for (const project of projects) {
if (project.owner_ref != null) {
users[project.owner_ref.toString()] = true
}
if (project.lastUpdatedBy != null) {
users[project.lastUpdatedBy.toString()] = true
}
}
const userIds = Object.keys(users)
async.eachSeries(
userIds,
(userId, cb) => {
UserGetter.getUser(
userId,
{ first_name: 1, last_name: 1, email: 1 },
(error, user) => {
if (error != null) {
return cb(error)
}
users[userId] = user
cb()
}
)
},
error => {
if (error != null) {
return callback(error)
}
for (const project of projects) {
if (project.owner_ref != null) {
project.owner = users[project.owner_ref.toString()]
}
if (project.lastUpdatedBy != null) {
project.lastUpdatedBy =
users[project.lastUpdatedBy.toString()] || null
}
}
callback(null, projects)
}
)
},
_buildPortalTemplatesList(affiliations) {
if (affiliations == null) {
affiliations = []
}
const portalTemplates = []
for (const aff of affiliations) {
if (
aff.portal &&
aff.portal.slug &&
aff.portal.templates_count &&
aff.portal.templates_count > 0
) {
const portalPath = aff.institution.isUniversity ? '/edu/' : '/org/'
portalTemplates.push({
name: aff.institution.name,
url: Settings.siteUrl + portalPath + aff.portal.slug,
})
}
}
return portalTemplates
},
}
var defaultSettingsForAnonymousUser = userId => ({
id: userId,
ace: {
mode: 'none',
theme: 'textmate',
fontSize: '12',
autoComplete: true,
spellCheckLanguage: '',
pdfViewer: '',
syntaxValidation: true,
},
subscription: {
freeTrial: {
allowed: true,
},
},
featureSwitches: {
github: false,
},
alphaProgram: false,
betaProgram: false,
})
var THEME_LIST = []
function generateThemeList() {
const files = fs.readdirSync(
Path.join(__dirname, '/../../../../node_modules/ace-builds/src-noconflict')
)
const result = []
for (const file of files) {
if (file.slice(-2) === 'js' && /^theme-/.test(file)) {
const cleanName = file.slice(0, -3).slice(6)
result.push(THEME_LIST.push(cleanName))
} else {
result.push(undefined)
}
}
}
generateThemeList()
module.exports = ProjectController
| overleaf/web/app/src/Features/Project/ProjectController.js/0 | {
"file_path": "overleaf/web/app/src/Features/Project/ProjectController.js",
"repo_id": "overleaf",
"token_count": 16390
} | 496 |
/* eslint-disable
max-len,
no-return-assign,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS101: Remove unnecessary use of Array.from
* DS102: Remove unnecessary code created because of implicit returns
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
// This file is shared between the frontend and server code of web, so that
// filename validation is the same in both implementations.
// The logic in all copies must be kept in sync:
// app/src/Features/Project/SafePath.js
// frontend/js/ide/directives/SafePath.js
// frontend/js/features/file-tree/util/safe-path.js
const load = function () {
let SafePath
// eslint-disable-next-line prefer-regex-literals
const BADCHAR_RX = new RegExp(
`\
[\
\\/\
\\\\\
\\*\
\\u0000-\\u001F\
\\u007F\
\\u0080-\\u009F\
\\uD800-\\uDFFF\
]\
`,
'g'
)
// eslint-disable-next-line prefer-regex-literals
const BADFILE_RX = new RegExp(
`\
(^\\.$)\
|(^\\.\\.$)\
|(^\\s+)\
|(\\s+$)\
`,
'g'
)
// Put a block on filenames which match javascript property names, as they
// can cause exceptions where the code puts filenames into a hash. This is a
// temporary workaround until the code in other places is made safe against
// property names.
//
// The list of property names is taken from
// ['prototype'].concat(Object.getOwnPropertyNames(Object.prototype))
// eslint-disable-next-line prefer-regex-literals
const BLOCKEDFILE_RX = new RegExp(`\
^(\
prototype\
|constructor\
|toString\
|toLocaleString\
|valueOf\
|hasOwnProperty\
|isPrototypeOf\
|propertyIsEnumerable\
|__defineGetter__\
|__lookupGetter__\
|__defineSetter__\
|__lookupSetter__\
|__proto__\
)$\
`)
const MAX_PATH = 1024 // Maximum path length, in characters. This is fairly arbitrary.
return (SafePath = {
// convert any invalid characters to underscores in the given filename
clean(filename) {
filename = filename.replace(BADCHAR_RX, '_')
// for BADFILE_RX replace any matches with an equal number of underscores
filename = filename.replace(BADFILE_RX, match =>
new Array(match.length + 1).join('_')
)
// replace blocked filenames 'prototype' with '@prototype'
filename = filename.replace(BLOCKEDFILE_RX, '@$1')
return filename
},
// returns whether the filename is 'clean' (does not contain any invalid
// characters or reserved words)
isCleanFilename(filename) {
return (
SafePath.isAllowedLength(filename) &&
!filename.match(BADCHAR_RX) &&
!filename.match(BADFILE_RX)
)
},
isBlockedFilename(filename) {
return BLOCKEDFILE_RX.test(filename)
},
// returns whether a full path is 'clean' - e.g. is a full or relative path
// that points to a file, and each element passes the rules in 'isCleanFilename'
isCleanPath(path) {
const elements = path.split('/')
const lastElementIsEmpty = elements[elements.length - 1].length === 0
if (lastElementIsEmpty) {
return false
}
for (const element of Array.from(elements)) {
if (element.length > 0 && !SafePath.isCleanFilename(element)) {
return false
}
}
// check for a top-level reserved name
if (BLOCKEDFILE_RX.test(path.replace(/^\/?/, ''))) {
return false
} // remove leading slash if present
return true
},
isAllowedLength(pathname) {
return pathname.length > 0 && pathname.length <= MAX_PATH
},
})
}
module.exports = load()
| overleaf/web/app/src/Features/Project/SafePath.js/0 | {
"file_path": "overleaf/web/app/src/Features/Project/SafePath.js",
"repo_id": "overleaf",
"token_count": 1358
} | 497 |
const SplitTestManager = require('./SplitTestManager')
const { SplitTest } = require('../../models/SplitTest')
const { CacheLoader } = require('cache-flow')
class SplitTestCache extends CacheLoader {
constructor() {
super('split-test', {
expirationTime: 60, // 1min in seconds
})
}
async load(name) {
return await SplitTestManager.getSplitTestByName(name)
}
serialize(value) {
return value ? value.toObject() : undefined
}
deserialize(value) {
return new SplitTest(value)
}
}
module.exports = new SplitTestCache()
| overleaf/web/app/src/Features/SplitTests/SplitTestCache.js/0 | {
"file_path": "overleaf/web/app/src/Features/SplitTests/SplitTestCache.js",
"repo_id": "overleaf",
"token_count": 184
} | 498 |
const SessionManager = require('../Authentication/SessionManager')
const SubscriptionHandler = require('./SubscriptionHandler')
const PlansLocator = require('./PlansLocator')
const SubscriptionViewModelBuilder = require('./SubscriptionViewModelBuilder')
const LimitationsManager = require('./LimitationsManager')
const RecurlyWrapper = require('./RecurlyWrapper')
const Settings = require('@overleaf/settings')
const logger = require('logger-sharelatex')
const GeoIpLookup = require('../../infrastructure/GeoIpLookup')
const FeaturesUpdater = require('./FeaturesUpdater')
const planFeatures = require('./planFeatures')
const GroupPlansData = require('./GroupPlansData')
const V1SubscriptionManager = require('./V1SubscriptionManager')
const Errors = require('../Errors/Errors')
const HttpErrorHandler = require('../Errors/HttpErrorHandler')
const SubscriptionErrors = require('./Errors')
const SplitTestHandler = require('../SplitTests/SplitTestHandler')
const AnalyticsManager = require('../Analytics/AnalyticsManager')
const RecurlyEventHandler = require('./RecurlyEventHandler')
const { expressify } = require('../../util/promises')
const OError = require('@overleaf/o-error')
const _ = require('lodash')
const SUBSCRIPTION_PAGE_SPLIT_TEST = 'subscription-page'
async function plansPage(req, res) {
const plans = SubscriptionViewModelBuilder.buildPlansList()
const {
currencyCode: recommendedCurrency,
} = await GeoIpLookup.promises.getCurrencyCode(
(req.query ? req.query.ip : undefined) || req.ip
)
res.render('subscriptions/plans', {
title: 'plans_and_pricing',
plans,
gaExperiments: Settings.gaExperiments.plansPage,
gaOptimize: true,
recomendedCurrency: recommendedCurrency,
planFeatures,
groupPlans: GroupPlansData,
})
}
// get to show the recurly.js page
async function paymentPage(req, res) {
const user = SessionManager.getSessionUser(req.session)
const plan = PlansLocator.findLocalPlanInSettings(req.query.planCode)
if (!plan) {
return HttpErrorHandler.unprocessableEntity(req, res, 'Plan not found')
}
const hasSubscription = await LimitationsManager.promises.userHasV1OrV2Subscription(
user
)
if (hasSubscription) {
res.redirect('/user/subscription?hasSubscription=true')
} else {
// LimitationsManager.userHasV2Subscription only checks Mongo. Double check with
// Recurly as well at this point (we don't do this most places for speed).
const valid = await SubscriptionHandler.promises.validateNoSubscriptionInRecurly(
user._id
)
if (!valid) {
res.redirect('/user/subscription?hasSubscription=true')
} else {
let currency = req.query.currency
? req.query.currency.toUpperCase()
: undefined
const {
currencyCode: recommendedCurrency,
countryCode,
} = await GeoIpLookup.promises.getCurrencyCode(
(req.query ? req.query.ip : undefined) || req.ip
)
if (recommendedCurrency && currency == null) {
currency = recommendedCurrency
}
res.render('subscriptions/new', {
title: 'subscribe',
currency,
countryCode,
plan,
showStudentPlan: req.query.ssp === 'true',
recurlyConfig: JSON.stringify({
currency,
subdomain: Settings.apis.recurly.subdomain,
}),
showCouponField: !!req.query.scf,
showVatField: !!req.query.svf,
gaOptimize: true,
})
}
}
}
async function userSubscriptionPage(req, res) {
const user = SessionManager.getSessionUser(req.session)
const results = await SubscriptionViewModelBuilder.promises.buildUsersSubscriptionViewModel(
user
)
const {
personalSubscription,
memberGroupSubscriptions,
managedGroupSubscriptions,
confirmedMemberAffiliations,
managedInstitutions,
managedPublishers,
v1SubscriptionStatus,
} = results
const hasSubscription = await LimitationsManager.promises.userHasV1OrV2Subscription(
user
)
const fromPlansPage = req.query.hasSubscription
const plans = SubscriptionViewModelBuilder.buildPlansList(
personalSubscription ? personalSubscription.plan : undefined
)
let subscriptionCopy = 'default'
if (
personalSubscription ||
hasSubscription ||
(memberGroupSubscriptions && memberGroupSubscriptions.length > 0) ||
(confirmedMemberAffiliations &&
confirmedMemberAffiliations.length > 0 &&
_.find(confirmedMemberAffiliations, affiliation => {
return affiliation.licence && affiliation.licence !== 'free'
}))
) {
AnalyticsManager.recordEvent(user._id, 'subscription-page-view')
} else {
try {
const testSegmentation = await SplitTestHandler.promises.getTestSegmentation(
user._id,
SUBSCRIPTION_PAGE_SPLIT_TEST
)
if (testSegmentation.enabled) {
subscriptionCopy = testSegmentation.variant
AnalyticsManager.recordEvent(user._id, 'subscription-page-view', {
splitTestId: SUBSCRIPTION_PAGE_SPLIT_TEST,
splitTestVariantId: testSegmentation.variant,
})
} else {
AnalyticsManager.recordEvent(user._id, 'subscription-page-view')
}
} catch (error) {
logger.error(
{ err: error },
`Failed to get segmentation for user '${user._id}' and split test '${SUBSCRIPTION_PAGE_SPLIT_TEST}'`
)
AnalyticsManager.recordEvent(user._id, 'subscription-page-view')
}
}
const data = {
title: 'your_subscription',
plans,
user,
hasSubscription,
subscriptionCopy,
fromPlansPage,
personalSubscription,
memberGroupSubscriptions,
managedGroupSubscriptions,
confirmedMemberAffiliations,
managedInstitutions,
managedPublishers,
v1SubscriptionStatus,
}
res.render('subscriptions/dashboard', data)
}
function createSubscription(req, res, next) {
const user = SessionManager.getSessionUser(req.session)
const recurlyTokenIds = {
billing: req.body.recurly_token_id,
threeDSecureActionResult:
req.body.recurly_three_d_secure_action_result_token_id,
}
const { subscriptionDetails } = req.body
LimitationsManager.userHasV1OrV2Subscription(
user,
function (err, hasSubscription) {
if (err) {
return next(err)
}
if (hasSubscription) {
logger.warn({ user_id: user._id }, 'user already has subscription')
return res.sendStatus(409) // conflict
}
return SubscriptionHandler.createSubscription(
user,
subscriptionDetails,
recurlyTokenIds,
function (err) {
if (!err) {
return res.sendStatus(201)
}
if (
err instanceof SubscriptionErrors.RecurlyTransactionError ||
err instanceof Errors.InvalidError
) {
logger.error({ err }, 'recurly transaction error, potential 422')
HttpErrorHandler.unprocessableEntity(
req,
res,
err.message,
OError.getFullInfo(err).public
)
} else {
logger.warn(
{ err, user_id: user._id },
'something went wrong creating subscription'
)
next(err)
}
}
)
}
)
}
function successfulSubscription(req, res, next) {
const user = SessionManager.getSessionUser(req.session)
return SubscriptionViewModelBuilder.buildUsersSubscriptionViewModel(
user,
function (error, { personalSubscription }) {
if (error) {
return next(error)
}
if (personalSubscription == null) {
res.redirect('/user/subscription/plans')
} else {
res.render('subscriptions/successful_subscription', {
title: 'thank_you',
personalSubscription,
})
}
}
)
}
function cancelSubscription(req, res, next) {
const user = SessionManager.getSessionUser(req.session)
logger.log({ user_id: user._id }, 'canceling subscription')
SubscriptionHandler.cancelSubscription(user, function (err) {
if (err) {
OError.tag(err, 'something went wrong canceling subscription', {
user_id: user._id,
})
return next(err)
}
// Note: this redirect isn't used in the main flow as the redirection is
// handled by Angular
res.redirect('/user/subscription/canceled')
})
}
function canceledSubscription(req, res, next) {
return res.render('subscriptions/canceled_subscription', {
title: 'subscription_canceled',
})
}
function cancelV1Subscription(req, res, next) {
const userId = SessionManager.getLoggedInUserId(req.session)
logger.log({ userId }, 'canceling v1 subscription')
V1SubscriptionManager.cancelV1Subscription(userId, function (err) {
if (err) {
OError.tag(err, 'something went wrong canceling v1 subscription', {
userId,
})
return next(err)
}
res.redirect('/user/subscription')
})
}
function updateSubscription(req, res, next) {
const origin = req && req.query ? req.query.origin : null
const user = SessionManager.getSessionUser(req.session)
const planCode = req.body.plan_code
if (planCode == null) {
const err = new Error('plan_code is not defined')
logger.warn(
{ user_id: user._id, err, planCode, origin, body: req.body },
'[Subscription] error in updateSubscription form'
)
return next(err)
}
logger.log({ planCode, user_id: user._id }, 'updating subscription')
SubscriptionHandler.updateSubscription(user, planCode, null, function (err) {
if (err) {
OError.tag(err, 'something went wrong updating subscription', {
user_id: user._id,
})
return next(err)
}
res.redirect('/user/subscription')
})
}
function cancelPendingSubscriptionChange(req, res, next) {
const user = SessionManager.getSessionUser(req.session)
logger.log({ user_id: user._id }, 'canceling pending subscription change')
SubscriptionHandler.cancelPendingSubscriptionChange(user, function (err) {
if (err) {
OError.tag(
err,
'something went wrong canceling pending subscription change',
{
user_id: user._id,
}
)
return next(err)
}
res.redirect('/user/subscription')
})
}
function updateAccountEmailAddress(req, res, next) {
const user = SessionManager.getSessionUser(req.session)
RecurlyWrapper.updateAccountEmailAddress(
user._id,
user.email,
function (error) {
if (error) {
return next(error)
}
res.sendStatus(200)
}
)
}
function reactivateSubscription(req, res, next) {
const user = SessionManager.getSessionUser(req.session)
logger.log({ user_id: user._id }, 'reactivating subscription')
SubscriptionHandler.reactivateSubscription(user, function (err) {
if (err) {
OError.tag(err, 'something went wrong reactivating subscription', {
user_id: user._id,
})
return next(err)
}
res.redirect('/user/subscription')
})
}
function recurlyCallback(req, res, next) {
logger.log({ data: req.body }, 'received recurly callback')
const event = Object.keys(req.body)[0]
const eventData = req.body[event]
RecurlyEventHandler.sendRecurlyAnalyticsEvent(event, eventData)
if (
[
'new_subscription_notification',
'updated_subscription_notification',
'expired_subscription_notification',
].includes(event)
) {
const recurlySubscription = eventData.subscription
SubscriptionHandler.syncSubscription(
recurlySubscription,
{ ip: req.ip },
function (err) {
if (err) {
return next(err)
}
res.sendStatus(200)
}
)
} else if (event === 'billing_info_updated_notification') {
const recurlyAccountCode = eventData.account.account_code
SubscriptionHandler.attemptPaypalInvoiceCollection(
recurlyAccountCode,
function (err) {
if (err) {
return next(err)
}
res.sendStatus(200)
}
)
} else {
res.sendStatus(200)
}
}
function renderUpgradeToAnnualPlanPage(req, res, next) {
const user = SessionManager.getSessionUser(req.session)
LimitationsManager.userHasV2Subscription(
user,
function (err, hasSubscription, subscription) {
let planName
if (err) {
return next(err)
}
const planCode = subscription
? subscription.planCode.toLowerCase()
: undefined
if ((planCode ? planCode.indexOf('annual') : undefined) !== -1) {
planName = 'annual'
} else if ((planCode ? planCode.indexOf('student') : undefined) !== -1) {
planName = 'student'
} else if (
(planCode ? planCode.indexOf('collaborator') : undefined) !== -1
) {
planName = 'collaborator'
}
if (hasSubscription) {
res.render('subscriptions/upgradeToAnnual', {
title: 'Upgrade to annual',
planName,
})
} else {
res.redirect('/user/subscription/plans')
}
}
)
}
function processUpgradeToAnnualPlan(req, res, next) {
const user = SessionManager.getSessionUser(req.session)
const { planName } = req.body
const couponCode = Settings.coupon_codes.upgradeToAnnualPromo[planName]
const annualPlanName = `${planName}-annual`
logger.log(
{ user_id: user._id, planName: annualPlanName },
'user is upgrading to annual billing with discount'
)
return SubscriptionHandler.updateSubscription(
user,
annualPlanName,
couponCode,
function (err) {
if (err) {
OError.tag(err, 'error updating subscription', {
user_id: user._id,
})
return next(err)
}
res.sendStatus(200)
}
)
}
async function extendTrial(req, res) {
const user = SessionManager.getSessionUser(req.session)
const {
subscription,
} = await LimitationsManager.promises.userHasV2Subscription(user)
try {
await SubscriptionHandler.promises.extendTrial(subscription, 14)
} catch (error) {
return res.sendStatus(500)
}
res.sendStatus(200)
}
function recurlyNotificationParser(req, res, next) {
let xml = ''
req.on('data', chunk => (xml += chunk))
req.on('end', () =>
RecurlyWrapper._parseXml(xml, function (error, body) {
if (error) {
return next(error)
}
req.body = body
next()
})
)
}
async function refreshUserFeatures(req, res) {
const { user_id: userId } = req.params
await FeaturesUpdater.promises.refreshFeatures(userId)
res.sendStatus(200)
}
module.exports = {
plansPage: expressify(plansPage),
paymentPage: expressify(paymentPage),
userSubscriptionPage: expressify(userSubscriptionPage),
createSubscription,
successfulSubscription,
cancelSubscription,
canceledSubscription,
cancelV1Subscription,
updateSubscription,
cancelPendingSubscriptionChange,
updateAccountEmailAddress,
reactivateSubscription,
recurlyCallback,
renderUpgradeToAnnualPlanPage,
processUpgradeToAnnualPlan,
extendTrial: expressify(extendTrial),
recurlyNotificationParser,
refreshUserFeatures: expressify(refreshUserFeatures),
}
| overleaf/web/app/src/Features/Subscription/SubscriptionController.js/0 | {
"file_path": "overleaf/web/app/src/Features/Subscription/SubscriptionController.js",
"repo_id": "overleaf",
"token_count": 5822
} | 499 |
/* eslint-disable
node/handle-callback-err,
*/
// 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 SystemMessageManager
const { SystemMessage } = require('../../models/SystemMessage')
module.exports = SystemMessageManager = {
getMessages(callback) {
if (callback == null) {
callback = function (error, messages) {}
}
callback(null, this._cachedMessages)
},
getMessagesFromDB(callback) {
if (callback == null) {
callback = function (error, messages) {}
}
return SystemMessage.find({}, callback)
},
clearMessages(callback) {
if (callback == null) {
callback = function (error) {}
}
return SystemMessage.deleteMany({}, callback)
},
createMessage(content, callback) {
if (callback == null) {
callback = function (error) {}
}
const message = new SystemMessage({ content })
return message.save(callback)
},
refreshCache() {
this.getMessagesFromDB((error, messages) => {
if (!error) {
this._cachedMessages = messages
}
})
},
}
const CACHE_TIMEOUT = 10 * 1000 * (Math.random() + 2) // 20-30 seconds
SystemMessageManager.refreshCache()
setInterval(() => SystemMessageManager.refreshCache(), CACHE_TIMEOUT)
| overleaf/web/app/src/Features/SystemMessages/SystemMessageManager.js/0 | {
"file_path": "overleaf/web/app/src/Features/SystemMessages/SystemMessageManager.js",
"repo_id": "overleaf",
"token_count": 511
} | 500 |
const Errors = require('../Errors/Errors')
class InvalidZipFileError extends Errors.BackwardCompatibleError {
constructor(options) {
super({
message: 'invalid_zip_file',
...options,
})
}
}
class EmptyZipFileError extends InvalidZipFileError {
constructor(options) {
super({
message: 'empty_zip_file',
...options,
})
}
}
class ZipContentsTooLargeError extends InvalidZipFileError {
constructor(options) {
super({
message: 'zip_contents_too_large',
...options,
})
}
}
module.exports = {
InvalidZipFileError,
EmptyZipFileError,
ZipContentsTooLargeError,
}
| overleaf/web/app/src/Features/Uploads/ArchiveErrors.js/0 | {
"file_path": "overleaf/web/app/src/Features/Uploads/ArchiveErrors.js",
"repo_id": "overleaf",
"token_count": 233
} | 501 |
const TeamInvitesHandler = require('../Subscription/TeamInvitesHandler')
const UserHandler = {
populateTeamInvites(user, callback) {
TeamInvitesHandler.createTeamInvitesForLegacyInvitedEmail(
user.email,
callback
)
},
setupLoginData(user, callback) {
this.populateTeamInvites(user, callback)
},
}
module.exports = UserHandler
| overleaf/web/app/src/Features/User/UserHandler.js/0 | {
"file_path": "overleaf/web/app/src/Features/User/UserHandler.js",
"repo_id": "overleaf",
"token_count": 122
} | 502 |
/* 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
*/
let UserMembershipViewModel
const UserGetter = require('../User/UserGetter')
const { isObjectIdInstance } = require('../Helpers/Mongo')
module.exports = UserMembershipViewModel = {
build(userOrEmail) {
if (userOrEmail._id) {
return buildUserViewModel(userOrEmail)
} else {
return buildUserViewModelWithEmail(userOrEmail)
}
},
buildAsync(userOrIdOrEmail, callback) {
if (callback == null) {
callback = function (error, viewModel) {}
}
if (!isObjectIdInstance(userOrIdOrEmail)) {
// userOrIdOrEmail is a user or an email and can be parsed by #build
return callback(null, UserMembershipViewModel.build(userOrIdOrEmail))
}
const userId = userOrIdOrEmail
const projection = {
email: 1,
first_name: 1,
last_name: 1,
lastLoggedIn: 1,
}
return UserGetter.getUser(userId, projection, function (error, user) {
if (error != null || user == null) {
return callback(null, buildUserViewModelWithId(userId.toString()))
}
return callback(null, buildUserViewModel(user))
})
},
}
var buildUserViewModel = function (user, isInvite) {
if (isInvite == null) {
isInvite = false
}
return {
_id: user._id || null,
email: user.email || null,
first_name: user.first_name || null,
last_name: user.last_name || null,
last_logged_in_at: user.lastLoggedIn || null,
invite: isInvite,
}
}
var buildUserViewModelWithEmail = email => buildUserViewModel({ email }, true)
var buildUserViewModelWithId = id => buildUserViewModel({ _id: id }, false)
| overleaf/web/app/src/Features/UserMembership/UserMembershipViewModel.js/0 | {
"file_path": "overleaf/web/app/src/Features/UserMembership/UserMembershipViewModel.js",
"repo_id": "overleaf",
"token_count": 726
} | 503 |
const fs = require('fs')
const Path = require('path')
const pug = require('pug')
const async = require('async')
const { promisify } = require('util')
const Settings = require('@overleaf/settings')
const MODULE_BASE_PATH = Path.resolve(__dirname + '/../../../modules')
const _modules = []
const _hooks = {}
let _viewIncludes = {}
function loadModules() {
const settingsCheckModule = Path.join(
MODULE_BASE_PATH,
'settings-check',
'index.js'
)
if (fs.existsSync(settingsCheckModule)) {
require(settingsCheckModule)
}
for (const moduleName of Settings.moduleImportSequence) {
const loadedModule = require(Path.join(
MODULE_BASE_PATH,
moduleName,
'index.js'
))
loadedModule.name = moduleName
_modules.push(loadedModule)
}
attachHooks()
}
function applyRouter(webRouter, privateApiRouter, publicApiRouter) {
for (const module of _modules) {
if (module.router && module.router.apply) {
module.router.apply(webRouter, privateApiRouter, publicApiRouter)
}
}
}
function applyNonCsrfRouter(webRouter, privateApiRouter, publicApiRouter) {
for (const module of _modules) {
if (module.nonCsrfRouter != null) {
module.nonCsrfRouter.apply(webRouter, privateApiRouter, publicApiRouter)
}
if (module.router && module.router.applyNonCsrfRouter) {
module.router.applyNonCsrfRouter(
webRouter,
privateApiRouter,
publicApiRouter
)
}
}
}
function loadViewIncludes(app) {
_viewIncludes = {}
for (const module of _modules) {
const object = module.viewIncludes || {}
for (const view in object) {
const partial = object[view]
if (!_viewIncludes[view]) {
_viewIncludes[view] = []
}
const filePath = Path.join(
MODULE_BASE_PATH,
module.name,
'app/views',
partial + '.pug'
)
_viewIncludes[view].push(
pug.compileFile(filePath, {
doctype: 'html',
compileDebug: Settings.debugPugTemplates,
})
)
}
}
}
function moduleIncludes(view, locals) {
const compiledPartials = _viewIncludes[view] || []
let html = ''
for (const compiledPartial of compiledPartials) {
html += compiledPartial(locals)
}
return html
}
function moduleIncludesAvailable(view) {
return (_viewIncludes[view] || []).length > 0
}
function linkedFileAgentsIncludes() {
const agents = {}
for (const module of _modules) {
for (const name in module.linkedFileAgents) {
const agentFunction = module.linkedFileAgents[name]
agents[name] = agentFunction()
}
}
return agents
}
function attachHooks() {
for (var module of _modules) {
if (module.hooks != null) {
for (const hook in module.hooks) {
const method = module.hooks[hook]
attachHook(hook, method)
}
}
}
}
function attachHook(name, method) {
if (_hooks[name] == null) {
_hooks[name] = []
}
_hooks[name].push(method)
}
function fireHook(name, ...rest) {
const adjustedLength = Math.max(rest.length, 1)
const args = rest.slice(0, adjustedLength - 1)
const callback = rest[adjustedLength - 1]
const methods = _hooks[name] || []
const callMethods = methods.map(method => cb => method(...args, cb))
async.series(callMethods, function (error, results) {
if (error) {
return callback(error)
}
callback(null, results)
})
}
module.exports = {
applyNonCsrfRouter,
applyRouter,
linkedFileAgentsIncludes,
loadViewIncludes,
moduleIncludes,
moduleIncludesAvailable,
hooks: {
attach: attachHook,
fire: fireHook,
},
promises: {
hooks: {
fire: promisify(fireHook),
},
},
}
loadModules()
| overleaf/web/app/src/infrastructure/Modules.js/0 | {
"file_path": "overleaf/web/app/src/infrastructure/Modules.js",
"repo_id": "overleaf",
"token_count": 1460
} | 504 |
const logger = require('logger-sharelatex')
const pug = require('pug')
const globby = require('globby')
const Settings = require('@overleaf/settings')
const path = require('path')
// Generate list of view names from app/views
const viewList = globby
.sync('app/views/**/*.pug', {
onlyFiles: true,
concurrency: 1,
ignore: '**/_*.pug',
})
.concat(
globby.sync('modules/*/app/views/**/*.pug', {
onlyFiles: true,
concurrency: 1,
ignore: '**/_*.pug',
})
)
.map(x => {
return x.replace(/\.pug$/, '') // strip trailing .pug extension
})
.filter(x => {
return !/^_/.test(x)
})
module.exports = {
precompileViews(app) {
const startTime = Date.now()
let success = 0
let failures = 0
viewList.forEach(view => {
const filename = path.resolve(view + '.pug') // express views are cached using the absolute path
try {
pug.compileFile(filename, {
cache: true,
compileDebug: Settings.debugPugTemplates,
})
logger.log({ filename }, 'compiled')
success++
} catch (err) {
logger.error({ filename, err: err.message }, 'error compiling')
failures++
}
})
logger.log(
{ timeTaken: Date.now() - startTime, failures, success },
'compiled templates'
)
},
}
| overleaf/web/app/src/infrastructure/Views.js/0 | {
"file_path": "overleaf/web/app/src/infrastructure/Views.js",
"repo_id": "overleaf",
"token_count": 553
} | 505 |
const mongoose = require('../infrastructure/Mongoose')
const { Schema } = mongoose
const { ObjectId } = Schema
const EXPIRY_IN_SECONDS = 60 * 60 * 24 * 30
const ExpiryDate = function () {
const timestamp = new Date()
timestamp.setSeconds(timestamp.getSeconds() + EXPIRY_IN_SECONDS)
return timestamp
}
const ProjectInviteSchema = new Schema(
{
email: String,
token: String,
sendingUserId: ObjectId,
projectId: ObjectId,
privileges: String,
createdAt: { type: Date, default: Date.now },
expires: {
type: Date,
default: ExpiryDate,
index: { expireAfterSeconds: 10 },
},
},
{
collection: 'projectInvites',
}
)
exports.ProjectInvite = mongoose.model('ProjectInvite', ProjectInviteSchema)
exports.ProjectInviteSchema = ProjectInviteSchema
exports.EXPIRY_IN_SECONDS = EXPIRY_IN_SECONDS
| overleaf/web/app/src/models/ProjectInvite.js/0 | {
"file_path": "overleaf/web/app/src/models/ProjectInvite.js",
"repo_id": "overleaf",
"token_count": 322
} | 506 |
extends ../layout
block content
main.content.content-alt#main-content
.container
.row
.col-md-6.col-md-offset-3
.card
.page-header
h1 Account Access Error
p.text-danger Sorry, an error occurred accessing your account. Please #[a(href="" ng-controller="ContactModal" ng-click="contactUsModal()") contact support] and provide any email addresses that you have used to sign in to Overleaf and/or ShareLaTeX for assistance.
| overleaf/web/app/views/general/account-merge-error.pug/0 | {
"file_path": "overleaf/web/app/views/general/account-merge-error.pug",
"repo_id": "overleaf",
"token_count": 158
} | 507 |
div(
ng-controller="FileViewController"
ng-show="ui.view == 'file'"
ng-if="openFile"
)
file-view(
file='file'
store-references-keys='storeReferencesKeys'
)
| overleaf/web/app/views/project/editor/file-view.pug/0 | {
"file_path": "overleaf/web/app/views/project/editor/file-view.pug",
"repo_id": "overleaf",
"token_count": 67
} | 508 |
if showSymbolPalette
symbol-palette(show="editor.showSymbolPalette" handle-select="editor.insertSymbol")
| overleaf/web/app/views/project/editor/symbol-palette.pug/0 | {
"file_path": "overleaf/web/app/views/project/editor/symbol-palette.pug",
"repo_id": "overleaf",
"token_count": 35
} | 509 |
//- Features Tables
mixin table_premium
table.card.plans-table.plans-table-main
tr
th
th #{translate("free")}
th #{translate("personal")}
th #{translate("collaborator")}
.outer.outer-top
.outer-content
.best-value
strong #{translate('best_value')}
th #{translate("professional")}
tr
td #{translate("price")}
td #{translate("free")}
td
+price_personal
td
+price_collaborator
td
+price_professional
for feature in planFeatures
tr
td(event-tracking="features-table" event-tracking-trigger="hover" event-tracking-ga="subscription-funnel" event-tracking-label=`${feature.feature}`)
if feature.info
span(tooltip=translate(feature.info)) #{translate(feature.feature)}
else
| #{translate(feature.feature)}
for plan in feature.plans
td(ng-non-bindable)
if feature.value == 'str'
| #{plan}
else if plan
i.fa.fa-check(aria-hidden="true")
span.sr-only Feature included
else
i.fa.fa-times(aria-hidden="true")
span.sr-only Feature not included
tr
td
td
+btn_buy_free('table')
td
+btn_buy_personal('table')
td
+btn_buy_collaborator('table')
.outer.outer-btm
.outer-content
td
+btn_buy_professional('table')
mixin table_cell_student(feature)
if feature.value == 'str'
| #{feature.student}
else if feature.student
i.fa.fa-check(aria-hidden="true")
span.sr-only Feature included
else
i.fa.fa-times(aria-hidden="true")
span.sr-only Feature not included
mixin table_student
table.card.plans-table.plans-table-student
tr
th
th #{translate("free")}
th #{translate("student")} (#{translate("annual")})
.outer.outer-top
.outer-content
.best-value
strong Best Value
th #{translate("student")}
tr
td #{translate("price")}
td #{translate("free")}
td
+price_student_annual
td
+price_student_monthly
for feature in planFeatures
tr
td(event-tracking="plans-page-table" event-tracking-trigger="hover" event-tracking-ga="subscription-funnel" event-tracking-label=`${feature.feature}`)
if feature.info
span(tooltip=translate(feature.info)) #{translate(feature.feature)}
else
| #{translate(feature.feature)}
td(ng-non-bindable)
if feature.value == 'str'
| #{feature.plans.free}
else if feature.plans.free
i.fa.fa-check(aria-hidden="true")
span.sr-only Feature included
else
i.fa.fa-times(aria-hidden="true")
span.sr-only Feature included
td(ng-non-bindable)
+table_cell_student(feature)
td(ng-non-bindable)
+table_cell_student(feature)
tr
td
td
+btn_buy_free('table')
td
+btn_buy_student('table', 'annual')
.outer.outer-btm
.outer-content
td
+btn_buy_student('table', 'monthly')
| overleaf/web/app/views/subscriptions/_plans_page_tables.pug/0 | {
"file_path": "overleaf/web/app/views/subscriptions/_plans_page_tables.pug",
"repo_id": "overleaf",
"token_count": 1309
} | 510 |
if (v1SubscriptionStatus['team'] && v1SubscriptionStatus['team']['default_plan_name'] != 'free')
- hasDisplayedSubscription = true
p
| You have a legacy group licence from Overleaf v1.
if (v1SubscriptionStatus['team']['will_end_at'])
p
| Your current group licence ends on
|
strong= moment(v1SubscriptionStatus['team']['will_end_at']).format('Do MMM YY')
|
| and will
|
if (v1SubscriptionStatus['team']['will_renew'])
| be automatically renewed.
else
| not be automatically renewed.
if (v1SubscriptionStatus['can_cancel_team'])
p
form(method="POST", action="/user/subscription/v1/cancel")
input(type="hidden", name="_csrf", value=csrfToken)
button().btn.btn-danger Stop automatic renewal
else
p
| Please
|
a(href="/contact") contact support
|
| to make changes to your plan
hr
if (v1SubscriptionStatus['product'])
- hasDisplayedSubscription = true
p
| You have a legacy Overleaf v1
|
strong= v1SubscriptionStatus['product']['display_name']
|
| plan.
p
| Your plan ends on
|
strong= moment(v1SubscriptionStatus['product']['will_end_at']).format('Do MMM YY')
|
| and will
|
if (v1SubscriptionStatus['product']['will_renew'])
| be automatically renewed.
else
| not be automatically renewed.
if (v1SubscriptionStatus['can_cancel'])
p
form(method="POST", action="/user/subscription/v1/cancel")
input(type="hidden", name="_csrf", value=csrfToken)
button().btn.btn-danger Stop automatic renewal
else
p
| Please
|
a(href="/contact") contact support
|
| to make changes to your plan
hr
| overleaf/web/app/views/subscriptions/dashboard/_v1_subscription_status.pug/0 | {
"file_path": "overleaf/web/app/views/subscriptions/dashboard/_v1_subscription_status.pug",
"repo_id": "overleaf",
"token_count": 719
} | 511 |
extends ../layout
block content
main.content#main-content
.container
.row
.col-md-8.col-md-offset-2.text-center
.page-header
h2 #{translate("restricted_no_permission")}
p
a(href="/")
i.fa.fa-arrow-circle-o-left(aria-hidden="true")
| #{translate("take_me_home")}
| overleaf/web/app/views/user/restricted.pug/0 | {
"file_path": "overleaf/web/app/views/user/restricted.pug",
"repo_id": "overleaf",
"token_count": 154
} | 512 |
#!/bin/bash
pushd ..
bin/run $*
RV=$?
popd
exit $RV
| overleaf/web/bin/run/0 | {
"file_path": "overleaf/web/bin/run",
"repo_id": "overleaf",
"token_count": 31
} | 513 |
import App from '../base'
import 'libs/passfield'
App.directive('asyncForm', ($http, validateCaptcha, validateCaptchaV3) => ({
controller: [
'$scope',
'$location',
function ($scope, $location) {
this.getEmail = () => $scope.email
this.getEmailFromQuery = () =>
$location.search().email || $location.search().new_email
return this
},
],
link(scope, element, attrs, ctrl) {
let response
const formName = attrs.asyncForm
scope[attrs.name].response = response = {}
scope[attrs.name].inflight = false
scope.email =
scope.email ||
scope.usersEmail ||
ctrl.getEmailFromQuery() ||
attrs.newEmail
const validateCaptchaIfEnabled = function (callback) {
scope.$applyAsync(() => {
scope[attrs.name].inflight = true
})
if (attrs.captchaActionName) {
validateCaptchaV3(attrs.captchaActionName)
}
if (attrs.captcha != null) {
validateCaptcha(callback)
} else {
callback()
}
}
const _submitRequest = function (grecaptchaResponse) {
const formData = {}
for (const data of Array.from(element.serializeArray())) {
formData[data.name] = data.value
}
if (grecaptchaResponse) {
formData['g-recaptcha-response'] = grecaptchaResponse
}
// clear the response object which may be referenced downstream
Object.keys(response).forEach(field => delete response[field])
// for asyncForm prevent automatic redirect to /login if
// authentication fails, we will handle it ourselves
const httpRequestFn = _httpRequestFn(element.attr('method'))
return httpRequestFn(element.attr('action'), formData, {
disableAutoLoginRedirect: true,
})
.then(function (httpResponse) {
const { data, headers } = httpResponse
scope[attrs.name].inflight = false
response.success = true
response.error = false
const onSuccessHandler = scope[attrs.onSuccess]
if (onSuccessHandler) {
onSuccessHandler(httpResponse)
return
}
if (data.redir) {
ga('send', 'event', formName, 'success')
return (window.location = data.redir)
} else if (data.message) {
response.message = data.message
if (data.message.type === 'error') {
response.success = false
response.error = true
return ga('send', 'event', formName, 'failure', data.message)
} else {
return ga('send', 'event', formName, 'success')
}
} else if (scope.$eval(attrs.asyncFormDownloadResponse)) {
const blob = new Blob([data], {
type: headers('Content-Type'),
})
location.href = URL.createObjectURL(blob) // Trigger file save
}
})
.catch(function (httpResponse) {
const { data, status } = httpResponse
scope[attrs.name].inflight = false
response.success = false
response.error = true
response.status = status
response.data = data
const onErrorHandler = scope[attrs.onError]
if (onErrorHandler) {
onErrorHandler(httpResponse)
return
}
let responseMessage
if (data.message && data.message.text) {
responseMessage = data.message.text
} else {
responseMessage = data.message
}
if (status === 400) {
// Bad Request
response.message = {
text:
responseMessage ||
'Invalid Request. Please correct the data and try again.',
type: 'error',
}
} else if (status === 403) {
// Forbidden
response.message = {
text:
responseMessage ||
'Session error. Please check you have cookies enabled. If the problem persists, try clearing your cache and cookies.',
type: 'error',
}
} else if (status === 429) {
response.message = {
text:
responseMessage ||
'Too many attempts. Please wait for a while and try again.',
type: 'error',
}
} else {
response.message = {
text:
responseMessage ||
'Something went wrong talking to the server :(. Please try again.',
type: 'error',
}
}
ga('send', 'event', formName, 'failure', data.message)
})
}
const submit = () =>
validateCaptchaIfEnabled(response => _submitRequest(response))
const _httpRequestFn = (method = 'post') => {
const $HTTP_FNS = {
post: $http.post,
get: $http.get,
}
return $HTTP_FNS[method.toLowerCase()]
}
element.on('submit', function (e) {
e.preventDefault()
submit()
})
if (attrs.autoSubmit) {
submit()
}
},
}))
App.directive('formMessages', () => ({
restrict: 'E',
template: `\
<div class="alert" ng-class="{
'alert-danger': form.response.message.type == 'error',
'alert-success': form.response.message.type != 'error'
}" ng-show="!!form.response.message" ng-bind-html="form.response.message.text">
</div>
<div ng-transclude></div>\
`,
transclude: true,
scope: {
form: '=for',
},
}))
| overleaf/web/frontend/js/directives/asyncForm.js/0 | {
"file_path": "overleaf/web/frontend/js/directives/asyncForm.js",
"repo_id": "overleaf",
"token_count": 2511
} | 514 |
/* eslint-disable
max-len,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import App from '../base'
export default App.directive('videoPlayState', $parse => ({
restrict: 'A',
link(scope, element, attrs) {
const videoDOMEl = element[0]
return scope.$watch(
() => $parse(attrs.videoPlayState)(scope),
function (shouldPlay) {
if (shouldPlay) {
videoDOMEl.currentTime = 0
return videoDOMEl.play()
} else {
return videoDOMEl.pause()
}
}
)
},
}))
| overleaf/web/frontend/js/directives/videoPlayState.js/0 | {
"file_path": "overleaf/web/frontend/js/directives/videoPlayState.js",
"repo_id": "overleaf",
"token_count": 302
} | 515 |
import PropTypes from 'prop-types'
import classNames from 'classnames'
import { useTranslation } from 'react-i18next'
import Icon from '../../../shared/components/icon'
function ChatToggleButton({ chatIsOpen, unreadMessageCount, onClick }) {
const { t } = useTranslation()
const classes = classNames(
'btn',
'btn-full-height',
'btn-full-height-no-border',
{ active: chatIsOpen }
)
const hasUnreadMessages = unreadMessageCount > 0
return (
// eslint-disable-next-line jsx-a11y/anchor-is-valid
<a role="button" className={classes} href="#" onClick={onClick}>
<Icon
type="fw"
modifier="comment"
classes={{ icon: hasUnreadMessages ? 'bounce' : undefined }}
/>
{hasUnreadMessages ? (
<span className="label label-info">{unreadMessageCount}</span>
) : null}
<p className="toolbar-label">{t('chat')}</p>
</a>
)
}
ChatToggleButton.propTypes = {
chatIsOpen: PropTypes.bool,
unreadMessageCount: PropTypes.number.isRequired,
onClick: PropTypes.func.isRequired,
}
export default ChatToggleButton
| overleaf/web/frontend/js/features/editor-navigation-toolbar/components/chat-toggle-button.js/0 | {
"file_path": "overleaf/web/frontend/js/features/editor-navigation-toolbar/components/chat-toggle-button.js",
"repo_id": "overleaf",
"token_count": 418
} | 516 |
import ControlLabel from 'react-bootstrap/lib/ControlLabel'
import { Alert, FormControl } from 'react-bootstrap'
import FormGroup from 'react-bootstrap/lib/FormGroup'
import { useCallback } from 'react'
import { Trans, useTranslation } from 'react-i18next'
import { useFileTreeCreateName } from '../../contexts/file-tree-create-name'
import PropTypes from 'prop-types'
import {
BlockedFilenameError,
DuplicateFilenameError,
InvalidFilenameError,
} from '../../errors'
/**
* A form component that renders a text input with label,
* plus a validation warning and/or an error message when needed
*/
export default function FileTreeCreateNameInput({
label,
focusName = false,
classes = {},
placeholder,
error,
}) {
const { t } = useTranslation()
// the value is stored in a context provider, so it's available elsewhere in the form
const { name, setName, touchedName, validName } = useFileTreeCreateName()
// focus the first part of the filename if needed
const inputRef = useCallback(
element => {
if (element && focusName) {
window.requestAnimationFrame(() => {
element.focus()
element.setSelectionRange(0, element.value.lastIndexOf('.'))
})
}
},
[focusName]
)
return (
<FormGroup controlId="new-doc-name" className={classes.formGroup}>
<ControlLabel>{label || t('file_name')}</ControlLabel>
<FormControl
type="text"
placeholder={placeholder || t('file_name')}
required
value={name}
onChange={event => setName(event.target.value)}
inputRef={inputRef}
/>
<FormControl.Feedback />
{touchedName && !validName && (
<Alert bsStyle="danger" className="row-spaced-small">
<Trans i18nKey="files_cannot_include_invalid_characters" />
</Alert>
)}
{error && <ErrorMessage error={error} />}
</FormGroup>
)
}
FileTreeCreateNameInput.propTypes = {
focusName: PropTypes.bool,
label: PropTypes.string,
classes: PropTypes.shape({
formGroup: PropTypes.string,
}),
placeholder: PropTypes.string,
error: PropTypes.oneOfType([PropTypes.object, PropTypes.string]),
}
function ErrorMessage({ error }) {
// if (typeof error === 'string') {
// return error
// }
switch (error.constructor) {
case DuplicateFilenameError:
return (
<Alert bsStyle="danger" className="row-spaced-small">
<Trans i18nKey="file_already_exists" />
</Alert>
)
case InvalidFilenameError:
return (
<Alert bsStyle="danger" className="row-spaced-small">
<Trans i18nKey="files_cannot_include_invalid_characters" />
</Alert>
)
case BlockedFilenameError:
return (
<Alert bsStyle="danger" className="row-spaced-small">
<Trans i18nKey="blocked_filename" />
</Alert>
)
default:
// return <Trans i18nKey="generic_something_went_wrong" />
return null // other errors are displayed elsewhere
}
}
ErrorMessage.propTypes = {
error: PropTypes.oneOfType([PropTypes.object, PropTypes.string]).isRequired,
}
| overleaf/web/frontend/js/features/file-tree/components/file-tree-create/file-tree-create-name-input.js/0 | {
"file_path": "overleaf/web/frontend/js/features/file-tree/components/file-tree-create/file-tree-create-name-input.js",
"repo_id": "overleaf",
"token_count": 1167
} | 517 |
import { useState } from 'react'
import { findDOMNode } from 'react-dom'
import PropTypes from 'prop-types'
import { useTranslation } from 'react-i18next'
import withoutPropagation from '../../../../infrastructure/without-propagation'
import { Dropdown, Overlay } from 'react-bootstrap'
import Icon from '../../../../shared/components/icon'
import FileTreeItemMenuItems from './file-tree-item-menu-items'
function FileTreeItemMenu({ id }) {
const { t } = useTranslation()
const [dropdownOpen, setDropdownOpen] = useState(false)
const [dropdownTarget, setDropdownTarget] = useState()
function handleToggle(wantOpen) {
setDropdownOpen(wantOpen)
}
function handleClick() {
handleToggle(false)
}
const toggleRef = component => {
if (component) {
// eslint-disable-next-line react/no-find-dom-node
setDropdownTarget(findDOMNode(component))
}
}
return (
<Dropdown
onClick={withoutPropagation(handleClick)}
pullRight
open={dropdownOpen}
id={`dropdown-${id}`}
onToggle={handleToggle}
>
<Dropdown.Toggle
noCaret
className="dropdown-toggle-no-background entity-menu-toggle"
onClick={withoutPropagation()}
ref={toggleRef}
>
<Icon type="ellipsis-v" accessibilityLabel={t('menu')} />
</Dropdown.Toggle>
<Overlay
bsRole="menu"
show={dropdownOpen}
target={dropdownTarget}
container={document.body}
>
<Menu dropdownId={`dropdown-${id}`} />
</Overlay>
</Dropdown>
)
}
FileTreeItemMenu.propTypes = {
id: PropTypes.string.isRequired,
}
function Menu({ dropdownId, style, className }) {
return (
<div className={`dropdown open ${className}`} style={style}>
<ul className="dropdown-menu" role="menu" aria-labelledby={dropdownId}>
<FileTreeItemMenuItems />
</ul>
</div>
)
}
Menu.propTypes = {
dropdownId: PropTypes.string.isRequired,
style: PropTypes.object,
className: PropTypes.string,
}
export default FileTreeItemMenu
| overleaf/web/frontend/js/features/file-tree/components/file-tree-item/file-tree-item-menu.js/0 | {
"file_path": "overleaf/web/frontend/js/features/file-tree/components/file-tree-item/file-tree-item-menu.js",
"repo_id": "overleaf",
"token_count": 808
} | 518 |
export class InvalidFilenameError extends Error {
constructor() {
super('invalid filename')
}
}
export class BlockedFilenameError extends Error {
constructor() {
super('blocked filename')
}
}
export class DuplicateFilenameError extends Error {
constructor() {
super('duplicate filename')
}
}
export class DuplicateFilenameMoveError extends Error {
constructor() {
super('duplicate filename on move')
}
}
| overleaf/web/frontend/js/features/file-tree/errors.js/0 | {
"file_path": "overleaf/web/frontend/js/features/file-tree/errors.js",
"repo_id": "overleaf",
"token_count": 127
} | 519 |
import { useState, useCallback } from 'react'
import PropTypes from 'prop-types'
import { useTranslation } from 'react-i18next'
import FileViewHeader from './file-view-header'
import FileViewImage from './file-view-image'
import FileViewText from './file-view-text'
import Icon from '../../../shared/components/icon'
const imageExtensions = ['png', 'jpg', 'jpeg', 'gif']
const textExtensions = window.ExposedSettings.textExtensions
export default function FileView({ file, storeReferencesKeys }) {
const [contentLoading, setContentLoading] = useState(true)
const [hasError, setHasError] = useState(false)
const { t } = useTranslation()
const extension = file.name.split('.').pop().toLowerCase()
const isUnpreviewableFile =
!imageExtensions.includes(extension) && !textExtensions.includes(extension)
const handleLoad = useCallback(() => {
setContentLoading(false)
}, [])
const handleError = useCallback(() => {
if (!hasError) {
setContentLoading(false)
setHasError(true)
}
}, [hasError])
const content = (
<>
<FileViewHeader file={file} storeReferencesKeys={storeReferencesKeys} />
{imageExtensions.includes(extension) && (
<FileViewImage
fileName={file.name}
fileId={file.id}
onLoad={handleLoad}
onError={handleError}
/>
)}
{textExtensions.includes(extension) && (
<FileViewText file={file} onLoad={handleLoad} onError={handleError} />
)}
</>
)
return (
<div className="file-view full-size">
{!hasError && content}
{!isUnpreviewableFile && contentLoading && <FileViewLoadingIndicator />}
{(isUnpreviewableFile || hasError) && (
<p className="no-preview">{t('no_preview_available')}</p>
)}
</div>
)
}
function FileViewLoadingIndicator() {
const { t } = useTranslation()
return (
<div className="loading-panel loading-panel-file-view">
<span>
<Icon type="refresh" modifier="spin" />
{t('loading')}…
</span>
</div>
)
}
FileView.propTypes = {
file: PropTypes.shape({
id: PropTypes.string,
name: PropTypes.string,
}).isRequired,
storeReferencesKeys: PropTypes.func.isRequired,
}
| overleaf/web/frontend/js/features/file-view/components/file-view.js/0 | {
"file_path": "overleaf/web/frontend/js/features/file-view/components/file-view.js",
"repo_id": "overleaf",
"token_count": 852
} | 520 |
import PropTypes from 'prop-types'
import { useTranslation } from 'react-i18next'
import { Dropdown } from 'react-bootstrap'
import PreviewLogsPaneEntry from './preview-logs-pane-entry'
import PreviewValidationIssue from './preview-validation-issue'
import PreviewDownloadFileList from './preview-download-file-list'
import PreviewError from './preview-error'
import Icon from '../../../shared/components/icon'
import usePersistedState from '../../../shared/hooks/use-persisted-state'
import ControlledDropdown from '../../../shared/components/controlled-dropdown'
function PreviewLogsPane({
logEntries = { all: [], errors: [], warnings: [], typesetting: [] },
rawLog = '',
validationIssues = {},
errors = {},
outputFiles = [],
isClearingCache,
isCompiling = false,
autoCompileHasLintingError = false,
variantWithFirstErrorPopup,
onLogEntryLocationClick,
onClearCache,
}) {
const { t } = useTranslation()
const {
all: allCompilerIssues = [],
errors: compilerErrors = [],
warnings: compilerWarnings = [],
typesetting: compilerTypesettingIssues = [],
} = logEntries
const allLogEntries = [
...compilerErrors,
...compilerWarnings,
...compilerTypesettingIssues,
]
const actionsUI = (
<div className="logs-pane-actions">
<button
className="btn btn-sm btn-danger logs-pane-actions-clear-cache"
onClick={onClearCache}
disabled={isClearingCache || isCompiling}
>
{isClearingCache ? (
<Icon type="refresh" spin />
) : (
<Icon type="trash-o" />
)}
<span>{t('clear_cached_files')}</span>
</button>
<ControlledDropdown
id="dropdown-files-logs-pane"
dropup
pullRight
disabled={isCompiling}
>
<Dropdown.Toggle
className="btn btn-sm btn-info dropdown-toggle"
title={t('other_logs_and_files')}
bsStyle="info"
/>
<Dropdown.Menu id="dropdown-files-logs-pane-list">
<PreviewDownloadFileList fileList={outputFiles} />
</Dropdown.Menu>
</ControlledDropdown>
</div>
)
const rawLogUI = (
<PreviewLogsPaneEntry
headerTitle={t('raw_logs')}
rawContent={rawLog}
entryAriaLabel={t('raw_logs_description')}
level="raw"
/>
)
return (
<div className="logs-pane">
<div className="logs-pane-content">
<LogsPaneInfoNotice
variantWithFirstErrorPopup={variantWithFirstErrorPopup}
/>
{autoCompileHasLintingError ? <AutoCompileLintingErrorEntry /> : null}
{errors ? <PreviewErrors errors={errors} /> : null}
{validationIssues ? (
<PreviewValidationIssues validationIssues={validationIssues} />
) : null}
{allCompilerIssues.length > 0 ? (
<PreviewLogEntries
logEntries={allLogEntries}
onLogEntryLocationClick={onLogEntryLocationClick}
/>
) : null}
{rawLog && rawLog !== '' ? rawLogUI : null}
{actionsUI}
</div>
</div>
)
}
const PreviewErrors = ({ errors }) => {
const nowTS = Date.now()
return Object.entries(errors).map(([name, exists], index) => {
return exists && <PreviewError key={`${nowTS}-${index}`} name={name} />
})
}
const PreviewValidationIssues = ({ validationIssues }) => {
const nowTS = Date.now()
return Object.keys(validationIssues).map((name, index) => (
<PreviewValidationIssue
key={`${nowTS}-${index}`}
name={name}
details={validationIssues[name]}
/>
))
}
const PreviewLogEntries = ({ logEntries, onLogEntryLocationClick }) => {
const { t } = useTranslation()
const nowTS = Date.now()
return logEntries.map((logEntry, index) => (
<PreviewLogsPaneEntry
key={`${nowTS}-${index}`}
headerTitle={logEntry.message}
rawContent={logEntry.content}
logType={logEntry.type}
formattedContent={logEntry.humanReadableHintComponent}
extraInfoURL={logEntry.extraInfoURL}
level={logEntry.level}
entryAriaLabel={t('log_entry_description', {
level: logEntry.level,
})}
sourceLocation={{
file: logEntry.file,
line: logEntry.line,
column: logEntry.column,
}}
onSourceLocationClick={onLogEntryLocationClick}
/>
))
}
function AutoCompileLintingErrorEntry() {
const { t } = useTranslation()
return (
<div className="log-entry">
<div className="log-entry-header log-entry-header-error">
<div className="log-entry-header-icon-container">
<Icon type="exclamation-triangle" modifier="fw" />
</div>
<h3 className="log-entry-header-title">
{t('code_check_failed_explanation')}
</h3>
</div>
</div>
)
}
function LogsPaneInfoNotice({ variantWithFirstErrorPopup }) {
const { t } = useTranslation()
const [dismissedInfoNotice, setDismissedInfoNotice] = usePersistedState(
`logs_pane.dismissed_info_notice`,
false
)
const surveyLink = variantWithFirstErrorPopup
? 'https://forms.gle/AUbDDRvroQ7KFwHR9'
: 'https://forms.gle/bRxevtGzBHRk8BKw8'
function handleDismissButtonClick() {
setDismissedInfoNotice(true)
}
return dismissedInfoNotice ? null : (
<div className="log-entry">
<div className="log-entry-header log-entry-header-raw">
<div className="log-entry-header-icon-container">
<span className="info-badge" />
</div>
<h3 className="log-entry-header-title">
{t('logs_pane_info_message')}
</h3>
<a
href={surveyLink}
target="_blank"
rel="noopener noreferrer"
className="log-entry-header-link log-entry-header-link-raw"
>
<span className="log-entry-header-link-location">
{t('give_feedback')}
</span>
</a>
<button
className="btn-inline-link log-entry-header-link"
type="button"
aria-label={t('dismiss')}
onClick={handleDismissButtonClick}
>
<span aria-hidden="true">×</span>
</button>
</div>
</div>
)
}
PreviewErrors.propTypes = {
errors: PropTypes.object.isRequired,
}
PreviewValidationIssues.propTypes = {
validationIssues: PropTypes.object.isRequired,
}
PreviewLogEntries.propTypes = {
logEntries: PropTypes.array.isRequired,
onLogEntryLocationClick: PropTypes.func.isRequired,
}
LogsPaneInfoNotice.propTypes = {
variantWithFirstErrorPopup: PropTypes.bool,
}
PreviewLogsPane.propTypes = {
logEntries: PropTypes.shape({
all: PropTypes.array,
errors: PropTypes.array,
warning: PropTypes.array,
typesetting: PropTypes.array,
}),
autoCompileHasLintingError: PropTypes.bool,
rawLog: PropTypes.string,
outputFiles: PropTypes.array,
isClearingCache: PropTypes.bool,
isCompiling: PropTypes.bool,
variantWithFirstErrorPopup: PropTypes.bool,
onLogEntryLocationClick: PropTypes.func.isRequired,
onClearCache: PropTypes.func.isRequired,
validationIssues: PropTypes.object,
errors: PropTypes.object,
}
export default PreviewLogsPane
| overleaf/web/frontend/js/features/preview/components/preview-logs-pane.js/0 | {
"file_path": "overleaf/web/frontend/js/features/preview/components/preview-logs-pane.js",
"repo_id": "overleaf",
"token_count": 3005
} | 521 |
import { useShareProjectContext } from './share-project-modal'
import EditMember from './edit-member'
import LinkSharing from './link-sharing'
import Invite from './invite'
import SendInvites from './send-invites'
import ViewMember from './view-member'
import OwnerInfo from './owner-info'
import SendInvitesNotice from './send-invites-notice'
import { useProjectContext } from '../../../shared/context/project-context'
export default function ShareModalBody() {
const { isAdmin } = useShareProjectContext()
const project = useProjectContext()
return (
<>
{isAdmin && <LinkSharing />}
<OwnerInfo />
{project.members.map(member =>
isAdmin ? (
<EditMember key={member._id} member={member} />
) : (
<ViewMember key={member._id} member={member} />
)
)}
{project.invites.map(invite => (
<Invite key={invite._id} invite={invite} isAdmin={isAdmin} />
))}
{isAdmin ? <SendInvites /> : <SendInvitesNotice />}
</>
)
}
| overleaf/web/frontend/js/features/share-project-modal/components/share-modal-body.js/0 | {
"file_path": "overleaf/web/frontend/js/features/share-project-modal/components/share-modal-body.js",
"repo_id": "overleaf",
"token_count": 384
} | 522 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.