repo stringlengths 7 63 | file_url stringlengths 81 284 | file_path stringlengths 5 200 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:02:33 2026-01-05 05:24:06 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
josuapsianturi/velflix | https://github.com/josuapsianturi/velflix/blob/057684c58e627783f1aa8247fb394d3a8b533d36/config/filesystems.php | config/filesystems.php | <?php
return [
/*
|--------------------------------------------------------------------------
| Default Filesystem Disk
|--------------------------------------------------------------------------
|
| Here you may specify the default filesystem disk that should be used
| by the framework. The "local" disk, as well as a variety of cloud
| based disks are available to your application. Just store away!
|
*/
'default' => env('FILESYSTEM_DRIVER', 'local'),
/*
|--------------------------------------------------------------------------
| Filesystem Disks
|--------------------------------------------------------------------------
|
| Here you may configure as many filesystem "disks" as you wish, and you
| may even configure multiple disks of the same driver. Defaults have
| been setup for each driver as an example of the required options.
|
| Supported Drivers: "local", "ftp", "sftp", "s3"
|
*/
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
],
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => env('APP_URL').'/storage',
'visibility' => 'public',
],
's3' => [
'driver' => 's3',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION'),
'bucket' => env('AWS_BUCKET'),
'url' => env('AWS_URL'),
'endpoint' => env('AWS_ENDPOINT'),
],
],
/*
|--------------------------------------------------------------------------
| Symbolic Links
|--------------------------------------------------------------------------
|
| Here you may configure the symbolic links that will be created when the
| `storage:link` Artisan command is executed. The array keys should be
| the locations of the links and the values should be their targets.
|
*/
'links' => [
public_path('storage') => storage_path('app/public'),
],
];
| php | MIT | 057684c58e627783f1aa8247fb394d3a8b533d36 | 2026-01-05T05:17:21.315532Z | false |
josuapsianturi/velflix | https://github.com/josuapsianturi/velflix/blob/057684c58e627783f1aa8247fb394d3a8b533d36/config/mail.php | config/mail.php | <?php
return [
/*
|--------------------------------------------------------------------------
| Default Mailer
|--------------------------------------------------------------------------
|
| This option controls the default mailer that is used to send any email
| messages sent by your application. Alternative mailers may be setup
| and used as needed; however, this mailer will be used by default.
|
*/
'default' => env('MAIL_MAILER', 'smtp'),
/*
|--------------------------------------------------------------------------
| Mailer Configurations
|--------------------------------------------------------------------------
|
| Here you may configure all of the mailers used by your application plus
| their respective settings. Several examples have been configured for
| you and you are free to add your own as your application requires.
|
| Laravel supports a variety of mail "transport" drivers to be used while
| sending an e-mail. You will specify which one you are using for your
| mailers below. You are free to add additional mailers as required.
|
| Supported: "smtp", "sendmail", "mailgun", "ses",
| "postmark", "log", "array"
|
*/
'mailers' => [
'smtp' => [
'transport' => 'smtp',
'host' => env('MAIL_HOST', 'smtp.mailgun.org'),
'port' => env('MAIL_PORT', 587),
'encryption' => env('MAIL_ENCRYPTION', 'tls'),
'username' => env('MAIL_USERNAME'),
'password' => env('MAIL_PASSWORD'),
'timeout' => null,
'auth_mode' => null,
],
'ses' => [
'transport' => 'ses',
],
'mailgun' => [
'transport' => 'mailgun',
],
'postmark' => [
'transport' => 'postmark',
],
'sendmail' => [
'transport' => 'sendmail',
'path' => '/usr/sbin/sendmail -bs',
],
'log' => [
'transport' => 'log',
'channel' => env('MAIL_LOG_CHANNEL'),
],
'array' => [
'transport' => 'array',
],
],
/*
|--------------------------------------------------------------------------
| Global "From" Address
|--------------------------------------------------------------------------
|
| You may wish for all e-mails sent by your application to be sent from
| the same address. Here, you may specify a name and address that is
| used globally for all e-mails that are sent by your application.
|
*/
'from' => [
'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'),
'name' => env('MAIL_FROM_NAME', 'Example'),
],
/*
|--------------------------------------------------------------------------
| Markdown Mail Settings
|--------------------------------------------------------------------------
|
| If you are using Markdown based email rendering, you may configure your
| theme and component paths here, allowing you to customize the design
| of the emails. Or, you may simply stick with the Laravel defaults!
|
*/
'markdown' => [
'theme' => 'default',
'paths' => [
resource_path('views/vendor/mail'),
],
],
];
| php | MIT | 057684c58e627783f1aa8247fb394d3a8b533d36 | 2026-01-05T05:17:21.315532Z | false |
josuapsianturi/velflix | https://github.com/josuapsianturi/velflix/blob/057684c58e627783f1aa8247fb394d3a8b533d36/config/cors.php | config/cors.php | <?php
return [
/*
|--------------------------------------------------------------------------
| Cross-Origin Resource Sharing (CORS) Configuration
|--------------------------------------------------------------------------
|
| Here you may configure your settings for cross-origin resource sharing
| or "CORS". This determines what cross-origin operations may execute
| in web browsers. You are free to adjust these settings as needed.
|
| To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
|
*/
'paths' => ['api/*', 'sanctum/csrf-cookie'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => false,
];
| php | MIT | 057684c58e627783f1aa8247fb394d3a8b533d36 | 2026-01-05T05:17:21.315532Z | false |
josuapsianturi/velflix | https://github.com/josuapsianturi/velflix/blob/057684c58e627783f1aa8247fb394d3a8b533d36/config/broadcasting.php | config/broadcasting.php | <?php
return [
/*
|--------------------------------------------------------------------------
| Default Broadcaster
|--------------------------------------------------------------------------
|
| This option controls the default broadcaster that will be used by the
| framework when an event needs to be broadcast. You may set this to
| any of the connections defined in the "connections" array below.
|
| Supported: "pusher", "ably", "redis", "log", "null"
|
*/
'default' => env('BROADCAST_DRIVER', 'null'),
/*
|--------------------------------------------------------------------------
| Broadcast Connections
|--------------------------------------------------------------------------
|
| Here you may define all of the broadcast connections that will be used
| to broadcast events to other systems or over websockets. Samples of
| each available type of connection are provided inside this array.
|
*/
'connections' => [
'pusher' => [
'driver' => 'pusher',
'key' => env('PUSHER_APP_KEY'),
'secret' => env('PUSHER_APP_SECRET'),
'app_id' => env('PUSHER_APP_ID'),
'options' => [
'cluster' => env('PUSHER_APP_CLUSTER'),
'useTLS' => true,
],
],
'ably' => [
'driver' => 'ably',
'key' => env('ABLY_KEY'),
],
'redis' => [
'driver' => 'redis',
'connection' => 'default',
],
'log' => [
'driver' => 'log',
],
'null' => [
'driver' => 'null',
],
],
];
| php | MIT | 057684c58e627783f1aa8247fb394d3a8b533d36 | 2026-01-05T05:17:21.315532Z | false |
josuapsianturi/velflix | https://github.com/josuapsianturi/velflix/blob/057684c58e627783f1aa8247fb394d3a8b533d36/config/auth.php | config/auth.php | <?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option controls the default authentication "guard" and password
| reset options for your application. You may change these defaults
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| here which uses session storage and the Eloquent user provider.
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| Supported: "session", "token"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| If you have multiple user tables or models you may configure multiple
| sources which represent each model / table. These sources may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| You may specify multiple password reset configurations if you have more
| than one user table or model in the application and you want to have
| separate password reset settings based on the specific user types.
|
| The expire time is the number of minutes that the reset token should be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
*/
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
],
/*
|--------------------------------------------------------------------------
| Password Confirmation Timeout
|--------------------------------------------------------------------------
|
| Here you may define the amount of seconds before a password confirmation
| times out and the user is prompted to re-enter their password via the
| confirmation screen. By default, the timeout lasts for three hours.
|
*/
'password_timeout' => 10800,
];
| php | MIT | 057684c58e627783f1aa8247fb394d3a8b533d36 | 2026-01-05T05:17:21.315532Z | false |
josuapsianturi/velflix | https://github.com/josuapsianturi/velflix/blob/057684c58e627783f1aa8247fb394d3a8b533d36/database/factories/UserFactory.php | database/factories/UserFactory.php | <?php
namespace Database\Factories;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
/**
* @psalm-suppress MissingTemplateParam
*/
class UserFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = User::class;
/**
* Define the model's default state.
*
* @return array
*/
public function definition()
{
return [
'name' => $this->faker->name,
'email' => $this->faker->unique()->safeEmail,
'email_verified_at' => now(),
'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
'remember_token' => Str::random(10),
];
}
/**
* Indicate that the model's email address should be unverified.
*
* @return \Illuminate\Database\Eloquent\Factories\Factory
*/
public function unverified()
{
return $this->state(function (array $attributes) {
return [
'email_verified_at' => null,
];
});
}
}
| php | MIT | 057684c58e627783f1aa8247fb394d3a8b533d36 | 2026-01-05T05:17:21.315532Z | false |
josuapsianturi/velflix | https://github.com/josuapsianturi/velflix/blob/057684c58e627783f1aa8247fb394d3a8b533d36/database/migrations/2014_10_12_000000_create_users_table.php | database/migrations/2014_10_12_000000_create_users_table.php | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('username')->unique()->nullable();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password')->nullable();
$table->rememberToken();
$table->string('provider_id')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
| php | MIT | 057684c58e627783f1aa8247fb394d3a8b533d36 | 2026-01-05T05:17:21.315532Z | false |
josuapsianturi/velflix | https://github.com/josuapsianturi/velflix/blob/057684c58e627783f1aa8247fb394d3a8b533d36/database/migrations/2014_10_12_100000_create_password_resets_table.php | database/migrations/2014_10_12_100000_create_password_resets_table.php | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePasswordResetsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('password_resets', function (Blueprint $table) {
$table->string('email')->index();
$table->string('token');
$table->timestamp('created_at')->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('password_resets');
}
}
| php | MIT | 057684c58e627783f1aa8247fb394d3a8b533d36 | 2026-01-05T05:17:21.315532Z | false |
josuapsianturi/velflix | https://github.com/josuapsianturi/velflix/blob/057684c58e627783f1aa8247fb394d3a8b533d36/database/migrations/2019_08_19_000000_create_failed_jobs_table.php | database/migrations/2019_08_19_000000_create_failed_jobs_table.php | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateFailedJobsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('failed_jobs', function (Blueprint $table) {
$table->id();
$table->string('uuid')->unique();
$table->text('connection');
$table->text('queue');
$table->longText('payload');
$table->longText('exception');
$table->timestamp('failed_at')->useCurrent();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('failed_jobs');
}
}
| php | MIT | 057684c58e627783f1aa8247fb394d3a8b533d36 | 2026-01-05T05:17:21.315532Z | false |
josuapsianturi/velflix | https://github.com/josuapsianturi/velflix/blob/057684c58e627783f1aa8247fb394d3a8b533d36/database/seeders/DatabaseSeeder.php | database/seeders/DatabaseSeeder.php | <?php
namespace Database\Seeders;
use App\Models\User;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* @return void
*/
public function run()
{
// to remove all the data from users table
User::truncate();
// create a user
DB::table('users')->insert([
'name' => 'user',
'username' => 'user',
'email' => 'user@gmail.com',
'password' => Hash::make('password'), // password
]);
// create admin user
DB::table('users')->insert([
'name' => 'admin',
'username' => 'admin',
'email' => 'admin@gmail.com',
'password' => Hash::make('password'),
]);
}
}
| php | MIT | 057684c58e627783f1aa8247fb394d3a8b533d36 | 2026-01-05T05:17:21.315532Z | false |
josuapsianturi/velflix | https://github.com/josuapsianturi/velflix/blob/057684c58e627783f1aa8247fb394d3a8b533d36/resources/lang/en/passwords.php | resources/lang/en/passwords.php | <?php
return [
/*
|--------------------------------------------------------------------------
| Password Reset Language Lines
|--------------------------------------------------------------------------
|
| The following language lines are the default lines which match reasons
| that are given by the password broker for a password update attempt
| has failed, such as for an invalid token or invalid new password.
|
*/
'reset' => 'Your password has been reset!',
'sent' => 'We have emailed your password reset link!',
'throttled' => 'Please wait before retrying.',
'token' => 'This password reset token is invalid.',
'user' => "We can't find a user with that email address.",
];
| php | MIT | 057684c58e627783f1aa8247fb394d3a8b533d36 | 2026-01-05T05:17:21.315532Z | false |
josuapsianturi/velflix | https://github.com/josuapsianturi/velflix/blob/057684c58e627783f1aa8247fb394d3a8b533d36/resources/lang/en/pagination.php | resources/lang/en/pagination.php | <?php
return [
/*
|--------------------------------------------------------------------------
| Pagination Language Lines
|--------------------------------------------------------------------------
|
| The following language lines are used by the paginator library to build
| the simple pagination links. You are free to change them to anything
| you want to customize your views to better match your application.
|
*/
'previous' => '« Previous',
'next' => 'Next »',
];
| php | MIT | 057684c58e627783f1aa8247fb394d3a8b533d36 | 2026-01-05T05:17:21.315532Z | false |
josuapsianturi/velflix | https://github.com/josuapsianturi/velflix/blob/057684c58e627783f1aa8247fb394d3a8b533d36/resources/lang/en/validation.php | resources/lang/en/validation.php | <?php
return [
/*
|--------------------------------------------------------------------------
| Validation Language Lines
|--------------------------------------------------------------------------
|
| The following language lines contain the default error messages used by
| the validator class. Some of these rules have multiple versions such
| as the size rules. Feel free to tweak each of these messages here.
|
*/
'accepted' => 'The :attribute must be accepted.',
'active_url' => 'The :attribute is not a valid URL.',
'after' => 'The :attribute must be a date after :date.',
'after_or_equal' => 'The :attribute must be a date after or equal to :date.',
'alpha' => 'The :attribute must only contain letters.',
'alpha_dash' => 'The :attribute must only contain letters, numbers, dashes and underscores.',
'alpha_num' => 'The :attribute must only contain letters and numbers.',
'array' => 'The :attribute must be an array.',
'before' => 'The :attribute must be a date before :date.',
'before_or_equal' => 'The :attribute must be a date before or equal to :date.',
'between' => [
'numeric' => 'The :attribute must be between :min and :max.',
'file' => 'The :attribute must be between :min and :max kilobytes.',
'string' => 'The :attribute must be between :min and :max characters.',
'array' => 'The :attribute must have between :min and :max items.',
],
'boolean' => 'The :attribute field must be true or false.',
'confirmed' => 'The :attribute confirmation does not match.',
'date' => 'The :attribute is not a valid date.',
'date_equals' => 'The :attribute must be a date equal to :date.',
'date_format' => 'The :attribute does not match the format :format.',
'different' => 'The :attribute and :other must be different.',
'digits' => 'The :attribute must be :digits digits.',
'digits_between' => 'The :attribute must be between :min and :max digits.',
'dimensions' => 'The :attribute has invalid image dimensions.',
'distinct' => 'The :attribute field has a duplicate value.',
'email' => 'The :attribute must be a valid email address.',
'ends_with' => 'The :attribute must end with one of the following: :values.',
'exists' => 'The selected :attribute is invalid.',
'file' => 'The :attribute must be a file.',
'filled' => 'The :attribute field must have a value.',
'gt' => [
'numeric' => 'The :attribute must be greater than :value.',
'file' => 'The :attribute must be greater than :value kilobytes.',
'string' => 'The :attribute must be greater than :value characters.',
'array' => 'The :attribute must have more than :value items.',
],
'gte' => [
'numeric' => 'The :attribute must be greater than or equal :value.',
'file' => 'The :attribute must be greater than or equal :value kilobytes.',
'string' => 'The :attribute must be greater than or equal :value characters.',
'array' => 'The :attribute must have :value items or more.',
],
'image' => 'The :attribute must be an image.',
'in' => 'The selected :attribute is invalid.',
'in_array' => 'The :attribute field does not exist in :other.',
'integer' => 'The :attribute must be an integer.',
'ip' => 'The :attribute must be a valid IP address.',
'ipv4' => 'The :attribute must be a valid IPv4 address.',
'ipv6' => 'The :attribute must be a valid IPv6 address.',
'json' => 'The :attribute must be a valid JSON string.',
'lt' => [
'numeric' => 'The :attribute must be less than :value.',
'file' => 'The :attribute must be less than :value kilobytes.',
'string' => 'The :attribute must be less than :value characters.',
'array' => 'The :attribute must have less than :value items.',
],
'lte' => [
'numeric' => 'The :attribute must be less than or equal :value.',
'file' => 'The :attribute must be less than or equal :value kilobytes.',
'string' => 'The :attribute must be less than or equal :value characters.',
'array' => 'The :attribute must not have more than :value items.',
],
'max' => [
'numeric' => 'The :attribute must not be greater than :max.',
'file' => 'The :attribute must not be greater than :max kilobytes.',
'string' => 'The :attribute must not be greater than :max characters.',
'array' => 'The :attribute must not have more than :max items.',
],
'mimes' => 'The :attribute must be a file of type: :values.',
'mimetypes' => 'The :attribute must be a file of type: :values.',
'min' => [
'numeric' => 'The :attribute must be at least :min.',
'file' => 'The :attribute must be at least :min kilobytes.',
'string' => 'The :attribute must be at least :min characters.',
'array' => 'The :attribute must have at least :min items.',
],
'multiple_of' => 'The :attribute must be a multiple of :value.',
'not_in' => 'The selected :attribute is invalid.',
'not_regex' => 'The :attribute format is invalid.',
'numeric' => 'The :attribute must be a number.',
'password' => 'The password is incorrect.',
'present' => 'The :attribute field must be present.',
'regex' => 'The :attribute format is invalid.',
'required' => 'The :attribute field is required.',
'required_if' => 'The :attribute field is required when :other is :value.',
'required_unless' => 'The :attribute field is required unless :other is in :values.',
'required_with' => 'The :attribute field is required when :values is present.',
'required_with_all' => 'The :attribute field is required when :values are present.',
'required_without' => 'The :attribute field is required when :values is not present.',
'required_without_all' => 'The :attribute field is required when none of :values are present.',
'prohibited' => 'The :attribute field is prohibited.',
'prohibited_if' => 'The :attribute field is prohibited when :other is :value.',
'prohibited_unless' => 'The :attribute field is prohibited unless :other is in :values.',
'same' => 'The :attribute and :other must match.',
'size' => [
'numeric' => 'The :attribute must be :size.',
'file' => 'The :attribute must be :size kilobytes.',
'string' => 'The :attribute must be :size characters.',
'array' => 'The :attribute must contain :size items.',
],
'starts_with' => 'The :attribute must start with one of the following: :values.',
'string' => 'The :attribute must be a string.',
'timezone' => 'The :attribute must be a valid zone.',
'unique' => 'The :attribute has already been taken.',
'uploaded' => 'The :attribute failed to upload.',
'url' => 'The :attribute format is invalid.',
'uuid' => 'The :attribute must be a valid UUID.',
/*
|--------------------------------------------------------------------------
| Custom Validation Language Lines
|--------------------------------------------------------------------------
|
| Here you may specify custom validation messages for attributes using the
| convention "attribute.rule" to name the lines. This makes it quick to
| specify a specific custom language line for a given attribute rule.
|
*/
'custom' => [
'attribute-name' => [
'rule-name' => 'custom-message',
],
],
/*
|--------------------------------------------------------------------------
| Custom Validation Attributes
|--------------------------------------------------------------------------
|
| The following language lines are used to swap our attribute placeholder
| with something more reader friendly such as "E-Mail Address" instead
| of "email". This simply helps us make our message more expressive.
|
*/
'attributes' => [],
];
| php | MIT | 057684c58e627783f1aa8247fb394d3a8b533d36 | 2026-01-05T05:17:21.315532Z | false |
josuapsianturi/velflix | https://github.com/josuapsianturi/velflix/blob/057684c58e627783f1aa8247fb394d3a8b533d36/resources/lang/en/auth.php | resources/lang/en/auth.php | <?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Language Lines
|--------------------------------------------------------------------------
|
| The following language lines are used during authentication for various
| messages that we need to display to the user. You are free to modify
| these language lines according to your application's requirements.
|
*/
'failed' => 'These credentials do not match our records.',
'password' => 'The provided password is incorrect.',
'throttle' => 'Too many login attempts. Please try again in :seconds seconds.',
];
| php | MIT | 057684c58e627783f1aa8247fb394d3a8b533d36 | 2026-01-05T05:17:21.315532Z | false |
josuapsianturi/velflix | https://github.com/josuapsianturi/velflix/blob/057684c58e627783f1aa8247fb394d3a8b533d36/resources/views/main.blade.php | resources/views/main.blade.php | <x-layout>
<x-header />
<x-nav :popular='$popular' />
<x-movies.index :popular='$popular' :genres='$genres' :trending='$trending' :comedies='$comedies' :action='$action' :western='$western' :horror='$horror' :thriller='$thriller' :animation='$animation' />
<x-footer />
</x-layout>
| php | MIT | 057684c58e627783f1aa8247fb394d3a8b533d36 | 2026-01-05T05:17:21.315532Z | false |
josuapsianturi/velflix | https://github.com/josuapsianturi/velflix/blob/057684c58e627783f1aa8247fb394d3a8b533d36/resources/views/home.blade.php | resources/views/home.blade.php | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Velflix</title>
<!-- Tailwind CDN -->
{{-- <script src="https://cdn.tailwindcss.com"></script> --}}
@vite('resources/css/app.css')
<!-- Alpine Plugins -->
<script defer src="https://unpkg.com/@alpinejs/collapse@3.x.x/dist/cdn.min.js"></script>
<!-- Alpine CDN -->
<script src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js" defer></script>
</head>
<style>
[x-cloak] { display: none !important; }
</style>
<body class="bg-black text-gray-100">
<x-header />
<nav class="mt-16">
<x-navbar />
</nav>
<x-gap />
<section>
<div class="full flex justify-center p-12">
<div class="flex w-3/5 flex-col items-center justify-center">
<div>
<div class="text-4xl">Enjoy on your TV.</div>
<div class="text-2xl">
watch on Smart TV, Playstation, Xbox, Chromecast, Apple TV, Blu-ray players, and more.
</div>
</div>
</div>
<img width="600" src="{{ asset('img/img1.png') }}" />
</div>
</section>
<x-gap />
<section>
<div class="full flex justify-center p-12">
<img width="600" src="{{ asset('img/img2.png') }}" />
<div class="flex w-3/5 flex-col items-center justify-center">
<div>
<div class="text-4xl">Download your shows to watch offline.</div>
<div class="text-2xl">
Save your favorites easily and always have something to watch. </div>
</div>
</div>
</div>
</section>
<x-gap />
<section>
<div class="full flex justify-center p-12">
<div class="flex w-3/5 flex-col items-center justify-center">
<div>
<div class="text-4xl">Watch everywhere.</div>
<div class="text-2xl">
Stream unlimited movies and TV shows on your phone, tablet, laptop, and TV. </div>
</div>
</div>
<img width="600" src="{{ asset('img/img3.png') }}" />
</section>
<x-gap />
<!-- FAQ -->
<section>
<x-faq />
</section>
<!-- End FAQ -->
<section class="z-30 flex flex-col items-center justify-center py-40 text-gray-100 lg:py-32">
<x-newsletter />
</section>
<x-gap />
<x-footer />
<x-flash />
</body>
</html>
| php | MIT | 057684c58e627783f1aa8247fb394d3a8b533d36 | 2026-01-05T05:17:21.315532Z | false |
josuapsianturi/velflix | https://github.com/josuapsianturi/velflix/blob/057684c58e627783f1aa8247fb394d3a8b533d36/resources/views/auth/login.blade.php | resources/views/auth/login.blade.php | <x-layout>
<section class="px-6 py-8">
<main class="mx-auto mt-10 max-w-lg rounded-xl border border-gray-200 bg-gray-100 p-6">
<h1 class="text-center text-xl font-bold">Log In</h1>
<form method="post" action="/login" class="mt-10">
@csrf
<!-- Email -->
<div class="mb-6">
<label for="email" class="mb-2 block text-xs font-bold uppercase text-gray-700">
Email
</label>
<input class="w-full border border-gray-400 p-2"
type="email"
name="email"
id="email"
value="{{ old('email') }}"
required
>
@error('email')
<p class="mt-2 text-xs text-red-500">{{ $message }}</p>
@enderror
</div>
<!-- Password -->
<div class="mb-6">
<label for="password" class="mb-2 block text-xs font-bold uppercase text-gray-700">
Password
</label>
<input class="w-full border border-gray-400 p-2"
type="password"
name="password"
id="password"
required
>
@error('password')
<p class="mt-2 text-xs text-red-500">{{ $message }}</p>
@enderror
</div>
<!-- Submit Button -->
<div class="mb-6 flex items-center justify-center">
<button type="submit"
class="mr-4 rounded bg-gray-700 px-4 py-2 text-white hover:bg-gray-800">
Log In
</button>
<a href="/login/google" class="rounded bg-green-700 px-4 py-2 text-white hover:bg-green-800">Login Google</a>
</div>
</form>
</main>
</section>
</x-layout>
| php | MIT | 057684c58e627783f1aa8247fb394d3a8b533d36 | 2026-01-05T05:17:21.315532Z | false |
josuapsianturi/velflix | https://github.com/josuapsianturi/velflix/blob/057684c58e627783f1aa8247fb394d3a8b533d36/resources/views/auth/register.blade.php | resources/views/auth/register.blade.php | <x-layout>
<section class="px-6 py-8">
<main class="mx-auto mt-10 max-w-lg rounded-xl border border-gray-200 bg-gray-100 p-6">
<h1 class="text-center text-xl font-bold">Register</h1>
<form action="/register" method="post">
@csrf
<!-- Name -->
<div class="mb-6">
<label for="name" class="mb-2 block text-xs font-bold uppercase text-gray-700">
Name
</label>
<input class="w-full border border-gray-400 p-2"
type="text"
name="name"
id="name"
value="{{ old('name') }}"
required
>
@error('name')
<p class="mt-2 text-xs text-red-500">{{ $message }}</p>
@enderror
</div>
<!-- End Name -->
<!-- Username -->
<div class="mb-6">
<label for="username" class="mb-2 block text-xs font-bold uppercase text-gray-700">
Username
</label>
<input class="w-full border border-gray-400 p-2"
type="text"
name="username"
id="username"
value="{{ old('username') }}"
required
>
@error('username')
<p class="mt-2 text-xs text-red-500">{{ $message }}</p>
@enderror
</div>
<!-- End Username -->
<!-- Email -->
<div class="mb-6">
<label for="email" class="mb-2 block text-xs font-bold uppercase text-gray-700">
Email
</label>
<input class="w-full border border-gray-400 p-2"
type="email"
name="email"
id="email"
value="{{ old('email') }}"
required
>
@error('email')
<p class="mt-2 text-xs text-red-500">{{ $message }}</p>
@enderror
</div>
<!-- End Email -->
<!-- Password -->
<div class="mb-6">
<label for="password" class="mb-2 block text-xs font-bold uppercase text-gray-700">
Password
</label>
<input class="w-full border border-gray-400 p-2"
type="password"
name="password"
id="password"
required
>
</div>
<!-- End Password -->
<!-- Submit Button -->
<div class="mb-6">
<button type="submit"
class="rounded bg-gray-700 px-4 py-2 text-white hover:bg-gray-800">
Submit
</button>
</div>
<!-- End Submit -->
</form>
</section>
</x-layout>
| php | MIT | 057684c58e627783f1aa8247fb394d3a8b533d36 | 2026-01-05T05:17:21.315532Z | false |
josuapsianturi/velflix | https://github.com/josuapsianturi/velflix/blob/057684c58e627783f1aa8247fb394d3a8b533d36/resources/views/errors/layout.blade.php | resources/views/errors/layout.blade.php | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>@yield('title')</title>
<!-- Styles -->
<style>
html, body {
background-color: #fff;
color: #636b6f;
font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
font-weight: 100;
height: 100vh;
margin: 0;
}
.full-height {
height: 100vh;
}
.flex-center {
align-items: center;
display: flex;
justify-content: center;
}
.position-ref {
position: relative;
}
.content {
text-align: center;
}
.title {
font-size: 36px;
padding: 20px;
}
</style>
</head>
<body>
<div class="flex-center position-ref full-height">
<div class="content">
<div class="title">
@yield('message')
</div>
</div>
</div>
</body>
</html>
| php | MIT | 057684c58e627783f1aa8247fb394d3a8b533d36 | 2026-01-05T05:17:21.315532Z | false |
josuapsianturi/velflix | https://github.com/josuapsianturi/velflix/blob/057684c58e627783f1aa8247fb394d3a8b533d36/resources/views/errors/500.blade.php | resources/views/errors/500.blade.php | @extends('errors::minimal')
@section('title', __('Server Error'))
@section('code', '500')
@section('message', __('Server Error'))
| php | MIT | 057684c58e627783f1aa8247fb394d3a8b533d36 | 2026-01-05T05:17:21.315532Z | false |
josuapsianturi/velflix | https://github.com/josuapsianturi/velflix/blob/057684c58e627783f1aa8247fb394d3a8b533d36/resources/views/errors/503.blade.php | resources/views/errors/503.blade.php | @extends('errors::minimal')
@section('title', __('Service Unavailable'))
@section('code', '503')
@section('message', __('Service Unavailable'))
| php | MIT | 057684c58e627783f1aa8247fb394d3a8b533d36 | 2026-01-05T05:17:21.315532Z | false |
josuapsianturi/velflix | https://github.com/josuapsianturi/velflix/blob/057684c58e627783f1aa8247fb394d3a8b533d36/resources/views/errors/429.blade.php | resources/views/errors/429.blade.php | @extends('errors::minimal')
@section('title', __('Too Many Requests'))
@section('code', '429')
@section('message', __('Too Many Requests'))
| php | MIT | 057684c58e627783f1aa8247fb394d3a8b533d36 | 2026-01-05T05:17:21.315532Z | false |
josuapsianturi/velflix | https://github.com/josuapsianturi/velflix/blob/057684c58e627783f1aa8247fb394d3a8b533d36/resources/views/errors/403.blade.php | resources/views/errors/403.blade.php | @extends('errors::minimal')
@section('title', __('Forbidden'))
@section('code', '403')
@section('message', __($exception->getMessage() ?: 'Forbidden'))
| php | MIT | 057684c58e627783f1aa8247fb394d3a8b533d36 | 2026-01-05T05:17:21.315532Z | false |
josuapsianturi/velflix | https://github.com/josuapsianturi/velflix/blob/057684c58e627783f1aa8247fb394d3a8b533d36/resources/views/errors/401.blade.php | resources/views/errors/401.blade.php | @extends('errors::minimal')
@section('title', __('Unauthorized'))
@section('code', '401')
@section('message', __('Unauthorized'))
| php | MIT | 057684c58e627783f1aa8247fb394d3a8b533d36 | 2026-01-05T05:17:21.315532Z | false |
josuapsianturi/velflix | https://github.com/josuapsianturi/velflix/blob/057684c58e627783f1aa8247fb394d3a8b533d36/resources/views/errors/minimal.blade.php | resources/views/errors/minimal.blade.php | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>@yield('title')</title>
<style>
/*! normalize.css v8.0.1 | MIT License | github.com/necolas/normalize.css */html{line-height:1.15;-webkit-text-size-adjust:100%}body{margin:0}a{background-color:transparent}code{font-family:monospace,monospace;font-size:1em}[hidden]{display:none}html{font-family:system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;line-height:1.5}*,:after,:before{box-sizing:border-box;border:0 solid #e2e8f0}a{color:inherit;text-decoration:inherit}code{font-family:Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}svg,video{display:block;vertical-align:middle}video{max-width:100%;height:auto}.bg-white{--bg-opacity:1;background-color:#fff;background-color:rgba(255,255,255,var(--bg-opacity))}.bg-gray-100{--bg-opacity:1;background-color:#f7fafc;background-color:rgba(247,250,252,var(--bg-opacity))}.border-gray-200{--border-opacity:1;border-color:#edf2f7;border-color:rgba(237,242,247,var(--border-opacity))}.border-gray-400{--border-opacity:1;border-color:#cbd5e0;border-color:rgba(203,213,224,var(--border-opacity))}.border-t{border-top-width:1px}.border-r{border-right-width:1px}.flex{display:flex}.grid{display:grid}.hidden{display:none}.items-center{align-items:center}.justify-center{justify-content:center}.font-semibold{font-weight:600}.h-5{height:1.25rem}.h-8{height:2rem}.h-16{height:4rem}.text-sm{font-size:.875rem}.text-lg{font-size:1.125rem}.leading-7{line-height:1.75rem}.mx-auto{margin-left:auto;margin-right:auto}.ml-1{margin-left:.25rem}.mt-2{margin-top:.5rem}.mr-2{margin-right:.5rem}.ml-2{margin-left:.5rem}.mt-4{margin-top:1rem}.ml-4{margin-left:1rem}.mt-8{margin-top:2rem}.ml-12{margin-left:3rem}.-mt-px{margin-top:-1px}.max-w-xl{max-width:36rem}.max-w-6xl{max-width:72rem}.min-h-screen{min-height:100vh}.overflow-hidden{overflow:hidden}.p-6{padding:1.5rem}.py-4{padding-top:1rem;padding-bottom:1rem}.px-4{padding-left:1rem;padding-right:1rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.pt-8{padding-top:2rem}.fixed{position:fixed}.relative{position:relative}.top-0{top:0}.right-0{right:0}.shadow{box-shadow:0 1px 3px 0 rgba(0,0,0,.1),0 1px 2px 0 rgba(0,0,0,.06)}.text-center{text-align:center}.text-gray-200{--text-opacity:1;color:#edf2f7;color:rgba(237,242,247,var(--text-opacity))}.text-gray-300{--text-opacity:1;color:#e2e8f0;color:rgba(226,232,240,var(--text-opacity))}.text-gray-400{--text-opacity:1;color:#cbd5e0;color:rgba(203,213,224,var(--text-opacity))}.text-gray-500{--text-opacity:1;color:#a0aec0;color:rgba(160,174,192,var(--text-opacity))}.text-gray-600{--text-opacity:1;color:#718096;color:rgba(113,128,150,var(--text-opacity))}.text-gray-700{--text-opacity:1;color:#4a5568;color:rgba(74,85,104,var(--text-opacity))}.text-gray-900{--text-opacity:1;color:#1a202c;color:rgba(26,32,44,var(--text-opacity))}.uppercase{text-transform:uppercase}.underline{text-decoration:underline}.antialiased{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.tracking-wider{letter-spacing:.05em}.w-5{width:1.25rem}.w-8{width:2rem}.w-auto{width:auto}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}@-webkit-keyframes spin{0%{transform:rotate(0deg)}to{transform:rotate(1turn)}}@keyframes spin{0%{transform:rotate(0deg)}to{transform:rotate(1turn)}}@-webkit-keyframes ping{0%{transform:scale(1);opacity:1}75%,to{transform:scale(2);opacity:0}}@keyframes ping{0%{transform:scale(1);opacity:1}75%,to{transform:scale(2);opacity:0}}@-webkit-keyframes pulse{0%,to{opacity:1}50%{opacity:.5}}@keyframes pulse{0%,to{opacity:1}50%{opacity:.5}}@-webkit-keyframes bounce{0%,to{transform:translateY(-25%);-webkit-animation-timing-function:cubic-bezier(.8,0,1,1);animation-timing-function:cubic-bezier(.8,0,1,1)}50%{transform:translateY(0);-webkit-animation-timing-function:cubic-bezier(0,0,.2,1);animation-timing-function:cubic-bezier(0,0,.2,1)}}@keyframes bounce{0%,to{transform:translateY(-25%);-webkit-animation-timing-function:cubic-bezier(.8,0,1,1);animation-timing-function:cubic-bezier(.8,0,1,1)}50%{transform:translateY(0);-webkit-animation-timing-function:cubic-bezier(0,0,.2,1);animation-timing-function:cubic-bezier(0,0,.2,1)}}@media (min-width:640px){.sm\:rounded-lg{border-radius:.5rem}.sm\:block{display:block}.sm\:items-center{align-items:center}.sm\:justify-start{justify-content:flex-start}.sm\:justify-between{justify-content:space-between}.sm\:h-20{height:5rem}.sm\:ml-0{margin-left:0}.sm\:px-6{padding-left:1.5rem;padding-right:1.5rem}.sm\:pt-0{padding-top:0}.sm\:text-left{text-align:left}.sm\:text-right{text-align:right}}@media (min-width:768px){.md\:border-t-0{border-top-width:0}.md\:border-l{border-left-width:1px}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}}@media (min-width:1024px){.lg\:px-8{padding-left:2rem;padding-right:2rem}}@media (prefers-color-scheme:dark){.dark\:bg-gray-800{--bg-opacity:1;background-color:#2d3748;background-color:rgba(45,55,72,var(--bg-opacity))}.dark\:bg-gray-900{--bg-opacity:1;background-color:#1a202c;background-color:rgba(26,32,44,var(--bg-opacity))}.dark\:border-gray-700{--border-opacity:1;border-color:#4a5568;border-color:rgba(74,85,104,var(--border-opacity))}.dark\:text-white{--text-opacity:1;color:#fff;color:rgba(255,255,255,var(--text-opacity))}.dark\:text-gray-400{--text-opacity:1;color:#cbd5e0;color:rgba(203,213,224,var(--text-opacity))}}
</style>
<style>
body {
font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
}
</style>
</head>
<body class="antialiased">
<div class="items-top relative flex min-h-screen justify-center bg-gray-100 dark:bg-gray-900 sm:items-center sm:pt-0">
<div class="mx-auto max-w-xl sm:px-6 lg:px-8">
<div class="flex items-center pt-8 sm:justify-start sm:pt-0">
<div class="border-r border-gray-400 px-4 text-lg tracking-wider text-gray-500">
@yield('code')
</div>
<div class="ml-4 text-lg uppercase tracking-wider text-gray-500">
@yield('message')
</div>
</div>
</div>
</div>
</body>
</html>
| php | MIT | 057684c58e627783f1aa8247fb394d3a8b533d36 | 2026-01-05T05:17:21.315532Z | false |
josuapsianturi/velflix | https://github.com/josuapsianturi/velflix/blob/057684c58e627783f1aa8247fb394d3a8b533d36/resources/views/errors/404.blade.php | resources/views/errors/404.blade.php | @extends('errors::minimal')
@section('title', __('Not Found'))
@section('code', '404')
@section('message', __('Not Found'))
| php | MIT | 057684c58e627783f1aa8247fb394d3a8b533d36 | 2026-01-05T05:17:21.315532Z | false |
josuapsianturi/velflix | https://github.com/josuapsianturi/velflix/blob/057684c58e627783f1aa8247fb394d3a8b533d36/resources/views/errors/419.blade.php | resources/views/errors/419.blade.php | @extends('errors::minimal')
@section('title', __('Page Expired'))
@section('code', '419')
@section('message', __('Page Expired'))
| php | MIT | 057684c58e627783f1aa8247fb394d3a8b533d36 | 2026-01-05T05:17:21.315532Z | false |
josuapsianturi/velflix | https://github.com/josuapsianturi/velflix/blob/057684c58e627783f1aa8247fb394d3a8b533d36/resources/views/components/navbar.blade.php | resources/views/components/navbar.blade.php | <div class="relative flex flex-col bg-gray-300">
<img class="absolute top-0 bottom-0 z-0 h-full w-full object-cover"
src="https://assets.nflxext.com/ffe/siteui/vlv3/e178a4e7-4f52-4661-b2ae-41efa25dca7c/60dd20cf-7213-48a1-b253-6484d62d96a8/IN-en-20210222-popsignuptwoweeks-perspective_alpha_website_small.jpg"
alt="">
<div class="absolute top-0 bottom-0 left-0 right-0 z-10 h-full w-full bg-black opacity-60"></div>
@auth
<div class="z-30 flex flex-row justify-end px-12 py-4">
<div class="cursor-pointer rounded bg-red-600 px-4 py-1 text-gray-100">
<a href="{{ route('velflix.index') }}" clas="px-4 py-1 text-gray-100 bg-red-600 rounded cursor-pointer">
Watch Movie ›
</a>
</div>
</div>
@endauth
<div class="z-30 flex flex-col items-center justify-center py-48 text-gray-100 lg:py-32">
<h1 class="w-full px-12 text-center text-4xl font-bold md:w-1/2 lg:px-0 lg:text-6xl">Unlimited movies,
TV shows and more.</h1>
<p class="mt-6 px-12 text-center text-xl md:text-2xl">Watch anywhere. Cancel anytime.</p>
<x-newsletter />
</div>
</div>
| php | MIT | 057684c58e627783f1aa8247fb394d3a8b533d36 | 2026-01-05T05:17:21.315532Z | false |
josuapsianturi/velflix | https://github.com/josuapsianturi/velflix/blob/057684c58e627783f1aa8247fb394d3a8b533d36/resources/views/components/flash.blade.php | resources/views/components/flash.blade.php | @if (session()->has('success'))
<div x-data="{show: true}"
x-init="setTimeout(() => show = false, 4000)"
x-show="show"
class="fixed bottom-3 right-3 rounded-xl bg-gray-700 px-4 py-2 text-sm text-white">
<p>{{ session('success') }}</p>
</div>
@endif
| php | MIT | 057684c58e627783f1aa8247fb394d3a8b533d36 | 2026-01-05T05:17:21.315532Z | false |
josuapsianturi/velflix | https://github.com/josuapsianturi/velflix/blob/057684c58e627783f1aa8247fb394d3a8b533d36/resources/views/components/velflix-card.blade.php | resources/views/components/velflix-card.blade.php | @props(['movie', 'genres'])
<div @click="open = true" class="mr-3 flex flex-col overflow-hidden rounded-md" style="background-color: #181818">
<div @click="open = true" class="w-72">
<a href="{{ route('movies.show', $movie['id']) }}">
<img class="h-56 w-full cursor-pointer"
src="{{ 'https://image.tmdb.org/t/p/w500' . $movie['poster_path'] }}"
alt="poster">
</a>
</div>
<div x-show="open" x-cloak class="">
<!-- Buttons Navigation -->
<div class="flex flex-row items-center justify-between m-4">
<div class="flex items-center justify-center space-x-2">
<button class="flex h-9 w-9 items-center justify-center rounded-full bg-white focus:outline-none" >
<x-icons name="caret-right-fill" />
</button>
<button class="flex h-8 w-8 items-center justify-center rounded-full border-2 border-gray-400 hover:border-gray-100">
<x-icons name="plus" />
</button>
<button class="flex h-8 w-8 items-center justify-center rounded-full border-2 border-gray-400 hover:border-gray-100">
<x-icons name="hand-thumbs-up" />
</button>
<button class="flex h-8 w-8 items-center justify-center rounded-full border-2 border-gray-400 hover:border-gray-100">
<x-icons name="hand-thumbs-down" />
</button>
</div>
<div class="">
<button class="flex items-center justify-center w-8 h-8 border-2 border-gray-400 rounded-full hover:border-gray-100 focus:outline-none ">
<x-bi-chevron-down class="h-4 w-4 text-white" />
</button>
</div>
</div>
<!-- End Buttons Navigation -->
<!-- Rating -->
<div class="mx-4 flex">
<span class="font-bold text-green-500">{{ $movie['vote_average'] * 10 . '%' }} Match</span>
</div>
<!-- End Rating -->
<!-- Genres -->
<div class="m-4 flex">
<span class="flex truncate text-sm font-medium text-gray-400">
@foreach ($movie['genre_ids'] as $genre)
@if ($loop->index)
·
{{ $genres->get($genre)}}
@else
@break
@endif
@endforeach
</span>
</div>
<!-- End Genres -->
</div>
</div>
| php | MIT | 057684c58e627783f1aa8247fb394d3a8b533d36 | 2026-01-05T05:17:21.315532Z | false |
josuapsianturi/velflix | https://github.com/josuapsianturi/velflix/blob/057684c58e627783f1aa8247fb394d3a8b533d36/resources/views/components/layout.blade.php | resources/views/components/layout.blade.php | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Velflix</title>
@vite('resources/css/app.css')
<script defer src="https://unpkg.com/@alpinejs/collapse@3.x.x/dist/cdn.min.js"></script>
<script defer src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/flickity@2/dist/flickity.min.css">
<script src="https://unpkg.com/flickity@2/dist/flickity.pkgd.min.js"></script>
@livewireStyles
</head>
<style>
[x-cloak] { display: none !important; }
</style>
<body style="background-color: #141414">
{{ $slot }}
<x-flash />
@livewireScripts
<script src="/js/app.js"></script>
@stack('scripts')
</body>
</html>
| php | MIT | 057684c58e627783f1aa8247fb394d3a8b533d36 | 2026-01-05T05:17:21.315532Z | false |
josuapsianturi/velflix | https://github.com/josuapsianturi/velflix/blob/057684c58e627783f1aa8247fb394d3a8b533d36/resources/views/components/nav.blade.php | resources/views/components/nav.blade.php | @props(['popular'])
<section class="relative h-screen w-full bg-black">
<div class="absolute z-10 h-full w-full">
<div class="flex h-full items-center justify-start px-16">
<div class="hidden w-2/5 flex-col space-y-4 py-12 lg:flex">
<h1 class="text-6xl font-semibold text-yellow-300">
{{ $popular[0]['title'] }}
</h1>
<p class="text-lg font-semibold text-white">
{{ $popular[0]['overview'] }}
</p>
<div class="flex w-full flex-row space-x-4">
<button
class="bg-gradient mt-5 flex w-28 items-center justify-center space-x-2 rounded bg-white px-2 py-2 shadow-md">
<x-bi-caret-right-fill class="h-6 w-6" />
<span class="font-semibold text-gray-800">Play</span>
</button>
<button
class="mt-5 flex w-36 items-center justify-center space-x-2 rounded-lg bg-gray-500 bg-opacity-50 px-3 py-2 font-semibold shadow-md">
<x-bi-info-circle class="h-5 w-5 font-bold text-white" />
<span class="font-semibold text-white">More Info</span>
</button>
</div>
</div>
</div>
</div>
<div class="absolute bottom-0 h-64 w-full bg-gradient-to-t from-black"></div>
<div class="-mt-8 object-cover lg:h-screen">
<img class="h-screen w-screen object-contain"
src="{{ 'https://image.tmdb.org/t/p/w500/' . $popular[0]['poster_path'] }}">
</div>
</section>
| php | MIT | 057684c58e627783f1aa8247fb394d3a8b533d36 | 2026-01-05T05:17:21.315532Z | false |
josuapsianturi/velflix | https://github.com/josuapsianturi/velflix/blob/057684c58e627783f1aa8247fb394d3a8b533d36/resources/views/components/gap.blade.php | resources/views/components/gap.blade.php | <div class="h-3 w-full" style="background-color: #222"></div>
| php | MIT | 057684c58e627783f1aa8247fb394d3a8b533d36 | 2026-01-05T05:17:21.315532Z | false |
josuapsianturi/velflix | https://github.com/josuapsianturi/velflix/blob/057684c58e627783f1aa8247fb394d3a8b533d36/resources/views/components/rating-script.blade.php | resources/views/components/rating-script.blade.php | @props(['rating', 'slug', 'event'])
<script>
@if ($event) window.livewire.on('{{ $event }}', params => { @endif
@if ($event)
var progressBarContainer = document.getElementById(params.slug)
@else
var progressBarContainer = document.getElementById('{{ $slug }}')
@endif
var bar = new ProgressBar.Circle(progressBarContainer, {
color: 'white',
// This has to be the same size as the maximum width to
// prevent clipping
strokeWidth: 6,
trailWidth: 3,
trailColor: '#4A5568',
easing: 'easeInOut',
duration: 2500,
text: {
autoStyleContainer: false
},
from: { color: '#48BB78', width: 6 },
to: { color: '#48BB78', width: 6 },
// Set default step function for all animate calls
step: function(state, circle) {
circle.path.setAttribute('stroke', state.color);
circle.path.setAttribute('stroke-width', state.width);
var value = Math.round(circle.value() * 100);
if (value === 0) {
circle.setText('0%');
} else {
circle.setText(value+'%');
}
}
});
@if ($event)
bar.animate(params.rating);
@else
bar.animate({{ $rating }} / 100);
@endif
@if ($event) }) @endif
</script>
| php | MIT | 057684c58e627783f1aa8247fb394d3a8b533d36 | 2026-01-05T05:17:21.315532Z | false |
josuapsianturi/velflix | https://github.com/josuapsianturi/velflix/blob/057684c58e627783f1aa8247fb394d3a8b533d36/resources/views/components/header.blade.php | resources/views/components/header.blade.php | <div class="body-font fixed top-0 z-50 w-full bg-black text-white">
<div class="flex flex-col flex-wrap items-center p-5 px-16 md:flex-row">
<a class="title-font mb-4 flex items-center text-2xl font-bold uppercase md:mb-0" style="color: #e50914">
Velflix
</a>
@auth
<ul class="ml-12 hidden w-1/2 flex-row space-x-3 text-sm lg:flex">
<li class="font-semibold">Home</li>
<li>Series</li>
<li>Films</li>
<li>Latest</li>
<li>My List</li>
<li>Watch Again</li>
</ul>
@endauth
<nav class="hidden flex-wrap items-center justify-center space-x-6 text-base font-bold md:ml-auto lg:flex">
@auth
<livewire:search-velflix />
<x-bi-gift class="h-5 w-5" />
<x-bi-bell-fill class="h-5 w-5" />
{{-- <span class="text-xs font-bold uppercase">Welcome, {{ auth()->user()->name }}!</span> --}}
<!-- User Profile -->
<div x-data="{ open: false }"
class="relative inline-block"
:class="{'text-gray-900': open, 'text-gray-600': !open }">
<!-- Dropdown Toggle Button -->
<button @click="open = !open" @click.away="open = false" class="flex items-center">
<img src="https://occ-0-58-64.1.nflxso.net/dnm/api/v6/0RO1pLmU93-gdXvuxd_iYjzPqkc/AAAABTw7t_oDR-SWh9ddj9kh9AlOqCabZMupMWano7R5wg9x1_KPjvABqKHNeCxcMddK7Ku9HsV6keglPmWPZeh0lKU.png?r=fcc"
alt="avatar">
<span :class="open = ! open ? '': '-rotate-180'" class="transform transition-transform duration-500">
<x-bi-chevron-down
class="h-4 w-4 stroke-current pl-1 text-white" />
</span>
</button>
<!-- End Dropdown Toggle Button -->
<!-- Dropdown Menu -->
<div x-cloak x-show="open"
x-transition:enter="transition ease-out duration-300"
x-transition:enter-start="opacity-0 transform scale-90"
x-transition:enter-end="opacity-100 transform scale-100"
x-transition:leave="transition ease-in duration-300"
x-transition:leave-start="opacity-100 transform scale-100"
x-transition:leave-end="opacity-0 transform scale-90"
class="absolute right-0 min-w-max rounded-md bg-white text-gray-500 shadow-xl">
<form action="/logout" method="post"
class="">
@csrf
<button type="submit" class="block rounded-md px-8 py-2 font-bold hover:bg-gray-200 hover:text-gray-600">Log Out</button>
@can('admin')
<a href="/admin" class="block rounded-b-md px-8 py-2 hover:bg-gray-200 hover:text-gray-600">Admin Dashboard</a>
@endcan
</form>
</div>
<!-- End User Profile -->
</div>
@else
<!-- User Profile -->
<div x-data="{ open: false }"
class="relative inline-block"
:class="{'text-gray-900': open, 'text-gray-600': !open }">
<!-- Dropdown Toggle Button -->
<button @click="open = !open" @click.away="open = false" class="flex items-center">
<img src="https://occ-0-58-64.1.nflxso.net/dnm/api/v6/0RO1pLmU93-gdXvuxd_iYjzPqkc/AAAABTw7t_oDR-SWh9ddj9kh9AlOqCabZMupMWano7R5wg9x1_KPjvABqKHNeCxcMddK7Ku9HsV6keglPmWPZeh0lKU.png?r=fcc"
alt="avatar">
<span :class="open = ! open ? '': '-rotate-180'" class="transform transition-transform duration-500">
<x-bi-chevron-down
class="h-4 w-4 stroke-current pl-1 text-white" />
</span>
</button>
<!-- End Dropdown Toggle Button -->
<!-- Dropdown Menu -->
<div x-cloak x-show="open"
x-transition:enter="transition ease-out duration-300"
x-transition:enter-start="opacity-0 transform scale-90"
x-transition:enter-end="opacity-100 transform scale-100"
x-transition:leave="transition ease-in duration-300"
x-transition:leave-start="opacity-100 transform scale-100"
x-transition:leave-end="opacity-0 transform scale-90"
class="absolute right-0 min-w-max rounded-md bg-white text-gray-500 shadow-xl">
<a href="/register" class="block rounded-t-md px-8 py-2 hover:bg-gray-200 hover:text-gray-600">Regsiter</a>
<a href="/login" class="block rounded-b-md px-8 py-2 hover:bg-gray-200 hover:text-gray-600">Log in</a>
</div>
<!-- End User Profile -->
</div>
@endauth
</nav>
</div>
</div>
| php | MIT | 057684c58e627783f1aa8247fb394d3a8b533d36 | 2026-01-05T05:17:21.315532Z | false |
josuapsianturi/velflix | https://github.com/josuapsianturi/velflix/blob/057684c58e627783f1aa8247fb394d3a8b533d36/resources/views/components/faq.blade.php | resources/views/components/faq.blade.php | <div class="container mx-auto mt-12 px-4 text-center xl:px-64">
<h2 class="text-5xl font-bold">Frequently Asked Questions</h2>
<div x-data="{ active: 1, items: [
{ id: 1, title: 'What is Velflix?', answer: 'Velflix is a streaming service that offers a wide variety of award-winning TV shows, movies, anime, documentaries, and more on thousands of internet-connected devices. You can watch as much as you want, whenever you want without a single commercial – all for one low monthly price' },
{ id: 2, title: 'How much does Velflix cost?', answer: 'Watch Velflix on your smartphone, tablet, Smart TV, laptop, or streaming device, all for one fixed monthly fee. Plans range from IDR54,000 to IDR186,000 a month. No extra costs, no contracts.'},
{ id: 3, title: 'Where can I watch?', answer: 'Watch anywhere, anytime, on an unlimited number of devices. Sign in with your Velflix account to watch instantly on the web at Velflix.com from your personal computer or on any internet-connected device that offers the Velflix app, including smart TVs, smartphones, tablets, streaming media players and game consoles.'},
{ id: 4, title: 'How do I cancel?', answer: 'Velflix is flexible. There are no pesky contracts and no commitments. You can easily cancel your account online in two clicks. There are no cancellation fees – start or stop your account anytime.'},
{ id: 5, title: 'What can I watch on Velflix?', answer: 'Velflix has an extensive library of feature films, documentaries, TV shows, anime, award-winning Velflix originals, and more. Watch as much as you want, anytime you want.'},
{ id: 6, title: 'Is Velflix good for kids?', answer: 'The Netflix Kids experience is included in your membership to give parents control while kids enjoy family-friendly TV shows and movies in their own space. Kids profiles come with PIN-protected parental controls that let you restrict the maturity rating of content kids can watch and block specific titles you don’t want kids to see.'},
]}"class="space-y-4"
>
<template x-for="{ id, title, answer } in items " :key="id" >
<div x-data="{
get expanded() {
return this.active === this.id
},
set expanded(value) {
this.active = value ? this.id : null
},
}" role="region" class="border border-black text-gray-100" style="background-color: #303030">
<h2>
<button
@click="expanded = !expanded"
:aria-expanded="expanded"
class="flex w-full items-center justify-between px-6 py-3 text-xl font-bold tracking-wider"
>
<span x-text="title"></span>
<span x-show="expanded" aria-hidden="true" class="ml-4">−</span>
<span x-show="!expanded" aria-hidden="true" class="ml-4">+</span>
</button>
</h2>
<div x-show="expanded" x-collapse.duration.500ms>
<div x-text="answer" class="px-6 pb-4"></div>
</div>
</div>
</template>
</div>
</div>
| php | MIT | 057684c58e627783f1aa8247fb394d3a8b533d36 | 2026-01-05T05:17:21.315532Z | false |
josuapsianturi/velflix | https://github.com/josuapsianturi/velflix/blob/057684c58e627783f1aa8247fb394d3a8b533d36/resources/views/components/icons.blade.php | resources/views/components/icons.blade.php | @props(['name'])
@if ($name === "hand-thumbs-up")
<svg {{ $attributes->class(['text-white w-4 h-4']) }} viewBox="0 0 24 24" >
<path d="M15.167 8.994h3.394l.068.023c1.56.138 2.867.987 2.867 2.73 0 .275-.046.527-.092.78.367.435.596.986.596 1.72 0 .963-.39 1.52-1.032 1.978.023.183.023.252.023.39 0 .963-.39 1.784-1.009 2.243.023.206.023.275.023.39 0 1.743-1.33 2.591-2.89 2.73L12.21 22c-2.04 0-3.05-.252-4.563-.895-.917-.39-1.353-.527-2.27-.619L4 20.371v-8.234l2.476-1.445 2.27-4.427c0-.046.085-1.552.253-4.52l.871-.389c.092-.069.275-.138.505-.184.664-.206 1.398-.252 2.132 0 1.261.436 2.064 1.537 2.408 3.258.142.829.226 1.695.26 2.564l-.008 2zm-4.42-2.246l-2.758 5.376L6 13.285v5.26c.845.113 1.44.3 2.427.72 1.37.58 2.12.735 3.773.735l4.816-.023c.742-.078.895-.3 1.015-.542.201-.4.201-.876 0-1.425.558-.184.917-.479 1.078-.883.182-.457.182-.966 0-1.528.601-.228.901-.64.901-1.238s-.202-1.038-.608-1.32c.23-.46.26-.892.094-1.294-.168-.404-.298-.627-1.043-.738l-.172-.015h-5.207l.095-2.09c.066-1.448-.009-2.875-.216-4.082-.216-1.084-.582-1.58-1.096-1.758-.259-.09-.546-.086-.876.014-.003.06-.081 1.283-.235 3.67z" fill="currentColor"></path>
</svg>
@endif
@if ($name === "plus")
<svg viewBox="0 0 24 24" {{ $attributes->class(['text-white w-4 h-4']) }}>
<path d="M13 11h8v2h-8v8h-2v-8H3v-2h8V3h2v8z" fill="currentColor"></path>
</svg>
@endif
@if ($name === "hand-thumbs-down")
<svg viewBox="0 0 24 24" {{ $attributes->class(['text-white w-4 h-4']) }}>
<path d="M8.833 15.006H5.44l-.068-.023c-1.56-.138-2.867-.987-2.867-2.73 0-.275.046-.527.092-.78C2.23 11.038 2 10.487 2 9.753c0-.963.39-1.52 1.032-1.978-.023-.183-.023-.252-.023-.39 0-.963.39-1.784 1.009-2.243-.023-.206-.023-.275-.023-.39 0-1.743 1.33-2.591 2.89-2.73L11.79 2c2.04 0 3.05.252 4.563.895.917.39 1.353.527 2.27.619L20 3.629v8.234l-2.476 1.445-2.27 4.427c0 .046-.085 1.552-.253 4.52l-.871.389c-.092.069-.275.138-.505.184-.664.206-1.398.252-2.132 0-1.261-.436-2.064-1.537-2.408-3.258a19.743 19.743 0 0 1-.26-2.564l.008-2zm4.42 2.246l2.758-5.376L18 10.715v-5.26c-.845-.113-1.44-.3-2.427-.72C14.203 4.156 13.453 4 11.8 4l-4.816.023c-.742.078-.895.3-1.015.542-.201.4-.201.876 0 1.425-.558.184-.917.479-1.078.883-.182.457-.182.966 0 1.528-.601.228-.901.64-.901 1.238s.202 1.038.608 1.32c-.23.46-.26.892-.094 1.294.168.404.298.627 1.043.738l.172.015h5.207l-.095 2.09c-.066 1.448.009 2.875.216 4.082.216 1.084.582 1.58 1.096 1.758.259.09.546.086.876-.014.003-.06.081-1.283.235-3.67z" fill="currentColor"></path>
</svg>
@endif
@if ($name === "caret-right-fill")
<svg viewBox="0 0 24 24" {{ $attributes->class(['text-black w-4 h-4']) }}>
<path d="M6 4l15 8-15 8z" fill="currentColor"></path>
</svg>
@endif
| php | MIT | 057684c58e627783f1aa8247fb394d3a8b533d36 | 2026-01-05T05:17:21.315532Z | false |
josuapsianturi/velflix | https://github.com/josuapsianturi/velflix/blob/057684c58e627783f1aa8247fb394d3a8b533d36/resources/views/components/footer.blade.php | resources/views/components/footer.blade.php | <footer class="mx-auto max-w-screen-lg py-8 text-sm" style="color: #7c7c7c">
<div class="my-4 ml-6 flex space-x-6" style="color: #808080">
<x-entypo-facebook class="h-w-7 w-7" />
<x-bi-instagram class="h-7 w-7" />
<x-bi-twitter class="h-7 w-7" />
<x-bi-youtube class="h-7 w-7" />
</div>
<div class="flex justify-between">
<div class="mx-6 space-y-3">
<div>Audio and Subtitles</div>
<div>Media centre</div>
<div>Privacy</div>
<div>Contact Us</div>
</div>
<div class="mx-6 space-y-3">
<div>Audio Description</div>
<div>Investor Relations</div>
<div>Legal Notices</div>
</div>
<div class="mx-6 space-y-3">
<div>Help Centre</div>
<div>Jobs</div>
<div>Cookie Preferences</div>
</div>
<div class="mx-6 space-y-3">
<div>Gift Cards</div>
<div>Terms of Use</div>
<div>Corporate Information</div>
</div>
</div>
</footer>
| php | MIT | 057684c58e627783f1aa8247fb394d3a8b533d36 | 2026-01-05T05:17:21.315532Z | false |
josuapsianturi/velflix | https://github.com/josuapsianturi/velflix/blob/057684c58e627783f1aa8247fb394d3a8b533d36/resources/views/components/movies.blade.php | resources/views/components/movies.blade.php | @props(['movies'])
<div class="">
<div class="mb-4 text-lg antialiased font-bold tracking-wider text-gray-200">
{{ $category }}
</div>
<div class="carousel" data-flickity='{ "freeScroll": true, "wrapAround": true }'
class="carousel flex flex-nowrap">
@foreach ($movies as $movie)
<div @click="open = true" class="mr-3 flex flex-col overflow-hidden rounded-md" style="background-color: #181818">
<div @click="open = true" class="w-72">
<a href="{{ route('movies.show', $movie['id']) }}">
<img class="h-56 w-full cursor-pointer"
src="{{ 'https://image.tmdb.org/t/p/w500' . $movie['poster_path'] }}"
alt="poster">
</a>
</div>
</div>
@endforeach
</div>
</div>
| php | MIT | 057684c58e627783f1aa8247fb394d3a8b533d36 | 2026-01-05T05:17:21.315532Z | false |
josuapsianturi/velflix | https://github.com/josuapsianturi/velflix/blob/057684c58e627783f1aa8247fb394d3a8b533d36/resources/views/components/newsletter.blade.php | resources/views/components/newsletter.blade.php | <p class="my-3 px-12 text-center">Want us to email you occasionally with Vetflix news?
</p>
<div class="relative mx-auto inline-block lg:bg-gray-100">
<form method="POST" action="/newsletter" class="text-sm lg:flex">
@csrf
<div class="flex items-center lg:py-4 lg:px-12">
<label for="email" class="hidden lg:inline-block">
<img src="/img/mailbox-icon.svg" alt="mailbox letter">
</label>
<div>
<input
id="email"
name="email"
type="text"
placeholder="Your email address"
class="py-3 pl-5 text-lg text-gray-500 focus-within:outline-none lg:bg-transparent lg:py-0">
@error('email')
<span class="text-xs text-red-500">{{ $message }}</span>
@enderror
</div>
</div>
<button type="submit"
class="flex items-center bg-red-600 py-2 px-14 text-xl text-white transition-colors duration-300 hover:bg-red-700 lg:mt-0 lg:ml-3"
>
Subscribe
<span class="ml-2 w-6 p-1">
<svg fill="currentColor" version="1.1" id="Capa_1" xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 512.002 512.002"
style="enable-background:new 0 0 512.002 512.002;" xml:space="preserve">
<g>
<g>
<path
d="M388.425,241.951L151.609,5.79c-7.759-7.733-20.321-7.72-28.067,0.04c-7.74,7.759-7.72,20.328,0.04,28.067l222.72,222.105 L123.574,478.106c-7.759,7.74-7.779,20.301-0.04,28.061c3.883,3.89,8.97,5.835,14.057,5.835c5.074,0,10.141-1.932,14.017-5.795 l236.817-236.155c3.737-3.718,5.834-8.778,5.834-14.05S392.156,245.676,388.425,241.951z" />
</g>
</g>
</svg>
</span>
</button>
</form>
</div>
| php | MIT | 057684c58e627783f1aa8247fb394d3a8b533d36 | 2026-01-05T05:17:21.315532Z | false |
josuapsianturi/velflix | https://github.com/josuapsianturi/velflix/blob/057684c58e627783f1aa8247fb394d3a8b533d36/resources/views/components/movies/index.blade.php | resources/views/components/movies/index.blade.php | @props(['popular', 'genres', 'trending', 'comedies', 'action', 'western', 'horror', 'thriller', 'animation'])
<div class="container my-6 mx-auto space-y-8 px-4">
<!-- Popular Movies -->
<x-movies :movies='$popular'>
<x-slot:category> Popular on Velflix › </x-slot:category>
</x-movies>
<!-- End Popular Movies -->
<!-- Trending Movies -->
<x-movies :movies='$trending'>
<x-slot:category> Trending on Velflix › </x-slot:category>
</x-movies>
<!-- End Trending Movies -->
<!-- Comedies Movies -->
<x-movies :movies='$comedies'>
<x-slot:category> Comedies › </x-slot:category>
</x-movies>
<!-- End Comedies Movies -->
<!-- Action Movies -->
<x-movies :movies='$action'>
<x-slot:category> Action › </x-slot:category>
</x-movies>
<!-- End Action Movies -->
<!-- Western Movies -->
<x-movies :movies='$western'>
<x-slot:category> Western › </x-slot:category>
</x-movies>
<!-- End Wester Movies -->
<!-- Horror Movies -->
<x-movies :movies=$horror>
<x-slot:category> Horror › </x-slot:category>
</x-movies>
<!-- End Horror Movies -->
<!-- Animation Movies -->
<x-movies :movies='$animation'>
<x-slot:category> Animation › </x-slot:category>
</x-movies>
<!-- End Animation Movies -->
</div>
| php | MIT | 057684c58e627783f1aa8247fb394d3a8b533d36 | 2026-01-05T05:17:21.315532Z | false |
josuapsianturi/velflix | https://github.com/josuapsianturi/velflix/blob/057684c58e627783f1aa8247fb394d3a8b533d36/resources/views/components/movies/show.blade.php | resources/views/components/movies/show.blade.php |
<x-layout>
<div class="flex h-full w-full items-center overflow-y-auto pt-4 shadow-lg">
<div class="container mx-auto overflow-y-auto rounded-lg lg:px-56">
<div class="rounded-xl bg-gray-800">
<div class="responsive-container relative overflow-hidden" style="padding-top: 56.25%">
<iframe class="responsive-iframe absolute top-0 left-0 h-full w-full rounded-t-xl"
src="https://www.youtube.com/embed/{{ $movies['videos']['results'][0]['key'] }}"
style="border:0;" allow="autoplay; encrypted-media" allowfullscreen>
</iframe>
</div>
<div class="modal-body px-8 py-3">
<div class="responsive-container relative overflow-hidden text-white">
<div class="my-4 flex w-full flex-row space-x-4">
<button class="bg-gradient flex w-28 items-center justify-center space-x-2 rounded bg-white px-2 py-2 shadow-md">
<x-bi-caret-right-fill class="h-6 w-6 text-black"/>
<span class="font-semibold text-black">Play</span>
</button>
<button class="mr-2 flex h-8 w-8 items-center justify-center rounded-full ring-2 ring-gray-400">
<x-bi-plus class="h-4 w-4 text-white"/>
</button>
<button class="mr-2 flex h-8 w-8 items-center justify-center rounded-full ring-2 ring-gray-400">
<x-bi-hand-thumbs-up class="h-4 w-4 text-white"/>
</button>
<button class="mr-8 flex h-8 w-8 items-center justify-center rounded-full ring-2 ring-gray-400">
<x-bi-hand-thumbs-down class="h-4 w-4 text-white" />
</button>
</div>
<div class="my-6 flex">
<div class="w-4/6">
<span class="mb-3 flex space-x-4">
<div class="flex items-center">
<div id="vote_average" class="relative h-16 w-16 rounded-full bg-gray-800 text-white">
{{-- @push('scripts')
<x-rating-script :slug="'vote_average'" :rating="$movies['vote_average'] * 10" :event='null' />
@endpush --}}
<div class="mx-4 flex">
<span class="font-bold text-green-500">{{ $movies['vote_average'] * 10 . '%' }}</span>
</div>
</div>
</div>
<div class="mt-2">
<div class="font-semibold text-white">{{ $movies['original_title'] }}</div>
<div class="text-sm text-gray-500">{{ date('Y', strtotime($movies['release_date'] )) }}</div>
</div>
</span>
<span>
{{ $movies['overview'] }}
</span>
</div>
<div class="w-2/6">
<span class="text-gray-500">
Cast:
<span class="flex truncate text-sm font-medium text-gray-400">
@foreach ($movies['credits']['cast'] as $cast)
<div class="">
{{ $cast['name'] }},
</div>
@endforeach
</span>
</span>
<span class="text-gray-500">
Genres:
<span class="flex truncate text-sm font-medium text-gray-400">
@foreach ($movies['genres'] as $genre)
<div class="">
{{ $genre['name'] }},
</div>
@endforeach
</span>
</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</x-layout>
| php | MIT | 057684c58e627783f1aa8247fb394d3a8b533d36 | 2026-01-05T05:17:21.315532Z | false |
josuapsianturi/velflix | https://github.com/josuapsianturi/velflix/blob/057684c58e627783f1aa8247fb394d3a8b533d36/resources/views/livewire/admin-controller.blade.php | resources/views/livewire/admin-controller.blade.php | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Velflix</title>
<!-- Tailwind CDN -->
@vite('resources/css/app.css')
<!-- Alpine Plugins -->
<script defer src="https://unpkg.com/@alpinejs/collapse@3.x.x/dist/cdn.min.js"></script>
<!-- Alpine CDN -->
<script src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js" defer></script>
</head>
<style>
[x-cloak] { display: none !important; }
</style>
<body class="bg-black text-gray-100">
<x-header />
<section class="mt-96 text-xl text-white">
This is Admin Page
</section>
</body>
</html>
| php | MIT | 057684c58e627783f1aa8247fb394d3a8b533d36 | 2026-01-05T05:17:21.315532Z | false |
josuapsianturi/velflix | https://github.com/josuapsianturi/velflix/blob/057684c58e627783f1aa8247fb394d3a8b533d36/resources/views/livewire/search-velflix.blade.php | resources/views/livewire/search-velflix.blade.php | <div class="relative border border-white bg-black p-1 text-white">
<x-bi-search class="absolute m-1 h-5 w-5" />
<input wire:model.debounce.500ms="searchVelflix" type="text" placeholder="Titles, people, genres" class="ml-8 bg-black text-white placeholder-gray-500 focus:outline-none">
@if (strlen($searchVelflix >= 3))
<div class="absolute mt-2 -ml-2 w-64 bg-gray-700 p-2 text-sm">
@if ($searchVelflixResults->count() > 0 )
<ul>
@foreach ($searchVelflixResults as $searchResults)
<a href="{{ route('movies.show', $searchResults['id']) }}" class="hover:bg-gray-400">
<li class="border-b border-gray-500 p-1">
{{ $searchResults['title'] }}
</li>
</a>
@endforeach
</ul>
@else
<div class="px-3 py-3">
<span> Your search for "{{ $searchVelflix }}" did not have any matches</span>
<span>Suggestions: </span>
<ul>
<li>Try different keywords</li>
<li>Looking for a film or TV programme ? </li>
<li>Try using a film, TV programme title, an actor or director.</li>
<li>Try a genre, such as comedy, romance, sports or drama.</li>
</ul>
</div>
@endif
</div>
@endif
</div>
| php | MIT | 057684c58e627783f1aa8247fb394d3a8b533d36 | 2026-01-05T05:17:21.315532Z | false |
jack-theripper/yandex | https://github.com/jack-theripper/yandex/blob/49f51b32f76cbfd123bb9fad7fdc63619121a884/src/Disk.php | src/Disk.php | <?php
/**
* Часть библиотеки для работы с сервисами Яндекса
*
* @package Arhitector\Yandex
* @version 2.0
* @author Arhitector
* @license MIT License
* @copyright 2016 Arhitector
* @link https://github.com/jack-theripper
*/
namespace Arhitector\Yandex;
use Arhitector\Yandex\Client\Container\ContainerTrait;
use Arhitector\Yandex\Client\Exception\UnsupportedException;
use Arhitector\Yandex\Client\OAuth;
use League\Event\Emitter;
use League\Event\EmitterTrait;
use Psr\Http\Message\RequestInterface;
use Laminas\Diactoros\Request;
use Laminas\Diactoros\Stream;
use Laminas\Diactoros\Uri;
/**
* Клиент для Яндекс.Диска
*
* @package Arhitector\Yandex
*/
class Disk extends OAuth implements \ArrayAccess, \IteratorAggregate, \Countable
{
use ContainerTrait, EmitterTrait {
toArray as protected _toArray;
}
/**
* @const адрес API
*/
const API_BASEPATH = 'https://cloud-api.yandex.net/v1/disk/';
/**
* @var array соответствие кодов ответа к типу исключения
*/
protected $exceptions = [
/**
* Некорректные данные (Bad Request).
*/
400 => 'Arhitector\Yandex\Client\Exception\UnsupportedException',
/**
* Не авторизован (Unauthorized).
*/
401 => 'Arhitector\Yandex\Client\Exception\UnauthorizedException',
/**
* Доступ запрещён (Forbidden).
* Возможно, у приложения недостаточно прав для данного действия.
*/
403 => 'Arhitector\Yandex\Client\Exception\ForbiddenException',
/**
* Не удалось найти запрошенный ресурс (Not Found).
*/
404 => 'Arhitector\Yandex\Client\Exception\NotFoundException',
/**
* Ресурс не может быть представлен в запрошенном формате (Not Acceptable).
*/
406 => 'Arhitector\Yandex\Disk\Exception\UnsupportedException',
/**
* Конфликт путей/имён.
*/
409 => [
/**
* Указанного пути не существует.
*/
'DiskPathDoesntExistsError' => 'Arhitector\Yandex\Client\Exception\NotFoundException',
/**
* Ресурс уже существует
*/
'DiskResourceAlreadyExistsError' => 'Arhitector\Yandex\Disk\Exception\AlreadyExistsException',
/**
* Уже существует папка с таким именем.
*/
'DiskPathPointsToExistentDirectoryError' => 'Arhitector\Yandex\Disk\Exception\AlreadyExistsException'
],
/**
* Ресурс не может быть представлен в запрошенном формате (Unsupported Media Type).
*/
415 => 'Arhitector\Yandex\Client\Exception\UnsupportedException',
/**
* Ресурс заблокирован (Locked).
* Возможно, над ним выполняется другая операция.
*/
423 => 'Arhitector\Yandex\Client\Exception\ForbiddenException',
/**
* Слишком много запросов(Too Many Requests).
*/
429 => 'Arhitector\Yandex\Client\Exception\ForbiddenException',
/**
* Сервис временно недоступен(Service Unavailable).
*/
503 => 'Arhitector\Yandex\Client\Exception\ServiceException',
/**
* Недостаточно свободного места (Insufficient Storage).
*/
507 => 'Arhitector\Yandex\Disk\Exception\OutOfSpaceException'
];
/**
* @var array идентификаторы операций за сессию
*/
protected $operations = [];
/**
* @var string имя класса коллекции ресурсов
*/
protected $collectionClass = Disk\Resource\Collection::class;
/**
* Конструктор
*
* @param mixed $token маркер доступа
*
* @throws \InvalidArgumentException
*
* @example
*
* new Disk('token')
* new Disk() -> setAccessToken('token')
* new Disk( new Client('token') )
*/
public function __construct($token = null)
{
$this->setEmitter(new Emitter);
if ($token instanceof AbstractClient) {
$token = $token->getAccessToken();
}
parent::__construct($token);
}
/**
* Получает информацию о диске
*
* @param array $allowed
*
* @return array
* @example
*
* array (size=5)
* 'trash_size' => int 9449304
* 'total_space' => float 33822867456
* 'used_space' => float 25863284099
* 'free_space' => float 7959583357
* 'system_folders' => array (size=2)
* 'applications' => string 'disk:/Приложения' (length=26)
* 'downloads' => string 'disk:/Загрузки/' (length=23)
*/
public function toArray(array $allowed = null)
{
if (!$this->_toArray()) {
$response = $this->send(new Request($this->uri, 'GET'));
if ($response->getStatusCode() == 200) {
$response = json_decode($response->getBody(), true);
if (!is_array($response)) {
throw new UnsupportedException('Получен не поддерживаемый формат ответа от API Диска.');
}
$this->setContents($response += [
'free_space' => $response['total_space'] - $response['used_space']
]);
}
}
return $this->_toArray($allowed);
}
/**
* Работа с ресурсами на диске
*
* @param string $path Путь к новому либо уже существующему ресурсу
* @param integer $limit
* @param integer $offset
*
* @return \Arhitector\Yandex\Disk\Resource\Closed
*
* @example
*
* $disk->getResource('any_file.ext') -> upload( __DIR__.'/file_to_upload');
* $disk->getResource('any_file.ext') // Mackey\Yandex\Disk\Resource\Closed
* ->toArray(); // если ресурса еще нет, то исключение NotFoundException
*
* array (size=11)
* 'public_key' => string 'wICbu9SPnY3uT4tFA6P99YXJwuAr2TU7oGYu1fTq68Y=' (length=44)
* 'name' => string 'Gameface - Gangsigns_trapsound.ru.mp3' (length=37)
* 'created' => string '2014-10-08T22:13:49+00:00' (length=25)
* 'public_url' => string 'https://yadi.sk/d/g0N4hNtXcrq22' (length=31)
* 'modified' => string '2014-10-08T22:13:49+00:00' (length=25)
* 'media_type' => string 'audio' (length=5)
* 'path' => string 'disk:/applications_swagga/1/Gameface - Gangsigns_trapsound.ru.mp3' (length=65)
* 'md5' => string '8c2559f3ce1ece12e749f9e5dfbda59f' (length=32)
* 'type' => string 'file' (length=4)
* 'mime_type' => string 'audio/mpeg' (length=10)
* 'size' => int 8099883
*/
public function getResource($path, $limit = 20, $offset = 0)
{
if (!is_string($path)) {
throw new \InvalidArgumentException('Ресурс, должен быть строкового типа - путь к файлу/папке.');
}
if (stripos($path, 'app:/') !== 0 && stripos($path, 'disk:/') !== 0) {
$path = 'disk:/' . ltrim($path, ' /');
}
return (new Disk\Resource\Closed($path, $this, $this->uri))
->setLimit($limit, $offset);
}
/**
* Список всех файлов.
*
* @param int $limit
* @param int $offset
*
* @return \Arhitector\Yandex\Disk\Resource\Collection
*
* @example
*
* $disk->getResources(100, 0) // Arhitector\Yandex\Disk\Resource\Collection
* ->toArray();
*
* array (size=2)
* 0 => object(Arhitector\Yandex\Disk\Resource\Closed)[30]
* .....
*/
public function getResources($limit = 20, $offset = 0)
{
$callback = function ($parameters) {
$response = $this->send(
new Request(
$this->uri
->withPath($this->uri->getPath() . 'resources/files')
->withQuery(http_build_query($parameters, '', '&')),
'GET'
)
);
if ($response->getStatusCode() == 200) {
$response = json_decode($response->getBody(), true);
if (isset($response['items'])) {
return array_map(function ($item) {
return new Disk\Resource\Closed($item, $this, $this->uri);
}, $response['items']);
}
}
return [];
};
return (new $this->collectionClass($callback))->setLimit($limit, $offset);
}
/**
* Работа с опубликованными ресурсами
*
* @param mixed $public_key Публичный ключ к опубликованному ресурсу.
*
* @return \Arhitector\Yandex\Disk\Resource\Opened
*
* @example
*
* $disk->getPublishResource('public_key') -> toArray()
*
* array (size=11)
* 'public_key' => string 'wICbu9SPnY3uT4tFA6P99YXJwuAr2TU7oGYu1fTq68Y=' (length=44)
* 'name' => string 'Gameface - Gangsigns_trapsound.ru.mp3' (length=37)
* 'created' => string '2014-10-08T22:13:49+00:00' (length=25)
* 'public_url' => string 'https://yadi.sk/d/g0N4hNtXcrq22' (length=31)
* 'modified' => string '2014-10-08T22:13:49+00:00' (length=25)
* 'media_type' => string 'audio' (length=5)
* 'path' => string 'disk:/applications_swagga/1/Gameface - Gangsigns_trapsound.ru.mp3' (length=65)
* 'md5' => string '8c2559f3ce1ece12e749f9e5dfbda59f' (length=32)
* 'type' => string 'file' (length=4)
* 'mime_type' => string 'audio/mpeg' (length=10)
* 'size' => int 8099883
*/
public function getPublishResource($public_key, $limit = 20, $offset = 0)
{
if (!is_string($public_key)) {
throw new \InvalidArgumentException('Публичный ключ ресурса должен быть строкового типа.');
}
return (new Disk\Resource\Opened($public_key, $this, $this->uri))
->setLimit($limit, $offset);
}
/**
* Получение списка опубликованных файлов и папок
*
* @param int $limit
* @param int $offset
*
* @return \Arhitector\Yandex\Disk\Resource\Collection
*/
public function getPublishResources($limit = 20, $offset = 0)
{
$callback = function ($parameters) {
$previous = $this->setAccessTokenRequired(true);
$response = $this->send(
new Request(
$this->uri
->withPath($this->uri->getPath() . 'resources/public')
->withQuery(http_build_query($parameters, '', '&')),
'GET'
)
);
$this->setAccessTokenRequired($previous);
if ($response->getStatusCode() == 200) {
$response = json_decode($response->getBody(), true);
if (isset($response['items'])) {
return array_map(function ($item) {
return new Disk\Resource\Opened($item, $this, $this->uri);
}, $response['items']);
}
}
return [];
};
return (new $this->collectionClass($callback))->setLimit($limit, $offset);
}
/**
* Ресурсы в корзине.
*
* @param string $path путь к файлу в корзине
* @param int $limit
* @param int $offset
*
* @return \Arhitector\Yandex\Disk\Resource\Removed
* @example
*
* $disk->getTrashResource('file.ext') -> toArray() // файл в корзине
* $disk->getTrashResource('trash:/file.ext') -> delete()
*/
public function getTrashResource($path, $limit = 20, $offset = 0)
{
if (!is_string($path)) {
throw new \InvalidArgumentException('Ресурс, должен быть строкового типа - путь к файлу/папке, либо NULL');
}
if (stripos($path, 'trash:/') === 0) {
$path = substr($path, 7);
}
return (new Disk\Resource\Removed('trash:/' . ltrim($path, ' /'), $this, $this->uri))
->setLimit($limit, $offset);
}
/**
* Содержимое всей корзины.
*
* @param int $limit
* @param int $offset
*
* @return \Arhitector\Yandex\Disk\Resource\Collection
*/
public function getTrashResources($limit = 20, $offset = 0)
{
$callback = function ($parameters) {
if (
!empty($parameters['sort'])
&& !in_array($parameters['sort'], ['deleted', 'created', '-deleted', '-created'], true)
) {
throw new \UnexpectedValueException('Допустимые значения сортировки - deleted, created и со знаком "минус".');
}
$response = $this->send(
new Request(
$this->uri
->withPath($this->uri->getPath() . 'trash/resources')
->withQuery(http_build_query($parameters + ['path' => 'trash:/'], '', '&')),
'GET'
)
);
if ($response->getStatusCode() == 200) {
$response = json_decode($response->getBody(), true);
if (isset($response['_embedded']['items'])) {
return array_map(function ($item) {
return new Disk\Resource\Removed($item, $this, $this->uri);
}, $response['_embedded']['items']);
}
}
return [];
};
return (new $this->collectionClass($callback))->setSort('created')->setLimit($limit, $offset);
}
/**
* Очистить корзину.
*
* @return bool|\Arhitector\Yandex\Disk\Operation
*/
public function cleanTrash()
{
$response = $this->send(new Request($this->uri->withPath($this->uri->getPath() . 'trash/resources'), 'DELETE'));
if ($response->getStatusCode() == 204) {
$response = json_decode($response->getBody(), true);
if (!empty($response['operation'])) {
return $response['operation'];
}
return true;
}
return false;
}
/**
* Последние загруженные файлы
*
* @param int $limit
* @param int $offset
*
* @return \Arhitector\Yandex\Disk\Resource\Collection
*
* @example
*
* $disk->uploaded(limit, offset) // коллекия закрытых ресурсов
*/
public function uploaded($limit = 20, $offset = 0)
{
$callback = function ($parameters) {
$response = $this->send(
new Request(
$this->uri
->withPath($this->uri->getPath() . 'resources/last-uploaded')
->withQuery(http_build_query($parameters, '', '&')),
'GET'
)
);
if ($response->getStatusCode() == 200) {
$response = json_decode($response->getBody(), true);
if (isset($response['items'])) {
return array_map(function ($item) {
return new Disk\Resource\Closed($item, $this, $this->uri);
}, $response['items']);
}
}
return [];
};
return (new $this->collectionClass($callback))->setLimit($limit, $offset);
}
/**
* Получить статус операции.
*
* @param string $identifier идентификатор операции или NULL
*
* @return \Arhitector\Yandex\Disk\Operation
*
* @example
*
* $disk->getOperation('identifier operation')
*/
public function getOperation($identifier)
{
return new Disk\Operation($identifier, $this, $this->getUri());
}
/**
* Возвращает количество асинхронных операций экземпляра.
*
* @return int
*/
#[\ReturnTypeWillChange]
public function count()
{
return sizeof($this->getOperations());
}
/**
* Получить все операции, полученные во время выполнения сценария
*
* @return array
*
* @example
*
* $disk->getOperations()
*
* array (size=124)
* 0 => 'identifier_1',
* 1 => 'identifier_2',
* 2 => 'identifier_3',
*/
public function getOperations()
{
return $this->operations;
}
/**
* Отправляет запрос.
*
* @param \Psr\Http\Message\RequestInterface $request
*
* @return \Psr\Http\Message\ResponseInterface
*/
public function send(RequestInterface $request)
{
$response = parent::send($request);
if ($response->getStatusCode() == 202) {
if (($responseBody = json_decode($response->getBody(), true)) && isset($responseBody['href'])) {
$operation = new Uri($responseBody['href']);
if (!$operation->getQuery()) {
$responseBody['operation'] = substr(strrchr($operation->getPath(), '/'), 1);
$stream = new Stream('php://temp', 'w');
$stream->write(json_encode($responseBody));
$this->addOperation($responseBody['operation']);
return $response->withBody($stream);
}
}
}
return $response;
}
/**
* Этот экземпляр используется в качестве обёртки
*
* @return boolean
*/
public function isWrapper()
{
//return in_array(\Mackey\Yandex\Disk\Stream\Wrapper::SCHEME, stream_get_wrappers());
return false;
}
/**
* Добавляет идентификатор операции в список.
*
* @param $identifier
*
* @return \Arhitector\Yandex\Disk
*/
protected function addOperation($identifier)
{
$this->operations[] = $identifier;
return $this;
}
}
| php | MIT | 49f51b32f76cbfd123bb9fad7fdc63619121a884 | 2026-01-05T05:17:32.521772Z | false |
jack-theripper/yandex | https://github.com/jack-theripper/yandex/blob/49f51b32f76cbfd123bb9fad7fdc63619121a884/src/AbstractClient.php | src/AbstractClient.php | <?php
/**
* Часть библиотеки для работы с сервисами Яндекса
*
* @package Arhitector\Yandex
* @version 2.0
* @author Arhitector
* @license MIT License
* @copyright 2016 Arhitector
* @link https://github.com/jack-theripper
*/
namespace Arhitector\Yandex;
use Arhitector\Yandex\Client\Exception\ServiceException;
use Arhitector\Yandex\Client\HttpClient;
use Arhitector\Yandex\Client\Stream\Factory;
use Http\Client\Common\Plugin\RedirectPlugin;
use Http\Client\Common\PluginClient;
use Http\Message\MessageFactory\DiactorosMessageFactory;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Laminas\Diactoros\Uri;
/**
* Базовый клиент, реализует способы аунтифиации
*
* @package Arhitector\Yandex
*/
abstract class AbstractClient
{
/**
* @const адрес API
*/
const API_BASEPATH = 'https://oauth.yandex.ru/';
/**
* @var \Psr\Http\Message\UriInterface
*/
protected $uri;
/**
* @var \HTTP\Client\HttpClient клиент
*/
protected $client;
/**
* @var string формат обмена данными
*/
protected $contentType = 'application/json; charset=utf-8';
/**
* @var array соответствие кодов ответа к типу исключения
*/
protected $exceptions = [
/**
* Не авторизован.
*/
401 => 'Arhitector\Yandex\Client\Exception\UnauthorizedException',
/**
* Доступ запрещён. Возможно, у приложения недостаточно прав для данного действия.
*/
403 => 'Arhitector\Yandex\Client\Exception\ForbiddenException',
/**
* Не удалось найти запрошенный ресурс.
*/
404 => 'Arhitector\Yandex\Client\Exception\NotFoundException'
];
/**
* @var string для обращения к API требуется маркер доступа
*/
protected $tokenRequired = true;
/**
* Конструктор
*/
public function __construct()
{
$this->uri = new Uri(static::API_BASEPATH);
$this->client = new PluginClient(new HttpClient(new DiactorosMessageFactory, new Factory, [
CURLOPT_SSL_VERIFYPEER => false
]), [
new RedirectPlugin
]);
}
/**
* Текущий Uri
*
* @return \Psr\Http\Message\UriInterface|Uri
*/
public function getUri()
{
return $this->uri;
}
/**
* Провести аунтификацию в соостветствии с типом сервиса
*
* @param \Psr\Http\Message\RequestInterface $request
*
* @return \Psr\Http\Message\RequestInterface
*/
abstract protected function authentication(RequestInterface $request);
/**
* Формат обмена данными
*
* @return string
*/
public function getContentType()
{
return $this->contentType;
}
/**
* Модифицирует и отправляет запрос.
*
* @param \Psr\Http\Message\RequestInterface $request
*
* @return \Psr\Http\Message\ResponseInterface
*/
public function send(RequestInterface $request)
{
$request = $this->authentication($request);
$defaultHeaders = [
'Accept' => $this->getContentType(),
'Content-Type' => $this->getContentType()
];
foreach ($defaultHeaders as $defaultHeader => $value) {
if (!$request->hasHeader($defaultHeader)) {
$request = $request->withHeader($defaultHeader, $value);
}
}
$response = $this->client->sendRequest($request);
$response = $this->transformResponseToException($request, $response);
return $response;
}
/**
* Устаналивает необходимость токена при запросе.
*
* @param $tokenRequired
*
* @return boolean возвращает предыдущее состояние
*/
protected function setAccessTokenRequired($tokenRequired)
{
$previous = $this->tokenRequired;
$this->tokenRequired = (bool) $tokenRequired;
return $previous;
}
/**
* Трансформирует ответ в исключения
*
* @param \Psr\Http\Message\RequestInterface $request
* @param \Psr\Http\Message\ResponseInterface $response
*
* @return \Psr\Http\Message\ResponseInterface если статус код не является ошибочным, то вернуть объект ответа
* @throws \Arhitector\Yandex\Client\Exception\ServiceException
*/
protected function transformResponseToException(RequestInterface $request, ResponseInterface $response)
{
if ($response->getStatusCode() >= 400 && $response->getStatusCode() < 500) {
throw new \RuntimeException($response->getReasonPhrase(), $response->getStatusCode());
}
if ($response->getStatusCode() >= 500 && $response->getStatusCode() < 600) {
throw new ServiceException($response->getReasonPhrase(), $response->getStatusCode());
}
return $response;
}
}
| php | MIT | 49f51b32f76cbfd123bb9fad7fdc63619121a884 | 2026-01-05T05:17:32.521772Z | false |
jack-theripper/yandex | https://github.com/jack-theripper/yandex/blob/49f51b32f76cbfd123bb9fad7fdc63619121a884/src/Client/HttpClient.php | src/Client/HttpClient.php | <?php
/**
* Часть библиотеки для работы с сервисами Яндекса
*
* @package Arhitector\Yandex\Client
* @version 2.0
* @author Arhitector
* @license MIT License
* @copyright 2016 Arhitector
* @link https://github.com/jack-theripper
*/
namespace Arhitector\Yandex\Client;
use Http\Client\Curl\CurlPromise;
use Http\Client\Curl\MultiRunner;
use Http\Client\Curl\PromiseCore;
use Http\Client\Curl\ResponseBuilder;
use Http\Client\Exception;
use Http\Client\Exception\RequestException;
use Http\Client\HttpClient as HttpClientInterface;
use Http\Client\HttpAsyncClient as HttpAsyncClientInterface;
use Http\Message\MessageFactory;
use Http\Message\StreamFactory;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
/**
* PSR-7 compatible cURL based HTTP client
*/
class HttpClient implements HttpClientInterface, HttpAsyncClientInterface
{
/**
* @access private
*/
const DEPENDENCY_MSG = 'You should either provide $%s argument or install "php-http/discovery"';
/**
* cURL options
*
* @var array
*/
protected $options;
/**
* PSR-7 message factory
*
* @var MessageFactory
*/
protected $messageFactory;
/**
* PSR-7 stream factory
*
* @var StreamFactory
*/
protected $streamFactory;
/**
* cURL synchronous requests handle
*
* @var resource|null
*/
protected $handle = null;
/**
* Simultaneous requests runner
*
* @var MultiRunner|null
*/
protected $multiRunner = null;
/**
* Create new client
*
* @param MessageFactory $messageFactory HTTP Message factory
* @param StreamFactory $streamFactory HTTP Stream factory
* @param array $options cURL options (see http://php.net/curl_setopt)
*
* @throws \LogicException If some factory not provided and php-http/discovery not installed
*/
public function __construct(MessageFactory $messageFactory, StreamFactory $streamFactory, array $options = [])
{
$this->handle = curl_init();
$this->messageFactory = $messageFactory;
$this->streamFactory = $streamFactory;
$this->options = $options;
}
/**
* Release resources if still active
*/
public function __destruct()
{
if (is_resource($this->handle))
{
curl_close($this->handle);
}
}
/**
* Sends a PSR-7 request and returns a PSR-7 response.
*
* @param RequestInterface $request
*
* @return ResponseInterface
*
* @throws \RuntimeException If creating the body stream fails.
* @throws \UnexpectedValueException if unsupported HTTP version requested
* @throws RequestException
*/
public function sendRequest(RequestInterface $request): ResponseInterface
{
$responseBuilder = $this->createResponseBuilder();
$options = $this->createCurlOptions($request, $responseBuilder);
curl_reset($this->handle);
curl_setopt_array($this->handle, $options);
curl_exec($this->handle);
if (curl_errno($this->handle) > 0) {
throw new RequestException(curl_error($this->handle), $request);
}
$response = $responseBuilder->getResponse();
$response->getBody()->seek(0);
return $response;
}
/**
* Sends a PSR-7 request in an asynchronous way.
*
* @param RequestInterface $request
*
* @return Promise
*
* @throws \RuntimeException If creating the body stream fails.
* @throws \UnexpectedValueException If unsupported HTTP version requested
* @throws Exception
*
* @since 1.0
*/
public function sendAsyncRequest(RequestInterface $request)
{
if ( ! $this->multiRunner instanceof MultiRunner)
{
$this->multiRunner = new MultiRunner();
}
$handle = curl_init();
$responseBuilder = $this->createResponseBuilder();
$options = $this->createCurlOptions($request, $responseBuilder);
curl_setopt_array($handle, $options);
$core = new PromiseCore($request, $handle, $responseBuilder);
$promise = new CurlPromise($core, $this->multiRunner);
$this->multiRunner->add($core);
return $promise;
}
/**
* Generates cURL options
*
* @param RequestInterface $request
* @param ResponseBuilder $responseBuilder
*
* @throws \UnexpectedValueException if unsupported HTTP version requested
* @throws \RuntimeException if can not read body
*
* @return array
*/
protected function createCurlOptions(RequestInterface $request, ResponseBuilder $responseBuilder)
{
$options = array_diff_key($this->options, array_flip([CURLOPT_INFILE, CURLOPT_INFILESIZE]));
$options[CURLOPT_HTTP_VERSION] = $this->getCurlHttpVersion($request->getProtocolVersion());
$options[CURLOPT_HEADERFUNCTION] = function ($ch, $data) use ($responseBuilder) {
$str = trim($data);
if ('' !== $str)
{
if (strpos(strtolower($str), 'http/') === 0)
{
$responseBuilder->setStatus($str)->getResponse();
}
else
{
$responseBuilder->addHeader($str);
}
}
return strlen($data);
};
$options[CURLOPT_CUSTOMREQUEST] = $request->getMethod();
$options[CURLOPT_URL] = (string) $request->getUri();
$options[CURLOPT_HEADER] = false;
if (in_array($request->getMethod(), ['GET', 'HEAD', 'TRACE', 'CONNECT']))
{
if ($request->getMethod() == 'HEAD')
{
$options[CURLOPT_NOBODY] = true;
unset($options[CURLOPT_READFUNCTION], $options[CURLOPT_WRITEFUNCTION]);
}
}
else
{
$options = $this->createCurlBody($request, $options);
}
$options[CURLOPT_WRITEFUNCTION] = function ($ch, $data) use ($responseBuilder) {
return $responseBuilder->getResponse()->getBody()->write($data);
};
$options[CURLOPT_HTTPHEADER] = $this->createHeaders($request, $options);
if ($request->getUri()->getUserInfo())
{
$options[CURLOPT_USERPWD] = $request->getUri()->getUserInfo();
}
$options[CURLOPT_FOLLOWLOCATION] = false;
return $options;
}
/**
* Create headers array for CURLOPT_HTTPHEADER
*
* @param RequestInterface $request
* @param array $options cURL options
*
* @return string[]
*/
protected function createHeaders(RequestInterface $request, array $options)
{
$headers = [];
$body = $request->getBody();
$size = $body->getSize();
foreach ($request->getHeaders() as $header => $values)
{
foreach ((array) $values as $value)
{
$headers[] = sprintf('%s: %s', $header, $value);
}
}
if ( ! $request->hasHeader('Transfer-Encoding') && $size === null)
{
$headers[] = 'Transfer-Encoding: chunked';
}
if ( ! $request->hasHeader('Expect') && in_array($request->getMethod(), ['POST', 'PUT']))
{
if ($request->getProtocolVersion() < 2.0 && ! $body->isSeekable() || $size === null || $size > 1048576)
{
$headers[] = 'Expect: 100-Continue';
}
else
{
$headers[] = 'Expect: ';
}
}
return $headers;
}
/**
* Create body
*
* @param RequestInterface $request
* @param array $options
*
* @return array
*/
protected function createCurlBody(RequestInterface $request, array $options)
{
$body = clone $request->getBody();
$size = $body->getSize();
// Avoid full loading large or unknown size body into memory. It doesn't replace "CURLOPT_READFUNCTION".
if ($size === null || $size > 1048576)
{
if ($body->isSeekable())
{
$body->rewind();
}
$options[CURLOPT_UPLOAD] = true;
if (isset($options[CURLOPT_READFUNCTION]) && is_callable($options[CURLOPT_READFUNCTION]))
{
$body = $body->detach();
$options[CURLOPT_READFUNCTION] = function($curl_handler, $handler, $length) use ($body, $options) {
return call_user_func($options[CURLOPT_READFUNCTION], $curl_handler, $body, $length);
};
}
else
{
$options[CURLOPT_READFUNCTION] = function($curl, $handler, $length) use ($body) {
return $body->read($length);
};
}
}
else
{
$options[CURLOPT_POSTFIELDS] = (string) $request->getBody();
}
return $options;
}
/**
* Return cURL constant for specified HTTP version
*
* @param string $version
*
* @throws \UnexpectedValueException if unsupported version requested
*
* @return int
*/
protected function getCurlHttpVersion($version)
{
if ($version == '1.1')
{
return CURL_HTTP_VERSION_1_1;
}
else
{
if ($version == '2.0')
{
if ( ! defined('CURL_HTTP_VERSION_2_0'))
{
throw new \UnexpectedValueException('libcurl 7.33 needed for HTTP 2.0 support');
}
return CURL_HTTP_VERSION_2_0;
}
else
{
return CURL_HTTP_VERSION_1_0;
}
}
}
/**
* Create new ResponseBuilder instance
*
* @return ResponseBuilder
*
* @throws \RuntimeException If creating the stream from $body fails.
*/
protected function createResponseBuilder()
{
try
{
$body = $this->streamFactory->createStream(fopen('php://temp', 'w+'));
}
catch (\InvalidArgumentException $e)
{
throw new \RuntimeException('Can not create "php://temp" stream.');
}
$response = $this->messageFactory->createResponse(200, null, [], $body);
return new ResponseBuilder($response);
}
} | php | MIT | 49f51b32f76cbfd123bb9fad7fdc63619121a884 | 2026-01-05T05:17:32.521772Z | false |
jack-theripper/yandex | https://github.com/jack-theripper/yandex/blob/49f51b32f76cbfd123bb9fad7fdc63619121a884/src/Client/OAuth.php | src/Client/OAuth.php | <?php
/**
* Часть библиотеки для работы с сервисами Яндекса
*
* @package Arhitector\Yandex\Client
* @version 2.0
* @author Arhitector
* @license MIT License
* @copyright 2016 Arhitector
* @link https://github.com/jack-theripper
*/
namespace Arhitector\Yandex\Client;
use Arhitector\Yandex\AbstractClient;
use Arhitector\Yandex\Client\Exception\UnauthorizedException;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Laminas\Diactoros\Request;
/**
* Клиент для Access Token
*
* @package Arhitector\Yandex\Client
*/
class OAuth extends AbstractClient
{
/**
* @var string OAuth-токен
*/
protected $token = null;
/**
* @var string ID приложения
*/
private $clientOauth;
/**
* @var string пароль приложения
*/
private $clientOauthSecret = null;
/**
* Конструктор
*
* @param string $token OAuth-токен
*
* @throws \InvalidArgumentException
*/
public function __construct($token = null)
{
parent::__construct();
if ($token !== null) {
$this->setAccessToken($token);
}
}
/**
* Устанавливает ID приложения
*
* @param string $client_id
*
* @return $this
* @throws \InvalidArgumentException
*/
public function setClientOauth($client_id)
{
if (!is_string($client_id)) {
throw new \InvalidArgumentException('ID приложения https://oauth.yandex.ru должен быть строкового типа.');
}
$this->clientOauth = $client_id;
return $this;
}
/**
* Возвращает ID приложения
*
* @return string
*/
public function getClientOauth()
{
return $this->clientOauth;
}
/**
* Устанавливает пароль приложения
*
* @param string $client_secret
*
* @return $this
* @throws \InvalidArgumentException
*/
public function setClientOauthSecret($client_secret)
{
if (!is_string($client_secret)) {
throw new \InvalidArgumentException('Пароль приложения https://oauth.yandex.ru должен быть строкового типа.');
}
$this->clientOauthSecret = $client_secret;
return $this;
}
/**
* Возвращает пароль приложения
*
* @return string
*/
public function getClientOauthSecret()
{
return $this->clientOauthSecret;
}
/**
* Устанавливает OAuth-токен.
*
* @param string $token
*
* @return $this
* @throws \InvalidArgumentException
*/
public function setAccessToken($token)
{
if (!is_string($token)) {
throw new \InvalidArgumentException('OAuth-токен должен быть строкового типа.');
}
$this->token = $token;
return $this;
}
/**
* Получает установленный токен
*
* @return string
*/
public function getAccessToken()
{
return (string) $this->token;
}
/**
* Запрашивает или обновляет токен
*
* @param string $username имя пользователя yandex
* @param string $password пароль от аккаунта
* @param bool $onlyToken вернуть только строковый токен
*
* @return object|string
* @throws UnauthorizedException
* @throws \Exception
* @example
*
* $client->refreshAccessToken('username', 'password');
*
* object(stdClass)[28]
* public 'token_type' => string 'bearer' (length=6)
* public 'access_token' => string 'c7621`6b09032dwf9a6a7ca765eb39b8' (length=32)
* public 'expires_in' => int 31536000
* public 'uid' => int 241`68329
* public 'created_at' => int 1456882032
*
* @example
*
* $client->refreshAccessToken('username', 'password', true);
*
* string 'c7621`6b09032dwf9a6a7ca765eb39b8' (length=32)
*/
public function refreshAccessToken($username, $password, $onlyToken = false)
{
if (!is_scalar($username) || !is_scalar($password)) {
throw new \InvalidArgumentException('Параметры "имя пользователя" и "пароль" должны быть простого типа.');
}
$previous = $this->setAccessTokenRequired(false);
$request = new Request(rtrim(self::API_BASEPATH, ' /') . '/token', 'POST');
$request->getBody()
->write(http_build_query([
'grant_type' => 'password',
'client_id' => $this->getClientOauth(),
'client_secret' => $this->getClientOauthSecret(),
'username' => (string) $username,
'password' => (string) $password
]));
try {
$response = json_decode($this->send($request)->wait()->getBody());
if ($onlyToken) {
return (string) $response->access_token;
}
$response->created_at = time();
return $response;
} catch (\Exception $exc) {
$response = json_decode($exc->getMessage());
if (isset($response->error_description)) {
throw new UnauthorizedException($response->error_description);
}
throw $exc;
} finally {
$this->setAccessTokenRequired($previous);
}
}
/**
* Провести аунтификацию в соостветствии с типом сервиса
*
* @param \Psr\Http\Message\RequestInterface $request
*
* @return \Psr\Http\Message\RequestInterface
*/
protected function authentication(RequestInterface $request)
{
if ($this->tokenRequired) {
return $request->withHeader('Authorization', sprintf('OAuth %s', $this->getAccessToken()));
}
return $request;
}
/**
* Трансформирует ответ в исключения.
* Ответ API, где использует OAuth, отличается от других сервисов.
*
* @param \Psr\Http\Message\RequestInterface $request
* @param \Psr\Http\Message\ResponseInterface $response
*
* @return \Psr\Http\Message\ResponseInterface если статус код не является ошибочным, то вернуть объект ответа
*/
protected function transformResponseToException(RequestInterface $request, ResponseInterface $response)
{
if (isset($this->exceptions[$response->getStatusCode()])) {
$exception = $this->exceptions[$response->getStatusCode()];
if (
$response->hasHeader('Content-Type')
&& stripos($response->getHeaderLine('Content-Type'), 'json') !== false
) {
$responseBody = json_decode($response->getBody(), true);
if (!isset($responseBody['message'])) {
$responseBody['message'] = (string) $response->getBody();
}
if (is_array($exception)) {
if (!isset($responseBody['error'], $exception[$responseBody['error']])) {
return parent::transformResponseToException($request, $response);
}
$exception = $exception[$responseBody['error']];
}
throw new $exception($responseBody['message'], $response->getStatusCode());
}
}
return parent::transformResponseToException($request, $response);
}
}
| php | MIT | 49f51b32f76cbfd123bb9fad7fdc63619121a884 | 2026-01-05T05:17:32.521772Z | false |
jack-theripper/yandex | https://github.com/jack-theripper/yandex/blob/49f51b32f76cbfd123bb9fad7fdc63619121a884/src/Client/SimpleKey.php | src/Client/SimpleKey.php | <?php
/**
* Часть библиотеки для работы с сервисами Яндекса
*
* @package Arhitector\Yandex\Client
* @version 2.0
* @author Arhitector
* @license MIT License
* @copyright 2016 Arhitector
* @link https://github.com/jack-theripper
*/
namespace Arhitector\Yandex\Client;
use Arhitector\Yandex\AbstractClient;
use Psr\Http\Message\RequestInterface;
/**
* Ключ API
*
* @package Arhitector\Yandex\Client
*/
class SimpleKey extends AbstractClient
{
/**
* @var string ключ API.
*/
protected $accessKey = null;
/**
* Конструктор
*
* @param string $accessKey ключ API.
*
* @throws \InvalidArgumentException
*/
public function __construct($accessKey = null)
{
parent::__construct();
if ($accessKey !== null)
{
$this->setAccessKey($accessKey);
}
}
/**
* Устанавливает ключ API.
*
* @param string $accessKey ключ API.
*
* @return $this
* @throws \InvalidArgumentException
*/
public function setAccessKey($accessKey)
{
if ( ! is_string($accessKey))
{
throw new \InvalidArgumentException('Ключ доступа должен быть строкового типа.');
}
$this->accessKey = $accessKey;
return $this;
}
/**
* Получает установленный ключ API.
*
* @return string
*/
public function getAccessKey()
{
return (string) $this->accessKey;
}
/**
* Провести аунтификацию в соостветствии с типом сервиса
*
* @param RequestInterface $request
*
* @return RequestInterface
*/
protected function authentication(RequestInterface $request)
{
$uri = $request->getUri();
$key = http_build_query(['key' => $this->getAccessKey()], '', '&');
if (strlen($uri->getQuery()) > 0)
{
$key = '&'.$key;
}
return $request->withUri($uri->withQuery($uri->getQuery().$key));
}
} | php | MIT | 49f51b32f76cbfd123bb9fad7fdc63619121a884 | 2026-01-05T05:17:32.521772Z | false |
jack-theripper/yandex | https://github.com/jack-theripper/yandex/blob/49f51b32f76cbfd123bb9fad7fdc63619121a884/src/Client/Container/Collection.php | src/Client/Container/Collection.php | <?php
/**
* Часть библиотеки для работы с сервисами Яндекса
*
* @package Arhitector\Yandex\Client
* @version 2.0
* @author Arhitector
* @license MIT License
* @copyright 2016 Arhitector
* @link https://github.com/jack-theripper
*/
namespace Arhitector\Yandex\Client\Container;
/**
* Коллекция на основе контейнера.
*
* @package Arhitector\Yandex\Client\Container
*/
class Collection implements \ArrayAccess, \IteratorAggregate, \Countable
{
use ContainerTrait;
/**
* Конструктор
*
* @param array $data данные
* @param boolean $readOnly только для чтения
*/
public function __construct(array $data = array(), $readOnly = false)
{
$this->setContents($data);
}
/**
* Получает первый элемент в списке
*
* @return mixed
*/
public function getFirst()
{
$elements = $this->toArray();
return reset($elements);
}
/**
* Получает последний элемент в списке
*
* @return \Arhitector\Yandex\Disk\AbstractResource
*/
public function getLast()
{
$elements = $this->toArray();
return end($elements);
}
} | php | MIT | 49f51b32f76cbfd123bb9fad7fdc63619121a884 | 2026-01-05T05:17:32.521772Z | false |
jack-theripper/yandex | https://github.com/jack-theripper/yandex/blob/49f51b32f76cbfd123bb9fad7fdc63619121a884/src/Client/Container/ContainerTrait.php | src/Client/Container/ContainerTrait.php | <?php
/**
* Часть библиотеки для работы с сервисами Яндекса
*
* @package Arhitector\Yandex\Client
* @version 2.0
* @author Arhitector
* @license MIT License
* @copyright 2016 Arhitector
* @link https://github.com/jack-theripper
*/
namespace Arhitector\Yandex\Client\Container;
/**
* Контейнер.
*
* @package Arhitector\Yandex\Client\Container
*/
trait ContainerTrait
{
/**
* @var array Контейнер данных.
*/
protected $store = [];
/**
* Countable
*
* @return integer Размер контейнера.
*/
#[\ReturnTypeWillChange]
public function count()
{
return count($this->toArray());
}
/**
* Получить данные контейнера в виде массива
*
* @param array $allowed получить только эти ключи
*
* @return array контейнер
*/
public function toArray(array $allowed = null)
{
$contents = $this->store;
if ($allowed !== null)
{
$contents = array_intersect_key($this->store, array_flip($allowed));
}
/*foreach ($contents as $index => $value)
{
if ($value instanceof Container || $value instanceof AbstractResource)
{
$contents[$index] = $value->toArray();
}
}*/
return $contents;
}
/**
* Получить данные контейнера в виде объекта
*
* @param array $allowed получить только эти ключи
*
* @return \stdClass контейнер
*/
public function toObject(array $allowed = null)
{
return (object) $this->toArray($allowed);
}
/**
* IteratorAggregate
*
* @return \IteratorAggregate итератор
*/
#[\ReturnTypeWillChange]
public function getIterator()
{
return new \ArrayIterator($this->toArray());
}
/**
* Магический метод isset
*
* @return boolean
*/
public function __isset($key)
{
return $this->has($key);
}
/**
* Проверить есть такой ключ в контейнере
*
* @param string $key
*
* @return bool
*/
public function has($key)
{
return $this->hasByIndex($key);
}
/**
* Поиск по индексу
*
* @param $index
*
* @return bool
*/
protected function hasByIndex($index)
{
return array_key_exists($index, $this->toArray());
}
/**
* Магический метод get
*
* @return mixed
*/
public function __get($key)
{
return $this->get($key);
}
/**
* Получить значение из контейнера по ключу
*
* @param string $index
* @param mixed $default Может быть функцией.
*
* @return mixed
*/
public function get($index, $default = null)
{
if ($this->hasByIndex($index))
{
return $this->store[$index];
}
if ($default instanceof \Closure)
{
return $default($this);
}
return $default;
}
/**
* Разрешает использование isset()
*
* @param string $key
*
* @return bool
*/
#[\ReturnTypeWillChange]
public function offsetExists($key)
{
return $this->has($key);
}
/**
* Разрешает доступ к ключам как к массиву
*
* @param string $key
*
* @return mixed
* @throws \OutOfBoundsException
*/
#[\ReturnTypeWillChange]
public function offsetGet($key)
{
return $this->get($key, function() use ($key) {
throw new \OutOfBoundsException('Индекс не существует '.$key);
});
}
/**
* Разрешает использование unset()
*
* @param string $key
*
* @return null
* @throws \RuntimeException
*/
#[\ReturnTypeWillChange]
public function offsetUnset($key)
{
return null;
}
/**
* Разрешает обновление свойств объекта как массива
*
* @param string $key
* @param mixed $value
*
* @return null
*/
#[\ReturnTypeWillChange]
public function offsetSet($key, $value)
{
return null;
}
/**
* Заменить все данные контейнера другими.
*
* @param array $content Новые данные.
*
* @return $this
*/
protected function setContents(array $content)
{
$this->store = $content;
return $this;
}
} | php | MIT | 49f51b32f76cbfd123bb9fad7fdc63619121a884 | 2026-01-05T05:17:32.521772Z | false |
jack-theripper/yandex | https://github.com/jack-theripper/yandex/blob/49f51b32f76cbfd123bb9fad7fdc63619121a884/src/Client/Stream/Progress.php | src/Client/Stream/Progress.php | <?php
/**
* Часть библиотеки для работы с сервисами Яндекса
*
* @package Arhitector\Yandex\Client\Stream
* @version 2.0
* @author Arhitector
* @license MIT License
* @copyright 2016 Arhitector
* @link https://github.com/jack-theripper
*/
namespace Arhitector\Yandex\Client\Stream;
use Laminas\Diactoros\Exception\UnseekableStreamException;
use League\Event\EmitterTrait;
use Psr\Http\Message\StreamInterface;
use Laminas\Diactoros\Stream;
/**
* Class Progress stream.
*
* @package Arhitector\Yandex\Client\Stream
*/
class Progress extends Stream implements StreamInterface
{
use EmitterTrait;
/**
* @var int Размер передаваемого тела.
*/
protected $totalSize = 0;
/**
* @var int Количество байт прочитанных из потока.
*/
protected $readSize = 0;
/**
* Progress constructor.
*
* @param resource|string $stream
* @param string $mode
*/
public function __construct($stream, $mode)
{
parent::__construct($stream, $mode);
$this->totalSize = $this->getSize();
}
/**
* Read data from the stream.
*
* @param int $length Read up to $length bytes from the object and return
* them. Fewer than $length bytes may be returned if underlying stream
* call returns fewer bytes.
*
* @return string Returns the data read from the stream, or an empty string
* if no bytes are available.
* @throws \RuntimeException if an error occurs.
*/
public function read($length): string
{
$this->readSize += $length;
$percent = round(100 / $this->totalSize * $this->readSize, 2);
$this->emit('progress', min(100.0, $percent));
return parent::read($length);
}
/**
* Returns the remaining contents in a string
*
* @return string
* @throws \RuntimeException if unable to read or an error occurs while
* reading.
*/
public function getContents(): string
{
$this->readSize = $this->totalSize;
$this->emit('progress', 100.0);
return parent::getContents();
}
/**
* Seek to a position in the stream.
*
* @param int $offset Stream offset
* @param int $whence Specifies how the cursor position will be calculated
* based on the seek offset. Valid values are identical to the built-in
* PHP $whence values for `fseek()`. SEEK_SET: Set position equal to
* offset bytes SEEK_CUR: Set position to current location plus offset
* SEEK_END: Set position to end-of-stream plus offset.
*
* @return void
* @throws \RuntimeException on failure.
*/
public function seek($offset, $whence = SEEK_SET): void
{
try {
parent::seek($offset, $whence); // <-- catch
$this->readSize = $offset;
} catch (UnseekableStreamException $exception) {
}
}
}
| php | MIT | 49f51b32f76cbfd123bb9fad7fdc63619121a884 | 2026-01-05T05:17:32.521772Z | false |
jack-theripper/yandex | https://github.com/jack-theripper/yandex/blob/49f51b32f76cbfd123bb9fad7fdc63619121a884/src/Client/Stream/Factory.php | src/Client/Stream/Factory.php | <?php
/**
* Часть библиотеки для работы с сервисами Яндекса
*
* @package Arhitector\Yandex\Client\Stream
* @version 2.0
* @author Arhitector
* @license MIT License
* @copyright 2016 Arhitector
* @link https://github.com/jack-theripper
*/
namespace Arhitector\Yandex\Client\Stream;
use Http\Message\StreamFactory;
use Psr\Http\Message\StreamInterface;
use Laminas\Diactoros\Stream;
/**
* Интерфейс для более эффективного управления потоками, нежели то, что предлагает http-php
*
* @package Arhitector\Yandex\Client\Stream
*/
class Factory implements StreamFactory
{
/**
* Create a new stream instance.
*
* @param StreamInterface $body
*
* @return null|\Laminas\Diactoros\Stream
* @throws \RuntimeException
* @throws \InvalidArgumentException
*/
public function createStream($body = null)
{
if (!$body instanceof StreamInterface) {
if (is_resource($body)) {
$body = new Stream($body);
} else {
$stream = new Stream('php://temp', 'rb+');
if (null !== $body) {
$stream->write((string) $body);
}
$body = $stream;
}
}
$body->rewind();
return $body;
}
}
| php | MIT | 49f51b32f76cbfd123bb9fad7fdc63619121a884 | 2026-01-05T05:17:32.521772Z | false |
jack-theripper/yandex | https://github.com/jack-theripper/yandex/blob/49f51b32f76cbfd123bb9fad7fdc63619121a884/src/Client/Exception/ForbiddenException.php | src/Client/Exception/ForbiddenException.php | <?php
/**
* Часть библиотеки для работы с сервисами Яндекса
*
* @package Arhitector\Yandex\Client\Exception
* @version 2.0
* @author Arhitector
* @license MIT License
* @copyright 2016 Arhitector
* @link https://github.com/jack-theripper
*/
namespace Arhitector\Yandex\Client\Exception;
use Http\Client\Exception;
/**
* Исключение доступ запрещён.
*/
class ForbiddenException extends \RuntimeException implements Exception
{
} | php | MIT | 49f51b32f76cbfd123bb9fad7fdc63619121a884 | 2026-01-05T05:17:32.521772Z | false |
jack-theripper/yandex | https://github.com/jack-theripper/yandex/blob/49f51b32f76cbfd123bb9fad7fdc63619121a884/src/Client/Exception/UnauthorizedException.php | src/Client/Exception/UnauthorizedException.php | <?php
/**
* Часть библиотеки для работы с сервисами Яндекса
*
* @package Arhitector\Yandex\Client\Exception
* @version 2.0
* @author Arhitector
* @license MIT License
* @copyright 2016 Arhitector
* @link https://github.com/jack-theripper
*/
namespace Arhitector\Yandex\Client\Exception;
use Http\Client\Exception;
/**
* Исключение не авторизован.
*/
class UnauthorizedException extends \RuntimeException implements Exception
{
/**
* Конструктор.
*
* @access public
*
* @param int $code Код исключения
* @param string $message Сообщение исключения
* @param \Exception $previous Предыдущее исключение
*/
public function __construct($message, $code = 401, \Exception $previous = null)
{
parent::__construct($message, $code, $previous);
}
} | php | MIT | 49f51b32f76cbfd123bb9fad7fdc63619121a884 | 2026-01-05T05:17:32.521772Z | false |
jack-theripper/yandex | https://github.com/jack-theripper/yandex/blob/49f51b32f76cbfd123bb9fad7fdc63619121a884/src/Client/Exception/NotFoundException.php | src/Client/Exception/NotFoundException.php | <?php
/**
* Часть библиотеки для работы с сервисами Яндекса
*
* @package Arhitector\Yandex\Client\Exception
* @version 2.0
* @author Arhitector
* @license MIT License
* @copyright 2016 Arhitector
* @link https://github.com/jack-theripper
*/
namespace Arhitector\Yandex\Client\Exception;
use Http\Client\Exception;
/**
* Исключение ресурс отсутствует.
*/
class NotFoundException extends \RuntimeException implements Exception
{
/**
* Конструктор.
*
* @access public
*
* @param int $code Код исключения
* @param string $message Сообщение исключения
* @param \Exception $previous Предыдущее исключение
*/
public function __construct($message, $code = null, \Exception $previous = null)
{
parent::__construct($message, 404, $previous);
}
} | php | MIT | 49f51b32f76cbfd123bb9fad7fdc63619121a884 | 2026-01-05T05:17:32.521772Z | false |
jack-theripper/yandex | https://github.com/jack-theripper/yandex/blob/49f51b32f76cbfd123bb9fad7fdc63619121a884/src/Client/Exception/ServiceException.php | src/Client/Exception/ServiceException.php | <?php
/**
* Часть библиотеки для работы с сервисами Яндекса
*
* @package Arhitector\Yandex\Client\Exception
* @version 2.0
* @author Arhitector
* @license MIT License
* @copyright 2016 Arhitector
* @link https://github.com/jack-theripper
*/
namespace Arhitector\Yandex\Client\Exception;
use Http\Client\Exception;
/**
* Исключение сервис недоступен.
*/
class ServiceException extends \RuntimeException implements Exception
{
} | php | MIT | 49f51b32f76cbfd123bb9fad7fdc63619121a884 | 2026-01-05T05:17:32.521772Z | false |
jack-theripper/yandex | https://github.com/jack-theripper/yandex/blob/49f51b32f76cbfd123bb9fad7fdc63619121a884/src/Client/Exception/UnsupportedException.php | src/Client/Exception/UnsupportedException.php | <?php
/**
* Часть библиотеки для работы с сервисами Яндекса
*
* @package Arhitector\Yandex\Client\Exception
* @version 2.0
* @author Arhitector
* @license MIT License
* @copyright 2016 Arhitector
* @link https://github.com/jack-theripper
*/
namespace Arhitector\Yandex\Client\Exception;
use Http\Client\Exception;
/**
* Исключение некорректные данные.
*/
class UnsupportedException extends \RuntimeException implements Exception
{
} | php | MIT | 49f51b32f76cbfd123bb9fad7fdc63619121a884 | 2026-01-05T05:17:32.521772Z | false |
jack-theripper/yandex | https://github.com/jack-theripper/yandex/blob/49f51b32f76cbfd123bb9fad7fdc63619121a884/src/Disk/Operation.php | src/Disk/Operation.php | <?php
/**
* Часть библиотеки для работы с сервисами Яндекса
*
* @package Arhitector\Yandex\Disk
* @version 2.0
* @author Arhitector
* @license MIT License
* @copyright 2016 Arhitector
* @link https://github.com/jack-theripper
*/
namespace Arhitector\Yandex\Disk;
use Arhitector\Yandex\Disk;
use Psr\Http\Message\UriInterface;
use Laminas\Diactoros\Request;
/**
* Получение информации об асинхронной операции.
*
* @package Arhitector\Yandex\Disk
*/
class Operation
{
/**
* @const успешно
*/
const SUCCESS = 'success';
/**
* @const выполняется
*/
const PENDING = 'in-progress';
/**
* @const неудача
*/
const FAILED = 'failed';
/**
* @var \Psr\Http\Message\UriInterface
*/
protected $uri;
/**
* @var \Arhitector\Yandex\Disk объект диска, породивший ресурс.
*/
protected $parent;
/**
* @var string идентификатор асинхронной операции.
*/
protected $identifier;
/**
* Конструктор.
*
* @param string $identifier идентификатор операции.
*/
public function __construct($identifier, Disk $disk, UriInterface $uri)
{
if (!is_string($identifier)) {
throw new \InvalidArgumentException('Ожидается строковый идентификатор асинхронной операции.');
}
$this->uri = $uri;
$this->parent = $disk;
$this->identifier = $identifier;
}
/**
* Текстовый статус операции.
*
* @return string|null NULL если не удалось получить статус.
*/
public function getStatus()
{
$response = $this->parent->send(new Request($this->uri->withPath($this->uri->getPath() . 'operations/'
. $this->getIdentifier()), 'GET'));
if ($response->getStatusCode() == 200) {
$response = json_decode($response->getBody(), true);
if (isset($response['status'])) {
return $response['status'];
}
}
return null;
}
/**
* Получает используемый идентификатор.
*
* @return string
*/
public function getIdentifier()
{
return $this->identifier;
}
/**
* Проверяет успешна ли операция.
*
* @return bool
*/
public function isSuccess()
{
return $this->getStatus() == self::SUCCESS;
}
/**
* Если операция завершилась неудачей.
*
* @return bool
*/
public function isFailure()
{
return $this->getStatus() != 'success';
}
/**
* Операция в процессе выполнения.
*
* @return bool
*/
public function isPending()
{
return $this->getStatus() == self::PENDING;
}
}
| php | MIT | 49f51b32f76cbfd123bb9fad7fdc63619121a884 | 2026-01-05T05:17:32.521772Z | false |
jack-theripper/yandex | https://github.com/jack-theripper/yandex/blob/49f51b32f76cbfd123bb9fad7fdc63619121a884/src/Disk/AbstractResource.php | src/Disk/AbstractResource.php | <?php
/**
* Часть библиотеки для работы с сервисами Яндекса
*
* @package Arhitector\Yandex\Disk
* @version 2.0
* @author Arhitector
* @license MIT License
* @copyright 2016 Arhitector
* @link https://github.com/jack-theripper
*/
namespace Arhitector\Yandex\Disk;
use Arhitector\Yandex\Client\Container\ContainerTrait;
use League\Event\EmitterTrait;
/**
* Базовый класс, описывающий ресурс.
*
* @package Arhitector\Yandex\Disk
*/
abstract class AbstractResource implements \ArrayAccess, \Countable, \IteratorAggregate
{
use ContainerTrait, FilterTrait, EmitterTrait {
toArray as protected _toArray;
has as hasProperty;
}
/**
* @var string Путь к ресурсу.
*/
protected $path;
/**
* @var \Psr\Http\Message\UriInterface
*/
protected $uri;
/**
* @var \Arhitector\Yandex\Disk объект диска, породивший ресурс.
*/
protected $client;
/**
* @var array допустимые фильтры.
*/
protected $parametersAllowed = ['limit', 'offset', 'preview_crop', 'preview_size', 'sort'];
/**
* Есть такой файл/папка на диске или свойство
*
* @param mixed $index
*
* @return bool
*/
public function has($index = null)
{
try
{
if ($this->toArray())
{
if ($index === null)
{
return true;
}
return $this->hasProperty($index);
}
}
catch (\Exception $exc)
{
}
return false;
}
/**
* Проверяет, является ли ресурс файлом
*
* @return bool
*/
public function isFile()
{
return $this->get('type', false) === 'file';
}
/**
* Проверяет, является ли ресурс папкой
*
* @return bool
*/
public function isDir()
{
return $this->get('type', false) === 'dir';
}
/**
* Проверяет, этот ресурс с открытым доступом или нет
*
* @return boolean
*/
public function isPublish()
{
return $this->has('public_key');
}
/**
* Получить путь к ресурсу
*
* @return string
*/
public function getPath()
{
return $this->path;
}
} | php | MIT | 49f51b32f76cbfd123bb9fad7fdc63619121a884 | 2026-01-05T05:17:32.521772Z | false |
jack-theripper/yandex | https://github.com/jack-theripper/yandex/blob/49f51b32f76cbfd123bb9fad7fdc63619121a884/src/Disk/FilterTrait.php | src/Disk/FilterTrait.php | <?php
/**
* Часть библиотеки для работы с сервисами Яндекса
*
* @package Arhitector\Yandex\Disk
* @version 2.0
* @author Arhitector
* @license MIT License
* @copyright 2016 Arhitector
* @link https://github.com/jack-theripper
*/
namespace Arhitector\Yandex\Disk;
use Arhitector\Yandex\Disk\Filter\PreviewTrait;
/**
* Опции, доступные при получении списка ресурсов.
* Эти фильтры используют возможности Яндекс.Диска.
*
* @package Arhitector\Yandex\Disk
*/
trait FilterTrait
{
use PreviewTrait;
/**
* @var array параметры в запросе
*/
protected $parameters = [];
/**
* @var bool были внесены изменения в параметры
*/
protected $isModified = false;
/**
* Количество ресурсов, вложенных в папку, описание которых следует вернуть в ответе
*
* @param integer $limit
* @param integer $offset установить смещение
*
* @return $this
*/
public function setLimit($limit, $offset = null)
{
if (filter_var($limit, FILTER_VALIDATE_INT) === false)
{
throw new \InvalidArgumentException('Параметр "limit" должен быть целым числом.');
}
$this->isModified = true;
$this->parameters['limit'] = (int) $limit;
if ($offset !== null)
{
$this->setOffset($offset);
}
return $this;
}
/**
* Количество вложенных ресурсов с начала списка, которые следует опустить в ответе
*
* @param integer $offset
*
* @return $this
*/
public function setOffset($offset)
{
if (filter_var($offset, FILTER_VALIDATE_INT) === false)
{
throw new \InvalidArgumentException('Параметр "offset" должен быть целым числом.');
}
$this->isModified = true;
$this->parameters['offset'] = (int) $offset;
return $this;
}
/**
* Атрибут, по которому сортируется список ресурсов, вложенных в папку.
*
* @param string $sort
* @param boolean $inverse TRUE чтобы сортировать в обратном порядке
*
* @return $this
* @throws \UnexpectedValueException
*/
public function setSort($sort, $inverse = false)
{
$sort = (string) $sort;
if ( ! in_array($sort, ['name', 'path', 'created', 'modified', 'size', 'deleted']))
{
throw new \UnexpectedValueException('Допустимые значения сортировки - name, path, created, modified, size');
}
if ($inverse)
{
$sort = '-'.$sort;
}
$this->isModified = true;
$this->parameters['sort'] = $sort;
return $this;
}
/**
* Возвращает все параметры
*
* @return array
*/
public function getParameters(array $allowed = null)
{
if ($allowed !== null)
{
return array_intersect_key($this->parameters, array_flip($allowed));
}
return $this->parameters;
}
/**
* Контейнер изменил состояние
*
* @return bool
*/
protected function isModified()
{
return (bool) $this->isModified;
}
} | php | MIT | 49f51b32f76cbfd123bb9fad7fdc63619121a884 | 2026-01-05T05:17:32.521772Z | false |
jack-theripper/yandex | https://github.com/jack-theripper/yandex/blob/49f51b32f76cbfd123bb9fad7fdc63619121a884/src/Disk/Resource/Collection.php | src/Disk/Resource/Collection.php | <?php
/**
* Часть библиотеки для работы с сервисами Яндекса
*
* @package Arhitector\Yandex\Disk
* @version 2.0
* @author Arhitector
* @license MIT License
* @copyright 2016 Arhitector
* @link https://github.com/jack-theripper
*/
namespace Arhitector\Yandex\Disk\Resource;
use Arhitector\Yandex\Client\Container\Collection as CollectionContainer;
use Arhitector\Yandex\Disk\Filter\MediaTypeTrait;
use Arhitector\Yandex\Disk\FilterTrait;
/**
* Коллекция ресурсов.
*
* @package Arhitector\Yandex\Disk\Resource
*/
class Collection extends CollectionContainer
{
use FilterTrait, MediaTypeTrait;
/**
* @var Callable
*/
protected $closure;
/**
* @var array какие параметры доступны для фильтра
*/
protected $parametersAllowed = ['limit', 'media_type', 'offset', 'preview_crop', 'preview_size', 'sort'];
/**
* Конструктор
*/
public function __construct(\Closure $data_closure = null)
{
$this->closure = $data_closure;
}
/**
* Получает информацию
*
* @return array
*/
public function toArray(array $allowed = null)
{
if ( ! parent::toArray() || $this->isModified())
{
$this->setContents(call_user_func($this->closure, $this->getParameters($this->parametersAllowed)));
$this->isModified = false;
}
return parent::toArray();
}
} | php | MIT | 49f51b32f76cbfd123bb9fad7fdc63619121a884 | 2026-01-05T05:17:32.521772Z | false |
jack-theripper/yandex | https://github.com/jack-theripper/yandex/blob/49f51b32f76cbfd123bb9fad7fdc63619121a884/src/Disk/Resource/Removed.php | src/Disk/Resource/Removed.php | <?php
/**
* Часть библиотеки для работы с сервисами Яндекса
*
* @package Arhitector\Yandex\Disk\Resource
* @version 2.0
* @author Arhitector
* @license MIT License
* @copyright 2016 Arhitector
* @link https://github.com/jack-theripper
*/
namespace Arhitector\Yandex\Disk\Resource;
use Arhitector\Yandex\Client\Container;
use Arhitector\Yandex\Disk;
use Arhitector\Yandex\Disk\AbstractResource;
use Laminas\Diactoros\Request;
/**
* Ресурс в корзине.
*
* @property-read string $name
* @property-read string $created
* @property-read string $deleted
* @property-read array|null $custom_properties
* @property-read string $origin_path
* @property-read string $modified
* @property-read string $media_type
* @property-read string $path
* @property-read string $md5
* @property-read string $type
* @property-read string $mime_type
* @property-read integer $size
*
* @package Arhitector\Yandex\Disk\Resource
*/
class Removed extends AbstractResource
{
/**
* Конструктор.
*
* @param string|array $path путь к ресурсу в корзине
* @param \Arhitector\Yandex\Disk $parent
* @param \Psr\Http\Message\UriInterface $uri
*/
public function __construct($path, Disk $parent, \Psr\Http\Message\UriInterface $uri)
{
if (is_array($path)) {
if (empty($path['path'])) {
throw new \InvalidArgumentException('Параметр "path" должен быть строкового типа.');
}
$this->setContents($path);
$path = $path['path'];
}
if (!is_scalar($path)) {
throw new \InvalidArgumentException('Параметр "path" должен быть строкового типа.');
}
$this->path = (string) $path;
$this->client = $parent;
$this->uri = $uri;
$this->setSort('created');
}
/**
* Получает информацию о ресурсе
*
* @return mixed
*/
public function toArray(array $allowed = null)
{
if (!$this->_toArray() || $this->isModified()) {
$response = $this->client->send((new Request($this->uri->withPath($this->uri->getPath() . 'trash/resources')
->withQuery(http_build_query(array_merge($this->getParameters($this->parametersAllowed), [
'path' => $this->getPath()
]), '', '&')), 'GET')));
if ($response->getStatusCode() == 200) {
$response = json_decode($response->getBody(), true);
if (!empty($response)) {
$this->isModified = false;
if (isset($response['_embedded'])) {
$response = array_merge($response, $response['_embedded']);
}
unset($response['_links'], $response['_embedded']);
if (isset($response['items'])) {
$response['items'] = new Container\Collection(array_map(function ($item) {
return new self($item, $this->client, $this->uri);
}, $response['items']));
}
$this->setContents($response);
}
}
}
return $this->_toArray($allowed);
}
/**
* Восстановление файла или папки из Корзины
* В корзине файлы с одинаковыми именами в действительности именют постфикс к имени в виде unixtime
*
* @param mixed $name оставляет имя как есть и если boolean это заменяет overwrite
* @param boolean $overwrite
* @return mixed
*/
public function restore($name = null, $overwrite = false)
{
if (is_bool($name)) {
$overwrite = $name;
$name = null;
}
if ($name instanceof Closed) {
$name = $name->getPath();
}
if (!empty($name) && !is_string($name)) {
throw new \InvalidArgumentException('Новое имя для восстанавливаемого ресурса должо быть строкой');
}
$request = new Request($this->uri->withPath($this->uri->getPath() . 'trash/resources/restore')
->withQuery(http_build_query([
'path' => $this->getPath(),
'name' => (string) $name,
'overwrite' => (bool) $overwrite
], '', '&')), 'PUT');
$response = $this->client->send($request);
if ($response->getStatusCode() == 201 || $response->getStatusCode() == 202) {
$this->setContents([]);
if ($response->getStatusCode() == 202) {
$response = json_decode($response->getBody(), true);
if (isset($response['operation'])) {
$response['operation'] = $this->client->getOperation($response['operation']);
$this->emit('operation', $response['operation'], $this, $this->client);
$this->client->emit('operation', $response['operation'], $this, $this->client);
return $response['operation'];
}
}
return $this->client->getResource($name);
}
return false;
}
/**
* Удаление файла или папки
*
* @return mixed
*/
public function delete()
{
try {
$response = $this->client->send(new Request($this->uri->withPath($this->uri->getPath() . 'trash/resources')
->withQuery(http_build_query([
'path' => $this->getPath()
], '', '&')), 'DELETE'));
if ($response->getStatusCode() == 202) {
$this->setContents([]);
$response = json_decode($response->getBody(), true);
if (!empty($response['operation'])) {
$response['operation'] = $this->client->getOperation($response['operation']);
$this->emit('operation', $response['operation'], $this, $this->client);
$this->client->emit('operation', $response['operation'], $this, $this->client);
return $response['operation'];
}
return true;
}
return $response->getStatusCode() == 204;
} catch (\Exception $exc) {
return false;
}
}
}
| php | MIT | 49f51b32f76cbfd123bb9fad7fdc63619121a884 | 2026-01-05T05:17:32.521772Z | false |
jack-theripper/yandex | https://github.com/jack-theripper/yandex/blob/49f51b32f76cbfd123bb9fad7fdc63619121a884/src/Disk/Resource/Opened.php | src/Disk/Resource/Opened.php | <?php
/**
* Часть библиотеки для работы с сервисами Яндекса
*
* @package Arhitector\Yandex\Disk\Resource
* @version 2.0
* @author Arhitector
* @license MIT License
* @copyright 2016 Arhitector
* @link https://github.com/jack-theripper
*/
namespace Arhitector\Yandex\Disk\Resource;
use Arhitector\Yandex\Client\Container;
use Arhitector\Yandex\Client\Exception\NotFoundException;
use Arhitector\Yandex\Disk;
use Arhitector\Yandex\Disk\AbstractResource;
use Arhitector\Yandex\Disk\Exception\AlreadyExistsException;
use Psr\Http\Message\StreamInterface;
use Laminas\Diactoros\Request;
use Laminas\Diactoros\Stream;
use Laminas\Diactoros\Uri;
/**
* Публичный ресурс.
*
* @package Arhitector\Yandex\Disk\Resource
*
* @property-read string $public_key публичный ключ
* @property-read string $name название файла
* @property-read string $created дата создания
* @property-read string $public_url публичный URL
* @property-read string $modified дата изменения
* @property-read string $media_type медиа тип файла
* @property-read string $path путь к папке
* @property-read string $md5 MD5 хэш сумма файла
* @property-read string $type это файл или папка
* @property-read string $mime_type
* @property-read int|float $size размер файла в байтах
*/
class Opened extends AbstractResource
{
/**
* @var string ресурс
*/
protected $publicKey;
/**
* Конструктор.
*
* @param string|array $public_key URL адрес или публичный ключ ресурса.
* @param \Arhitector\Yandex\Disk $parent
* @param \Psr\Http\Message\UriInterface $uri
*/
public function __construct($public_key, Disk $parent, \Psr\Http\Message\UriInterface $uri)
{
if (is_array($public_key)) {
if (empty($public_key['public_key'])) {
throw new \InvalidArgumentException('Параметр "public_key" должен быть строкового типа.');
}
$this->setContents($public_key);
$public_key = $public_key['public_key'];
$this->store['docviewer'] = $this->createDocViewerUrl();
}
if (!is_scalar($public_key)) {
throw new \InvalidArgumentException('Параметр "public_key" должен быть строкового типа.');
}
$this->publicKey = (string) $public_key;
$this->client = $parent;
$this->uri = $uri;
}
/**
* Получить публичный ключ
*
* @return string|null
*/
public function getPublicKey()
{
return $this->publicKey;
}
/**
* Получает информацию о ресурсе
*
* @return mixed
*/
public function toArray(array $allowed = null)
{
if (!$this->_toArray() || $this->isModified()) {
$response = $this->client->send((new Request($this->uri->withPath($this->uri->getPath() . 'public/resources')
->withQuery(http_build_query(array_merge($this->getParameters($this->parametersAllowed), [
'public_key' => $this->getPublicKey()
]), '', '&')), 'GET')));
if ($response->getStatusCode() == 200) {
$response = json_decode($response->getBody(), true);
if (!empty($response)) {
$this->isModified = false;
if (isset($response['_embedded'])) {
$response = array_merge($response, $response['_embedded']);
}
unset($response['_links'], $response['_embedded']);
if (isset($response['items'])) {
$response['items'] = new Container\Collection(array_map(function ($item) {
return new self($item, $this->client, $this->uri);
}, $response['items']));
}
$this->setContents($response);
$this->store['docviewer'] = $this->createDocViewerUrl();
}
}
}
return $this->_toArray($allowed);
}
/**
* Получает прямую ссылку
*
* @return string
* @throws mixed
*
* @TODO Не работает для файлов вложенных в публичную папку.
*/
public function getLink()
{
if (!$this->has()) {
throw new NotFoundException('Не удалось найти запрошенный ресурс.');
}
$response = $this->client->send(new Request($this->uri->withPath($this->uri->getPath() . 'public/resources/download')
->withQuery(http_build_query([
'public_key' => $this->getPublicKey(),
'path' => (string) $this->getPath()
], '', '&')), 'GET'));
if ($response->getStatusCode() == 200) {
$response = json_decode($response->getBody(), true);
if (isset($response['href'])) {
return $response['href'];
}
}
throw new \UnexpectedValueException('Не удалось запросить разрешение на скачивание, повторите заново');
}
/**
* Скачивание публичного файла или папки
*
* @param resource|StreamInterface|string $destination Путь, по которому будет сохранён файл
* StreamInterface будет записан в поток
* resource открытый на запись
* @param boolean $overwrite флаг перезаписи
* @param boolean $check_hash провести проверку целостности скачанного файла
* на основе хэша MD5
*
* @return bool
*/
public function download($destination, $overwrite = false, $check_hash = false)
{
$destination_type = gettype($destination);
if (is_resource($destination)) {
$destination = new Stream($destination);
}
if ($destination instanceof StreamInterface) {
if (!$destination->isWritable()) {
throw new \OutOfBoundsException('Дескриптор файла должен быть открыт с правами на запись.');
}
} else if ($destination_type == 'string') {
if (is_file($destination) && !$overwrite) {
throw new AlreadyExistsException('По указанному пути "' . $destination . '" уже существует ресурс.');
}
if (!is_writable(dirname($destination))) {
throw new \OutOfBoundsException('Запрещена запись в директорию, в которой должен быть расположен файл.');
}
$destination = new Stream($destination, 'w+b');
} else {
throw new \InvalidArgumentException('Такой тип параметра $destination не поддерживается.');
}
$response = $this->client->send(new Request($this->getLink(), 'GET'));
if ($response->getStatusCode() == 200) {
$stream = $response->getBody();
if ($check_hash) {
$ctx = hash_init('md5');
while (!$stream->eof()) {
$read_data = $stream->read(1048576);
$destination->write($read_data);
hash_update($ctx, $read_data);
}
} else {
while (!$stream->eof()) {
$destination->write($stream->read(16384));
}
}
$stream->close();
$this->emit('downloaded', $this, $destination, $this->client);
$this->client->emit('downloaded', $this, $destination, $this->client);
if ($destination_type == 'object') {
return $destination;
} else if ($check_hash && $destination_type == 'string' && $this->isFile()) {
if (hash_final($ctx, false) !== $this->get('md5', null)) {
throw new \RangeException('Ресурс скачан, но контрольные суммы различаются.');
}
}
return $destination->getSize();
}
return false;
}
/**
* Этот файл или такой же находится на моём диске
* Метод требует Access Token
*
* @return boolean
*/
public function hasEqual()
{
if ($this->has() && ($path = $this->get('name'))) {
try {
return $this->client->getResource(((string) $this->get('path')) . '/' . $path)
->get('md5', false) === $this->get('md5');
} catch (\Exception $exc) {
}
}
return false;
}
/**
* Сохранение публичного файла в «Загрузки» или отдельный файл из публичной папки
*
* @param string $name Имя, под которым файл следует сохранить в папку «Загрузки»
* @param string $path Путь внутри публичной папки.
*
* @return mixed
*/
public function save($name = null, $path = null)
{
$parameters = [];
/**
* @var mixed $name Имя, под которым файл следует сохранить в папку «Загрузки»
*/
if (is_string($name)) {
$parameters['name'] = $name;
} else if ($name instanceof Closed) {
$parameters['name'] = substr(strrchr($name->getPath(), '/'), 1);
}
/**
* @var string $path (необязательный)
* Путь внутри публичной папки. Следует указать, если в значении параметра public_key передан
* ключ публичной папки, в которой находится нужный файл.
* Путь в значении параметра следует кодировать в URL-формате.
*/
if (is_string($path)) {
$parameters['path'] = $path;
} else if ($this->getPath() !== null) {
$parameters['path'] = $this->getPath();
}
/**
* Если к моменту ответа запрос удалось обработать без ошибок, API отвечает кодом 201 Created и возвращает
* ссылку на сохраненный файл в теле ответа (в объекте Link).
* Если операция сохранения была запущена, но еще не завершилась, Яндекс.Диск отвечает кодом 202 Accepted.
*/
$response = $this->client->send((new Request($this->uri->withPath($this->uri->getPath()
. 'public/resources/save-to-disk')
->withQuery(http_build_query([
'public_key' => $this->getPublicKey()
] + $parameters, '', '&')), 'POST')));
if ($response->getStatusCode() == 202 || $response->getStatusCode() == 201) {
$response = json_decode($response->getBody(), true);
if (isset($response['operation'])) {
$response['operation'] = $this->client->getOperation($response['operation']);
$this->emit('operation', $response['operation'], $this, $this->client);
$this->client->emit('operation', $response['operation'], $this, $this->client);
return $response['operation'];
}
if (isset($response['href'])) {
parse_str((new Uri($response['href']))->getQuery(), $path);
if (isset($path['path'])) {
return $this->client->getResource($path['path']);
}
}
}
return false;
}
/**
* Устанавливает путь внутри публичной папки
*
* @param string $path
*
* @return $this
*/
public function setPath($path)
{
if (!is_scalar($path)) {
throw new \InvalidArgumentException('Параметр "path" должен быть строкового типа.');
}
$this->path = (string) $path;
return $this;
}
/**
* Получает ссылку для просмотра документа.
*
* @return bool|string
* @throws \InvalidArgumentException
*/
protected function createDocViewerUrl()
{
if ($this->isFile()) {
$docviewer = [
'name' => $this->get('name'),
'url' => sprintf('ya-disk-public://%s', $this->get('public_key'))
];
return (string) (new Uri('https://docviewer.yandex.ru/'))
->withQuery(http_build_query($docviewer, '', '&'));
}
return false;
}
}
| php | MIT | 49f51b32f76cbfd123bb9fad7fdc63619121a884 | 2026-01-05T05:17:32.521772Z | false |
jack-theripper/yandex | https://github.com/jack-theripper/yandex/blob/49f51b32f76cbfd123bb9fad7fdc63619121a884/src/Disk/Resource/Closed.php | src/Disk/Resource/Closed.php | <?php
/**
* Часть библиотеки для работы с сервисами Яндекса
*
* @package Arhitector\Yandex\Disk\Resource
* @version 2.0
* @author Arhitector
* @license MIT License
* @copyright 2016 Arhitector
* @link https://github.com/jack-theripper
*/
namespace Arhitector\Yandex\Disk\Resource;
use Arhitector\Yandex\Client\Container;
use Arhitector\Yandex\Client\Exception\NotFoundException;
use Arhitector\Yandex\Client\Stream\Progress;
use Arhitector\Yandex\Disk;
use Arhitector\Yandex\Disk\AbstractResource;
use Arhitector\Yandex\Disk\Exception\AlreadyExistsException;
use League\Event\Event;
use Psr\Http\Message\StreamInterface;
use Laminas\Diactoros\Request;
use Laminas\Diactoros\Stream;
use Laminas\Diactoros\Uri;
/**
* Закрытый ресурс.
*
* @property-read string $name
* @property-read string $created
* @property-read array|null $custom_properties
* @property-read string $modified
* @property-read string $media_type
* @property-read string $path
* @property-read string $md5
* @property-read string $type
* @property-read string $mime_type
* @property-read integer $size
* @property-read string $docviewer
*
* @package Arhitector\Yandex\Disk\Resource
*/
class Closed extends AbstractResource
{
/**
* Конструктор.
*
* @param string|array $resource путь к существующему либо новому ресурсу
* @param \Arhitector\Yandex\Disk $parent
* @param \Psr\Http\Message\UriInterface $uri
*/
public function __construct($resource, Disk $parent, \Psr\Http\Message\UriInterface $uri)
{
if (is_array($resource)) {
if (empty($resource['path'])) {
throw new \InvalidArgumentException('Параметр "path" должен быть строкового типа.');
}
$this->setContents($resource);
$this->store['docviewer'] = $this->createDocViewerUrl();
$resource = $resource['path'];
}
if (!is_scalar($resource)) {
throw new \InvalidArgumentException('Параметр "path" должен быть строкового типа.');
}
$this->path = (string) $resource;
$this->client = $parent;
$this->uri = $uri;
}
/**
* Получает информацию о ресурсе
*
* @param array $allowed выбрать ключи
*
* @return mixed
*
* @TODO добавить clearModify(), тем самым сделать возможность получать списки ресурсов во вложенных папках.
*/
public function toArray(array $allowed = null)
{
if (!$this->_toArray() || $this->isModified()) {
$response = $this->client->send(new Request($this->uri->withPath($this->uri->getPath() . 'resources')
->withQuery(http_build_query(array_merge($this->getParameters($this->parametersAllowed), [
'path' => $this->getPath()
]), '', '&')), 'GET'));
if ($response->getStatusCode() == 200) {
$response = json_decode($response->getBody(), true);
if (!empty($response)) {
$this->isModified = false;
if (isset($response['_embedded'])) {
$response = array_merge($response, $response['_embedded']);
}
unset($response['_links'], $response['_embedded']);
if (isset($response['items'])) {
$response['items'] = new Container\Collection(array_map(function ($item) {
return new self($item, $this->client, $this->uri);
}, $response['items']));
}
$this->setContents($response);
$this->store['docviewer'] = $this->createDocViewerUrl();
}
}
}
return $this->_toArray($allowed);
}
/**
* Позводляет получить метаинформацию из custom_properties
*
* @param string $index
* @param mixed $default
*
* @return mixed|null
*/
public function getProperty($index, $default = null)
{
$properties = $this->get('custom_properties', []);
if (isset($properties[$index])) {
return $properties[$index];
}
if ($default instanceof \Closure) {
return $default($this);
}
return $default;
}
/**
* Получает всю метаинформацию и custom_properties
*
* @return array
*/
public function getProperties()
{
return $this->get('custom_properties', []);
}
/**
* Добавление метаинформации для ресурса
*
* @param mixed $meta строка либо массив значений
* @param mixed $value NULL чтобы удалить определённую метаинформаию когда $meta строка
*
* @return Closed
* @throws \LengthException
*/
public function set($meta, $value = null)
{
if (!is_array($meta)) {
if (!is_scalar($meta)) {
throw new \InvalidArgumentException('Индекс метаинформации должен быть простого типа.');
}
$meta = [(string) $meta => $value];
}
if (empty($meta)) {
throw new \OutOfBoundsException('Не было передано ни одного значения для добавления метаинформации.');
}
/*if (mb_strlen(json_encode($meta, JSON_UNESCAPED_UNICODE), 'UTF-8') > 1024)
{
throw new \LengthException('Максимальный допустимый размер объекта метаинформации составляет 1024 байт.');
}*/
$request = (new Request($this->uri->withPath($this->uri->getPath() . 'resources')
->withQuery(http_build_query(['path' => $this->getPath()], '', '&')), 'PATCH'));
$request->getBody()
->write(json_encode(['custom_properties' => $meta]));
$response = $this->client->send($request);
if ($response->getStatusCode() == 200) {
$this->setContents(json_decode($response->getBody(), true));
$this->store['docviewer'] = $this->createDocViewerUrl();
}
return $this;
}
/**
* Разрешает обновление свойств объекта как массива
*
* @param string $key
* @param mixed $value
*
* @return void
*/
#[\ReturnTypeWillChange]
public function offsetSet($key, $value)
{
$this->set($key, $value);
}
/**
* Магический метод set. Добавляет метаинформацию
*
* @return void
*/
public function __set($key, $value)
{
$this->set($key, $value);
}
/**
* Разрешает использование unset() к метаинформации
*
* @param string $key
*
* @return void
* @throws \RuntimeException
*/
#[\ReturnTypeWillChange]
public function offsetUnset($key)
{
$this->set($key, null);
}
/**
* Магический метод unset. Удаляет метаинформацию.
*
* @return void
*/
public function __unset($key)
{
$this->set($key, null);
}
/**
* Удаление файла или папки
*
* @param boolean $permanently TRUE Признак безвозвратного удаления
*
* @return bool|\Arhitector\Yandex\Disk\Operation|\Arhitector\Yandex\Disk\Resource\Removed
*/
public function delete($permanently = false)
{
$response = $this->client->send(new Request($this->uri->withPath($this->uri->getPath() . 'resources')
->withQuery(http_build_query([
'path' => $this->getPath(),
'permanently' => (bool) $permanently
])), 'DELETE'));
if ($response->getStatusCode() == 202 || $response->getStatusCode() == 204) {
$this->setContents([]);
$this->emit('delete', $this, $this->client);
$this->client->emit('delete', $this, $this->client);
if ($response->getStatusCode() == 202) {
$response = json_decode($response->getBody(), true);
if (isset($response['operation'])) {
$response['operation'] = $this->client->getOperation($response['operation']);
$this->emit('operation', $response['operation'], $this, $this->client);
$this->client->emit('operation', $response['operation'], $this, $this->client);
return $response['operation'];
}
}
try {
/*$resource = $this->client->getTrashResource('/', 0);
$resource = $this->client->getTrashResources(1, $resource->get('total', 0) - 1)->getFirst();
if ($resource->has() && $resource->get('origin_path') == $this->getPath())
{
return $resource;
}*/
} catch (\Exception $exc) {
}
return true;
}
return false;
}
/**
* Перемещение файла или папки.
* Перемещать файлы и папки на Диске можно, указывая текущий путь к ресурсу и его новое положение.
* Если запрос был обработан без ошибок, API составляет тело ответа в зависимости от вида указанного ресурса –
* ответ для пустой папки или файла отличается от ответа для непустой папки. (Если запрос вызвал ошибку,
* возвращается подходящий код ответа, а тело ответа содержит описание ошибки).
* Приложения должны самостоятельно следить за статусами запрошенных операций.
*
* @param string|\Arhitector\Yandex\Disk\Resource\Closed $destination новый путь.
* @param boolean $overwrite признак перезаписи файлов. Учитывается,
* если ресурс перемещается в папку, в которой
* уже есть ресурс с таким именем.
*
* @return bool|\Arhitector\Yandex\Disk\Operation
*/
public function move($destination, $overwrite = false)
{
if ($destination instanceof Closed) {
$destination = $destination->getPath();
}
$response = $this->client->send(new Request($this->uri->withPath($this->uri->getPath() . 'resources/move')
->withQuery(http_build_query([
'from' => $this->getPath(),
'path' => $destination,
'overwrite' => (bool) $overwrite
], '', '&')), 'POST'));
if ($response->getStatusCode() == 202 || $response->getStatusCode() == 201) {
$this->path = $destination;
$response = json_decode($response->getBody(), true);
if (isset($response['operation'])) {
$response['operation'] = $this->client->getOperation($response['operation']);
$this->emit('operation', $response['operation'], $this, $this->client);
$this->client->emit('operation', $response['operation'], $this, $this->client);
return $response['operation'];
}
return true;
}
return false;
}
/**
* Создание папки, если ресурса с таким же именем нет
*
* @return \Arhitector\Yandex\Disk\Resource\Closed
* @throws mixed
*/
public function create()
{
try {
$this->client->send(new Request($this->uri->withPath($this->uri->getPath() . 'resources')
->withQuery(http_build_query([
'path' => $this->getPath()
], '', '&')), 'PUT'));
$this->setContents([]);
} catch (\Exception $exc) {
throw $exc;
}
return $this;
}
/**
* Публикация ресурса\Закрытие доступа
*
* @param boolean $publish TRUE открыть доступ, FALSE закрыть доступ
*
* @return \Arhitector\Yandex\Disk\Resource\Closed|\Arhitector\Yandex\Disk\Resource\Opened
*/
public function setPublish($publish = true)
{
$request = 'resources/unpublish';
if ($publish) {
$request = 'resources/publish';
}
$response = $this->client->send(new Request($this->uri->withPath($this->uri->getPath() . $request)
->withQuery(http_build_query([
'path' => $this->getPath()
], '', '&')), 'PUT'));
if ($response->getStatusCode() == 200) {
$this->setContents([]);
if ($publish && $this->has('public_key')) {
return $this->client->getPublishResource($this->get('public_key'));
}
}
return $this;
}
/**
* Скачивает файл
*
* @param resource|StreamInterface|string $destination Путь, по которому будет сохранён файл
* StreamInterface будет записан в поток
* resource открытый на запись
* @param mixed $overwrite
*
* @return bool
*
* @throws NotFoundException
* @throws AlreadyExistsException
* @throws \OutOfBoundsException
* @throws \UnexpectedValueException
*/
public function download($destination, $overwrite = false)
{
$destination_type = gettype($destination);
if (!$this->has()) {
throw new NotFoundException('Не удалось найти запрошенный ресурс.');
}
if (is_resource($destination)) {
$destination = new Stream($destination);
}
if ($destination instanceof StreamInterface) {
if (!$destination->isWritable()) {
throw new \OutOfBoundsException('Дескриптор файла должен быть открыт с правами на запись.');
}
} else {
if ($destination_type == 'string') {
if (is_file($destination) && !$overwrite) {
throw new AlreadyExistsException('По указанному пути "' . $destination . '" уже существует ресурс.');
}
if (!is_writable(dirname($destination))) {
throw new \OutOfBoundsException('Запрещена запись в директорию, в которой должен быть расположен файл.');
}
$destination = new Stream($destination, 'w+b');
} else {
throw new \InvalidArgumentException('Такой тип параметра $destination не поддерживается.');
}
}
$response = $this->client->send(new Request($this->uri->withPath($this->uri->getPath() . 'resources/download')
->withQuery(http_build_query(['path' => $this->getPath()], '', '&')), 'GET'));
if ($response->getStatusCode() == 200) {
$response = json_decode($response->getBody(), true);
if (isset($response['href'])) {
$response = $this->client->send(new Request($response['href'], 'GET'));
if ($response->getStatusCode() == 200) {
$stream = $response->getBody();
while (!$stream->eof()) {
$destination->write($stream->read(16384));
}
$stream->close();
$this->emit('downloaded', $this, $destination, $this->client);
$this->client->emit('downloaded', $this, $destination, $this->client);
if ($destination_type == 'object') {
return $destination;
}
return $destination->getSize();
}
return false;
}
}
throw new \UnexpectedValueException('Не удалось запросить разрешение на скачивание, повторите заново.');
}
/**
* Копирование файла или папки
*
* @param string|Closed $destination
* @param bool $overwrite
*
* @return bool
*/
public function copy($destination, $overwrite = false)
{
if ($destination instanceof Closed) {
$destination = $destination->getPath();
}
$response = $this->client->send(new Request($this->uri->withPath($this->uri->getPath() . 'resources/copy')
->withQuery(http_build_query([
'from' => $this->getPath(),
'path' => $destination,
'overwrite' => (bool) $overwrite
], '', '&')), 'POST'));
if ($response->getStatusCode() == 201) {
$response = json_decode($response->getBody(), true);
if (isset($response['operation'])) {
$response['operation'] = $this->client->getOperation($response['operation']);
$this->emit('operation', $response['operation'], $this, $this->client);
$this->client->emit('operation', $response['operation'], $this, $this->client);
return $response['operation'];
}
return true;
}
return false;
}
/**
* Загрузить файл на диск
*
* @param mixed $file_path может быть как путь к локальному файлу, так и URL к файлу.
* @param bool $overwrite если ресурс существует на Яндекс.Диске TRUE перезапишет ресурс.
* @param bool $disable_redirects помогает запретить редиректы по адресу, TRUE запретит пере адресацию.
*
* @return bool|\Arhitector\Yandex\Disk\Operation
*
* @throws mixed
*
* @TODO Добавить, если передана папка - сжать папку в архив и загрузить.
*/
public function upload($file_path, $overwrite = false, $disable_redirects = false)
{
if (is_string($file_path)) {
$scheme = substr($file_path, 0, 7);
if ($scheme == 'http://' or $scheme == 'https:/') {
try {
$response = $this->client->send(new Request($this->uri->withPath($this->uri->getPath() . 'resources/upload')
->withQuery(http_build_query([
'url' => $file_path,
'path' => $this->getPath(),
'disable_redirects' => (int) $disable_redirects
], '', '&')), 'POST'));
} catch (AlreadyExistsException $exc) {
// параметр $overwrite не работает т.к. диск не поддерживает {AlreadyExistsException:409}->rename->delete
throw new AlreadyExistsException(
$exc->getMessage() . ' Перезапись для удалённой загрузки не доступна.',
$exc->getCode(),
$exc
);
}
$response = json_decode($response->getBody(), true);
if (isset($response['operation'])) {
$response['operation'] = $this->client->getOperation($response['operation']);
$this->emit('operation', $response['operation'], $this, $this->client);
$this->client->emit('operation', $response['operation'], $this, $this->client);
return $response['operation'];
}
return false;
}
$file_path = realpath($file_path);
if (!is_file($file_path)) {
throw new \OutOfBoundsException('Локальный файл по такому пути: "' . $file_path . '" отсутствует.');
}
} else {
if (!is_resource($file_path)) {
throw new \InvalidArgumentException('Параметр "путь к файлу" должен быть строкового типа или открытый файловый дескриптор на чтение.');
}
}
$access_upload = json_decode($this->client->send(new Request($this->uri->withPath($this->uri->getPath() . 'resources/upload')
->withQuery(http_build_query([
'path' => $this->getPath(),
'overwrite' => (int) ((bool) $overwrite),
], '', '&')), 'GET'))
->getBody(), true);
if (!isset($access_upload['href'])) {
// $this->client->setRetries = 1
throw new \RuntimeException('Не возможно загрузить локальный файл - не получено разрешение.');
}
if ($this->getEmitter()->hasListeners('progress')) {
$stream = new Progress($file_path, 'rb');
$stream->addListener('progress', function (Event $event, $percent) {
$this->emit('progress', $percent);
});
} else {
$stream = new Stream($file_path, 'rb');
}
$response = $this->client->send((new Request($access_upload['href'], 'PUT', $stream)));
$this->emit('uploaded', $this, $this->client, $stream, $response);
$this->client->emit('uploaded', $this, $this->client, $stream, $response);
return $response->getStatusCode() == 201;
}
/**
* Получает прямую ссылку
*
* @return string
* @throws mixed
*
* @TODO Не работает для файлов вложенных в публичную папку.
*/
public function getLink()
{
if (!$this->has()) {
throw new NotFoundException('Не удалось найти запрошенный ресурс.');
}
$response = $this->client->send(new Request($this->uri->withPath($this->uri->getPath() . 'resources/download')
->withQuery(http_build_query([
'path' => (string) $this->getPath()
], '', '&')), 'GET'));
if ($response->getStatusCode() == 200) {
$response = json_decode($response->getBody(), true);
if (isset($response['href'])) {
return $response['href'];
}
}
throw new \UnexpectedValueException('Не удалось запросить разрешение на скачивание, повторите заново');
}
/**
* Получает ссылку для просмотра документа. Достпно владельцу аккаунта.
*
* @return bool|string
*/
protected function createDocViewerUrl()
{
if ($this->isFile()) {
$docviewer = [
'url' => $this->get('path'),
'name' => $this->get('name')
];
if (strpos($docviewer['url'], 'disk:/') === 0) {
$docviewer['url'] = substr($docviewer['url'], 6);
}
$docviewer['url'] = "ya-disk:///disk/{$docviewer['url']}";
return (string) (new Uri('https://docviewer.yandex.ru'))
->withQuery(http_build_query($docviewer, '', '&'));
}
return false;
}
}
| php | MIT | 49f51b32f76cbfd123bb9fad7fdc63619121a884 | 2026-01-05T05:17:32.521772Z | false |
jack-theripper/yandex | https://github.com/jack-theripper/yandex/blob/49f51b32f76cbfd123bb9fad7fdc63619121a884/src/Disk/Filter/PreviewTrait.php | src/Disk/Filter/PreviewTrait.php | <?php
/**
* Часть библиотеки для работы с сервисами Яндекса
*
* @package Arhitector\Yandex\Disk\Filter
* @version 2.0
* @author Arhitector
* @license MIT License
* @copyright 2016 Arhitector
* @link https://github.com/jack-theripper
*/
namespace Arhitector\Yandex\Disk\Filter;
/**
* Фильтр для превью.
* Использует возможности Яндес.Диска.
*
* @package Arhitector\Yandex\Disk\Filter
*/
trait PreviewTrait
{
/**
* Обрезать превью согласно размеру
*
* @param boolean $crop
*
* @return $this
*/
public function setPreviewCrop($crop)
{
$this->isModified = true;
$this->parameters['preview_crop'] = (bool) $crop;
return $this;
}
/**
* Размер уменьшенного превью файла
*
* @param mixed $preview S, M, L, XL, XXL, XXXL, <ширина>, <ширина>x, x<высота>, <ширина>x<высота>
*
* @return $this
* @throws \UnexpectedValueException
*/
public function setPreview($preview)
{
if (is_scalar($preview))
{
$preview = strtoupper($preview);
$previewNum = str_replace('X', '', $preview, $replaces);
if (in_array($preview, ['S', 'M', 'L', 'XL', 'XXL', 'XXXL']) || (is_numeric($previewNum) && $replaces < 2))
{
if (is_numeric($previewNum))
{
$preview = strtolower($preview);
}
$this->isModified = true;
$this->parameters['preview_size'] = $preview;
return $this;
}
}
throw new \UnexpectedValueException('Допустимые значения размера превью - S, M, L, XL, XXL, XXXL, <ширина>, <ширина>x, x<высота>, <ширина>x<высота>');
}
/**
* Получает установленное значение "setPreview".
*
* @return string
*/
public function getPreview()
{
if (isset($this->parameters['preview_size']))
{
return $this->parameters['preview_size'];
}
return null;
}
/**
* Получает установленное значение "setPreviewCrop".
*
* @return string
*/
public function getPreviewCrop()
{
if (isset($this->parameters['preview_crop']))
{
return $this->parameters['preview_crop'];
}
return null;
}
} | php | MIT | 49f51b32f76cbfd123bb9fad7fdc63619121a884 | 2026-01-05T05:17:32.521772Z | false |
jack-theripper/yandex | https://github.com/jack-theripper/yandex/blob/49f51b32f76cbfd123bb9fad7fdc63619121a884/src/Disk/Filter/MediaTypeTrait.php | src/Disk/Filter/MediaTypeTrait.php | <?php
/**
* Часть библиотеки для работы с сервисами Яндекса
*
* @package Arhitector\Yandex\Disk
* @version 2.0
* @author Arhitector
* @license MIT License
* @copyright 2016 Arhitector
* @link https://github.com/jack-theripper
*/
namespace Arhitector\Yandex\Disk\Filter;
/**
* Аyдио-файлы.
*/
const MEDIA_TYPE_AUDIO = 'audio';
/**
* Файлы резервных и временных копий.
*/
const MEDIA_TYPE_BACKUP = 'backup';
/**
* Электронные книги.
*/
const MEDIA_TYPE_BOOK = 'book';
/**
* Сжатые и архивированные файлы.
*/
const MEDIA_TYPE_ZIP = 'compressed';
/**
* Файлы с базами данных.
*/
const MEDIA_TYPE_DATA = 'data';
/**
* Файлы с кодом (C++, Java, XML и т. п.), а также служебные файлы IDE.
*/
const MEDIA_TYPE_SRC = 'development';
/**
* Образы носителей информации и сопутствующие файлы (например, ISO и CUE).
*/
const MEDIA_TYPE_DISKIMAGE = 'diskimage';
/**
* Документы офисных форматов (Word, OpenOffice и т. п.).
*/
const MEDIA_TYPE_DOC = 'document';
/**
* Зашифрованные файлы.
*/
const MEDIA_TYPE_ENCODED = 'encoded';
/**
* Исполняемые файлы.
*/
const MEDIA_TYPE_EXE = 'executable';
/**
* Файлы с флэш-видео или анимацией.
*/
const MEDIA_TYPE_FLASH = 'flash';
/**
* Файлы шрифтов.
*/
const MEDIA_TYPE_FONT = 'font';
/**
* Изображения.
*/
const MEDIA_TYPE_IMG = 'image';
/**
* файлы настроек для различных программ.
*/
const MEDIA_TYPE_SETTINGS = 'settings';
/**
* Файлы офисных таблиц (Excel, Numbers, Lotus).
*/
const MEDIA_TYPE_TABLE = 'spreadsheet';
/**
* Текстовые файлы.
*/
const MEDIA_TYPE_TEXT = 'text';
/**
* Неизвестный тип.
*/
const MEDIA_TYPE_UNKNOWN = 'unknown';
/**
* Видео-файлы.
*/
const MEDIA_TYPE_VIDEO = 'video';
/**
* Различные файлы, используемые браузерами и сайтами (CSS, сертификаты, файлы закладок).
*/
const MEDIA_TYPE_WEB = 'web';
/**
* Фильтрация по медиа типам.
*
* @package Arhitector\Yandex\Disk\Filter
*/
trait MediaTypeTrait
{
/**
* @var string[] все доступные медиа типы
*/
protected $mediaTypes = [
MEDIA_TYPE_AUDIO,
MEDIA_TYPE_BACKUP,
MEDIA_TYPE_BOOK,
MEDIA_TYPE_ZIP,
MEDIA_TYPE_DATA,
MEDIA_TYPE_SRC,
MEDIA_TYPE_DISKIMAGE,
MEDIA_TYPE_DOC,
MEDIA_TYPE_ENCODED,
MEDIA_TYPE_EXE,
MEDIA_TYPE_FLASH,
MEDIA_TYPE_FONT,
MEDIA_TYPE_IMG,
MEDIA_TYPE_SETTINGS,
MEDIA_TYPE_TABLE,
MEDIA_TYPE_TEXT,
MEDIA_TYPE_UNKNOWN,
MEDIA_TYPE_VIDEO,
MEDIA_TYPE_WEB,
];
/**
* Тип файлов, которые нужно включить в список.
*
* @param string $media_type медиа тип (`MEDIA_TYPE_*` константы) или несколько типов перечисленных через запятую
* @return $this
* @throws \UnexpectedValueException
*/
public function setMediaType($media_type)
{
$media_types = explode(',', $media_type);
if (array_diff($media_types, $this->getMediaTypes())) {
throw new \UnexpectedValueException(
'Неверный тип файла, допустимые значения: "'.implode('", "', $this->getMediaTypes()).'".'
);
}
$this->isModified = true;
$this->parameters['media_type'] = $media_type;
return $this;
}
/**
* Получает установленное значение.
*
* @return string|null
*/
public function getMediaType()
{
return $this->parameters['media_type'] ?? null;
}
/**
* Все возможные типы файлов.
*
* @return string[]
*/
public function getMediaTypes()
{
return $this->mediaTypes;
}
}
| php | MIT | 49f51b32f76cbfd123bb9fad7fdc63619121a884 | 2026-01-05T05:17:32.521772Z | false |
jack-theripper/yandex | https://github.com/jack-theripper/yandex/blob/49f51b32f76cbfd123bb9fad7fdc63619121a884/src/Disk/Filter/RelativePathTrait.php | src/Disk/Filter/RelativePathTrait.php | <?php
/**
* Часть библиотеки для работы с сервисами Яндекса
*
* @package Arhitector\Yandex\Disk
* @version 2.0
* @author Arhitector
* @license MIT License
* @copyright 2016 Arhitector
* @link https://github.com/jack-theripper
*/
namespace Arhitector\Yandex\Disk\Filter;
/**
* Относительный путь к ресурсу внутри публичной папки.
*
* @package Arhitector\Yandex\Disk\Filter
*/
trait RelativePathTrait
{
/**
* Относительный путь к ресурсу внутри публичной папки.
*
* @param string $path
*
* @return $this
*/
public function setRelativePath($path)
{
if ( ! is_string($path))
{
throw new \InvalidArgumentException('Относительный путь к ресурсу должен быть строкового типа.');
}
$this->isModified = true;
$this->parameters['path'] = '/'.ltrim($path, ' /');
return $this;
}
/**
* Получает установленное значение.
*
* @return string
*/
public function getRelativePath()
{
if (isset($this->parameters['path']))
{
return $this->parameters['path'];
}
return null;
}
} | php | MIT | 49f51b32f76cbfd123bb9fad7fdc63619121a884 | 2026-01-05T05:17:32.521772Z | false |
jack-theripper/yandex | https://github.com/jack-theripper/yandex/blob/49f51b32f76cbfd123bb9fad7fdc63619121a884/src/Disk/Filter/TypeTrait.php | src/Disk/Filter/TypeTrait.php | <?php
/**
* Часть библиотеки для работы с сервисами Яндекса
*
* @package Arhitector\Yandex\Disk
* @version 2.0
* @author Arhitector
* @license MIT License
* @copyright 2016 Arhitector
* @link https://github.com/jack-theripper
*/
namespace Arhitector\Yandex\Disk\Filter;
/**
* Тип - файл/папка.
*
* @package Arhitector\Yandex\Disk\Filter
*/
trait TypeTrait
{
/**
* Тип ресурса
*
* @param string $type
*
* @return $this
* @throws \UnexpectedValueException
*/
public function setType($type)
{
if ( ! is_string($type) || ! in_array($type, ['file', 'dir']))
{
throw new \UnexpectedValueException('Тип ресурса, допустимые значения - "file", "dir".');
}
$this->isModified = true;
$this->parameters['type'] = $type;
return $this;
}
/**
* Получает установленное значение.
*
* @return string
*/
public function getType()
{
if (isset($this->parameters['type']))
{
return $this->parameters['type'];
}
return null;
}
} | php | MIT | 49f51b32f76cbfd123bb9fad7fdc63619121a884 | 2026-01-05T05:17:32.521772Z | false |
jack-theripper/yandex | https://github.com/jack-theripper/yandex/blob/49f51b32f76cbfd123bb9fad7fdc63619121a884/src/Disk/Exception/OutOfSpaceException.php | src/Disk/Exception/OutOfSpaceException.php | <?php
/**
* Часть библиотеки для работы с сервисами Яндекса
*
* @package Arhitector\Yandex\Disk\Exception
* @version 2.0
* @author Arhitector
* @license MIT License
* @copyright 2016 Arhitector
* @link https://github.com/jack-theripper
*/
namespace Arhitector\Yandex\Disk\Exception;
use Http\Client\Exception;
/**
* Исключение недостаточно свободного места
*
* @package Arhitector\Yandex\Disk\Exception
*/
class OutOfSpaceException extends \RuntimeException implements Exception
{
} | php | MIT | 49f51b32f76cbfd123bb9fad7fdc63619121a884 | 2026-01-05T05:17:32.521772Z | false |
jack-theripper/yandex | https://github.com/jack-theripper/yandex/blob/49f51b32f76cbfd123bb9fad7fdc63619121a884/src/Disk/Exception/AlreadyExistsException.php | src/Disk/Exception/AlreadyExistsException.php | <?php
/**
* Часть библиотеки для работы с сервисами Яндекса
*
* @package Arhitector\Yandex\Disk\Exception
* @version 2.0
* @author Arhitector
* @license MIT License
* @copyright 2016 Arhitector
* @link https://github.com/jack-theripper
*/
namespace Arhitector\Yandex\Disk\Exception;
use Http\Client\Exception;
/**
* Исключение ресурс существует
*
* @package Arhitector\Yandex\Disk\Exception
*/
class AlreadyExistsException extends \RuntimeException implements Exception
{
} | php | MIT | 49f51b32f76cbfd123bb9fad7fdc63619121a884 | 2026-01-05T05:17:32.521772Z | false |
jack-theripper/yandex | https://github.com/jack-theripper/yandex/blob/49f51b32f76cbfd123bb9fad7fdc63619121a884/example/manual_request.php | example/manual_request.php | <?php
/**
* Пример показывает как нестандартный запрос к API Яндекс.Диска.
*/
use Laminas\Diactoros\Request;
require_once __DIR__.'/../vendor/autoload.php';
$token = 'Access Token';
$disk = new Arhitector\Yandex\Disk($token);
// Внимание! В запрос будет передан Access Token
$request = new Request('https://cloud-api.yandex.net/v1/disk/resources?path=O2cXW1AEVWI222.jpg', 'GET');
$response = $disk->send($request);
var_dump($response->getBody()->getContents());
// Но и этот факт можно использовать, например как получить превью закрытого ресурса
$resource = $disk->getResource('disk:/O2cXW1AEVWI222.jpg')
->setPreview('100x250');
$request = new Request($resource->preview, 'GET');
$response = $disk->send($request);
header('Content-type: image/jpeg');
echo $response->getBody();
| php | MIT | 49f51b32f76cbfd123bb9fad7fdc63619121a884 | 2026-01-05T05:17:32.521772Z | false |
jack-theripper/yandex | https://github.com/jack-theripper/yandex/blob/49f51b32f76cbfd123bb9fad7fdc63619121a884/example/disk.php | example/disk.php | <?php
/**
* Created by Arhitector.
* Date: 05.06.2016
* Time: 17:30
*/
error_reporting(E_ALL);
require_once __DIR__.'/../vendor/autoload.php';
$disk = new Arhitector\Yandex\Disk();
$disk->setAccessToken('');
/**
* Список всех файлов на диске, метод getResources([int limit = 20, [int offset = 0]].
* Возвращает объект "Arhitector\Yandex\Disk\Resource\Collection"
*/
/*$resources = $disk->getResources()
->setLimit(10) // количество файлов, getResources может принять "limit" первым параметром.
->setOffset(0) // смещениеб пуеКуыщгксуы vj;tn ghbyznm "offset" вторым параметром.
->setMediaType('image') // мультимедиа тип файлов, все типы $resources->getMediaTypes()
->setPreview('100x250') // размер превью изображений
->setPreviewCrop(true) // обрезать превью согласно размеру
->setSort('name', true) // способ сортировки, второй параметр TRUE означает "в обратном порядке"
;*/
//$first = $resources->getFirst(); // Arhitector\Yandex\Disk\Resource\Closed
//$last = $resources->getLast(); // Arhitector\Yandex\Disk\Resource\Closed
//var_dump($first->toArray(), $last->toArray(), $resources->toArray());
/**
* Работа с одним ресурсом, метод "getResource"
* первым параметром принимает путь к ресурсу - папке или файлу.
* вторым и третим принимает "limit" и "offset", если ресурс - это папка.
*/
//$resource = $disk->getResource('app:/picture.jpg');
//$has = $resource->has(); // проверить есть ли ресурс на диске.
/*if ( ! $has)
{
// загружает локальный файл на диск. второй параметр отвечает за перезапись файла, если такой есть на диске.
// загружает удаленный файл на диск, передайте ссылку http на удаленный файл.
$resource->upload(__DIR__.'/image.jpg');
}*/
//$has_moved = $resource->move('image2.jpg'); // переместить, boolean
//$result = $resource->upload('http://<..>file.zip');
//var_dump($result->getStatus(), $result->getIdentifier());
//$resource->custom_index_1 = 'value'; // добавить метаинформацию в "custom_properties"
//$resource->set('custom_index_2', 'value'); // добавить метаинформацию в "custom_properties"
//$resource['custom_index_3'] = 'value'; // добавить метаинформацию в "custom_properties"
//unset($resource['custom_index_3']); // удалить метаинформацию, или передать NULL в "set" чтобы удалить
//echo '<a href="'.$resource->docviewer.'" target="_blank">View</a>';
//$resource->download(__DIR__.'/image_downloaded.jpg'); // скачать файл с диска
//var_dump($has, $resource->getProperties(), $resource->toObject());
//$resource = $disk->getPublishResource('https://yadi.sk/d/WSS6bK_ksQ5ck');
//var_dump($resource->items->get(0)->getLink(), $resource->toArray());
//var_dump($resource->download(__DIR__.'/down.zip', true));
//var_dump($resource->items->getFirst()->toArray(), $resource->toArray());
//$resources = $disk->getTrashResources(5);
//$resources = $disk->getTrashResource('trash:/image2.jpg');
//var_dump($resources->toArray());
/*
$disk->addListener('operation', function ($event, $operation) {
var_dump($operation->getStatus(), func_get_args());
});*/
//var_dump($disk->toArray());
//$resources = $disk->getResources();
//$resources->setMediaType('video');
//$resources = $disk->getTrashResources();
//$resources = $disk->cleanTrash();
//$resources = $disk->uploaded();
//$resources = $disk->getResource('disk:/applu.mp3');
//$resources = $disk->getResource('rich.txt');
//$resources = $disk->getTrashResources(1);
//$resources->setSort('deleted', true);
//$resources->setLimit(1, 1);
//$resources = $disk->getTrashResource('/', 10);
//$resources->setSort('deleted', false);
/*$resources->addListener('operation', function () {
var_dump('$resources', func_get_args());
});*/
//$result = $resources->create();
//$result = $resources->delete(false);
//$resources->set('nama', rand());
//$resources->rollin = 'bakc';
//unset($resources['rollin']);
//echo $resources->docviewer;
//var_dump($disk->getOperation('0ec0c6a835b72b8860261cc2d5aaf26968b83b7f8eac3118b240eedd')->getStatus());
//$result = $resources->move('rich');
//$result = $resources->setPublish(true);
//$result = $resources->download(__DIR__.'/data_big');
//$result = $resources->upload(__DIR__.'/data_big.data', true);
//var_dump($result, $resources->toArray());
//var_dump($resources->toArray());
//var_dump($disk); | php | MIT | 49f51b32f76cbfd123bb9fad7fdc63619121a884 | 2026-01-05T05:17:32.521772Z | false |
jack-theripper/yandex | https://github.com/jack-theripper/yandex/blob/49f51b32f76cbfd123bb9fad7fdc63619121a884/example/client_oauth.php | example/client_oauth.php | <?php
/**
* Created by Arhitector.
* Date: 05.06.2016
* Time: 16:47
*/
require_once __DIR__.'/../vendor/autoload.php';
$oauth = new Arhitector\Yandex\Client\OAuth();
var_dump($oauth);
| php | MIT | 49f51b32f76cbfd123bb9fad7fdc63619121a884 | 2026-01-05T05:17:32.521772Z | false |
jack-theripper/yandex | https://github.com/jack-theripper/yandex/blob/49f51b32f76cbfd123bb9fad7fdc63619121a884/example/backup_dir_to_ydisk.php | example/backup_dir_to_ydisk.php | <?php
/**
* This file could be used as an example of uploading the whole directory to YDisk recursively
* or as a ready-to-use command line script, please find usage below, or just run it in console
*/
error_reporting(E_ALL);
require_once __DIR__.'/../vendor/autoload.php';
class YDiskBackup
{
protected $auth_token;
protected $backup_src_dir;
protected $disk_dest_resrouce;
protected $is_overwrite_enabled = false;
protected $is_md5_check_enabled = true;
protected $is_quiet_mod_enanled = false;
private $disk;
/* use \Psr\Log\LoggerTrait; */
/**
* YDiskBackup constructor.
* @param $auth_token Authorization token
* @param $backup_src_dir Directory to backup
* @param $disk_dest_resource Destination YD resource to backup to
* @param bool $force_overwrite Overwrite files if exist OR md5 is different
* @param bool $check_md5 Whether MD5 checksums should be verified
* @param bool $be_quiet Whether verbose output is enabled
*/
public function __construct($auth_token, $backup_src_dir, $disk_dest_resource, $force_overwrite = false, $verify_md5 = true, $be_quiet = false)
{
$this->auth_token = $auth_token;
$this->backup_src_dir = $backup_src_dir;
$this->disk_dest_resrouce = $disk_dest_resource;
$this->disk = new Arhitector\Yandex\Disk();
$this->disk->setAccessToken($auth_token);
$this->is_md5_check_enabled = $verify_md5;
$this->is_overwrite_enabled = $force_overwrite;
$this->is_quiet_mod_enanled = $be_quiet;
return $this;
}
public function run()
{
$this->iterateDirectory('');
}
protected function backupFile($src_path, $dest_resource)
{
$this->info("Backing $src_path up to $dest_resource...");
$res = $this->disk->getResource($dest_resource);
if ( $res->has() === true
and $this->is_overwrite_enabled === false
and $this->is_md5_check_enabled === false )
{
$this->info("The resource $dest_resource exists. Please use overwrite flag to force upload");
return;
}
if ( $res->has() === false )
{
$result = $res->upload($src_path);
$this->info("Upload request status: $result");
}
elseif ( $this->is_md5_check_enabled )
{
$src_file_md5 = md5_file($src_path);
$dest_file_md5 = $res->get('md5');
if ( strcmp($src_file_md5, $dest_file_md5) !== 0 )
{
$this->warn("Failed md5 check: src [$src_file_md5] dest [$dest_file_md5]");
if ( $this->is_overwrite_enabled )
{
$result = $res->upload($src_path, true);
$this->info("Overwrite upload request status: $result");
}
else
{
$this->warn("Please consider using overwrite flag to force upload.");
}
}
else
{
$this->info("File is alreay on Disk and md5 is equal, skipping.");
}
}
else
{
$this->info("File exists on Disk, md5 check is disabled, skipping.");
}
}
protected function iterateDirectory($cur_rel_path)
{
$cur_dir = $this->backup_src_dir.$cur_rel_path;
$dir_handle = opendir($cur_dir);
$this->info('Iterating directory: '.$cur_dir);
while ( $file = readdir($dir_handle) )
{
if ($file[0] == '.') continue; // skip '.' '..' and hidden files
$file_next = $cur_dir.DIRECTORY_SEPARATOR.$file;
$target_resource_path = $this->disk_dest_resrouce.$cur_rel_path.'/'.$file;
if ( is_dir($file_next) )
{
$res = $this->disk->getResource($target_resource_path);
if ( $res->has() === false )
{
$this->info("The Dir resource '$target_resource_path' doesn't exist. Going to create one");
$res->create();
}
$this->iterateDirectory($cur_rel_path.DIRECTORY_SEPARATOR.$file);
}
else
{
$this->backupFile($file_next, $target_resource_path);
}
}
}
public function log($level, $message, array $context = array())
{
if ($this->is_quiet_mod_enanled) return;
$pid = 'N/A';
if (function_exists('getmypid'))
{
$pid = getmypid();
}
echo date('Y-m-d H:i:s').' ('.$pid.')'.' ['.$level.'] '.$message.(count($context) ? '. Context: '.var_export($context, true) : '')."\n";
}
public function info($message, array $context = array())
{
return $this->log('INFO', $message, $context);
}
public function warn($message, array $context = array())
{
return $this->log('WARN', $message, $context);
}
}
/**
* Fetch options from the command line arguments
*/
$usage = "Usage: php ".basename(__FILE__)." --token=TOKEN src_backup_dir dest_ydisk_resource";
$longopts = array(
"--token: YD authorisaztion token, required" => "token:",
"--force: force overwrite, default 'no'" => "force::",
"--verify: verify MD5 checksums, default 'no'" => "verify::",
"--quiet: disable verbose output, default 'no'" => "quiet::",
);
$options = getopt('', $longopts);
if ($argc < 4
or !array_key_exists('token', $options) or strlen($options['token']) < 32
or $argv[$argc-2][0] == '-' or $argv[$argc-1][0] == '-')
{
echo "$usage\nAvailable options: \n";
foreach ($longopts as $opt_desc => $opt)
{
echo " $opt_desc\n";
}
echo "\nExample:\n".basename(__FILE__)." --token=270d7f9b7e23a15a7 /var/local/database_dump/ disk:/Backups/DataBase\n\n";
exit(1);
}
$backup_src_dir = $argv[$argc-2];
$disk_dest_resource = $argv[$argc-1];
foreach (array('force', 'verify', 'quiet') as $option)
{
if (array_key_exists($option, $options))
{
if ($options[$option] == 'yes')
{
$options[$option] = true;
}
}
else
{
$options[$option] = false;
}
}
/**
* Do the backup with these options
*/
$ydBackup = new YDiskBackup($options['token'], realpath($backup_src_dir), $disk_dest_resource, $options['force'], $options['verify'], $options['quiet']);
$ydBackup->run(); | php | MIT | 49f51b32f76cbfd123bb9fad7fdc63619121a884 | 2026-01-05T05:17:32.521772Z | false |
salesforce-marketingcloud/FuelSDK-PHP | https://github.com/salesforce-marketingcloud/FuelSDK-PHP/blob/8494244d071dc60cc709eedd92cbd0f3a7a7c965/src/ET_Continue.php | src/ET_Continue.php | <?php
// spl_autoload_register( function($class_name) {
// include_once 'src/'.$class_name.'.php';
// });
namespace FuelSdk;
/**
* This class represents ContinueRequest for SOAP operation.
*/
class ET_Continue extends ET_Constructor
{
/**
* Initializes a new instance of the class.
* @param ET_Client $authStub The ET client object which performs the auth token, refresh token using clientID clientSecret
* @param string $request_id The request ID from the SOAP response
*/
function __construct($authStub, $request_id)
{
$authStub->refreshToken();
$rrm = array();
$request = array();
$retrieveRequest = array();
$retrieveRequest["ContinueRequest"] = $request_id;
$retrieveRequest["ObjectType"] = null;
$request["RetrieveRequest"] = $retrieveRequest;
$rrm["RetrieveRequestMsg"] = $request;
$return = $authStub->__soapCall("Retrieve", $rrm, null, null , $out_header);
parent::__construct($return, $authStub->__getLastResponseHTTPCode());
if ($this->status){
if (property_exists($return, "Results")){
// We always want the results property when doing a retrieve to be an array
if (is_array($return->Results)){
$this->results = $return->Results;
} else {
$this->results = array($return->Results);
}
} else {
$this->results = array();
}
$this->moreResults = false;
if ($return->OverallStatus == "MoreDataAvailable") {
$this->moreResults = true;
}
if ($return->OverallStatus != "OK" && $return->OverallStatus != "MoreDataAvailable")
{
$this->status = false;
$this->message = $return->OverallStatus;
}
$this->request_id = $return->RequestID;
}
}
}
?> | php | MIT | 8494244d071dc60cc709eedd92cbd0f3a7a7c965 | 2026-01-05T05:17:42.419088Z | false |
salesforce-marketingcloud/FuelSDK-PHP | https://github.com/salesforce-marketingcloud/FuelSDK-PHP/blob/8494244d071dc60cc709eedd92cbd0f3a7a7c965/src/ET_ClickEvent.php | src/ET_ClickEvent.php | <?php
// spl_autoload_register( function($class_name) {
// include_once 'src/'.$class_name.'.php';
// });
namespace FuelSdk;
/**
* Represents ClickEvent Class.
* Contains information regarding a click on a link contained in a message.
*/
class ET_ClickEvent extends ET_GetSupport
{
/**
* @var bool Gets or sets a boolean value indicating whether to get since last batch. true if get since last batch; otherwise, false.
*/
public $getSinceLastBatch;
/**
* Initializes a new instance of the class and set the since last batch to true.
*/
function __construct()
{
$this->obj = "ClickEvent";
$this->getSinceLastBatch = true;
}
}
?> | php | MIT | 8494244d071dc60cc709eedd92cbd0f3a7a7c965 | 2026-01-05T05:17:42.419088Z | false |
salesforce-marketingcloud/FuelSDK-PHP | https://github.com/salesforce-marketingcloud/FuelSDK-PHP/blob/8494244d071dc60cc709eedd92cbd0f3a7a7c965/src/ET_ProfileAttribute.php | src/ET_ProfileAttribute.php | <?php
// spl_autoload_register( function($class_name) {
// include_once 'src/'.$class_name.'.php';
// });
namespace FuelSdk;
/**
* This class defines any additional attribute for a subscriber.
*/
class ET_ProfileAttribute extends ET_BaseObject
{
/**
* Initializes a new instance of the class and set the since last batch to true.
*/
function __construct()
{
$this->obj = "PropertyDefinition";
}
/**
* This method is used to create Property Definition for a subscriber
* @return ET_Configure Object of type ET_Configure which contains http status code, response, etc from the POST SOAP service
*/
function post()
{
return new ET_Configure($this->authStub, $this->obj, "create", $this->props);
}
/**
* This method is used to get Property Definition for a subscriber
* @return ET_Info Object of type ET_Info which contains http status code, response, etc from the GET SOAP service
*/
function get()
{
return new ET_Info($this->authStub, 'Subscriber', true);
}
/**
* This method is used to update Property Definition for a subscriber
* @return ET_Configure Object of type ET_Configure which contains http status code, response, etc from the UPDATE SOAP service
*/
function patch()
{
return new ET_Configure($this->authStub, $this->obj, "update", $this->props);
}
/**
* This method is used to delete Property Definition for a subscriber
* @return ET_Configure Object of type ET_Configure which contains http status code, response, etc from the DELETE SOAP service
*/
function delete()
{
return new ET_Configure($this->authStub, $this->obj, "delete", $this->props);
}
}
?> | php | MIT | 8494244d071dc60cc709eedd92cbd0f3a7a7c965 | 2026-01-05T05:17:42.419088Z | false |
salesforce-marketingcloud/FuelSDK-PHP | https://github.com/salesforce-marketingcloud/FuelSDK-PHP/blob/8494244d071dc60cc709eedd92cbd0f3a7a7c965/src/ET_CUDSupport.php | src/ET_CUDSupport.php | <?php
// spl_autoload_register( function($class_name) {
// include_once 'src/'.$class_name.'.php';
// });
namespace FuelSdk;
use \Exception;
/**
* This class represents the create, update, delete operation for SOAP service.
*/
class ET_CUDSupport extends ET_GetSupport
{
/**
* @return ET_Post Object of type ET_Post which contains http status code, response, etc from the POST SOAP service
*/
public function post()
{
$originalProps = $this->props;
if (property_exists($this, 'folderProperty') && !is_null($this->folderProperty) && !is_null($this->folderId)){
$this->props[$this->folderProperty] = $this->folderId;
} else if (property_exists($this, 'folderProperty') && !is_null($this->authStub->packageName)){
if (is_null($this->authStub->packageFolders)) {
$getPackageFolder = new ET_Folder();
$getPackageFolder->authStub = $this->authStub;
$getPackageFolder->props = array("ID", "ContentType");
$getPackageFolder->filter = array("Property" => "Name", "SimpleOperator" => "equals", "Value" => $this->authStub->packageName);
$resultPackageFolder = $getPackageFolder->get();
if ($resultPackageFolder->status){
$this->authStub->packageFolders = array();
foreach ($resultPackageFolder->results as $result){
$this->authStub->packageFolders[$result->ContentType] = $result->ID;
}
} else {
throw new Exception('Unable to retrieve folders from account due to: '.$resultPackageFolder->message);
}
}
if (!array_key_exists($this->folderMediaType,$this->authStub->packageFolders )){
if (is_null($this->authStub->parentFolders)) {
$parentFolders = new ET_Folder();
$parentFolders->authStub = $this->authStub;
$parentFolders->props = array("ID", "ContentType");
$parentFolders->filter = array("Property" => "ParentFolder.ID", "SimpleOperator" => "equals", "Value" => "0");
$resultParentFolders = $parentFolders->get();
if ($resultParentFolders->status) {
$this->authStub->parentFolders = array();
foreach ($resultParentFolders->results as $result){
$this->authStub->parentFolders[$result->ContentType] = $result->ID;
}
} else {
throw new Exception('Unable to retrieve folders from account due to: '.$resultParentFolders->message);
}
}
$newFolder = new ET_Folder();
$newFolder->authStub = $this->authStub;
$newFolder->props = array("Name" => $this->authStub->packageName, "Description" => $this->authStub->packageName, "ContentType"=> $this->folderMediaType, "IsEditable"=>"true", "ParentFolder" => array("ID" => $this->authStub->parentFolders[$this->folderMediaType]));
$folderResult = $newFolder->post();
if ($folderResult->status) {
$this->authStub->packageFolders[$this->folderMediaType] = $folderResult->results[0]->NewID;
} else {
throw new Exception('Unable to create folder for Post due to: '.$folderResult->message);
}
}
$this->props[$this->folderProperty] = $this->authStub->packageFolders[$this->folderMediaType];
}
$response = new ET_Post($this->authStub, $this->obj, $this->props);
$this->props = $originalProps;
return $response;
}
/**
* @return ET_Patch Object of type ET_Patch which contains http status code, response, etc from the PATCH SOAP service
*/
public function patch()
{
$originalProps = $this->props;
if (property_exists($this, 'folderProperty') && !is_null($this->folderProperty) && !is_null($this->folderId)){
$this->props[$this->folderProperty] = $this->folderId;
}
$response = new ET_Patch($this->authStub, $this->obj, $this->props);
$this->props = $originalProps;
return $response;
}
/**
* @return ET_Delete Object of type ET_Delete which contains http status code, response, etc from the DELETE SOAP service
*/
public function delete()
{
$response = new ET_Delete($this->authStub, $this->obj, $this->props);
return $response;
}
}
?> | php | MIT | 8494244d071dc60cc709eedd92cbd0f3a7a7c965 | 2026-01-05T05:17:42.419088Z | false |
salesforce-marketingcloud/FuelSDK-PHP | https://github.com/salesforce-marketingcloud/FuelSDK-PHP/blob/8494244d071dc60cc709eedd92cbd0f3a7a7c965/src/ET_UnsubEvent.php | src/ET_UnsubEvent.php | <?php
// spl_autoload_register( function($class_name) {
// include_once 'src/'.$class_name.'.php';
// });
namespace FuelSdk;
/**
* Contains information regarding a specific unsubscription action taken by a subscriber.
*/
class ET_UnsubEvent extends ET_GetSupport
{
/**
* @var bool Gets or sets a boolean value indicating whether this object get since last batch. true if get since last batch; otherwise, false.
*/
public $getSinceLastBatch;
/**
* Initializes a new instance of the class and set the since last batch to true.
*/
function __construct()
{
$this->obj = "UnsubEvent";
$this->getSinceLastBatch = true;
}
}
?> | php | MIT | 8494244d071dc60cc709eedd92cbd0f3a7a7c965 | 2026-01-05T05:17:42.419088Z | false |
salesforce-marketingcloud/FuelSDK-PHP | https://github.com/salesforce-marketingcloud/FuelSDK-PHP/blob/8494244d071dc60cc709eedd92cbd0f3a7a7c965/src/ET_PatchRest.php | src/ET_PatchRest.php | <?php
// spl_autoload_register( function($class_name) {
// include_once 'src/'.$class_name.'.php';
// });
namespace FuelSdk;
/**
* This class represents the PATCH operation for REST service.
*/
class ET_PatchRest extends ET_Constructor
{
/**
* Initializes a new instance of the class.
* @param ET_Client $authStub The ET client object which performs the auth token, refresh token using clientID clientSecret
* @param string $url The endpoint URL
* @param array $props Dictionary type array which may hold e.g. array('id' => '', 'key' => '')
*/
function __construct($authStub, $url, $props, $qs="")
{
// $restResponse = ET_Util::restPatch($url, json_encode($props), $authStub);
$restResponse = ET_Util::restPatch($url, json_encode($props), $authStub, $qs);
parent::__construct($restResponse->body, $restResponse->httpcode, true);
}
}
?> | php | MIT | 8494244d071dc60cc709eedd92cbd0f3a7a7c965 | 2026-01-05T05:17:42.419088Z | false |
salesforce-marketingcloud/FuelSDK-PHP | https://github.com/salesforce-marketingcloud/FuelSDK-PHP/blob/8494244d071dc60cc709eedd92cbd0f3a7a7c965/src/ET_Send.php | src/ET_Send.php | <?php
// spl_autoload_register( function($class_name) {
// include_once 'src/'.$class_name.'.php';
// });
namespace FuelSdk;
/**
* Used to send email and retrieve aggregate data based on a JobID.
*/
class ET_Send extends ET_CUDSupport
{
/**
* Initializes a new instance of the class and sets the obj property of parent.
*/
function __construct()
{
$this->obj = "Send";
}
}
?> | php | MIT | 8494244d071dc60cc709eedd92cbd0f3a7a7c965 | 2026-01-05T05:17:42.419088Z | false |
salesforce-marketingcloud/FuelSDK-PHP | https://github.com/salesforce-marketingcloud/FuelSDK-PHP/blob/8494244d071dc60cc709eedd92cbd0f3a7a7c965/src/ET_Asset.php | src/ET_Asset.php | <?php
// spl_autoload_register( function($class_name) {
// include_once 'src/'.$class_name.'.php';
// });
namespace FuelSdk;
/**
* An asset is an instance of any kind of content in the CMS.
*/
class ET_Asset extends ET_CUDSupportRest
{
/**
* The constructor will assign endpoint, urlProps, urlPropsRequired fields of parent ET_BaseObjectRest
*/
function __construct()
{
$this->path = "/guide/v1/contentItems/portfolio/{id}";
$this->urlProps = array("id");
$this->urlPropsRequired = array();
}
// method for calling a Fuel API using POST
/**
* @return object The stdClass object with property httpcode and body from the REST service after upload is finished
*/
public function upload()
{
// TODO create unit test for this function
$completeURL = $this->authStub->baseUrl . "/guide/v1/contentItems/portfolio/fileupload";
$post = array('file_contents'=>'@'.$this->props['filePath']);
$ch = curl_init();
$headers = array("User-Agent: ".ET_Util::getSDKVersion(), "Authorization: Bearer ".$this->authStub->getAuthToken());
curl_setopt ($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $completeURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
// Disable VerifyPeer for SSL
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$outputJSON = curl_exec($ch);
//curl_close ($ch);
$responseObject = new stdClass();
$responseObject->body = $outputJSON;
$responseObject->httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close ($ch);
return $responseObject;
}
/**
* @return null
*/
public function patch()
{
return null;
}
/**
* @return null
*/
public function delete()
{
return null;
}
}
?> | php | MIT | 8494244d071dc60cc709eedd92cbd0f3a7a7c965 | 2026-01-05T05:17:42.419088Z | false |
salesforce-marketingcloud/FuelSDK-PHP | https://github.com/salesforce-marketingcloud/FuelSDK-PHP/blob/8494244d071dc60cc709eedd92cbd0f3a7a7c965/src/ET_Client.php | src/ET_Client.php | <?php
//require __DIR__ . '/../vendor/autoload.php';
namespace FuelSdk;
use \RobRichards\WsePhp\WSSESoap;
use \Firebase\JWT;
use \Datetime;
use \SoapClient;
use \stdClass;
use \DateInterval;
use \DOMDocument;
use \DOMXPath;
use \Exception;
/**
* Auto load method to load dependent classes
*/
/**
* Defines a Client interface class which manages the authentication process.
* This is the main client class which performs authentication, obtains auth token, if expired refresh auth token.
* Settings/Configuration can be passed to this class during construction or set it in config.php file.
* Configuration passed as parameter overrides the values from the configuration file.
*
*/
class ET_Client extends SoapClient
{
/**
* @var string $packageName Folder/Package Name
*/
public $packageName;
/**
* @var array $packageFolders Array of Folder object properties.
*/
public $packageFolders;
/**
* @var ET_Folder Parent folder object.
*/
public $parentFolders;
/**
* @var string Proxy host.
*/
public $proxyHost;
/**
* @var string Proxy port.
*/
public $proxyPort;
/**
* @var string Proxy username.
*/
public $proxyUserName;
/**
* @var string Proxy password.
*/
public $proxyPassword;
/**
* @var boolean Require verification of peer name.
*/
public $sslVerifyPeer;
/**
* @var string APIs hostname
*/
public $baseUrl;
private $wsdlLoc, $debugSOAP, $lastHTTPCode, $clientId,
$clientSecret, $appsignature, $endpoint,
$tenantTokens, $tenantKey, $xmlLoc, $baseAuthUrl, $baseSoapUrl,
$useOAuth2Authentication, $accountId, $redirectURI, $applicationType, $authorizationCode, $scope;
private $defaultBaseSoapUrl = 'https://webservice.exacttarget.com/Service.asmx';
/**
* Initializes a new instance of the ET_Client class.
*
* @param boolean $getWSDL Flag to indicate whether to load WSDL from source.
* If true, WSDL is load from the source and saved in to path set in xmlLoc variable.
* If false, WSDL stored in the path set in xmlLoc is loaded.
* @param boolean $debug Flag to indicate whether debug information needs to be logged.
* Logging is enabled when the value is set to true and disabled when set to false.
* @param array $params Array of settings as string.</br>
* <b>Following are the possible settings.</b></br>
* <i><b>defaultwsdl</b></i> - WSDL location/path</br>
* <i><b>clientid</b></i> - Client Identifier optained from App Center</br>
* <i><b>clientsecred</b></i> - Client secret associated with clientid</br>
* <i><b>appsignature</b></i> - Application signature optained from App Center</br>
* <i><b>baseUrl</b></i> - ExactTarget SOAP API Url</br>
* <i><b>baseAuthUrl</b></i> - ExactTarget authentication rest api resource url</br>
* <b>If your application behind a proxy server, use the following setting</b></br>
* <i><b>proxyhost</b></i> - proxy server host name or ip address</br>
* <i><b>proxyport</b></i> - proxy server prot number</br>
* <i><b>proxyusername</b></i> - proxy server user name</br>
* <i><b>proxypassword</b></i> - proxy server password</br>
* <i><b>sslverifypeer</b></i> - Require verification of peer name</br>
*/
function __construct($getWSDL = false, $debug = false, $params = null)
{
$tenantTokens = array();
$config = false;
$this->xmlLoc = 'ExactTargetWSDL.xml';
if (file_exists(realpath("config.php")))
$config = include 'config.php';
if ($config)
{
$this->wsdlLoc = $config['defaultwsdl'];
$this->clientId = $config['clientid'];
$this->clientSecret = $config['clientsecret'];
$this->appsignature = $config['appsignature'];
$this->baseAuthUrl = $config["baseAuthUrl"];
if (array_key_exists('baseSoapUrl', $config)) {
if (!empty($config["baseSoapUrl"])) {
$this->baseSoapUrl = $config["baseSoapUrl"];
} else {
$this->baseSoapUrl = $this->defaultBaseSoapUrl;
}
}
if(array_key_exists('useOAuth2Authentication', $config)){$this->useOAuth2Authentication = $config['useOAuth2Authentication'];}
if(array_key_exists("baseUrl", $config))
{
$this->baseUrl = $config["baseUrl"];
}
else
{
if($this->isNullOrEmptyString($this->useOAuth2Authentication) || $this->useOAuth2Authentication === false) {
throw new Exception("baseUrl is null: Must be provided in config file when instantiating ET_Client");
}
}
if (array_key_exists('accountId', $config)){$this->accountId = $config['accountId'];}
if (array_key_exists('applicationType', $config))
{
$this->applicationType = $config['applicationType'];
}
if (array_key_exists('redirectURI', $config))
{
$this->redirectURI = $config['redirectURI'];
}
if (array_key_exists('authorizationCode', $config))
{
$this->authorizationCode = $config['authorizationCode'];
}
if (array_key_exists('scope', $config)){$this->scope = $config['scope'];}
if (array_key_exists('xmlloc', $config)){$this->xmlLoc = $config['xmlloc'];}
if(array_key_exists('proxyhost', $config)){$this->proxyHost = $config['proxyhost'];}
if (array_key_exists('proxyport', $config)){$this->proxyPort = $config['proxyport'];}
if (array_key_exists('proxyusername', $config)){$this->proxyUserName = $config['proxyusername'];}
if (array_key_exists('proxypassword', $config)){$this->proxyPassword = $config['proxypassword'];}
if (array_key_exists('sslverifypeer', $config)){$this->sslVerifyPeer = $config['sslverifypeer'];}
}
if ($params)
{
if (array_key_exists('defaultwsdl', $params)){$this->wsdlLoc = $params['defaultwsdl'];}
else {$this->wsdlLoc = "https://webservice.exacttarget.com/etframework.wsdl";}
if (array_key_exists('clientid', $params)){$this->clientId = $params['clientid'];}
if (array_key_exists('clientsecret', $params)){$this->clientSecret = $params['clientsecret'];}
if (array_key_exists('appsignature', $params)){$this->appsignature = $params['appsignature'];}
if (array_key_exists('xmlloc', $params)){$this->xmlLoc = $params['xmlloc'];}
if (array_key_exists('proxyhost', $params)){$this->proxyHost = $params['proxyhost'];}
if (array_key_exists('proxyport', $params)){$this->proxyPort = $params['proxyport'];}
if (array_key_exists('proxyusername', $params)) {$this->proxyUserName = $params['proxyusername'];}
if (array_key_exists('proxypassword', $params)) {$this->proxyPassword = $params['proxypassword'];}
if (array_key_exists('sslverifypeer', $params)) {$this->sslVerifyPeer = $params['sslverifypeer'];}
if (array_key_exists('baseUrl', $params))
{
$this->baseUrl = $params['baseUrl'];
}
else
{
$this->baseUrl = "https://www.exacttargetapis.com";
}
if (array_key_exists('baseAuthUrl', $params))
{
$this->baseAuthUrl = $params['baseAuthUrl'];
}
else
{
$this->baseAuthUrl = "https://auth.exacttargetapis.com";
}
if (array_key_exists('baseSoapUrl', $params))
{
if (!empty($params["baseSoapUrl"])) {
$this->baseSoapUrl = $params['baseSoapUrl'];
} else {
$this->baseSoapUrl = $this->defaultBaseSoapUrl;
}
}
if (array_key_exists('useOAuth2Authentication', $params))
{
$this->useOAuth2Authentication = $params['useOAuth2Authentication'];
}
if (array_key_exists('accountId', $params))
{
$this->accountId = $params['accountId'];
}
if (array_key_exists('scope', $params))
{
$this->scope = $params['scope'];
}
if (array_key_exists('applicationType', $params))
{
$this->applicationType = $params['applicationType'];
}
if (array_key_exists('redirectURI', $params))
{
$this->redirectURI = $params['redirectURI'];
}
if (array_key_exists('authorizationCode', $params))
{
$this->authorizationCode = $params['authorizationCode'];
}
}
$this->debugSOAP = $debug;
if (empty($this->applicationType)){
$this->applicationType = 'server';
}
if($this->applicationType == 'public' || $this->applicationType == 'web'){
if (empty($this->redirectURI) || empty($this->authorizationCode)){
throw new Exception('redirectURI or authorizationCode is null: Must be provided in config file or passed when instantiating ET_Client');
}
}
if($this->applicationType == 'public'){
if (empty($this->clientId)){
throw new Exception('clientid is null: Must be provided in config file or passed when instantiating ET_Client');
}
}
else {
if (empty($this->clientId) || empty($this->clientSecret)) {
throw new Exception('clientid or clientsecret is null: Must be provided in config file or passed when instantiating ET_Client');
}
}
if ($getWSDL){$this->CreateWSDL($this->wsdlLoc);}
if ($params && array_key_exists('jwt', $params)){
if (!property_exists($this,'appsignature') || is_null($this->appsignature)){
throw new Exception('Unable to utilize JWT for SSO without appsignature: Must be provided in config file or passed when instantiating ET_Client');
}
$decodedJWT = JWT::decode($params['jwt'], $this->appsignature);
$dv = new DateInterval('PT'.$decodedJWT->request->user->expiresIn.'S');
$newexpTime = new DateTime();
$this->setAuthToken($this->tenantKey, $decodedJWT->request->user->oauthToken, $newexpTime->add($dv));
$this->setInternalAuthToken($this->tenantKey, $decodedJWT->request->user->internalOauthToken);
$this->setRefreshToken($this->tenantKey, $decodedJWT->request->user->refreshToken);
$this->packageName = $decodedJWT->request->application->package;
}
$this->refreshToken();
if ($this->baseSoapUrl) {
$this->endpoint = $this->baseSoapUrl;
} else {
$cache = new ET_CacheService($this->clientId, $this->clientSecret);
$cacheData = $cache->get();
if (!is_null($cacheData) && $cacheData->url) {
$this->endpoint = $cacheData->url;
} else {
try {
$url = $this->baseUrl."/platform/v1/endpoints/soap";
$endpointResponse = ET_Util::restGet($url, $this, $this->getAuthToken($this->tenantKey));
$endpointObject = json_decode($endpointResponse->body);
if ($endpointObject && property_exists($endpointObject,"url")){
$this->endpoint = $endpointObject->url;
} else {
$this->endpoint = $this->defaultBaseSoapUrl;
}
} catch (Exception $e) {
$this->endpoint = $this->defaultBaseSoapUrl;
}
$cache->write($this->endpoint);
}
}
$context = stream_context_create([
'ssl' => [
'verify_peer' => ET_Util::shouldVerifySslPeer($this->sslVerifyPeer)
]
]);
$soapOptions = array(
'stream_context' => $context
);
if (!empty($this->proxyHost)) {
$soapOptions['proxy_host'] = $this->proxyHost;
}
if (!empty($this->proxyPort)) {
$soapOptions['proxy_port'] = $this->proxyPort;
}
if (!empty($this->proxyUserName)) {
$soapOptions['proxy_username'] = $this->proxyUserName;
}
if (!empty($this->proxyPassword)) {
$soapOptions['proxy_password'] = $this->proxyPassword;
}
parent::__construct($this->xmlLoc, $soapOptions);
parent::__setLocation($this->endpoint);
}
/**
* Gets the refresh token using the authentication URL.
*
* @param boolean $forceRefresh Flag to indicate a force refresh of authentication toekn.
* @return void
*/
function refreshToken($forceRefresh = false)
{
if ($this->useOAuth2Authentication === true){
$this->refreshTokenWithOAuth2($forceRefresh);
return;
}
if (property_exists($this, "sdl") && $this->sdl == 0){
parent::__construct($this->xmlLoc, array('trace'=>1, 'exceptions'=>0));
}
try {
$currentTime = new DateTime();
if (is_null($this->getAuthTokenExpiration($this->tenantKey))){
$timeDiff = 0;
} else {
$timeDiff = $currentTime->diff($this->getAuthTokenExpiration($this->tenantKey))->format('%i');
$timeDiff = $timeDiff + (60 * $currentTime->diff($this->getAuthTokenExpiration($this->tenantKey))->format('%H'));
}
if (is_null($this->getAuthToken($this->tenantKey)) || ($timeDiff < 5) || $forceRefresh ){
$url = $this->tenantKey == null
? $this->baseAuthUrl."/v1/requestToken?legacy=1"
: $this->baseUrl."/provisioning/v1/tenants/{$this->tenantKey}/requestToken?legacy=1";
$jsonRequest = new stdClass();
$jsonRequest->clientId = $this->clientId;
$jsonRequest->clientSecret = $this->clientSecret;
$jsonRequest->accessType = "offline";
if (!is_null($this->getRefreshToken($this->tenantKey))){
$jsonRequest->refreshToken = $this->getRefreshToken($this->tenantKey);
}
$authResponse = ET_Util::restPost($url, json_encode($jsonRequest), $this);
$authObject = json_decode($authResponse->body);
//echo "auth: \n";
//print_r($authResponse);
if ($authResponse && property_exists($authObject,"accessToken")){
$dv = new DateInterval('PT'.$authObject->expiresIn.'S');
$newexpTime = new DateTime();
$this->setAuthToken($this->tenantKey, $authObject->accessToken, $newexpTime->add($dv));
$this->setInternalAuthToken($this->tenantKey, $authObject->legacyToken);
if (property_exists($authObject,'refreshToken')){
$this->setRefreshToken($this->tenantKey, $authObject->refreshToken);
}
} else {
throw new Exception('Unable to validate App Keys(ClientID/ClientSecret) provided, requestToken response:'.$authResponse->body );
}
}
} catch (Exception $e) {
throw new Exception('Unable to validate App Keys(ClientID/ClientSecret) provided.: '.$e->getMessage());
}
}
function createPayloadForOauth2(){
$payload = new stdClass();
$payload->client_id = $this->clientId;
if($this->applicationType != 'public') {
$payload->client_secret = $this->clientSecret;
}
$refreshKey = $this->getRefreshToken(null);
if(!empty($refreshKey)){
$payload->grant_type = 'refresh_token';
$payload->refresh_token = $refreshKey;
} else if($this->applicationType == 'public' || $this->applicationType == 'web'){
$payload->grant_type = 'authorization_code';
$payload->code = $this->authorizationCode;
$payload->redirect_uri = $this->redirectURI;
} else {
$payload->grant_type = 'client_credentials';
}
if (!empty(trim($this->accountId))){
$payload->account_id = $this->accountId;
}
if (!empty(trim($this->scope))){
$payload->scope = $this->scope;
}
return $payload;
}
function refreshTokenWithOAuth2($forceRefresh = false)
{
if (property_exists($this, "sdl") && $this->sdl == 0){
parent::__construct($this->xmlLoc, array('trace'=>1, 'exceptions'=>0));
}
try {
$currentTime = new DateTime();
if (is_null($this->getAuthTokenExpiration($this->tenantKey))){
$timeDiff = 0;
} else {
$timeDiff = $currentTime->diff($this->getAuthTokenExpiration($this->tenantKey))->format('%i');
$timeDiff = $timeDiff + (60 * $currentTime->diff($this->getAuthTokenExpiration($this->tenantKey))->format('%H'));
}
if (is_null($this->getAuthToken($this->tenantKey)) || ($timeDiff < 5) || $forceRefresh ){
$url = $this->baseAuthUrl."/v2/token";
$jsonRequest = $this->createPayloadForOauth2();
$authResponse = ET_Util::restPost($url, json_encode($jsonRequest), $this);
$authObject = json_decode($authResponse->body);
if ($authResponse && property_exists($authObject,"access_token")){
$dv = new DateInterval('PT'.$authObject->expires_in.'S');
$newexpTime = new DateTime();
$this->setAuthToken($this->tenantKey, $authObject->access_token, $newexpTime->add($dv));
$this->setInternalAuthToken($this->tenantKey, $authObject->access_token);
$this->baseUrl = $authObject->rest_instance_url;
$this->baseSoapUrl= $authObject->soap_instance_url."Service.asmx";
if (property_exists($authObject,'refresh_token')){
$this->setRefreshToken($this->tenantKey, $authObject->refresh_token);
}
} else {
throw new Exception('Unable to validate App Keys(ClientID/ClientSecret) provided, requestToken response:'.$authResponse->body );
}
}
} catch (Exception $e) {
throw new Exception('Unable to validate App Keys(ClientID/ClientSecret) provided.: '.$e->getMessage());
}
}
/**
* Returns the HTTP code return by the last SOAP/Rest call
*
* @return lastHTTPCode
*/
function __getLastResponseHTTPCode()
{
return $this->lastHTTPCode;
}
/**
* Create the WSDL file at specified location.
* @param string location or path of the WSDL file to be created.
* @return void
*/
function CreateWSDL($wsdlLoc)
{
try{
$getNewWSDL = true;
$remoteTS = $this->GetLastModifiedDate($wsdlLoc);
if (file_exists($this->xmlLoc)){
$localTS = filemtime($this->xmlLoc);
if ($remoteTS <= $localTS)
{
$getNewWSDL = false;
}
}
if ($getNewWSDL){
$newWSDL = file_get_contents($wsdlLoc);
file_put_contents($this->xmlLoc, $newWSDL);
}
}
catch (Exception $e) {
throw new Exception('Unable to store local copy of WSDL file:'.$e->getMessage()."\n");
}
}
/**
* Returns last modified date of the URL
*
* @param [type] $remotepath
* @return string Last modified date
*/
function GetLastModifiedDate($remotepath)
{
$curl = curl_init($remotepath);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, ET_Util::shouldVerifySslPeer($this->sslVerifyPeer));
curl_setopt($curl, CURLOPT_NOBODY, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_FILETIME, true);
if (!empty($this->proxyHost)) {
curl_setopt($curl, CURLOPT_PROXY, $this->proxyHost);
}
if (!empty($this->proxyPort)) {
curl_setopt($curl, CURLOPT_PROXYPORT, $this->proxyPort);
}
if (!empty($this->proxyUserName) && !empty($this->proxyPassword)) {
curl_setopt($curl, CURLOPT_PROXYAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_PROXYUSERPWD, $this->proxyUserName.':'.$this->proxyPassword);
}
$result = curl_exec($curl);
if ($result === false) {
throw new Exception(curl_error($curl));
}
return curl_getinfo($curl, CURLINFO_FILETIME);
}
/**
* Perfoms an soap request.
*
* @param string $request Soap request xml
* @param string $location Url as string
* @param string $saction Soap action name
* @param string $version Future use
* @param integer $one_way Future use
* @return string Soap web service request result
*/
function __doRequest($request, $location, $saction, $version, $one_way = 0)
{
$doc = new DOMDocument();
$doc->loadXML($request);
if($this->useOAuth2Authentication === true){
$this->addOAuth($doc, $this->getAuthToken($this->tenantKey));
$content = $doc->saveXML();
}
else{
$objWSSE = new WSSESoap($doc);
$objWSSE->addUserToken("*", "*", FALSE);
$this->addOAuth($doc, $this->getInternalAuthToken($this->tenantKey));
$content = $objWSSE->saveXML();
}
if ($this->debugSOAP){
error_log ('FuelSDK SOAP Request: ');
error_log (str_replace($this->getInternalAuthToken($this->tenantKey),"REMOVED",$content));
}
$headers = array("Content-Type: text/xml","SOAPAction: ".$saction, "User-Agent: ".ET_Util::getSDKVersion());
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $location);
curl_setopt ($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $content);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, ET_Util::shouldVerifySslPeer($this->sslVerifyPeer));
curl_setopt($ch, CURLOPT_USERAGENT, ET_Util::getSDKVersion());
if (!empty($this->proxyHost)) {
curl_setopt($ch, CURLOPT_PROXY, $this->proxyHost);
}
if (!empty($this->proxyPort)) {
curl_setopt($ch, CURLOPT_PROXYPORT, $this->proxyPort);
}
if (!empty($this->proxyUserName) && !empty($this->proxyPassword)) {
curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_PROXYUSERPWD, $this->proxyUserName.':'.$this->proxyPassword);
}
$output = curl_exec($ch);
$this->lastHTTPCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $output;
}
/**
* Add OAuth token to the header of the soap request
*
* @param string $doc Soap request as xml string
* @param string $token OAuth token
* @return void
*/
public function addOAuth( $doc, $token)
{
$soapDoc = $doc;
$envelope = $doc->documentElement;
$soapNS = $envelope->namespaceURI;
$soapPFX = $envelope->prefix;
$SOAPXPath = new DOMXPath($doc);
$SOAPXPath->registerNamespace('wssoap', $soapNS);
$headers = $SOAPXPath->query('//wssoap:Envelope/wssoap:Header');
$header = $headers->item(0);
if (! $header) {
$header = $soapDoc->createElementNS($soapNS, $soapPFX.':Header');
$envelope->insertBefore($header, $envelope->firstChild);
}
if ($this->useOAuth2Authentication === true){
$authnode = $soapDoc->createElementNS('http://exacttarget.com','fueloauth',$token);
}
else{
$SOAPXPath->registerNamespace('wswsse', 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd');
$authnode = $soapDoc->createElementNS('http://exacttarget.com', 'oAuth');
$oauthtoken = $soapDoc->createElementNS(null,'oAuthToken',$token);
$authnode->appendChild($oauthtoken);
}
$header->appendChild($authnode);
}
/**
* Get the authentication token.
* @return string
*/
public function getAuthToken($tenantKey = null)
{
$tenantKey = $tenantKey == null ? $this->tenantKey : $tenantKey;
if ($this->tenantTokens[$tenantKey] == null) {
$this->tenantTokens[$tenantKey] = array();
}
return isset($this->tenantTokens[$tenantKey]['authToken'])
? $this->tenantTokens[$tenantKey]['authToken']
: null;
}
/**
* Set the authentication token in the tenantTokens array.
* @param string $tenantKey Tenant key for which auth toke to be set
* @param string $authToken Authentication token to be set
* @param string $authTokenExpiration Authentication token expiration value
*/
function setAuthToken($tenantKey, $authToken, $authTokenExpiration)
{
if ($this->tenantTokens[$tenantKey] == null) {
$this->tenantTokens[$tenantKey] = array();
}
$this->tenantTokens[$tenantKey]['authToken'] = $authToken;
$this->tenantTokens[$tenantKey]['authTokenExpiration'] = $authTokenExpiration;
}
/**
* Get the Auth Token Expiration.
* @param string $tenantKey Tenant key for which authenication token is returned
* @return string Authenticaiton token for the tenant key
*/
function getAuthTokenExpiration($tenantKey)
{
$tenantKey = $tenantKey == null ? $this->tenantKey : $tenantKey;
if ($this->tenantTokens[$tenantKey] == null) {
$this->tenantTokens[$tenantKey] = array();
}
return isset($this->tenantTokens[$tenantKey]['authTokenExpiration'])
? $this->tenantTokens[$tenantKey]['authTokenExpiration']
: null;
}
/**
* Get the internal authentication token.
* @param string $tenantKey
* @return string Internal authenication token
*/
function getInternalAuthToken($tenantKey)
{
$tenantKey = $tenantKey == null ? $this->tenantKey : $tenantKey;
if ($this->tenantTokens[$tenantKey] == null) {
$this->tenantTokens[$tenantKey] = array();
}
return isset($this->tenantTokens[$tenantKey]['internalAuthToken'])
? $this->tenantTokens[$tenantKey]['internalAuthToken']
: null;
}
/**
* Set the internal auth tokan.
* @param string $tenantKey
* @param string $internalAuthToken
*/
function setInternalAuthToken($tenantKey, $internalAuthToken) {
if ($this->tenantTokens[$tenantKey] == null) {
$this->tenantTokens[$tenantKey] = array();
}
$this->tenantTokens[$tenantKey]['internalAuthToken'] = $internalAuthToken;
}
/**
* Set the refresh authentication token.
* @param string $tenantKey Tenant key to which refresh token is set
* @param string $refreshToken Refresh authenication token
*/
function setRefreshToken($tenantKey, $refreshToken)
{
if ($this->tenantTokens[$tenantKey] == null) {
$this->tenantTokens[$tenantKey] = array();
}
$this->tenantTokens[$tenantKey]['refreshToken'] = $refreshToken;
}
/**
* Get the refresh token for the tenant.
*
* @param string $tenantKey
* @return string Refresh token for the tenant
*/
public function getRefreshToken($tenantKey)
{
$tenantKey = $tenantKey == null ? $this->tenantKey : $tenantKey;
if ($this->tenantTokens[$tenantKey] == null) {
$this->tenantTokens[$tenantKey] = array();
}
return isset($this->tenantTokens[$tenantKey]['refreshToken'])
? $this->tenantTokens[$tenantKey]['refreshToken']
: null;
}
/**
* Add subscriber to list.
*
* @param string $emailAddress Email address of the subscriber
* @param array $listIDs Array of list id to which the subscriber is added
* @param string $subscriberKey Newly added subscriber key
* @return mixed post or patch response object. If the subscriber already existing patch response is returned otherwise post response returned.
*/
function AddSubscriberToList($emailAddress, $listIDs, $subscriberKey = null)
{
$newSub = new ET_Subscriber;
$newSub->authStub = $this;
$lists = array();
foreach ($listIDs as $key => $value){
$lists[] = array("ID" => $value);
}
//if (is_string($emailAddress)) {
$newSub->props = array("EmailAddress" => $emailAddress, "Lists" => $lists);
if ($subscriberKey != null ){
$newSub->props['SubscriberKey'] = $subscriberKey;
}
// Try to add the subscriber
$postResponse = $newSub->post();
if ($postResponse->status == false) {
// If the subscriber already exists in the account then we need to do an update.
// Update Subscriber On List
if ($postResponse->results[0]->ErrorCode == "12014") {
$patchResponse = $newSub->patch();
return $patchResponse;
}
}
return $postResponse;
}
function AddSubscribersToLists($subs, $listIDs)
{
//Create Lists
foreach ($listIDs as $key => $value){
$lists[] = array("ID" => $value);
}
for ($i = 0; $i < count($subs); $i++) {
$copyLists = array();
foreach ($lists as $k => $v) {
$NewProps = array();
foreach($v as $prop => $value) {
$NewProps[$prop] = $value;
}
$copyLists[$k] = $NewProps;
}
$subs[$i]["Lists"] = $copyLists;
}
$response = new ET_Post($this, "Subscriber", $subs, true);
return $response;
}
/**
* Create a new data extension based on the definition passed
*
* @param array $dataExtensionDefinitions Data extension definition properties as an array
* @return mixed post response object
*/
function CreateDataExtensions($dataExtensionDefinitions)
{
$newDEs = new ET_DataExtension();
$newDEs->authStub = $this;
$newDEs->props = $dataExtensionDefinitions;
$postResponse = $newDEs->post();
return $postResponse;
}
/**
* Starts an send operation for the TriggerredSend records
*
* @param array $arrayOfTriggeredRecords Array of TriggeredSend records
* @return mixed Send reponse object
*/
function SendTriggeredSends($arrayOfTriggeredRecords)
{
$sendTS = new ET_TriggeredSend();
$sendTS->authStub = $this;
$sendTS->props = $arrayOfTriggeredRecords;
$sendResponse = $sendTS->send();
return $sendResponse;
}
/**
* Create an email send definition, send the email based on the definition and delete the definition.
*
* @param string $emailID Email identifier for which the email is sent
* @param string $listID Send definition list identifier
* @param string $sendClassficationCustomerKey Send classification customer key
* @return mixed Final delete action result
*/
function SendEmailToList($emailID, $listID, $sendClassficationCustomerKey)
{
$email = new ET_Email_SendDefinition();
$email->props = array("Name"=> uniqid(), "CustomerKey"=>uniqid(), "Description"=>"Created with FuelSDK");
$email->props["SendClassification"] = array("CustomerKey"=>$sendClassficationCustomerKey);
$email->props["SendDefinitionList"] = array("List"=> array("ID"=>$listID), "DataSourceTypeID"=>"List");
$email->props["Email"] = array("ID"=>$emailID);
$email->authStub = $this;
$result = $email->post();
if ($result->status) {
$sendresult = $email->send();
if ($sendresult->status) {
$deleteresult = $email->delete();
return $sendresult;
} else {
throw new Exception("Unable to send using send definition due to: ".print_r($result,true));
}
} else {
throw new Exception("Unable to create send definition due to: ".print_r($result,true));
}
}
/**
* Create an email send definition, send the email based on the definition and delete the definition.
*
* @param string $emailID Email identifier for which the email is sent
* @param string $sendableDataExtensionCustomerKey Sendable data extension customer key
* @param string $sendClassficationCustomerKey Send classification customer key
* @return mixed Final delete action result
*/
function SendEmailToDataExtension($emailID, $sendableDataExtensionCustomerKey, $sendClassficationCustomerKey)
{
$email = new ET_Email_SendDefinition();
$email->props = array("Name"=>uniqid(), "CustomerKey"=>uniqid(), "Description"=>"Created with FuelSDK");
$email->props["SendClassification"] = array("CustomerKey"=> $sendClassficationCustomerKey);
$email->props["SendDefinitionList"] = array("CustomerKey"=> $sendableDataExtensionCustomerKey, "DataSourceTypeID"=>"CustomObject");
$email->props["Email"] = array("ID"=>$emailID);
$email->authStub = $this;
$result = $email->post();
if ($result->status) {
$sendresult = $email->send();
if ($sendresult->status) {
$deleteresult = $email->delete();
return $sendresult;
} else {
throw new Exception("Unable to send using send definition due to:".print_r($result,true));
}
} else {
throw new Exception("Unable to create send definition due to: ".print_r($result,true));
}
}
/**
* Create an import definition and start the import process
*
* @param string $listId List identifier. Used as the destination object identifier.
* @param string $fileName Name of the file to be imported
* @return mixed Returns the import process result
*/
function CreateAndStartListImport($listId,$fileName)
{
$import = new ET_Import();
$import->authStub = $this;
$import->props = array("Name"=> "SDK Generated Import ".uniqid());
$import->props["CustomerKey"] = uniqid();
$import->props["Description"] = "SDK Generated Import";
$import->props["AllowErrors"] = "true";
$import->props["DestinationObject"] = array("ID"=>$listId);
$import->props["FieldMappingType"] = "InferFromColumnHeadings";
$import->props["FileSpec"] = $fileName;
$import->props["FileType"] = "CSV";
$import->props["RetrieveFileTransferLocation"] = array("CustomerKey"=>"ExactTarget Enhanced FTP");
$import->props["UpdateType"] = "AddAndUpdate";
$result = $import->post();
if ($result->status) {
return $import->start();
} else {
throw new Exception("Unable to create import definition due to: ".print_r($result,true));
}
}
/**
* Create an import definition and start the import process
*
* @param string $dataExtensionCustomerKey Data extension customer key. Used as the destination object identifier.
* @param string $fileName Name of the file to be imported
* @param bool $overwrite Flag to indicate to overwrite the uploaded file
* @return mixed Returns the import process result
*/
function CreateAndStartDataExtensionImport($dataExtensionCustomerKey, $fileName, $overwrite)
{
$import = new ET_Import();
$import->authStub = $this;
$import->props = array("Name"=> "SDK Generated Import ".uniqid());
$import->props["CustomerKey"] = uniqid();
$import->props["Description"] = "SDK Generated Import";
$import->props["AllowErrors"] = "true";
| php | MIT | 8494244d071dc60cc709eedd92cbd0f3a7a7c965 | 2026-01-05T05:17:42.419088Z | true |
salesforce-marketingcloud/FuelSDK-PHP | https://github.com/salesforce-marketingcloud/FuelSDK-PHP/blob/8494244d071dc60cc709eedd92cbd0f3a7a7c965/src/ET_Constructor.php | src/ET_Constructor.php | <?php
namespace FuelSdk;
/**
* This class represents the contructor for all web service (SOAP/REST) operation and holds HTTP status code, response, result, etc.
*/
class ET_Constructor
{
/**
* @var bool holds the status of the web service operation: true=success, false=failure
*/
public $status;
/**
* @var int holds the HTTP status code e.g. 200, 404, etc
*/
public $code;
/**
* @var string holds error message for SOAP call, else holds raw response if json_decode fails
*/
public $message;
/**
* @var stdClass Object contains the complete result of the web service operation
*/
public $results;
/**
* @var string the request identifier
*/
public $request_id;
/**
* @var bool whether more results are available or not
*/
public $moreResults;
/**
* Initializes a new instance of the class.
* @param string $requestresponse The response from the request
* @param int $httpcode The HTTP status code e.g. 200, 404. etc
* @param bool $restcall Whether to make REST or SOAP call, default is false i.e. SOAP calls
*/
function __construct($requestresponse, $httpcode, $restcall = false)
{
$this->code = $httpcode;
if (!$restcall) {
if(is_soap_fault($requestresponse)) {
$this->status = false;
$this->message = "SOAP Fault: (faultcode: {$requestresponse->faultcode}, faultstring: {$requestresponse->faultstring})";
$this->message = "{$requestresponse->faultcode} {$requestresponse->faultstring})";
} else {
$this->status = true;
}
} else {
if ($this->code != 200 && $this->code != 201 && $this->code != 202) {
$this->status = false;
} else {
$this->status = true;
}
if (json_decode($requestresponse) != null){
$this->results = json_decode($requestresponse);
} else {
$this->message = $requestresponse;
}
}
}
}
?> | php | MIT | 8494244d071dc60cc709eedd92cbd0f3a7a7c965 | 2026-01-05T05:17:42.419088Z | false |
salesforce-marketingcloud/FuelSDK-PHP | https://github.com/salesforce-marketingcloud/FuelSDK-PHP/blob/8494244d071dc60cc709eedd92cbd0f3a7a7c965/src/ET_BaseObjectRest.php | src/ET_BaseObjectRest.php | <?php
namespace FuelSdk;
/**
* This class represents the base object for REST operation.
*/
class ET_BaseObjectRest
{
/**
* @var ET_Client The ET client object which performs the auth token, refresh token using clientID clientSecret
*/
public $authStub;
/**
* @var array Dictionary type array which may hold e.g. array('id' => '', 'key' => '')
*/
public $props;
/**
* @var string Organization Identifier.
*/
public $organizationId;
/**
* @var string Organization Key.
*/
public $organizationKey;
/**
* @var string $path path to use when constructing the endpoint URL ($client->baseUrl.$this->path)
*/
protected $path;
/**
* @var string[] $urlProps array of string having properties or fields name found in the endpoint URL
*/
protected $urlProps;
/**
* @var string[] $urlPropsRequired array of string having only required fields*/
protected $urlPropsRequired;
}
?> | php | MIT | 8494244d071dc60cc709eedd92cbd0f3a7a7c965 | 2026-01-05T05:17:42.419088Z | false |
salesforce-marketingcloud/FuelSDK-PHP | https://github.com/salesforce-marketingcloud/FuelSDK-PHP/blob/8494244d071dc60cc709eedd92cbd0f3a7a7c965/src/ET_ExtractDescription.php | src/ET_ExtractDescription.php | <?php
namespace FuelSdk;
/**
* Contains information about the opening of a message send by a subscriber.
*/
class ET_ExtractDescription extends ET_GetSupport
{
/**
* @var bool Gets or sets a boolean value indicating whether this object get since last batch. true if get since last batch; otherwise, false.
*/
//public $getSinceLastBatch;
/**
* Initializes a new instance of the class and set the since last batch to true.
*/
function __construct()
{
$this->obj = "ExtractDescription";
//$this->getSinceLastBatch = true;
}
}
?> | php | MIT | 8494244d071dc60cc709eedd92cbd0f3a7a7c965 | 2026-01-05T05:17:42.419088Z | false |
salesforce-marketingcloud/FuelSDK-PHP | https://github.com/salesforce-marketingcloud/FuelSDK-PHP/blob/8494244d071dc60cc709eedd92cbd0f3a7a7c965/src/ET_SentEvent.php | src/ET_SentEvent.php | <?php
// spl_autoload_register( function($class_name) {
// include_once 'src/'.$class_name.'.php';
// });
namespace FuelSdk;
/**
* Contains tracking data related to a send, including information on individual subscribers.
*/
class ET_SentEvent extends ET_GetSupport
{
/**
* @var bool Gets or sets a boolean value indicating whether this object get since last batch. true if get since last batch; otherwise, false.
*/
public $getSinceLastBatch;
/**
* Initializes a new instance of the class and set the since last batch to true.
*/
function __construct()
{
$this->obj = "SentEvent";
$this->getSinceLastBatch = true;
}
}
?> | php | MIT | 8494244d071dc60cc709eedd92cbd0f3a7a7c965 | 2026-01-05T05:17:42.419088Z | false |
salesforce-marketingcloud/FuelSDK-PHP | https://github.com/salesforce-marketingcloud/FuelSDK-PHP/blob/8494244d071dc60cc709eedd92cbd0f3a7a7c965/src/ET_Email.php | src/ET_Email.php | <?php
// spl_autoload_register( function($class_name) {
// include_once 'src/'.$class_name.'.php';
// });
namespace FuelSdk;
/**
* ET_Email - Represents an email in a Marketing Cloud account.
*/
class ET_Email extends ET_CUDSupport
{
/**
* @var int Gets or sets the folder identifier.
*/
public $folderId;
/**
* Initializes a new instance of the class and will assign obj, folderProperty, folderMediaType property
*/
function __construct()
{
$this->obj = "Email";
$this->folderProperty = "CategoryID";
$this->folderMediaType = "email";
}
}
?> | php | MIT | 8494244d071dc60cc709eedd92cbd0f3a7a7c965 | 2026-01-05T05:17:42.419088Z | false |
salesforce-marketingcloud/FuelSDK-PHP | https://github.com/salesforce-marketingcloud/FuelSDK-PHP/blob/8494244d071dc60cc709eedd92cbd0f3a7a7c965/src/ET_List.php | src/ET_List.php | <?php
// spl_autoload_register( function($class_name) {
// include_once 'src/'.$class_name.'.php';
// });
namespace FuelSdk;
/**
* This class represents a marketing list of subscribers.
*/
class ET_List extends ET_CUDWithUpsertSupport
{
/**
* @var int Gets or sets the folder identifier.
*/
public $folderId;
/**
* Initializes a new instance of the class and set the property obj, folderProperty and folderMediaType to appropriate values.
*/
function __construct()
{
$this->obj = "List";
$this->folderProperty = "Category";
$this->folderMediaType = "list";
}
}
?> | php | MIT | 8494244d071dc60cc709eedd92cbd0f3a7a7c965 | 2026-01-05T05:17:42.419088Z | false |
salesforce-marketingcloud/FuelSDK-PHP | https://github.com/salesforce-marketingcloud/FuelSDK-PHP/blob/8494244d071dc60cc709eedd92cbd0f3a7a7c965/src/ET_Util.php | src/ET_Util.php | <?php
namespace FuelSdk;
use \stdClass;
/**
* This utility class performs all the REST operation over CURL.
*/
class ET_Util
{
// Function for calling a Fuel API using GET
/**
* @param string $url The resource URL for the REST API
* @param ET_Client $authStub The ET client object which performs the auth token, refresh token using clientID clientSecret
* @return string The response payload from the REST service
*/
public static function restGet($url, $authStub, $isAuthConnection="")
{
$ch = curl_init();
$headers = array("User-Agent: ".self::getSDKVersion());
if($isAuthConnection !== ""){
$authorization = "Authorization: Bearer ".$isAuthConnection;
$headers = array("User-Agent: ".self::getSDKVersion(), $authorization);
//echo "inside GET auth conn\n";
}
curl_setopt ($ch, CURLOPT_HTTPHEADER, $headers);
// Uses the URL passed in that is specific to the API used
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPGET, true);
// Need to set ReturnTransfer to True in order to store the result in a variable
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Disable VerifyPeer for SSL
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, self::shouldVerifySslPeer($authStub->sslVerifyPeer));
//proxy setting
if (!empty($authStub->proxyHost)) {
curl_setopt($ch, CURLOPT_PROXY, $authStub->proxyHost);
}
if (!empty($authStub->proxyPort)) {
curl_setopt($ch, CURLOPT_PROXYPORT, $authStub->proxyPort);
}
if (!empty($authStub->proxyUserName) && !empty($authStub->proxyPassword)) {
curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_PROXYUSERPWD, $authStub->proxyUserName.':'.$authStub->proxyPassword);
}
$outputJSON = curl_exec($ch);
$responseObject = new stdClass();
$responseObject->body = $outputJSON;
$responseObject->httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
return $responseObject;
}
// Function for calling a Fuel API using POST
/**
* @param string $url The resource URL for the REST API
* @param string $content A string of JSON which will be passed to the REST API
* @param ET_Client $authStub The ET client object which performs the auth token, refresh token using clientID clientSecret
* @return string The response payload from the REST service
*/
public static function restPost($url, $content, $authStub, $isAuthConnection="")
{
$ch = curl_init();
// Uses the URL passed in that is specific to the API used
curl_setopt($ch, CURLOPT_URL, $url);
// When posting to a Fuel API, content-type has to be explicitly set to application/json
$headers = array("Content-Type: application/json", "User-Agent: ".self::getSDKVersion());
if($isAuthConnection !== ""){
$authorization = "Authorization: Bearer ".$isAuthConnection;
$headers = array("Content-Type: application/json", "User-Agent: ".self::getSDKVersion(), $authorization);
}
curl_setopt ($ch, CURLOPT_HTTPHEADER, $headers);
// The content is the JSON payload that defines the request
curl_setopt ($ch, CURLOPT_POSTFIELDS, $content);
//Need to set ReturnTransfer to True in order to store the result in a variable
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Disable VerifyPeer for SSL
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, self::shouldVerifySslPeer($authStub->sslVerifyPeer));
//proxy setting
if (!empty($authStub->proxyHost)) {
curl_setopt($ch, CURLOPT_PROXY, $authStub->proxyHost);
}
if (!empty($authStub->proxyPort)) {
curl_setopt($ch, CURLOPT_PROXYPORT, $authStub->proxyPort);
}
if (!empty($authStub->proxyUserName) && !empty($authStub->proxyPassword)) {
curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_PROXYUSERPWD, $authStub->proxyUserName.':'.$authStub->proxyPassword);
}
$outputJSON = curl_exec($ch);
$responseObject = new stdClass();
$responseObject->body = $outputJSON;
$responseObject->httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
return $responseObject;
}
// Function for calling a Fuel API using PATCH
/**
* @param string $url The resource URL for the REST API
* @param string $content A string of JSON which will be passed to the REST API
* @param ET_Client $authStub The ET client object which performs the auth token, refresh token using clientID clientSecret
* @return string The response payload from the REST service
*/
public static function restPatch($url, $content, $authStub, $isAuthConnection="")
{
$ch = curl_init();
// Uses the URL passed in that is specific to the API used
curl_setopt($ch, CURLOPT_URL, $url);
// When posting to a Fuel API, content-type has to be explicitly set to application/json
$headers = array("Content-Type: application/json", "User-Agent: ".self::getSDKVersion());
if($isAuthConnection !== ""){
$authorization = "Authorization: Bearer ".$isAuthConnection;
$headers = array("Content-Type: application/json", "User-Agent: ".self::getSDKVersion(), $authorization);
}
curl_setopt ($ch, CURLOPT_HTTPHEADER, $headers);
// The content is the JSON payload that defines the request
curl_setopt ($ch, CURLOPT_POSTFIELDS, $content);
//Need to set ReturnTransfer to True in order to store the result in a variable
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//Need to set the request to be a PATCH
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PATCH" );
// Disable VerifyPeer for SSL
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, self::shouldVerifySslPeer($authStub->sslVerifyPeer));
//proxy setting
if (!empty($authStub->proxyHost)) {
curl_setopt($ch, CURLOPT_PROXY, $authStub->proxyHost);
}
if (!empty($authStub->proxyPort)) {
curl_setopt($ch, CURLOPT_PROXYPORT, $authStub->proxyPort);
}
if (!empty($authStub->proxyUserName) && !empty($authStub->proxyPassword)) {
curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_PROXYUSERPWD, $authStub->proxyUserName.':'.$authStub->proxyPassword);
}
$outputJSON = curl_exec($ch);
$responseObject = new stdClass();
$responseObject->body = $outputJSON;
$responseObject->httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
return $responseObject;
}
// Function for calling a Fuel API using PATCH
/**
* @param string $url The resource URL for the REST API
* @param string $content A string of JSON which will be passed to the REST API
* @param ET_Client $authStub The ET client object which performs the auth token, refresh token using clientID clientSecret
* @return string The response payload from the REST service
*/
public static function restPut($url, $content, $authStub, $isAuthConnection="")
{
$ch = curl_init();
// Uses the URL passed in that is specific to the API used
curl_setopt($ch, CURLOPT_URL, $url);
// When posting to a Fuel API, content-type has to be explicitly set to application/json
$headers = array("Content-Type: application/json", "User-Agent: ".self::getSDKVersion());
if($isAuthConnection !== ""){
$authorization = "Authorization: Bearer ".$isAuthConnection;
$headers = array("Content-Type: application/json", "User-Agent: ".self::getSDKVersion(), $authorization);
}
curl_setopt ($ch, CURLOPT_HTTPHEADER, $headers);
// The content is the JSON payload that defines the request
curl_setopt ($ch, CURLOPT_POSTFIELDS, $content);
//Need to set ReturnTransfer to True in order to store the result in a variable
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//Need to set the request to be a PATCH
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT" );
// Disable VerifyPeer for SSL
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, self::shouldVerifySslPeer($authStub->sslVerifyPeer));
//proxy setting
if (!empty($authStub->proxyHost)) {
curl_setopt($ch, CURLOPT_PROXY, $authStub->proxyHost);
}
if (!empty($authStub->proxyPort)) {
curl_setopt($ch, CURLOPT_PROXYPORT, $authStub->proxyPort);
}
if (!empty($authStub->proxyUserName) && !empty($authStub->proxyPassword)) {
curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_PROXYUSERPWD, $authStub->proxyUserName.':'.$authStub->proxyPassword);
}
$outputJSON = curl_exec($ch);
$responseObject = new stdClass();
$responseObject->body = $outputJSON;
$responseObject->httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
return $responseObject;
}
// Function for calling a Fuel API using DELETE
/**
* @param string $url The resource URL for the REST API
* @param ET_Client $authStub The ET client object which performs the auth token, refresh token using clientID clientSecret
* @return string The response payload from the REST service
*/
public static function restDelete($url, $authStub, $isAuthConnection="")
{
$ch = curl_init();
$headers = array("User-Agent: ".self::getSDKVersion());
if($isAuthConnection !== ""){
$authorization = "Authorization: Bearer ".$isAuthConnection;
$headers = array("Content-Type: application/json", "User-Agent: ".self::getSDKVersion(), $authorization);
}
curl_setopt ($ch, CURLOPT_HTTPHEADER, $headers);
// Uses the URL passed in that is specific to the API used
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPGET, true);
// Need to set ReturnTransfer to True in order to store the result in a variable
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Disable VerifyPeer for SSL
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, self::shouldVerifySslPeer($authStub->sslVerifyPeer));
// Set CustomRequest up for Delete
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
//proxy setting
if (!empty($authStub->proxyHost)) {
curl_setopt($ch, CURLOPT_PROXY, $authStub->proxyHost);
}
if (!empty($authStub->proxyPort)) {
curl_setopt($ch, CURLOPT_PROXYPORT, $authStub->proxyPort);
}
if (!empty($authStub->proxyUserName) && !empty($authStub->proxyPassword)) {
curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_PROXYUSERPWD, $authStub->proxyUserName.':'.$authStub->proxyPassword);
}
$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$outputJSON = curl_exec($ch);
$responseObject = new stdClass();
$responseObject->body = $outputJSON;
$responseObject->httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
return $responseObject;
}
/**
* @param array $array The array
* @return bool Returns true if the parameter array is dictionary type array, false otherwise.
*/
public static function isAssoc($array)
{
return ($array !== array_values($array));
}
/**
* This method will not change until a major release.
*
* @api
*
* @return string
*/
public static function getSDKVersion()
{
return "FuelSDK-PHP-v1.4.0";
}
/**
* Returns true if the sslverifypeer config value is explicitly set to true, otherwise false.
* @param $configValue The config value for the sslverifypeer config key
* @return bool
*/
public static function shouldVerifySslPeer($configValue)
{
return $configValue === true ? true : false;
}
}
?> | php | MIT | 8494244d071dc60cc709eedd92cbd0f3a7a7c965 | 2026-01-05T05:17:42.419088Z | false |
salesforce-marketingcloud/FuelSDK-PHP | https://github.com/salesforce-marketingcloud/FuelSDK-PHP/blob/8494244d071dc60cc709eedd92cbd0f3a7a7c965/src/ET_Configure.php | src/ET_Configure.php | <?php
// spl_autoload_register( function($class_name) {
// include_once 'src/'.$class_name.'.php';
// });
namespace FuelSdk;
use \SoapVar;
/**
* This class represents configurations required for SOAP operation.
*/
class ET_Configure extends ET_Constructor
{
/**
* Initializes a new instance of the class.
* @param ET_Client $authStub The ET client object which performs the auth token, refresh token using clientID clientSecret
* @param string $objType Object name, e.g. "ImportDefinition", "DataExtension", etc
* @param string $action Action names e.g. "create", "delete", "update", etc
* @param array $props Dictionary type array which may hold e.g. array('id' => '', 'key' => '')
*/
function __construct($authStub, $objType, $action, $props)
{
$authStub->refreshToken();
$configure = array();
$configureRequest = array();
$configureRequest['Action'] = $action;
$configureRequest['Configurations'] = array();
if (!ET_Util::isAssoc($props)) {
foreach ($props as $value){
$configureRequest['Configurations'][] = new SoapVar($value, SOAP_ENC_OBJECT, $objType, "http://exacttarget.com/wsdl/partnerAPI");
}
} else {
$configureRequest['Configurations'][] = new SoapVar($props, SOAP_ENC_OBJECT, $objType, "http://exacttarget.com/wsdl/partnerAPI");
}
$configure['ConfigureRequestMsg'] = $configureRequest;
$return = $authStub->__soapCall("Configure", $configure, null, null , $out_header);
parent::__construct($return, $authStub->__getLastResponseHTTPCode());
if ($this->status){
if (property_exists($return->Results, "Result")){
if (is_array($return->Results->Result)){
$this->results = $return->Results->Result;
} else {
$this->results = array($return->Results->Result);
}
if ($return->OverallStatus != "OK"){
$this->status = false;
}
} else {
$this->status = false;
}
}
}
}
?> | php | MIT | 8494244d071dc60cc709eedd92cbd0f3a7a7c965 | 2026-01-05T05:17:42.419088Z | false |
salesforce-marketingcloud/FuelSDK-PHP | https://github.com/salesforce-marketingcloud/FuelSDK-PHP/blob/8494244d071dc60cc709eedd92cbd0f3a7a7c965/src/ET_DataExtension.php | src/ET_DataExtension.php | <?php
// spl_autoload_register( function($class_name) {
// include_once 'src/'.$class_name.'.php';
// });
namespace FuelSdk;
/**
* ETDataExtension - Represents a data extension within an account.
*/
class ET_DataExtension extends ET_CUDSupport
{
/**
* @var ET_DataExtension_Column[] Gets or sets array of DE columns.
*/
public $columns;
/**
* Initializes a new instance of the class.
*/
function __construct()
{
$this->obj = "DataExtension";
}
/**
* Post this instance.
* @return ET_Post Object of type ET_Post which contains http status code, response, etc from the POST SOAP service
*/
public function post()
{
$originalProps = $this->props;
if (ET_Util::isAssoc($this->props)){
$this->props["Fields"] = array("Field"=>array());
if (!is_null($this->columns) && is_array($this->columns)){
foreach ($this->columns as $column){
array_push($this->props['Fields']['Field'], $column);
}
}
} else {
$newProps = array();
foreach ($this->props as $DE) {
$newDE = $DE;
$newDE["Fields"] = array("Field"=>array());
if (!is_null($DE['columns']) && is_array($DE['columns'])){
foreach ($DE['columns'] as $column){
array_push($newDE['Fields']['Field'], $column);
}
}
array_push($newProps, $newDE);
}
$this->props = $newProps;
}
$response = parent::post();
$this->props = $originalProps;
return $response;
}
/**
* Patch this instance.
* @return ET_Patch Object of type ET_Patch which contains http status code, response, etc from the PATCH SOAP service
*/
public function patch()
{
$this->props["Fields"] = array("Field"=>array());
foreach ($this->columns as $column){
array_push($this->props['Fields']['Field'], $column);
}
$response = parent::patch();
unset($this->props["Fields"]);
return $response;
}
}
?> | php | MIT | 8494244d071dc60cc709eedd92cbd0f3a7a7c965 | 2026-01-05T05:17:42.419088Z | false |
salesforce-marketingcloud/FuelSDK-PHP | https://github.com/salesforce-marketingcloud/FuelSDK-PHP/blob/8494244d071dc60cc709eedd92cbd0f3a7a7c965/src/ET_ContentArea.php | src/ET_ContentArea.php | <?php
// spl_autoload_register( function($class_name) {
// include_once 'src/'.$class_name.'.php';
// });
namespace FuelSdk;
/**
* ET_ContentArea - Represents a ContentArea class.
* A ContentArea represents a defined section of reusable content. One or many ContentAreas can be defined for an Email object.
* A ContentArea is always acted upon in the context of an Email object.
*/
class ET_ContentArea extends ET_CUDSupport
{
/**
* @var int $folderId Gets or sets the folder identifier.
*/
public $folderId;
/**
* Initializes a new instance of the class and will assign obj, folderProperty, folderMediaType property
*/
function __construct()
{
$this->obj = "ContentArea";
$this->folderProperty = "CategoryID";
$this->folderMediaType = "content";
}
}
?> | php | MIT | 8494244d071dc60cc709eedd92cbd0f3a7a7c965 | 2026-01-05T05:17:42.419088Z | false |
salesforce-marketingcloud/FuelSDK-PHP | https://github.com/salesforce-marketingcloud/FuelSDK-PHP/blob/8494244d071dc60cc709eedd92cbd0f3a7a7c965/src/autoload.php | src/autoload.php | <?php
// This file can be used if you do not use composer to get all the dependencies.
//Then you need to download all the dependencies manually and change the first require line accordingly.
require __DIR__ . '/../vendor/autoload.php';
spl_autoload_register( function($class_name) {
if (file_exists('src/'.$class_name.'.php'))
include_once 'src/'.$class_name.'.php';
else
include_once 'tests/'.$class_name.'.php';
});
date_default_timezone_set('UTC'); | php | MIT | 8494244d071dc60cc709eedd92cbd0f3a7a7c965 | 2026-01-05T05:17:42.419088Z | false |
salesforce-marketingcloud/FuelSDK-PHP | https://github.com/salesforce-marketingcloud/FuelSDK-PHP/blob/8494244d071dc60cc709eedd92cbd0f3a7a7c965/src/ET_TriggeredSend.php | src/ET_TriggeredSend.php | <?php
// spl_autoload_register( function($class_name) {
// include_once 'src/'.$class_name.'.php';
// });
namespace FuelSdk;
/**
* Defines a triggered send in the account.
*/
class ET_TriggeredSend extends ET_CUDSupport
{
/**
* @var array Gets or sets the subscribers. e.g. array("EmailAddress" => "", "SubscriberKey" => "")
*/
public $subscribers;
/**
* @var int Gets or sets the folder identifier.
*/
public $folderId;
/**
* Initializes a new instance of the class.
*/
function __construct()
{
$this->obj = "TriggeredSendDefinition";
$this->folderProperty = "CategoryID";
$this->folderMediaType = "triggered_send";
}
/**
* Send this instance.
* @return ET_Post Object of type ET_Post which contains http status code, response, etc from the POST SOAP service
*/
public function Send()
{
$tscall = array("TriggeredSendDefinition" => $this->props , "Subscribers" => $this->subscribers);
$response = new ET_Post($this->authStub, "TriggeredSend", $tscall);
return $response;
}
}
?> | php | MIT | 8494244d071dc60cc709eedd92cbd0f3a7a7c965 | 2026-01-05T05:17:42.419088Z | false |
salesforce-marketingcloud/FuelSDK-PHP | https://github.com/salesforce-marketingcloud/FuelSDK-PHP/blob/8494244d071dc60cc709eedd92cbd0f3a7a7c965/src/ET_Perform.php | src/ET_Perform.php | <?php
// spl_autoload_register( function($class_name) {
// include_once 'src/'.$class_name.'.php';
// });
namespace FuelSdk;
use \SoapVar;
/**
* This class represents the PERFORM operation for SOAP service.
*/
class ET_Perform extends ET_Constructor
{
/**
* Initializes a new instance of the class.
* @param ET_Client $authStub The ET client object which performs the auth token, refresh token using clientID clientSecret
* @param string $objType Object name, e.g. "ImportDefinition", "DataExtension", etc
* @param string $action Action names e.g. "create", "delete", "update", etc
* @param array $props Dictionary type array which may hold e.g. array('id' => '', 'key' => '')
*/
function __construct($authStub, $objType, $action, $props)
{
$authStub->refreshToken();
$perform = array();
$performRequest = array();
$performRequest['Action'] = $action;
$performRequest['Definitions'] = array();
$performRequest['Definitions'][] = new SoapVar($props, SOAP_ENC_OBJECT, $objType, "http://exacttarget.com/wsdl/partnerAPI");
$perform['PerformRequestMsg'] = $performRequest;
$return = $authStub->__soapCall("Perform", $perform, null, null , $out_header);
parent::__construct($return, $authStub->__getLastResponseHTTPCode());
print_r($return);
if ($this->status){
if (property_exists($return->Results, "Result")){
if (is_array($return->Results->Result)){
$this->results = $return->Results->Result;
} else {
$this->results = array($return->Results->Result);
}
if ($return->OverallStatus != "OK"){
$this->status = false;
}
} else {
$this->status = false;
}
}
}
}
?> | php | MIT | 8494244d071dc60cc709eedd92cbd0f3a7a7c965 | 2026-01-05T05:17:42.419088Z | false |
salesforce-marketingcloud/FuelSDK-PHP | https://github.com/salesforce-marketingcloud/FuelSDK-PHP/blob/8494244d071dc60cc709eedd92cbd0f3a7a7c965/src/ET_OEM_Client.php | src/ET_OEM_Client.php | <?php
// spl_autoload_register( function($class_name) {
// include_once 'src/'.$class_name.'.php';
// });
namespace FuelSdk;
/**
* The class can create and retrieve specific tenant.
*/
class ET_OEM_Client extends ET_Client
{
/**
* @param array $tenantInfo Dictionary type array which may hold e.g. array('key' => '')
*/
function CreateTenant($tenantInfo)
{
$key = $tenantInfo['key'];
unset($tenantInfo['key']);
$completeURL = $this->baseUrl . "/provisioning/v1/tenants/{$key}";
return new ET_PutRest($this, $completeURL, $tenantInfo, $this->getAuthToken());
}
/**
* @return ET_GetRest Object of type ET_GetRest which contains http status code, response, etc from the GET REST service
*/
function GetTenants()
{
$completeURL = $this->baseUrl . "/provisioning/v1/tenants/";
return new ET_GetRest($this, $completeURL, $this->getAuthToken());
}
}
?> | php | MIT | 8494244d071dc60cc709eedd92cbd0f3a7a7c965 | 2026-01-05T05:17:42.419088Z | false |
salesforce-marketingcloud/FuelSDK-PHP | https://github.com/salesforce-marketingcloud/FuelSDK-PHP/blob/8494244d071dc60cc709eedd92cbd0f3a7a7c965/src/ET_Post.php | src/ET_Post.php | <?php
// spl_autoload_register( function($class_name) {
// include_once 'src/'.$class_name.'.php';
// });
namespace FuelSdk;
use \SoapVar;
/**
* This class represents the POST operation for SOAP service.
*/
class ET_Post extends ET_Constructor
{
/**
* Initializes a new instance of the class.
* @param ET_Client $authStub The ET client object which performs the auth token, refresh token using clientID clientSecret
* @param string $objType Object name, e.g. "ImportDefinition", "DataExtension", etc
* @param array $props Dictionary type array which may hold e.g. array('id' => '', 'key' => '')
* @param bool $upsert If true SaveAction is UpdateAdd, otherwise not. By default false.
*/
function __construct($authStub, $objType, $props, $upsert = false)
{
$authStub->refreshToken();
$cr = array();
$objects = array();
if (ET_Util::isAssoc($props)){
$objects["Objects"] = new SoapVar($props, SOAP_ENC_OBJECT, $objType, "http://exacttarget.com/wsdl/partnerAPI");
} else {
$objects["Objects"] = array();
foreach($props as $object){
$objects["Objects"][] = new SoapVar($object, SOAP_ENC_OBJECT, $objType, "http://exacttarget.com/wsdl/partnerAPI");
}
}
if ($upsert) {
$objects["Options"] = array('SaveOptions' => array('SaveOption' => array('PropertyName' => '*', 'SaveAction' => 'UpdateAdd' )));
} else {
$objects["Options"] = "";
}
$cr["CreateRequest"] = $objects;
$return = $authStub->__soapCall("Create", $cr, null, null , $out_header);
parent::__construct($return, $authStub->__getLastResponseHTTPCode());
if ($this->status){
if (property_exists($return, "Results")){
// We always want the results property when doing a retrieve to be an array
if (is_array($return->Results)){
$this->results = $return->Results;
} else {
$this->results = array($return->Results);
}
} else {
$this->status = false;
}
if ($return->OverallStatus != "OK")
{
$this->status = false;
}
}
}
}
?> | php | MIT | 8494244d071dc60cc709eedd92cbd0f3a7a7c965 | 2026-01-05T05:17:42.419088Z | false |
salesforce-marketingcloud/FuelSDK-PHP | https://github.com/salesforce-marketingcloud/FuelSDK-PHP/blob/8494244d071dc60cc709eedd92cbd0f3a7a7c965/src/ET_Email_SendDefinition.php | src/ET_Email_SendDefinition.php | <?php
// spl_autoload_register( function($class_name) {
// include_once 'src/'.$class_name.'.php';
// });
namespace FuelSdk;
/**
* This class contains the message information, sender profile, delivery profile, and audience information.
*/
class ET_Email_SendDefinition extends ET_CUDSupport
{
/** @var int Gets or sets the folder identifier. */
public $folderId;
/** @var string|null contains last task ID if available */
public $lastTaskID;
/**
* Initializes a new instance of the class.
*/
function __construct()
{
$this->obj = "EmailSendDefinition";
$this->folderProperty = "CategoryID";
$this->folderMediaType = "userinitiatedsends";
}
/**
* Send this instance.
* @return ET_Perform Object of type ET_Perform which contains http status code, response, etc from the START SOAP service
*/
function send()
{
$originalProps = $this->props;
$response = new ET_Perform($this->authStub, $this->obj, 'start', $this->props);
if ($response->status) {
$this->lastTaskID = $response->results[0]->Task->ID;
}
$this->props = $originalProps;
return $response;
}
/**
* Status of this instance.
* @return ET_Get Object of type ET_Get which contains http status code, response, etc from the GET SOAP service
*/
function status()
{
$this->filter = array('Property' => 'ID','SimpleOperator' => 'equals','Value' => $this->lastTaskID);
$response = new ET_Get($this->authStub, 'Send', array('ID','CreatedDate', 'ModifiedDate', 'Client.ID', 'Email.ID', 'SendDate','FromAddress','FromName','Duplicates','InvalidAddresses','ExistingUndeliverables','ExistingUnsubscribes','HardBounces','SoftBounces','OtherBounces','ForwardedEmails','UniqueClicks','UniqueOpens','NumberSent','NumberDelivered','NumberTargeted','NumberErrored','NumberExcluded','Unsubscribes','MissingAddresses','Subject','PreviewURL','SentDate','EmailName','Status','IsMultipart','SendLimit','SendWindowOpen','SendWindowClose','BCCEmail','EmailSendDefinition.ObjectID','EmailSendDefinition.CustomerKey'), $this->filter);
$this->lastRequestID = $response->request_id;
return $response;
}
}
?> | php | MIT | 8494244d071dc60cc709eedd92cbd0f3a7a7c965 | 2026-01-05T05:17:42.419088Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.