├── .env.dev
├── .github
├── ISSUE_TEMPLATE
│ ├── bug.yaml
│ ├── documentation.yaml
│ └── feature.yaml
├── PULL_REQUEST_TEMPLATE.md
└── workflows
│ ├── analyse.yml
│ ├── lint.yml
│ └── test.yml
├── .gitignore
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── Dockerfile
├── LICENSE
├── README.md
├── composer.json
├── composer.lock
├── docker-compose.yml
├── docs
├── add-new-adapter.md
└── sms-pricing.md
├── phpcs.xml
├── phpunit.xml
├── src
└── Utopia
│ └── Messaging
│ ├── Adapter.php
│ ├── Adapter
│ ├── Chat
│ │ └── Discord.php
│ ├── Email.php
│ ├── Email
│ │ ├── Mailgun.php
│ │ ├── Mock.php
│ │ ├── SMTP.php
│ │ └── Sendgrid.php
│ ├── Push.php
│ ├── Push
│ │ ├── APNS.php
│ │ └── FCM.php
│ ├── SMS.php
│ └── SMS
│ │ ├── Clickatell.php
│ │ ├── Fast2SMS.php
│ │ ├── GEOSMS.php
│ │ ├── GEOSMS
│ │ └── CallingCode.php
│ │ ├── Infobip.php
│ │ ├── Inforu.php
│ │ ├── Mock.php
│ │ ├── Msg91.php
│ │ ├── Plivo.php
│ │ ├── Seven.php
│ │ ├── Sinch.php
│ │ ├── Telesign.php
│ │ ├── Telnyx.php
│ │ ├── TextMagic.php
│ │ ├── Twilio.php
│ │ └── Vonage.php
│ ├── Helpers
│ └── JWT.php
│ ├── Message.php
│ ├── Messages
│ ├── Discord.php
│ ├── Email.php
│ ├── Email
│ │ └── Attachment.php
│ ├── Push.php
│ └── SMS.php
│ ├── Priority.php
│ └── Response.php
└── tests
├── Messaging
└── Adapter
│ ├── Base.php
│ ├── Chat
│ └── DiscordTest.php
│ ├── Email
│ ├── EmailTest.php
│ ├── MailgunTest.php
│ ├── SMTPTest.php
│ └── SendgridTest.php
│ ├── Push
│ ├── APNSTest.php
│ ├── Base.php
│ └── FCMTest.php
│ └── SMS
│ ├── Fast2SMSTest.php
│ ├── GEOSMS
│ └── CallingCodeTest.php
│ ├── GEOSMSTest.php
│ ├── InforuTest.php
│ ├── Msg91Test.php
│ ├── SMSTest.php
│ ├── TelesignTest.php
│ ├── TelnyxTest.php
│ ├── TwilioTest.php
│ └── VonageTest.php
└── assets
└── image.png
/.env.dev:
--------------------------------------------------------------------------------
1 | MAILGUN_API_KEY=
2 | MAILGUN_DOMAIN=
3 | SENDGRID_API_KEY=
4 | FCM_SERVICE_ACCOUNT_JSON=
5 | FCM_TO=
6 | TWILIO_ACCOUNT_SID=
7 | TWILIO_AUTH_TOKEN=
8 | TWILIO_TO=
9 | TWILIO_FROM=
10 | TELNYX_API_KEY=
11 | TELNYX_PUBLIC_KEY=
12 | APNS_AUTHKEY=
13 | APNS_AUTH_ID=
14 | APNS_TEAM_ID=
15 | APNS_BUNDLE_ID=
16 | APNS_TO=
17 | MSG_91_SENDER_ID=
18 | MSG_91_AUTH_KEY=
19 | MSG_91_TO=
20 | MSG_91_FROM=
21 | TEST_EMAIL=
22 | TEST_FROM_EMAIL=
23 | TEST_CC_EMAIL=
24 | TEST_BCC_EMAIL=
25 | TEST_BCC_NAME=
26 | VONAGE_API_KEY=
27 | VONAGE_API_SECRET=
28 | VONAGE_TO=
29 | VONAGE_FROM=
30 | DISCORD_WEBHOOK_URL=
31 | FAST2SMS_API_KEY=
32 | FAST2SMS_SENDER_ID=
33 | FAST2SMS_MESSAGE_ID=
34 | FAST2SMS_TO=
35 | INFORU_API_TOKEN=
36 | INFORU_SENDER_ID=
37 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/bug.yaml:
--------------------------------------------------------------------------------
1 | name: "🐛 Bug Report"
2 | description: "Submit a bug report to help us improve"
3 | title: "🐛 Bug Report: "
4 | labels: [bug]
5 | body:
6 | - type: markdown
7 | attributes:
8 | value: |
9 | Thanks for taking the time to fill out our bug report form 🙏
10 | - type: textarea
11 | id: steps-to-reproduce
12 | validations:
13 | required: true
14 | attributes:
15 | label: "👟 Reproduction steps"
16 | description: "How do you trigger this bug? Please walk us through it step by step."
17 | placeholder: "When I ..."
18 | - type: textarea
19 | id: expected-behavior
20 | validations:
21 | required: true
22 | attributes:
23 | label: "👍 Expected behavior"
24 | description: "What did you think would happen?"
25 | placeholder: "It should ..."
26 | - type: textarea
27 | id: actual-behavior
28 | validations:
29 | required: true
30 | attributes:
31 | label: "👎 Actual Behavior"
32 | description: "What did actually happen? Add screenshots, if applicable."
33 | placeholder: "It actually ..."
34 | - type: textarea
35 | id: version
36 | attributes:
37 | label: "🎲 Version"
38 | description: "What version of are you running?"
39 | validations:
40 | required: true
41 | - type: dropdown
42 | id: operating-system
43 | attributes:
44 | label: "💻 Operating system"
45 | description: "What OS is your server / device running on?"
46 | options:
47 | - Linux
48 | - MacOS
49 | - Windows
50 | - Something else
51 | validations:
52 | required: true
53 | - type: textarea
54 | id: environment
55 | validations:
56 | required: false
57 | attributes:
58 | label: "🧱 Your Environment"
59 | description: "Is your environment customized in any way?"
60 | placeholder: "I use Cloudflare for ..."
61 | - type: checkboxes
62 | id: no-duplicate-issues
63 | attributes:
64 | label: "👀 Have you spent some time to check if this issue has been raised before?"
65 | description: "Have you Googled for a similar issue or checked our older issues for a similar bug?"
66 | options:
67 | - label: "I checked and didn't find similar issue"
68 | required: true
69 | - type: checkboxes
70 | id: read-code-of-conduct
71 | attributes:
72 | label: "🏢 Have you read the Code of Conduct?"
73 | options:
74 | - label: "I have read the [Code of Conduct](https://github.com/utopia-php/messaging/blob/HEAD/CODE_OF_CONDUCT.md)"
75 | required: true
76 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/documentation.yaml:
--------------------------------------------------------------------------------
1 | name: "📚 Documentation"
2 | description: "Report an issue related to documentation"
3 | title: "📚 Documentation: "
4 | labels: [documentation]
5 | body:
6 | - type: markdown
7 | attributes:
8 | value: |
9 | Thanks for taking the time to make our documentation better 🙏
10 | - type: textarea
11 | id: issue-description
12 | validations:
13 | required: true
14 | attributes:
15 | label: "💭 Description"
16 | description: "A clear and concise description of what the issue is."
17 | placeholder: "Documentation should not ..."
18 | - type: checkboxes
19 | id: no-duplicate-issues
20 | attributes:
21 | label: "👀 Have you spent some time to check if this issue has been raised before?"
22 | description: "Have you Googled for a similar issue or checked our older issues for a similar bug?"
23 | options:
24 | - label: "I checked and didn't find similar issue"
25 | required: true
26 | - type: checkboxes
27 | id: read-code-of-conduct
28 | attributes:
29 | label: "🏢 Have you read the Code of Conduct?"
30 | options:
31 | - label: "I have read the [Code of Conduct](https://github.com/utopia-php/messaging/blob/HEAD/CODE_OF_CONDUCT.md)"
32 | required: true
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/feature.yaml:
--------------------------------------------------------------------------------
1 | name: 🚀 Feature
2 | description: "Submit a proposal for a new feature"
3 | title: "🚀 Feature: "
4 | labels: [feature]
5 | body:
6 | - type: markdown
7 | attributes:
8 | value: |
9 | Thanks for taking the time to fill out our feature request form 🙏
10 | - type: textarea
11 | id: feature-description
12 | validations:
13 | required: true
14 | attributes:
15 | label: "🔖 Feature description"
16 | description: "A clear and concise description of what the feature is."
17 | placeholder: "You should add ..."
18 | - type: textarea
19 | id: pitch
20 | validations:
21 | required: true
22 | attributes:
23 | label: "🎤 Pitch"
24 | description: "Please explain why this feature should be implemented and how it would be used. Add examples, if applicable."
25 | placeholder: "In my use-case, ..."
26 | - type: checkboxes
27 | id: no-duplicate-issues
28 | attributes:
29 | label: "👀 Have you spent some time to check if this issue has been raised before?"
30 | description: "Have you Googled for a similar issue or checked our older issues for a similar bug?"
31 | options:
32 | - label: "I checked and didn't find similar issue"
33 | required: true
34 | - type: checkboxes
35 | id: read-code-of-conduct
36 | attributes:
37 | label: "🏢 Have you read the Code of Conduct?"
38 | options:
39 | - label: "I have read the [Code of Conduct](https://github.com/utopia-php/messaging/blob/HEAD/CODE_OF_CONDUCT.md)"
40 | required: true
--------------------------------------------------------------------------------
/.github/PULL_REQUEST_TEMPLATE.md:
--------------------------------------------------------------------------------
1 |
11 |
12 | ## What does this PR do?
13 |
14 | (Provide a description of what this PR does.)
15 |
16 | ## Test Plan
17 |
18 | (Write your test plan here. If you changed any code, please provide us with clear instructions on how you verified your changes work.)
19 |
20 | ## Related PRs and Issues
21 |
22 | (If this PR is related to any other PR or resolves any issue or related to any issue link all related PR and issues here.)
23 |
24 | ### Have you read the [Contributing Guidelines on issues](https://github.com/utopia-php/messaging/blob/master/CONTRIBUTING.md)?
25 |
26 | (Write your answer here.)
27 |
--------------------------------------------------------------------------------
/.github/workflows/analyse.yml:
--------------------------------------------------------------------------------
1 | name: "Static Analysis"
2 |
3 | on: [pull_request]
4 | jobs:
5 | analyse:
6 | name: Analyse
7 | runs-on: ubuntu-latest
8 |
9 | steps:
10 | - name: Checkout repository
11 | uses: actions/checkout@v3
12 | with:
13 | fetch-depth: 2
14 |
15 | - run: git checkout HEAD^2
16 |
17 | - name: Run Static Analysis
18 | run: |
19 | docker run --rm -v $PWD:/app composer sh -c \
20 | "composer install --profile --ignore-platform-reqs && composer analyse"
21 |
--------------------------------------------------------------------------------
/.github/workflows/lint.yml:
--------------------------------------------------------------------------------
1 | name: "Linter"
2 |
3 | on: [pull_request]
4 | jobs:
5 | lint:
6 | name: Linter
7 | runs-on: ubuntu-latest
8 |
9 | steps:
10 | - name: Checkout repository
11 | uses: actions/checkout@v3
12 | with:
13 | fetch-depth: 2
14 |
15 | - run: git checkout HEAD^2
16 |
17 | - name: Run Linter
18 | run: |
19 | docker run --rm -v $PWD:/app composer sh -c \
20 | "composer install --profile --ignore-platform-reqs && composer lint"
21 |
--------------------------------------------------------------------------------
/.github/workflows/test.yml:
--------------------------------------------------------------------------------
1 | name: "Tests"
2 |
3 | on: [pull_request]
4 | jobs:
5 | tests:
6 | name: Unit & E2E
7 | runs-on: ubuntu-latest
8 |
9 | steps:
10 | - name: Checkout repository
11 | uses: actions/checkout@v4
12 | with:
13 | fetch-depth: 2
14 | - run: git checkout HEAD^2
15 | - name: Run Tests
16 | env:
17 | MAILGUN_API_KEY: ${{ secrets.MAILGUN_API_KEY }}
18 | MAILGUN_DOMAIN: ${{ secrets.MAILGUN_DOMAIN }}
19 | SENDGRID_API_KEY: ${{ secrets.SENDGRID_API_KEY }}
20 | FCM_SERVICE_ACCOUNT_JSON: ${{ secrets.FCM_SERVICE_ACCOUNT_JSON }}
21 | FCM_TO: ${{ secrets.FCM_TO }}
22 | TWILIO_ACCOUNT_SID: ${{ secrets.TWILIO_ACCOUNT_SID }}
23 | TWILIO_AUTH_TOKEN: ${{ secrets.TWILIO_AUTH_TOKEN }}
24 | TWILIO_TO: ${{ secrets.TWILIO_TO }}
25 | TWILIO_FROM: ${{ secrets.TWILIO_FROM }}
26 | TELNYX_API_KEY: ${{ secrets.TELNYX_API_KEY }}
27 | TELNYX_PUBLIC_KEY: ${{ secrets.TELNYX_PUBLIC_KEY }}
28 | APNS_AUTHKEY_8KVVCLA3HL: ${{ secrets.APNS_AUTHKEY_8KVVCLA3HL }}
29 | APNS_AUTH_ID: ${{ secrets.APNS_AUTH_ID }}
30 | APNS_TEAM_ID: ${{ secrets.APNS_TEAM_ID }}
31 | APNS_BUNDLE_ID: ${{ secrets.APNS_BUNDLE_ID }}
32 | APNS_TO: ${{ secrets.APNS_TO }}
33 | MSG_91_SENDER_ID: ${{ secrets.MSG_91_SENDER_ID }}
34 | MSG_91_AUTH_KEY: ${{ secrets.MSG_91_AUTH_KEY }}
35 | MSG_91_TO: ${{ secrets.MSG_91_TO }}
36 | MSG_91_FROM: ${{ secrets.MSG_91_FROM }}
37 | TEST_EMAIL: ${{ secrets.TEST_EMAIL }}
38 | TEST_FROM_EMAIL: ${{ secrets.TEST_FROM_EMAIL }}
39 | TEST_CC_EMAIL: ${{ secrets.TEST_CC_EMAIL }}
40 | TEST_BCC_EMAIL: ${{ secrets.TEST_BCC_EMAIL }}
41 | TEST_BCC_NAME: ${{ secrets.TEST_BCC_NAME }}
42 | VONAGE_API_KEY: ${{ secrets.VONAGE_API_KEY }}
43 | VONAGE_API_SECRET: ${{ secrets.VONAGE_API_SECRET }}
44 | VONAGE_TO: ${{ secrets.VONAGE_TO }}
45 | VONAGE_FROM: ${{ secrets.VONAGE_FROM }}
46 | DISCORD_WEBHOOK_URL: ${{ secrets.DISCORD_WEBHOOK_URL }}
47 | FAST2SMS_API_KEY: ${{ secrets.FAST2SMS_API_KEY }}
48 | FAST2SMS_SENDER_ID: ${{ secrets.FAST2SMS_SENDER_ID }}
49 | FAST2SMS_MESSAGE_ID: ${{ secrets.FAST2SMS_MESSAGE_ID }}
50 | FAST2SMS_TO: ${{ secrets.FAST2SMS_TO }}
51 | INFORU_API_TOKEN: ${{ secrets.INFORU_API_TOKEN }}
52 | INFORU_SENDER_ID: ${{ secrets.INFORU_SENDER_ID }}
53 | run: |
54 | docker compose up -d --build
55 | sleep 5
56 | docker compose exec tests vendor/bin/phpunit
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .idea
2 | vendor
3 | Makefile
4 | .envrc
5 | .env
6 | *.p8
7 |
8 | ### Linux ###
9 | *~
10 |
11 | # temporary files which can be created if a process still has a handle open of a deleted file
12 | .fuse_hidden*
13 |
14 | # KDE directory preferences
15 | .directory
16 |
17 | # Linux trash folder which might appear on any partition or disk
18 | .Trash-*
19 |
20 | # .nfs files are created when an open file is removed but is still being accessed
21 | .nfs*
22 |
23 | ### macOS ###
24 | # General
25 | .DS_Store
26 | .AppleDouble
27 | .LSOverride
28 |
29 | # Icon must end with two \r
30 | Icon
31 |
32 |
33 | # Thumbnails
34 | ._*
35 |
36 | # Files that might appear in the root of a volume
37 | .DocumentRevisions-V100
38 | .fseventsd
39 | .Spotlight-V100
40 | .TemporaryItems
41 | .Trashes
42 | .VolumeIcon.icns
43 | .com.apple.timemachine.donotpresent
44 |
45 | # Directories potentially created on remote AFP share
46 | .AppleDB
47 | .AppleDesktop
48 | Network Trash Folder
49 | Temporary Items
50 | .apdisk
51 |
52 | ### macOS Patch ###
53 | # iCloud generated files
54 | *.icloud
55 |
56 | ### PHPUnit ###
57 | # Covers PHPUnit
58 | # Reference: https://phpunit.de/
59 |
60 | # Generated files
61 | .phpunit.result.cache
62 | .phpunit.cache
63 |
64 | # PHPUnit
65 | /app/phpunit.xml
66 |
67 | # Build data
68 | /build/
69 |
70 | ### Windows ###
71 | # Windows thumbnail cache files
72 | Thumbs.db
73 | Thumbs.db:encryptable
74 | ehthumbs.db
75 | ehthumbs_vista.db
76 |
77 | # Dump file
78 | *.stackdump
79 |
80 | # Folder config file
81 | [Dd]esktop.ini
82 |
83 | # Recycle Bin used on file shares
84 | $RECYCLE.BIN/
85 |
86 | # Windows Installer files
87 | *.cab
88 | *.msi
89 | *.msix
90 | *.msm
91 | *.msp
92 |
93 | # Windows shortcuts
94 | *.lnk
95 |
96 | # End of https://www.toptal.com/developers/gitignore/api/macos,linux,windows,phpunit
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Contributor Covenant Code of Conduct
2 |
3 | ## Our Pledge
4 |
5 | In the interest of fostering an open and welcoming environment, we as
6 | contributors and maintainers pledge to make participation in our project and
7 | our community a harassment-free experience for everyone, regardless of age, body
8 | size, disability, ethnicity, sex characteristics, gender identity, expression,
9 | level of experience, education, socio-economic status, nationality, personal
10 | appearance, race, religion, or sexual identity and orientation.
11 |
12 | ## Our Standards
13 |
14 | Examples of behavior that contributes to creating a positive environment
15 | include:
16 |
17 | - Using welcoming and inclusive language
18 | - Being respectful of differing viewpoints and experiences
19 | - Gracefully accepting constructive criticism
20 | - Focusing on what is best for the community
21 | - Showing empathy towards other community members
22 |
23 | Examples of unacceptable behavior by participants include:
24 |
25 | - The use of sexualized language or imagery and unwelcome sexual attention or
26 | advances
27 | - Trolling, insulting/derogatory comments, and personal or political attacks
28 | - Public or private harassment
29 | - Publishing others' private information, such as a physical or electronic
30 | address, without explicit permission
31 | - Other conduct which could reasonably be considered inappropriate in a
32 | professional setting
33 |
34 | ## Our Responsibilities
35 |
36 | Project maintainers are responsible for clarifying the standards of acceptable
37 | behavior and are expected to take appropriate and fair corrective action in
38 | response to any instances of unacceptable behavior.
39 |
40 | Project maintainers have the right and responsibility to remove, edit, or
41 | reject comments, commits, code, wiki edits, issues, and other contributions
42 | that are not aligned to this Code of Conduct, or to ban temporarily or
43 | permanently any contributor for other behaviors that they deem inappropriate,
44 | threatening, offensive, or harmful.
45 |
46 | ## Scope
47 |
48 | This Code of Conduct applies both within project spaces and in public spaces
49 | when an individual is representing the project or its community. Examples of
50 | representing a project or community include using an official project e-mail
51 | address, posting via an official social media account, or acting as an appointed
52 | representative at an online or offline event. Representation of a project may be
53 | further defined and clarified by project maintainers.
54 |
55 | ## Enforcement
56 |
57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be
58 | reported by contacting the project team at team@appwrite.io. All
59 | complaints will be reviewed and investigated and will result in a response that
60 | is deemed necessary and appropriate to the circumstances. The project team is
61 | obligated to maintain confidentiality with regard to the reporter of an incident.
62 | Further details of specific enforcement policies may be posted separately.
63 |
64 | Project maintainers who do not follow or enforce the Code of Conduct in good
65 | faith may face temporary or permanent repercussions as determined by other
66 | members of the project's leadership.
67 |
68 | ## Attribution
69 |
70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
72 |
73 | [homepage]: https://www.contributor-covenant.org
74 |
75 | For answers to common questions about this code of conduct, see
76 | https://www.contributor-covenant.org/faq
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing
2 |
3 | We would ❤️ for you to contribute to Utopia-php and help make it better! We want contributing to Utopia-php to be fun, enjoyable, and educational for anyone and everyone. All contributions are welcome, including issues, new docs as well as updates and tweaks, blog posts, workshops, and more.
4 |
5 | ## How to Start?
6 |
7 | If you are worried or don’t know where to start, check out our next section explaining what kind of help we could use and where can you get involved. You can reach out with questions to [Eldad Fux (@eldadfux)](https://twitter.com/eldadfux) or anyone from the [Appwrite team on Discord](https://discord.gg/GSeTUeA). You can also submit an issue, and a maintainer can guide you!
8 |
9 | ## Code of Conduct
10 |
11 | Help us keep Utopia-php open and inclusive. Please read and follow our [Code of Conduct](/CODE_OF_CONDUCT.md).
12 |
13 | ## Submit a Pull Request 🚀
14 |
15 | Branch naming convention is as following
16 |
17 | `TYPE-ISSUE_ID-DESCRIPTION`
18 |
19 | example:
20 |
21 | ```
22 | doc-548-submit-a-pull-request-section-to-contribution-guide
23 | ```
24 |
25 | When `TYPE` can be:
26 |
27 | - **feat** - is a new feature
28 | - **doc** - documentation only changes
29 | - **cicd** - changes related to CI/CD system
30 | - **fix** - a bug fix
31 | - **refactor** - code change that neither fixes a bug nor adds a feature
32 |
33 | **All PRs must include a commit message with the changes description!**
34 |
35 | For the initial start, fork the project and use git clone command to download the repository to your computer. A standard procedure for working on an issue would be to:
36 |
37 | 1. `git pull`, before creating a new branch, pull the changes from upstream. Your master needs to be up to date.
38 |
39 | ```
40 | $ git pull
41 | ```
42 |
43 | 2. Create new branch from `master` like: `doc-548-submit-a-pull-request-section-to-contribution-guide`
44 |
45 | ```
46 | $ git checkout -b [name_of_your_new_branch]
47 | ```
48 |
49 | 3. Work - commit - repeat ( be sure to be in your branch )
50 |
51 | 4. Push changes to GitHub
52 |
53 | ```
54 | $ git push origin [name_of_your_new_branch]
55 | ```
56 |
57 | 5. Submit your changes for review
58 | If you go to your repository on GitHub, you'll see a `Compare & pull request` button. Click on that button.
59 | 6. Start a Pull Request
60 | Now submit the pull request and click on `Create pull request`.
61 | 7. Get a code review approval/reject
62 | 8. After approval, merge your PR
63 | 9. GitHub will automatically delete the branch after the merge is done. (they can still be restored).
64 |
65 | ## Introducing New Features
66 |
67 | We would 💖 you to contribute to Utopia-php, but we would also like to make sure Utopia-php is as great as possible and loyal to its vision and mission statement 🙏.
68 |
69 | For us to find the right balance, please open an issue explaining your ideas before introducing a new pull request.
70 |
71 | This will allow the Utopia-php community to have sufficient discussion about the new feature value and how it fits in the product roadmap and vision.
72 |
73 | This is also important for the Utopia-php lead developers to be able to give technical input and different emphasis regarding the feature design and architecture. Some bigger features might need to go through our [RFC process](https://github.com/appwrite/rfc).
74 |
75 | ## Other Ways to Help
76 |
77 | Pull requests are great, but there are many other areas where you can help Utopia-php.
78 |
79 | ### Blogging & Speaking
80 |
81 | Blogging, speaking about, or creating tutorials about one of Utopia-php’s many features is great way to contribute and help our project grow.
82 |
83 | ### Presenting at Meetups
84 |
85 | Presenting at meetups and conferences about your Utopia-php projects. Your unique challenges and successes in building things with Utopia-php can provide great speaking material. We’d love to review your talk abstract/CFP, so get in touch with us if you’d like some help!
86 |
87 | ### Sending Feedbacks & Reporting Bugs
88 |
89 | Sending feedback is a great way for us to understand your different use cases of Utopia-php better. If you had any issues, bugs, or want to share about your experience, feel free to do so on our GitHub issues page or at our [Discord channel](https://discord.gg/GSeTUeA).
90 |
91 | ### Submitting New Ideas
92 |
93 | If you think Utopia-php could use a new feature, please open an issue on our GitHub repository, stating as much information as you can think about your new idea and it's implications. We would also use this issue to gather more information, get more feedback from the community, and have a proper discussion about the new feature.
94 |
95 | ### Improving Documentation
96 |
97 | Submitting documentation updates, enhancements, designs, or bug fixes. Spelling or grammar fixes will be very much appreciated.
98 |
99 | ### Helping Someone
100 |
101 | Searching for Utopia-php, GitHub or StackOverflow and helping someone else who needs help. You can also help by teaching others how to contribute to Utopia-php's repo!
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM composer:2.0 AS composer
2 |
3 | ARG TESTING=false
4 | ENV TESTING=$TESTING
5 |
6 | WORKDIR /usr/local/src/
7 |
8 | COPY composer.lock /usr/local/src/
9 | COPY composer.json /usr/local/src/
10 |
11 | RUN composer install \
12 | --ignore-platform-reqs \
13 | --optimize-autoloader \
14 | --no-plugins \
15 | --no-scripts \
16 | --prefer-dist
17 |
18 | FROM php:8.3.11-cli-alpine3.20
19 |
20 | WORKDIR /usr/local/src/
21 |
22 | COPY --from=composer /usr/local/src/vendor /usr/local/src/vendor
23 | COPY . /usr/local/src/
24 |
25 | CMD [ "tail", "-f", "/dev/null" ]
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2021 utopia
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Utopia Messaging
2 |
3 | [](https://travis-ci.com/utopia-php/database)
4 | 
5 | [](https://appwrite.io/discord)
6 |
7 | Utopia Messaging library is simple and lite library for sending messages using multiple messaging adapters. This library is aiming to be as simple and easy to learn and use. This library is maintained by the [Appwrite team](https://appwrite.io).
8 |
9 | Although this library is part of the [Utopia Framework](https://github.com/utopia-php/framework) project it is dependency free, and can be used as standalone with any other PHP project or framework.
10 |
11 | ## Getting Started
12 |
13 | Install using composer:
14 | ```bash
15 | composer require utopia-php/messaging
16 | ```
17 |
18 | ## Email
19 |
20 | ```php
21 | Hello World'
31 | );
32 |
33 | $messaging = new Sendgrid('YOUR_API_KEY');
34 | $messaging->send($message);
35 |
36 | $messaging = new Mailgun('YOUR_API_KEY', 'YOUR_DOMAIN');
37 | $messaging->send($message);
38 | ```
39 |
40 | ## SMS
41 |
42 | ```php
43 | send($message);
56 |
57 | $messaging = new Telesign('YOUR_USERNAME', 'YOUR_PASSWORD');
58 | $messaging->send($message);
59 | ```
60 |
61 | ## Push
62 |
63 | ```php
64 | send($message);
76 | ```
77 |
78 | ## Adapters
79 |
80 | > Want to implement any of the missing adapters or have an idea for another? We would love to hear from you! Please check out our [contribution guide](./CONTRIBUTING.md) and [new adapter guide](./docs/add-new-adapter.md) for more information.
81 |
82 | ### Email
83 | - [x] [SendGrid](https://sendgrid.com/)
84 | - [x] [Mailgun](https://www.mailgun.com/)
85 | - [ ] [Mailjet](https://www.mailjet.com/)
86 | - [ ] [Mailchimp](https://www.mailchimp.com/)
87 | - [ ] [Postmark](https://postmarkapp.com/)
88 | - [ ] [SparkPost](https://www.sparkpost.com/)
89 | - [ ] [SendinBlue](https://www.sendinblue.com/)
90 | - [ ] [MailSlurp](https://www.mailslurp.com/)
91 | - [ ] [ElasticEmail](https://elasticemail.com/)
92 | - [ ] [SES](https://aws.amazon.com/ses/)
93 |
94 | ### SMS
95 | - [x] [Twilio](https://www.twilio.com/)
96 | - [x] [Twilio Notify](https://www.twilio.com/notify)
97 | - [x] [Telesign](https://www.telesign.com/)
98 | - [x] [Textmagic](https://www.textmagic.com/)
99 | - [x] [Msg91](https://msg91.com/)
100 | - [x] [Vonage](https://www.vonage.com/)
101 | - [x] [Plivo](https://www.plivo.com/)
102 | - [x] [Infobip](https://www.infobip.com/)
103 | - [x] [Clickatell](https://www.clickatell.com/)
104 | - [ ] [AfricasTalking](https://africastalking.com/)
105 | - [x] [Sinch](https://www.sinch.com/)
106 | - [x] [Seven](https://www.seven.io/)
107 | - [ ] [SmsGlobal](https://www.smsglobal.com/)
108 | - [x] [Inforu](https://www.inforu.co.il/)
109 |
110 | ### Push
111 | - [x] [FCM](https://firebase.google.com/docs/cloud-messaging)
112 | - [x] [APNS](https://developer.apple.com/documentation/usernotifications)
113 | - [ ] [OneSignal](https://onesignal.com/)
114 | - [ ] [Pusher](https://pusher.com/)
115 | - [ ] [WebPush](https://developer.mozilla.org/en-US/docs/Web/API/Push_API)
116 | - [ ] [UrbanAirship](https://www.urbanairship.com/)
117 | - [ ] [Pushwoosh](https://www.pushwoosh.com/)
118 | - [ ] [PushBullet](https://www.pushbullet.com/)
119 | - [ ] [Pushy](https://pushy.me/)
120 |
121 | ## System Requirements
122 |
123 | Utopia Messaging requires PHP 8.0 or later. We recommend using the latest PHP version whenever possible.
124 |
125 | ## Tests
126 |
127 | To run all unit tests, use the following Docker command:
128 |
129 | ```bash
130 | composer test
131 | ```
132 |
133 | To run static code analysis, use the following Psalm command:
134 |
135 | ```bash
136 | composer lint
137 | ```
138 |
139 | ## Copyright and license
140 |
141 | The MIT License (MIT) [http://www.opensource.org/licenses/mit-license.php](http://www.opensource.org/licenses/mit-license.php)
142 |
--------------------------------------------------------------------------------
/composer.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "utopia-php/messaging",
3 | "description": "A simple, light and advanced PHP messaging library",
4 | "type": "library",
5 | "keywords": ["php","messaging", "upf", "utopia", "utopia-php", "library"],
6 | "license": "MIT",
7 | "minimum-stability": "stable",
8 | "scripts": {
9 | "test": "./vendor/bin/phpunit",
10 | "lint": "./vendor/bin/pint --preset psr12 --test",
11 | "format": "./vendor/bin/pint --preset psr12",
12 | "analyse": "./vendor/bin/phpstan analyse --memory-limit=2G --level=6 src tests"
13 | },
14 | "autoload": {
15 | "psr-4": {
16 | "Utopia\\Messaging\\": "src/Utopia/Messaging"
17 | }
18 | },
19 | "autoload-dev": {
20 | "psr-4": {
21 | "Utopia\\Tests\\": "tests/Messaging"
22 | }
23 | },
24 | "require": {
25 | "php": ">=8.0.0",
26 | "ext-curl": "*",
27 | "ext-openssl": "*",
28 | "phpmailer/phpmailer": "6.9.1",
29 | "giggsey/libphonenumber-for-php-lite": "8.13.36"
30 | },
31 | "require-dev": {
32 | "phpunit/phpunit": "11.*",
33 | "laravel/pint": "1.*",
34 | "phpstan/phpstan": "1.*"
35 | },
36 | "config": {
37 | "platform": {
38 | "php": "8.3"
39 | }
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/docker-compose.yml:
--------------------------------------------------------------------------------
1 | services:
2 | tests:
3 | build:
4 | context: .
5 | volumes:
6 | - ./src:/usr/local/src/src
7 | - ./tests:/usr/local/src/tests
8 | - ./phpunit.xml:/usr/local/src/phpunit.xml
9 | environment:
10 | - MAILGUN_API_KEY
11 | - MAILGUN_DOMAIN
12 | - SENDGRID_API_KEY
13 | - FCM_SERVICE_ACCOUNT_JSON
14 | - FCM_TO
15 | - TWILIO_ACCOUNT_SID
16 | - TWILIO_AUTH_TOKEN
17 | - TWILIO_TO
18 | - TWILIO_FROM
19 | - TELNYX_API_KEY
20 | - TELNYX_PUBLIC_KEY
21 | - APNS_AUTHKEY_8KVVCLA3HL
22 | - APNS_AUTH_ID
23 | - APNS_TEAM_ID
24 | - APNS_BUNDLE_ID
25 | - APNS_TO
26 | - MSG_91_SENDER_ID
27 | - MSG_91_AUTH_KEY
28 | - MSG_91_TO
29 | - MSG_91_FROM
30 | - TEST_EMAIL
31 | - TEST_FROM_EMAIL
32 | - TEST_CC_EMAIL
33 | - TEST_BCC_EMAIL
34 | - TEST_BCC_NAME
35 | - VONAGE_API_KEY
36 | - VONAGE_API_SECRET
37 | - VONAGE_TO
38 | - VONAGE_FROM
39 | - DISCORD_WEBHOOK_URL
40 | - FAST2SMS_API_KEY
41 | - FAST2SMS_SENDER_ID
42 | - FAST2SMS_MESSAGE_ID
43 | - FAST2SMS_TO
44 | - INFORU_API_TOKEN
45 | - INFORU_SENDER_ID
46 |
47 | maildev:
48 | image: appwrite/mailcatcher:1.0.0
49 | ports:
50 | - '10000:1080'
51 |
52 | request-catcher:
53 | image: appwrite/requestcatcher:1.0.0
54 | ports:
55 | - '10001:5000'
--------------------------------------------------------------------------------
/docs/add-new-adapter.md:
--------------------------------------------------------------------------------
1 | # Adding A New Messaging Adapter
2 |
3 | This document is a part of Utopia PHP contributors guide. Before you continue reading this document make sure you have read the [Code of Conduct](../CODE_OF_CONDUCT.md) and the [Contribution Guide](../CONTRIBUTING.md).
4 |
5 | ## Getting Started
6 |
7 | Messaging adapter allow utilization of different messaging services in a consistent way. This document will guide you through the process of adding a new messaging adapter to the Utopia PHP Messaging library.
8 |
9 | ## 1. Prerequisites
10 |
11 | It's really easy to contribute to an open source project, but when using GitHub, there are a few steps we need to follow. This section will take you step-by-step through the process of preparing your own local version of `utopia-php/messaging`, where you can make any changes without affecting the upstream repository right away.
12 |
13 | > If you are experienced with GitHub or have made a pull request before, you can skip to [Implement A New Messaging Adapter](#2-implement-new-messaging-adapter).
14 |
15 | ### 1.1 Fork The Repository
16 |
17 | Before making any changes, you will need to fork the `utopia-php/messaging` repository to keep branches on the upstream repo clean. To do that, visit the [repository](https://github.com/utopia-php/messaging) and click the **Fork** button.
18 |
19 | This will redirect you from `github.com/utopia-php/messaging` to `github.com/YOUR_USERNAME/messaging`, meaning all further changes will reflect on your copy of the repository. Once you are there, click the highlighted `Code` button, copy the URL and clone the repository to your computer using either a Git UI or the `git clone` command:
20 |
21 | ```shell
22 | $ git clone COPIED_URL
23 | ```
24 |
25 | > To fork a repository, you will need the git-cli binaries installed and a basic understanding of CLI. If you are a beginner, we recommend you to use `Github Desktop`. It is a clean and simple visual Git client.
26 |
27 | Finally, you will need to create a `feat-XXX-YYY-messaging-adapter` branch based on the `master` branch and switch to it. The `XXX` should represent the issue ID and `YYY` the Storage adapter name.
28 |
29 | ## 2. Implement A New Messaging Adapter
30 |
31 | In order to start implementing a new messaging adapter, add new file inside `src/Utopia/Messaging/Adapters/XXX/YYY.php` where `XXX` is the type of adapter (**Email**, **SMS** or **Push**), and `YYY` is the name of the messaging provider in `PascalCase` casing. Inside the file you should create a class that extends the base `Email`, `SMS` or `Push` abstract adapter class.
32 |
33 | Inside the class, you need to implement four methods:
34 |
35 | - `__construct()` - This method should accept all the required parameters for the adapter to work. For example, the `SendGrid` adapter requires an API key, so the constructor should look like this:
36 |
37 | ```php
38 | public function __construct(private string $apiKey)
39 | ```
40 |
41 | - `getName()` - This method should return the display name of the adapter. For example, the `SendGrid` adapter should return `SendGrid`:
42 |
43 | ```php
44 | public function getName(): string
45 | {
46 | return 'SendGrid';
47 | }
48 | ```
49 |
50 | - `getMaxMessagesPerRequest()` - This method should return the maximum number of messages that can be sent in a single request. For example, `SendGrid` can send 1000 messages per request, so this method should return 1000:
51 |
52 | ```php
53 | public function getMaxMessagesPerRequest(): int
54 | {
55 | return 1000;
56 | }
57 | ```
58 |
59 | - `process()` - This method should accept a message object of the same type as the base adapter, and send it to the messaging provider, returning the response as a string. For example, the `SendGrid` adapter should accept an `Email` message object and send it to the SendGrid API:
60 |
61 | ```php
62 | public function process(Email $message): string
63 | {
64 | // Send message to SendGrid API
65 | }
66 | ```
67 |
68 | The base `Adapter` class includes a two helper functions called `request()` and `requestMulti()` that can be used to send HTTP requests to the messaging provider.
69 |
70 | The `request()` function will send a single request and accepts the following parameters:
71 |
72 | - `method` - The HTTP method to use. For example, `POST`, `GET`, `PUT`, `PATCH` or `DELETE`.
73 | - `url` - The URL to send the request to.
74 | - `headers` - An array of headers to send with the request.
75 | - `body` - The body of the request as a string, or null if no body is required.
76 | - `timeout` - The timeout in seconds for the request.
77 |
78 | The `requestMulti()` function will send multiple concurrent requests via HTTP/2 multiplexing, and accepts the following parameters:
79 |
80 | - `method` - The HTTP method to use. For example, `POST`, `GET`, `PUT`, `PATCH` or `DELETE`.
81 | - `urls` - An array of URLs to send the requests to.
82 | - `headers` - An array of headers to send with the requests.
83 | - `bodies` - An array of bodies of the requests as strings, or an empty array if no body is required.
84 | - `timeout` - The timeout in seconds for the requests.
85 |
86 | `urls` and `bodies` must either be the same length, or one of them must contain only a single element. If `urls` contains only a single element, it will be used for all requests. If `bodies` contains only a single element, it will be used for all requests.
87 |
88 | The default content type of the request is `x-www-form-urlencoded`, but you can change it by adding a `Content-Type` header. No encoding is applied to the body, so you need to make sure it is encoded properly before sending the request.
89 |
90 | Putting it all together, the `SendGrid` adapter should look like this:
91 |
92 | ### Full Example
93 |
94 | ```php
95 | request(
121 | method: 'POST',
122 | url: 'https://api.sendgrid.com/v3/mail/send',
123 | headers: [
124 | 'Content-Type: application/json',
125 | 'Authorization: Bearer ' . $this->apiKey,
126 | ],
127 | body: \json_encode([
128 | 'personalizations' => [
129 | [
130 | 'to' => \array_map(
131 | fn($to) => ['email' => $to],
132 | $message->getTo()
133 | ),
134 | 'subject' => $message->getSubject(),
135 | ],
136 | ],
137 | 'from' => [
138 | 'email' => $message->getFrom(),
139 | ],
140 | 'content' => [
141 | [
142 | 'type' => $message->isHtml() ? 'text/html' : 'text/plain',
143 | 'value' => $message->getContent(),
144 | ],
145 | ],
146 | ]),
147 | );
148 | }
149 | }
150 | ```
151 |
152 | ## 3. Test your adapter
153 |
154 | After you finish adding your new adapter, you need to ensure that it is usable. Use your newly created adapter to make some sample requests to your messaging service.
155 |
156 | If everything goes well, raise a pull request and be ready to respond to any feedback which can arise during code review.
157 |
158 | ## 4. Raise a pull request
159 |
160 | First of all, commit the changes with the message `Added YYY adapter` and push it. This will publish a new branch to your forked version of `utopia-php/messaging`. If you visit it at `github.com/YOUR_USERNAME/messaging`, you will see a new alert saying you are ready to submit a pull request. Follow the steps GitHub provides, and at the end, you will have your pull request submitted.
161 |
162 | ## 🤕 Stuck ?
163 | If you need any help with the contribution, feel free to head over to [our discord channel](https://appwrite.io/discord) and we'll be happy to help you out.
164 |
--------------------------------------------------------------------------------
/docs/sms-pricing.md:
--------------------------------------------------------------------------------
1 | # SMS Provider pricing
2 |
3 | ### In case you wonder which provider will suite you with best price
4 |
5 | - _The list includes only implemented providers_
6 | - _The list is sorted by unit price low -> high_
7 |
8 | ## SMS Target
9 |
10 | _You can add your country with a full pricing table._
11 |
12 | - [United States](#united-states)
13 | - [India](#india)
14 | - [Israel](#israel)
15 |
16 | ## United States
17 |
18 | _In most providers when you're sending SMS to US numbers you must own a US phone number to provide it in the `from` field. Other might add random phone number they have_
19 |
20 | | Provider | Unit Price | 10K |
21 | |------------|------------|-------|
22 | | Plivo | 0.0050 | 50 $ |
23 | | Telesign | 0.0062 | 62 $ |
24 | | Msg91 | 0.0067 | 67 $ |
25 | | Vonage | 0.0067 | 67 $ |
26 | | Infobip | 0.0070 | 70 $ |
27 | | Clickatell | 0.0075 | 75 $ |
28 | | Twilio | 0.0079 | 79 $ |
29 | | Sinch | 0.0120 | 120 $ |
30 | | Textmagic | 0.0400 | 400 $ |
31 | | Telnyx | 0.0440 | 440 $ |
32 | | Seven | 0.0810 | 810 $ |
33 |
34 | ## India
35 |
36 | | Provider | Unit Price | 10K |
37 | |------------|------------|-------|
38 | | Msg91 | 0.0030 | 30 $ |
39 | | Clickatell | 0.0426 | 426 $ |
40 | | Vonage | 0.0449 | 449 $ |
41 | | Telesign | 0.0485 | 485 $ |
42 | | Telnyx | 0.0490 | 490 $ |
43 | | Twilio | 0.0490 | 490 $ |
44 | | Plivo | 0.0560 | 560 $ |
45 | | Seven | 0.0810 | 810 $ |
46 | | Infobip | n/a | |
47 | | Sinch | n/a | |
48 | | Textmagic | n/a | |
49 |
50 | ## Israel
51 |
52 | | Provider | Unit Price | 10K |
53 | |------------|------------|----------|
54 | | Telesign | 0.0768 | 768 $ |
55 | | Seven | 0.0810 | 810 $ |
56 | | Msg91 | 0.0845 | 845 $ |
57 | | Plivo | 0.101 | 1010 $ |
58 | | Vonage | 0.1019 | 1019 $ |
59 | | Infobip | 0.106 | 1060 $ |
60 | | Telnyx | 0.1100 | 1100 $ |
61 | | Twilio | 0.112 | 1120 $ |
62 | | Clickatell | 0.13144 | 1314.4 $ |
63 | | Sinch | n/a | |
64 | | Textmagic | n/a | |
65 |
--------------------------------------------------------------------------------
/phpcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | ./src
5 | ./tests
6 |
7 |
8 |
9 | *
10 |
11 |
--------------------------------------------------------------------------------
/phpunit.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
11 | ./tests/
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/src/Utopia/Messaging/Adapter.php:
--------------------------------------------------------------------------------
1 | >
37 | * } | array>
41 | * }> GEOSMS adapter returns an array of results keyed by adapter name.
42 | *
43 | * @throws \Exception
44 | */
45 | public function send(Message $message): array
46 | {
47 | if (!\is_a($message, $this->getMessageType())) {
48 | throw new \Exception('Invalid message type.');
49 | }
50 | if (\method_exists($message, 'getTo') && \count($message->getTo()) > $this->getMaxMessagesPerRequest()) {
51 | throw new \Exception("{$this->getName()} can only send {$this->getMaxMessagesPerRequest()} messages per request.");
52 | }
53 | if (!\method_exists($this, 'process')) {
54 | throw new \Exception('Adapter does not implement process method.');
55 | }
56 |
57 | return $this->process($message);
58 | }
59 |
60 | /**
61 | * Send a single HTTP request.
62 | *
63 | * @param string $method The HTTP method to use.
64 | * @param string $url The URL to send the request to.
65 | * @param array $headers An array of headers to send with the request.
66 | * @param array|null $body The body of the request.
67 | * @param int $timeout The timeout in seconds.
68 | * @return array{
69 | * url: string,
70 | * statusCode: int,
71 | * response: array|string|null,
72 | * error: string|null
73 | * }
74 | *
75 | * @throws \Exception If the request fails.
76 | */
77 | protected function request(
78 | string $method,
79 | string $url,
80 | array $headers = [],
81 | array $body = null,
82 | int $timeout = 30
83 | ): array {
84 | $ch = \curl_init();
85 |
86 | foreach ($headers as $header) {
87 | if (\str_contains($header, 'application/json')) {
88 | $body = \json_encode($body);
89 | break;
90 | }
91 | if (\str_contains($header, 'application/x-www-form-urlencoded')) {
92 | $body = \http_build_query($body);
93 | break;
94 | }
95 | }
96 |
97 | if (!\is_null($body)) {
98 | \curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
99 |
100 | if (\is_string($body)) {
101 | $headers[] = 'Content-Length: '.\strlen($body);
102 | }
103 | }
104 |
105 | \curl_setopt_array($ch, [
106 | CURLOPT_CUSTOMREQUEST => $method,
107 | CURLOPT_URL => $url,
108 | CURLOPT_HTTPHEADER => $headers,
109 | CURLOPT_RETURNTRANSFER => true,
110 | CURLOPT_USERAGENT => "Appwrite {$this->getName()} Message Sender",
111 | CURLOPT_TIMEOUT => $timeout,
112 | ]);
113 |
114 | $response = \curl_exec($ch);
115 |
116 | \curl_close($ch);
117 |
118 | try {
119 | $response = \json_decode($response, true, flags: JSON_THROW_ON_ERROR);
120 | } catch (\JsonException) {
121 | // Ignore
122 | }
123 |
124 | return [
125 | 'url' => $url,
126 | 'statusCode' => \curl_getinfo($ch, CURLINFO_RESPONSE_CODE),
127 | 'response' => $response,
128 | 'error' => \curl_error($ch),
129 | ];
130 | }
131 |
132 | /**
133 | * Send multiple concurrent HTTP requests using HTTP/2 multiplexing.
134 | *
135 | * @param array $urls
136 | * @param array $headers
137 | * @param array> $bodies
138 | * @return array|null,
143 | * error: string|null
144 | * }>
145 | *
146 | * @throws Exception
147 | */
148 | protected function requestMulti(
149 | string $method,
150 | array $urls,
151 | array $headers = [],
152 | array $bodies = [],
153 | int $timeout = 30
154 | ): array {
155 | if (empty($urls)) {
156 | throw new \Exception('No URLs provided. Must provide at least one URL.');
157 | }
158 |
159 | foreach ($headers as $header) {
160 | if (\str_contains($header, 'application/json')) {
161 | foreach ($bodies as $i => $body) {
162 | $bodies[$i] = \json_encode($body);
163 | }
164 | break;
165 | }
166 | if (\str_contains($header, 'application/x-www-form-urlencoded')) {
167 | foreach ($bodies as $i => $body) {
168 | $bodies[$i] = \http_build_query($body);
169 | }
170 | break;
171 | }
172 | }
173 |
174 | $sh = \curl_share_init();
175 | $mh = \curl_multi_init();
176 | $ch = \curl_init();
177 |
178 | \curl_share_setopt($sh, CURLSHOPT_SHARE, CURL_LOCK_DATA_DNS);
179 | \curl_share_setopt($sh, CURLSHOPT_SHARE, CURL_LOCK_DATA_CONNECT);
180 |
181 | \curl_setopt_array($ch, [
182 | CURLOPT_SHARE => $sh,
183 | CURLOPT_CUSTOMREQUEST => $method,
184 | CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_2_0,
185 | CURLOPT_HTTPHEADER => $headers,
186 | CURLOPT_RETURNTRANSFER => true,
187 | CURLOPT_FORBID_REUSE => false,
188 | CURLOPT_FRESH_CONNECT => false,
189 | CURLOPT_TIMEOUT => $timeout,
190 | ]);
191 |
192 | $urlCount = \count($urls);
193 | $bodyCount = \count($bodies);
194 |
195 | if (!($urlCount == $bodyCount || $urlCount == 1 || $bodyCount == 1)) {
196 | throw new \Exception('URL and body counts must be equal or one must equal 1.');
197 | }
198 |
199 | if ($urlCount > $bodyCount) {
200 | $bodies = \array_pad($bodies, $urlCount, $bodies[0]);
201 | } elseif ($urlCount < $bodyCount) {
202 | $urls = \array_pad($urls, $bodyCount, $urls[0]);
203 | }
204 |
205 | for ($i = 0; $i < \count($urls); $i++) {
206 | if (!empty($bodies[$i])) {
207 | $headers[] = 'Content-Length: '.\strlen($bodies[$i]);
208 | }
209 |
210 | \curl_setopt($ch, CURLOPT_URL, $urls[$i]);
211 | \curl_setopt($ch, CURLOPT_POSTFIELDS, $bodies[$i]);
212 | \curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
213 | \curl_setopt($ch, CURLOPT_PRIVATE, $i);
214 | \curl_multi_add_handle($mh, \curl_copy_handle($ch));
215 | }
216 |
217 | $active = true;
218 | do {
219 | $status = \curl_multi_exec($mh, $active);
220 |
221 | if ($active) {
222 | \curl_multi_select($mh);
223 | }
224 | } while ($active && $status == CURLM_OK);
225 |
226 | $responses = [];
227 |
228 | // Check each handle's result
229 | while ($info = \curl_multi_info_read($mh)) {
230 | $ch = $info['handle'];
231 |
232 | $response = \curl_multi_getcontent($ch);
233 |
234 | try {
235 | $response = \json_decode($response, true, flags: JSON_THROW_ON_ERROR);
236 | } catch (\JsonException) {
237 | // Ignore
238 | }
239 |
240 | $responses[] = [
241 | 'index' => (int)\curl_getinfo($ch, CURLINFO_PRIVATE),
242 | 'url' => \curl_getinfo($ch, CURLINFO_EFFECTIVE_URL),
243 | 'statusCode' => \curl_getinfo($ch, CURLINFO_RESPONSE_CODE),
244 | 'response' => $response,
245 | 'error' => \curl_error($ch),
246 | ];
247 |
248 | \curl_multi_remove_handle($mh, $ch);
249 | \curl_close($ch);
250 | }
251 |
252 | \curl_multi_close($mh);
253 | \curl_share_close($sh);
254 |
255 | return $responses;
256 | }
257 |
258 |
259 | /**
260 | * @param string $phone
261 | * @return int|null
262 | * @throws Exception
263 | */
264 | public function getCountryCode(string $phone): ?int
265 | {
266 | if (empty($phone)) {
267 | throw new Exception('$phone cannot be empty.');
268 | }
269 |
270 | $helper = PhoneNumberUtil::getInstance();
271 |
272 | try {
273 | return $helper
274 | ->parse($phone)
275 | ->getCountryCode();
276 |
277 | } catch (\Throwable $th) {
278 | throw new Exception("Error parsing phone: " . $th->getMessage());
279 | }
280 | }
281 | }
282 |
--------------------------------------------------------------------------------
/src/Utopia/Messaging/Adapter/Chat/Discord.php:
--------------------------------------------------------------------------------
1 | = 2) {
43 | $webhookParts = explode('/', $parts[1]);
44 | $this->webhookId = $webhookParts[0];
45 | }
46 | if (empty($this->webhookId)) {
47 | throw new InvalidArgumentException('Discord webhook ID cannot be empty.');
48 | }
49 | }
50 |
51 | public function getName(): string
52 | {
53 | return static::NAME;
54 | }
55 |
56 | public function getType(): string
57 | {
58 | return static::TYPE;
59 | }
60 |
61 | public function getMessageType(): string
62 | {
63 | return static::MESSAGE_TYPE;
64 | }
65 |
66 | public function getMaxMessagesPerRequest(): int
67 | {
68 | return 1;
69 | }
70 |
71 | /**
72 | * @return array{deliveredTo: int, type: string, results: array>}
73 | *
74 | * @throws \Exception
75 | */
76 | protected function process(DiscordMessage $message): array
77 | {
78 | $query = [];
79 |
80 | if (!\is_null($message->getWait())) {
81 | $query['wait'] = $message->getWait();
82 | }
83 | if (!\is_null($message->getThreadId())) {
84 | $query['thread_id'] = $message->getThreadId();
85 | }
86 |
87 | $queryString = '';
88 | foreach ($query as $key => $value) {
89 | if (empty($queryString)) {
90 | $queryString .= '?';
91 | }
92 | $queryString .= $key.'='.$value;
93 | }
94 |
95 | $response = new Response($this->getType());
96 | $result = $this->request(
97 | method: 'POST',
98 | url: "{$this->webhookURL}{$queryString}",
99 | headers: [
100 | 'Content-Type: application/json',
101 | ],
102 | body: [
103 | 'content' => $message->getContent(),
104 | 'username' => $message->getUsername(),
105 | 'avatar_url' => $message->getAvatarUrl(),
106 | 'tts' => $message->getTTS(),
107 | 'embeds' => $message->getEmbeds(),
108 | 'allowed_mentions' => $message->getAllowedMentions(),
109 | 'components' => $message->getComponents(),
110 | 'attachments' => $message->getAttachments(),
111 | 'flags' => $message->getFlags(),
112 | 'thread_name' => $message->getThreadName(),
113 | ],
114 | );
115 |
116 | $statusCode = $result['statusCode'];
117 |
118 | if ($statusCode >= 200 && $statusCode < 300) {
119 | $response->setDeliveredTo(1);
120 | $response->addResult($this->webhookId);
121 | } elseif ($statusCode >= 400 && $statusCode < 500) {
122 | $response->addResult($this->webhookId, 'Bad Request.');
123 | } else {
124 | $response->addResult($this->webhookId, 'Unknown Error.');
125 | }
126 |
127 | return $response->toArray();
128 | }
129 | }
130 |
--------------------------------------------------------------------------------
/src/Utopia/Messaging/Adapter/Email.php:
--------------------------------------------------------------------------------
1 | >}
29 | *
30 | * @throws \Exception
31 | */
32 | abstract protected function process(EmailMessage $message): array;
33 | }
34 |
--------------------------------------------------------------------------------
/src/Utopia/Messaging/Adapter/Email/Mailgun.php:
--------------------------------------------------------------------------------
1 | isEU ? $euDomain : $usDomain;
53 |
54 | $body = [
55 | 'to' => \implode(',', $message->getTo()),
56 | 'from' => "{$message->getFromName()}<{$message->getFromEmail()}>",
57 | 'subject' => $message->getSubject(),
58 | 'text' => $message->isHtml() ? null : $message->getContent(),
59 | 'html' => $message->isHtml() ? $message->getContent() : null,
60 | 'h:Reply-To: '."{$message->getReplyToName()}<{$message->getReplyToEmail()}>",
61 | ];
62 |
63 | if (\count($message->getTo()) > 1) {
64 | $body['recipient-variables'] = json_encode(array_fill_keys($message->getTo(), []));
65 | }
66 |
67 | if (!\is_null($message->getCC())) {
68 | foreach ($message->getCC() as $cc) {
69 | if (!empty($cc['email'])) {
70 | $ccString = !empty($cc['name'])
71 | ? "{$cc['name']}<{$cc['email']}>"
72 | : $cc['email'];
73 |
74 | $body['cc'] = !empty($body['cc'])
75 | ? "{$body['cc']},{$ccString}"
76 | : $ccString;
77 | }
78 | }
79 | }
80 |
81 | if (!\is_null($message->getBCC())) {
82 | foreach ($message->getBCC() as $bcc) {
83 | if (!empty($bcc['email'])) {
84 | $bccString = !empty($bcc['name'])
85 | ? "{$bcc['name']}<{$bcc['email']}>"
86 | : $bcc['email'];
87 |
88 | $body['bcc'] = !empty($body['bcc'])
89 | ? "{$body['bcc']},{$bccString}"
90 | : $bccString;
91 | }
92 | }
93 | }
94 |
95 | $isMultipart = false;
96 |
97 | if (!\is_null($message->getAttachments())) {
98 | $size = 0;
99 |
100 | foreach ($message->getAttachments() as $attachment) {
101 | $size += \filesize($attachment->getPath());
102 | }
103 |
104 | if ($size > self::MAX_ATTACHMENT_BYTES) {
105 | throw new \Exception('Attachments size exceeds the maximum allowed size of ');
106 | }
107 |
108 | foreach ($message->getAttachments() as $index => $attachment) {
109 | $isMultipart = true;
110 |
111 | $body["attachment[$index]"] = \curl_file_create(
112 | $attachment->getPath(),
113 | $attachment->getType(),
114 | $attachment->getName(),
115 | );
116 | }
117 | }
118 |
119 | $response = new Response($this->getType());
120 |
121 | $headers = [
122 | 'Authorization: Basic ' . \base64_encode("api:$this->apiKey"),
123 | ];
124 |
125 | if ($isMultipart) {
126 | $headers[] = 'Content-Type: multipart/form-data';
127 | } else {
128 | $headers[] = 'Content-Type: application/x-www-form-urlencoded';
129 | }
130 |
131 | $result = $this->request(
132 | method: 'POST',
133 | url: "https://$domain/v3/$this->domain/messages",
134 | headers: $headers,
135 | body: $body,
136 | );
137 |
138 | $statusCode = $result['statusCode'];
139 |
140 | if ($statusCode >= 200 && $statusCode < 300) {
141 | $response->setDeliveredTo(\count($message->getTo()));
142 | foreach ($message->getTo() as $to) {
143 | $response->addResult($to);
144 | }
145 | } elseif ($statusCode >= 400 && $statusCode < 500) {
146 | foreach ($message->getTo() as $to) {
147 | if (\is_string($result['response'])) {
148 | $response->addResult($to, $result['response']);
149 | } elseif (isset($result['response']['message'])) {
150 | $response->addResult($to, $result['response']['message']);
151 | } else {
152 | $response->addResult($to, 'Unknown error');
153 | }
154 | }
155 | }
156 |
157 | return $response->toArray();
158 | }
159 | }
160 |
--------------------------------------------------------------------------------
/src/Utopia/Messaging/Adapter/Email/Mock.php:
--------------------------------------------------------------------------------
1 | getType());
31 | $mail = new PHPMailer();
32 | $mail->isSMTP();
33 | $mail->XMailer = 'Utopia Mailer';
34 | $mail->Host = 'maildev';
35 | $mail->Port = 1025;
36 | $mail->SMTPAuth = false;
37 | $mail->Username = '';
38 | $mail->Password = '';
39 | $mail->SMTPSecure = '';
40 | $mail->SMTPAutoTLS = false;
41 | $mail->CharSet = 'UTF-8';
42 | $mail->Subject = $message->getSubject();
43 | $mail->Body = $message->getContent();
44 | $mail->AltBody = \strip_tags($message->getContent());
45 | $mail->setFrom($message->getFromEmail(), $message->getFromName());
46 | $mail->addReplyTo($message->getReplyToEmail(), $message->getReplyToName());
47 | $mail->isHTML($message->isHtml());
48 |
49 | foreach ($message->getTo() as $to) {
50 | $mail->addAddress($to);
51 | }
52 |
53 | if (!empty($message->getCC())) {
54 | foreach ($message->getCC() as $cc) {
55 | $mail->addCC($cc['email'], $cc['name'] ?? '');
56 | }
57 | }
58 |
59 | if (!empty($message->getBCC())) {
60 | foreach ($message->getBCC() as $bcc) {
61 | $mail->addBCC($bcc['email'], $bcc['name'] ?? '');
62 | }
63 | }
64 |
65 | if (!$mail->send()) {
66 | foreach ($message->getTo() as $to) {
67 | $response->addResult($to, $mail->ErrorInfo);
68 | }
69 | } else {
70 | $response->setDeliveredTo(\count($message->getTo()));
71 | foreach ($message->getTo() as $to) {
72 | $response->addResult($to);
73 | }
74 | }
75 |
76 | return $response->toArray();
77 | }
78 | }
79 |
--------------------------------------------------------------------------------
/src/Utopia/Messaging/Adapter/Email/SMTP.php:
--------------------------------------------------------------------------------
1 | smtpSecure, ['', 'ssl', 'tls'])) {
33 | throw new \InvalidArgumentException('Invalid SMTP secure prefix. Must be "", "ssl" or "tls"');
34 | }
35 | }
36 |
37 | public function getName(): string
38 | {
39 | return static::NAME;
40 | }
41 |
42 | public function getMaxMessagesPerRequest(): int
43 | {
44 | return 1000;
45 | }
46 |
47 | /**
48 | * {@inheritdoc}
49 | */
50 | protected function process(EmailMessage $message): array
51 | {
52 | $response = new Response($this->getType());
53 | $mail = new PHPMailer();
54 | $mail->isSMTP();
55 | $mail->XMailer = $this->xMailer;
56 | $mail->Host = $this->host;
57 | $mail->Port = $this->port;
58 | $mail->SMTPAuth = !empty($this->username) && !empty($this->password);
59 | $mail->Username = $this->username;
60 | $mail->Password = $this->password;
61 | $mail->SMTPSecure = $this->smtpSecure;
62 | $mail->SMTPAutoTLS = $this->smtpAutoTLS;
63 | $mail->CharSet = 'UTF-8';
64 | $mail->Subject = $message->getSubject();
65 | $mail->Body = $message->getContent();
66 | $mail->setFrom($message->getFromEmail(), $message->getFromName());
67 | $mail->addReplyTo($message->getReplyToEmail(), $message->getReplyToName());
68 | $mail->isHTML($message->isHtml());
69 |
70 | // Strip tags misses style tags, so we use regex to remove them
71 | $mail->AltBody = \preg_replace('/