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
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/database/migrations/2025_07_23_122315_add_order_column_to_status_page_monitor_table.php
database/migrations/2025_07_23_122315_add_order_column_to_status_page_monitor_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. */ public function up(): void { Schema::table('status_page_monitor', function (Blueprint $table) { // check if the 'order' column already exists if (Schema::hasColumn('status_page_monitor', 'order')) { return; // Column already exists, no need to add it again } // Add the 'order' column to the status_page_monitor table $table->integer('order')->default(0)->after('monitor_id'); }); } /** * Reverse the migrations. */ public function down(): void { Schema::table('status_page_monitor', function (Blueprint $table) { $table->dropColumn('order'); }); } };
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/database/migrations/0001_01_01_000002_create_jobs_table.php
database/migrations/0001_01_01_000002_create_jobs_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. */ public function up(): void { Schema::create('jobs', function (Blueprint $table) { $table->id(); $table->string('queue')->index(); $table->longText('payload'); $table->unsignedTinyInteger('attempts'); $table->unsignedInteger('reserved_at')->nullable(); $table->unsignedInteger('available_at'); $table->unsignedInteger('created_at'); }); Schema::create('job_batches', function (Blueprint $table) { $table->string('id')->primary(); $table->string('name'); $table->integer('total_jobs'); $table->integer('pending_jobs'); $table->integer('failed_jobs'); $table->longText('failed_job_ids'); $table->mediumText('options')->nullable(); $table->integer('cancelled_at')->nullable(); $table->integer('created_at'); $table->integer('finished_at')->nullable(); }); 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. */ public function down(): void { Schema::dropIfExists('jobs'); Schema::dropIfExists('job_batches'); Schema::dropIfExists('failed_jobs'); } };
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/database/migrations/2025_08_07_183540_create_telescope_entries_table.php
database/migrations/2025_08_07_183540_create_telescope_entries_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Get the migration connection name. */ public function getConnection(): ?string { return config('telescope.storage.database.connection'); } /** * Run the migrations. */ public function up(): void { $schema = Schema::connection($this->getConnection()); if (! $schema->hasTable('telescope_entries')) { $schema->create('telescope_entries', function (Blueprint $table) { $table->bigIncrements('sequence'); $table->uuid('uuid'); $table->uuid('batch_id'); $table->string('family_hash')->nullable(); $table->boolean('should_display_on_index')->default(true); $table->string('type', 20); $table->longText('content'); $table->dateTime('created_at')->nullable(); $table->unique('uuid'); $table->index('batch_id'); $table->index('family_hash'); $table->index('created_at'); $table->index(['type', 'should_display_on_index']); }); } if (! $schema->hasTable('telescope_entries_tags')) { $schema->create('telescope_entries_tags', function (Blueprint $table) { $table->uuid('entry_uuid'); $table->string('tag'); $table->primary(['entry_uuid', 'tag']); $table->index('tag'); $table->foreign('entry_uuid') ->references('uuid') ->on('telescope_entries') ->onDelete('cascade'); }); } if (! $schema->hasTable('telescope_monitoring')) { $schema->create('telescope_monitoring', function (Blueprint $table) { $table->string('tag')->primary(); }); } } /** * Reverse the migrations. */ public function down(): void { $schema = Schema::connection($this->getConnection()); $schema->dropIfExists('telescope_entries_tags'); $schema->dropIfExists('telescope_entries'); $schema->dropIfExists('telescope_monitoring'); } };
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/database/migrations/2025_08_16_104837_add_missing_monitor_fields.php
database/migrations/2025_08_16_104837_add_missing_monitor_fields.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. */ public function up(): void { // Add response time fields to monitor_histories Schema::table('monitor_histories', function (Blueprint $table) { $table->integer('response_time')->nullable()->after('uptime_status'); $table->integer('status_code')->nullable()->after('response_time'); $table->timestamp('checked_at')->nullable()->after('status_code'); $table->index(['monitor_id', 'response_time']); }); // Add response time statistics to monitor_uptime_dailies Schema::table('monitor_uptime_dailies', function (Blueprint $table) { $table->float('avg_response_time')->nullable()->after('uptime_percentage'); $table->float('min_response_time')->nullable()->after('avg_response_time'); $table->float('max_response_time')->nullable()->after('min_response_time'); $table->integer('total_checks')->default(0)->after('max_response_time'); $table->integer('failed_checks')->default(0)->after('total_checks'); }); // Add metadata fields to monitors Schema::table('monitors', function (Blueprint $table) { $table->string('display_name')->nullable()->after('url'); $table->text('description')->nullable()->after('display_name'); $table->integer('expected_status_code')->default(200)->after('uptime_check_enabled'); $table->integer('max_response_time')->nullable()->after('expected_status_code'); $table->json('check_locations')->nullable()->after('max_response_time'); $table->json('notification_settings')->nullable()->after('check_locations'); }); // Create monitor_incidents table Schema::create('monitor_incidents', function (Blueprint $table) { $table->id(); $table->foreignId('monitor_id')->constrained()->onDelete('cascade'); $table->enum('type', ['down', 'degraded', 'recovered']); $table->timestamp('started_at'); $table->timestamp('ended_at')->nullable(); $table->integer('duration_minutes')->nullable(); $table->text('reason')->nullable(); $table->integer('response_time')->nullable(); $table->integer('status_code')->nullable(); $table->timestamps(); $table->index(['monitor_id', 'started_at']); $table->index(['monitor_id', 'type']); }); // Create monitor_performance_hourly table Schema::create('monitor_performance_hourly', function (Blueprint $table) { $table->id(); $table->foreignId('monitor_id')->constrained()->onDelete('cascade'); $table->timestamp('hour'); $table->float('avg_response_time')->nullable(); $table->float('p95_response_time')->nullable(); $table->float('p99_response_time')->nullable(); $table->integer('success_count')->default(0); $table->integer('failure_count')->default(0); $table->timestamps(); $table->unique(['monitor_id', 'hour']); $table->index(['monitor_id', 'hour']); }); } /** * Reverse the migrations. */ public function down(): void { // Remove fields from monitor_histories Schema::table('monitor_histories', function (Blueprint $table) { $table->dropIndex(['monitor_id', 'response_time']); $table->dropColumn(['response_time', 'status_code', 'checked_at']); }); // Remove fields from monitor_uptime_dailies Schema::table('monitor_uptime_dailies', function (Blueprint $table) { $table->dropColumn([ 'avg_response_time', 'min_response_time', 'max_response_time', 'total_checks', 'failed_checks', ]); }); // Remove fields from monitors Schema::table('monitors', function (Blueprint $table) { $table->dropColumn([ 'display_name', 'description', 'expected_status_code', 'max_response_time', 'check_locations', 'notification_settings', ]); }); // Drop new tables Schema::dropIfExists('monitor_performance_hourly'); Schema::dropIfExists('monitor_incidents'); } };
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/database/migrations/2025_08_19_081445_add_unique_constraint_to_monitor_histories_table.php
database/migrations/2025_08_19_081445_add_unique_constraint_to_monitor_histories_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Support\Facades\DB; return new class extends Migration { /** * Run the migrations. */ public function up(): void { // First, remove duplicate records, keeping the latest one for each monitor-minute combination $this->removeDuplicateHistories(); // Add unique constraint for monitor_id + created_at (rounded to minute) // Since SQLite doesn't support function-based unique constraints directly, // we'll use a unique index on monitor_id + minute-rounded created_at DB::statement('CREATE UNIQUE INDEX monitor_histories_unique_minute ON monitor_histories (monitor_id, datetime(created_at, "start of minute"))'); } /** * Reverse the migrations. */ public function down(): void { DB::statement('DROP INDEX IF EXISTS monitor_histories_unique_minute'); } /** * Remove duplicate history records, keeping the latest one for each monitor-minute combination */ private function removeDuplicateHistories(): void { // Get all duplicate records grouped by monitor_id and minute $duplicates = DB::select(' SELECT monitor_id, datetime(created_at, "start of minute") as minute_start, COUNT(*) as count FROM monitor_histories GROUP BY monitor_id, datetime(created_at, "start of minute") HAVING count > 1 '); echo 'Found '.count($duplicates)." minute periods with duplicate records\n"; foreach ($duplicates as $duplicate) { // Keep the latest record for each monitor-minute combination $keepRecord = DB::selectOne(' SELECT id FROM monitor_histories WHERE monitor_id = ? AND datetime(created_at, "start of minute") = ? ORDER BY created_at DESC, id DESC LIMIT 1 ', [$duplicate->monitor_id, $duplicate->minute_start]); if (! $keepRecord) { echo "Warning: No record found for monitor {$duplicate->monitor_id} at {$duplicate->minute_start}\n"; continue; } // Delete all other records for this monitor-minute combination $deletedCount = DB::delete(' DELETE FROM monitor_histories WHERE monitor_id = ? AND datetime(created_at, "start of minute") = ? AND id != ? ', [$duplicate->monitor_id, $duplicate->minute_start, $keepRecord->id]); if ($deletedCount > 0) { echo "Removed {$deletedCount} duplicate records for monitor {$duplicate->monitor_id} at {$duplicate->minute_start}\n"; } } } };
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/database/migrations/2025_08_19_071638_create_monitor_statistics_table.php
database/migrations/2025_08_19_071638_create_monitor_statistics_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. */ public function up(): void { if (Schema::hasTable('monitor_statistics')) { return; } Schema::create('monitor_statistics', function (Blueprint $table) { $table->id(); $table->foreignId('monitor_id')->constrained()->cascadeOnDelete(); // Time periods $table->decimal('uptime_1h', 5, 2)->default(100.00); $table->decimal('uptime_24h', 5, 2)->default(100.00); $table->decimal('uptime_7d', 5, 2)->default(100.00); $table->decimal('uptime_30d', 5, 2)->default(100.00); $table->decimal('uptime_90d', 5, 2)->default(100.00); // Response time statistics (24h) $table->integer('avg_response_time_24h')->nullable(); $table->integer('min_response_time_24h')->nullable(); $table->integer('max_response_time_24h')->nullable(); // Incident counts $table->integer('incidents_24h')->default(0); $table->integer('incidents_7d')->default(0); $table->integer('incidents_30d')->default(0); // Total checks count for different periods $table->integer('total_checks_24h')->default(0); $table->integer('total_checks_7d')->default(0); $table->integer('total_checks_30d')->default(0); // Recent history cache (JSON for last 100 minutes) $table->json('recent_history_100m')->nullable(); $table->timestamp('calculated_at'); $table->timestamps(); $table->unique('monitor_id'); $table->index('calculated_at'); }); } /** * Reverse the migrations. */ public function down(): void { Schema::dropIfExists('monitor_statistics'); } };
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/database/migrations/2025_06_26_162525_create_social_accounts_table.php
database/migrations/2025_06_26_162525_create_social_accounts_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. */ public function up(): void { Schema::create('social_accounts', function (Blueprint $table) { $table->id(); $table->bigInteger('user_id'); $table->string('provider_id')->unique(); $table->string('provider_name'); $table->timestamps(); }); } /** * Reverse the migrations. */ public function down(): void { Schema::dropIfExists('social_accounts'); } };
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/database/migrations/2025_07_24_065055_add_unique_to_monitor_uptime_dailies_table.php
database/migrations/2025_07_24_065055_add_unique_to_monitor_uptime_dailies_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. */ public function up(): void { // 1. Hapus data duplikat terlebih dahulu // Query ini akan menyimpan record dengan 'id' tertinggi (paling baru) // untuk setiap kombinasi 'monitor_id' dan 'date', lalu menghapus sisanya. DB::table('monitor_uptime_dailies') ->whereIn('id', function ($query) { $query->select('id') ->from('monitor_uptime_dailies') ->whereIn('id', function ($subQuery) { $subQuery->select(DB::raw('MIN(id)')) ->from('monitor_uptime_dailies') ->groupBy('monitor_id', 'date') ->having(DB::raw('COUNT(*)'), '>', 1); }); })->delete(); Schema::table('monitor_uptime_dailies', function (Blueprint $table) { // 2. Hapus index lama jika ada (opsional, tergantung struktur Anda) // Pastikan nama indexnya benar. Anda bisa cek di database client. // Jika tidak yakin, Anda bisa comment baris ini. // $table->dropIndex('monitor_uptime_dailies_date_index'); // 3. Sekarang aman untuk menambahkan unique constraint $table->unique(['monitor_id', 'date'], 'monitor_uptime_daily_unique'); }); } /** * Reverse the migrations. */ public function down(): void { Schema::table('monitor_uptime_dailies', function (Blueprint $table) { // Urutan di 'down' adalah kebalikan dari 'up' $table->dropUnique('monitor_uptime_daily_unique'); // $table->index('date', 'monitor_uptime_dailies_date_index'); }); } };
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/database/migrations/2025_08_15_084216_add_is_pinned_to_user_monitor_table.php
database/migrations/2025_08_15_084216_add_is_pinned_to_user_monitor_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. */ public function up(): void { Schema::table('user_monitor', function (Blueprint $table) { $table->boolean('is_pinned')->default(false)->after('is_active'); }); } /** * Reverse the migrations. */ public function down(): void { Schema::table('user_monitor', function (Blueprint $table) { $table->dropColumn('is_pinned'); }); } };
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/database/migrations/2025_07_25_000000_add_is_admin_to_users_table.php
database/migrations/2025_07_25_000000_add_is_admin_to_users_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { public function up(): void { Schema::table('users', function (Blueprint $table) { $table->boolean('is_admin')->default(false)->after('password'); }); } public function down(): void { Schema::table('users', function (Blueprint $table) { $table->dropColumn('is_admin'); }); } };
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/database/migrations/2025_06_26_171319_alter_users_table.php
database/migrations/2025_06_26_171319_alter_users_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. */ public function up(): void { Schema::table('users', function (Blueprint $table) { $table->string('email')->nullable(true)->change(); $table->string('password')->nullable(true)->change(); }); } /** * Reverse the migrations. */ public function down(): void { Schema::table('users', function (Blueprint $table) { $table->string('email')->nullable(false)->change(); $table->string('password')->nullable(false)->change(); }); } };
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/database/migrations/2025_05_28_014043_create_monitors_table.php
database/migrations/2025_05_28_014043_create_monitors_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Spatie\UptimeMonitor\Models\Enums\CertificateStatus; use Spatie\UptimeMonitor\Models\Enums\UptimeStatus; class CreateMonitorsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('monitors', function (Blueprint $table) { $table->increments('id'); $table->string('url')->unique(); $table->boolean('is_public')->default(true); $table->boolean('uptime_check_enabled')->default(true); $table->string('look_for_string')->default(''); $table->string('uptime_check_interval_in_minutes')->default(5); $table->string('uptime_status')->default(UptimeStatus::NOT_YET_CHECKED); $table->text('uptime_check_failure_reason')->nullable(); $table->integer('uptime_check_times_failed_in_a_row')->default(0); $table->timestamp('uptime_status_last_change_date')->nullable(); $table->timestamp('uptime_last_check_date')->nullable(); $table->timestamp('uptime_check_failed_event_fired_on_date')->nullable(); $table->string('uptime_check_method')->default('get'); $table->text('uptime_check_payload')->nullable(); $table->text('uptime_check_additional_headers')->nullable(); $table->string('uptime_check_response_checker')->nullable(); $table->boolean('certificate_check_enabled')->default(false); $table->string('certificate_status')->default(CertificateStatus::NOT_YET_CHECKED); $table->timestamp('certificate_expiration_date')->nullable(); $table->string('certificate_issuer')->nullable(); $table->string('certificate_check_failure_reason')->default(''); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('monitors'); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/database/migrations/2025_06_04_204329_create_telescope_entries_table.php
database/migrations/2025_06_04_204329_create_telescope_entries_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Get the migration connection name. */ public function getConnection(): ?string { return config('telescope.storage.database.connection'); } /** * Run the migrations. */ public function up(): void { $schema = Schema::connection($this->getConnection()); if (! $schema->hasTable('telescope_entries')) { $schema->create('telescope_entries', function (Blueprint $table) { $table->bigIncrements('sequence'); $table->uuid('uuid'); $table->uuid('batch_id'); $table->string('family_hash')->nullable(); $table->boolean('should_display_on_index')->default(true); $table->string('type', 20); $table->longText('content'); $table->dateTime('created_at')->nullable(); $table->unique('uuid'); $table->index('batch_id'); $table->index('family_hash'); $table->index('created_at'); $table->index(['type', 'should_display_on_index']); }); } if (! $schema->hasTable('telescope_entries_tags')) { $schema->create('telescope_entries_tags', function (Blueprint $table) { $table->uuid('entry_uuid'); $table->string('tag'); $table->primary(['entry_uuid', 'tag']); $table->index('tag'); $table->foreign('entry_uuid') ->references('uuid') ->on('telescope_entries') ->onDelete('cascade'); }); } if (! $schema->hasTable('telescope_monitoring')) { $schema->create('telescope_monitoring', function (Blueprint $table) { $table->string('tag')->primary(); }); } } /** * Reverse the migrations. */ public function down(): void { $schema = Schema::connection($this->getConnection()); $schema->dropIfExists('telescope_entries_tags'); $schema->dropIfExists('telescope_entries'); $schema->dropIfExists('telescope_monitoring'); } };
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/database/migrations/2025_06_27_125605_create_monitor_uptime_dailies_table.php
database/migrations/2025_06_27_125605_create_monitor_uptime_dailies_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. */ public function up(): void { Schema::create('monitor_uptime_dailies', function (Blueprint $table) { $table->id(); $table->foreignId('monitor_id')->constrained('monitors')->onDelete('cascade'); $table->date('date')->index(); $table->double('uptime_percentage')->default(0); $table->timestamps(); }); } /** * Reverse the migrations. */ public function down(): void { Schema::dropIfExists('monitor_uptime_dailies'); } };
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/database/migrations/2025_12_16_154456_add_confirmation_settings_to_monitors_table.php
database/migrations/2025_12_16_154456_add_confirmation_settings_to_monitors_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. */ public function up(): void { Schema::table('monitors', function (Blueprint $table) { // Confirmation settings for reducing false positives $table->unsignedSmallInteger('confirmation_delay_seconds')->nullable()->after('transient_failures_count'); $table->unsignedTinyInteger('confirmation_retries')->nullable()->after('confirmation_delay_seconds'); $table->string('sensitivity', 10)->default('medium')->after('confirmation_retries'); }); } /** * Reverse the migrations. */ public function down(): void { Schema::table('monitors', function (Blueprint $table) { $table->dropColumn([ 'confirmation_delay_seconds', 'confirmation_retries', 'sensitivity', ]); }); } };
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/database/migrations/2025_08_01_035827_create_health_tables.php
database/migrations/2025_08_01_035827_create_health_tables.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; use Spatie\Health\Models\HealthCheckResultHistoryItem; use Spatie\Health\ResultStores\EloquentHealthResultStore; return new class extends Migration { public function up() { // Skip this migration during testing if (app()->environment('testing')) { return; } $connection = (new HealthCheckResultHistoryItem)->getConnectionName(); $tableName = EloquentHealthResultStore::getHistoryItemInstance()->getTable(); // Check if table already exists if (Schema::connection($connection)->hasTable($tableName)) { return; } Schema::connection($connection)->create($tableName, function (Blueprint $table) { $table->id(); $table->string('check_name'); $table->string('check_label'); $table->string('status'); $table->text('notification_message')->nullable(); $table->string('short_summary')->nullable(); $table->json('meta'); $table->timestamp('ended_at'); $table->uuid('batch'); $table->timestamps(); }); Schema::connection($connection)->table($tableName, function (Blueprint $table) { $table->index('created_at'); $table->index('batch'); }); } };
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/database/migrations/2025_08_16_103721_update_monitors_to_https.php
database/migrations/2025_08_16_103721_update_monitors_to_https.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Support\Facades\DB; return new class extends Migration { /** * Run the migrations. */ public function up(): void { // Update all HTTP URLs to HTTPS DB::table('monitors') ->where('url', 'like', 'http://%') ->update([ 'url' => DB::raw("CONCAT('https://', SUBSTRING(url, 8))"), ]); } /** * Reverse the migrations. */ public function down(): void { // This migration is not reversible as we can't determine // which URLs were originally HTTP vs HTTPS } };
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/database/migrations/2025_08_16_090721_add_custom_domains_to_status_pages.php
database/migrations/2025_08_16_090721_add_custom_domains_to_status_pages.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. */ public function up(): void { Schema::table('status_pages', function (Blueprint $table) { $table->string('custom_domain')->nullable()->unique()->after('path'); $table->boolean('custom_domain_verified')->default(false)->after('custom_domain'); $table->string('custom_domain_verification_token')->nullable()->after('custom_domain_verified'); $table->timestamp('custom_domain_verified_at')->nullable()->after('custom_domain_verification_token'); $table->boolean('force_https')->default(true)->after('custom_domain_verified_at'); // Add index for faster lookups $table->index('custom_domain'); }); } /** * Reverse the migrations. */ public function down(): void { Schema::table('status_pages', function (Blueprint $table) { $table->dropIndex(['custom_domain']); $table->dropColumn([ 'custom_domain', 'custom_domain_verified', 'custom_domain_verification_token', 'custom_domain_verified_at', 'force_https', ]); }); } };
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/database/migrations/2025_08_19_072542_add_checked_at_index_to_monitor_histories_table.php
database/migrations/2025_08_19_072542_add_checked_at_index_to_monitor_histories_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. */ public function up(): void { Schema::table('monitor_histories', function (Blueprint $table) { // Add composite index for monitor_id + checked_at for efficient range queries $table->index(['monitor_id', 'checked_at']); // Add composite index for monitor_id + uptime_status + checked_at for filtered queries $table->index(['monitor_id', 'uptime_status', 'checked_at']); }); } /** * Reverse the migrations. */ public function down(): void { Schema::table('monitor_histories', function (Blueprint $table) { $table->dropIndex(['monitor_id', 'checked_at']); $table->dropIndex(['monitor_id', 'uptime_status', 'checked_at']); }); } };
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/database/migrations/0001_01_01_000001_create_cache_table.php
database/migrations/0001_01_01_000001_create_cache_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. */ public function up(): void { Schema::create('cache', function (Blueprint $table) { $table->string('key')->primary(); $table->mediumText('value'); $table->integer('expiration'); }); Schema::create('cache_locks', function (Blueprint $table) { $table->string('key')->primary(); $table->string('owner'); $table->integer('expiration'); }); } /** * Reverse the migrations. */ public function down(): void { Schema::dropIfExists('cache'); Schema::dropIfExists('cache_locks'); } };
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/database/migrations/2025_06_10_035439_create_user_monitor_table.php
database/migrations/2025_06_10_035439_create_user_monitor_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. */ public function up(): void { Schema::create('user_monitor', function (Blueprint $table) { $table->id(); $table->foreignId('user_id')->constrained('users')->onDelete('cascade'); $table->foreignId('monitor_id')->constrained('monitors')->onDelete('cascade'); $table->boolean('is_active')->default(true); $table->timestamps(); $table->unique(['user_id', 'monitor_id'], 'user_monitor_unique'); }); } /** * Reverse the migrations. */ public function down(): void { Schema::dropIfExists('user_monitor'); } };
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/database/migrations/2025_06_19_041703_create_monitor_histories_table.php
database/migrations/2025_06_19_041703_create_monitor_histories_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. */ public function up(): void { Schema::create('monitor_histories', function (Blueprint $table) { $table->id(); $table->foreignId('monitor_id') ->constrained('monitors') ->onDelete('cascade'); $table->string('uptime_status')->nullable(); $table->string('message')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. */ public function down(): void { Schema::dropIfExists('monitor_histories'); } };
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/database/migrations/2025_07_05_044506_create_notification_channels_table.php
database/migrations/2025_07_05_044506_create_notification_channels_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. */ public function up(): void { Schema::create('notification_channels', function (Blueprint $table) { $table->id(); $table->foreignId('user_id')->constrained()->onDelete('cascade'); $table->string('type'); // 'telegram', 'slack', 'email', etc. $table->string('destination'); // chat_id, email, webhook, etc. $table->boolean('is_enabled')->default(true); $table->json('metadata')->nullable(); // optional, for additional info $table->timestamps(); // Add indexes for performance $table->index(['user_id', 'is_enabled']); $table->index(['type', 'is_enabled']); // Prevent duplicate channels $table->unique(['user_id', 'type', 'destination']); }); } /** * Reverse the migrations. */ public function down(): void { Schema::dropIfExists('notification_channels'); } };
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/database/migrations/2025_08_07_183132_create_queue_tables.php
database/migrations/2025_08_07_183132_create_queue_tables.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Get the migration connection name. */ public function getConnection(): ?string { return config('queue.connections.database.connection'); } /** * Run the migrations. */ public function up(): void { $schema = Schema::connection($this->getConnection()); if (! $schema->hasTable('jobs')) { Schema::create('jobs', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('queue')->index(); $table->longText('payload'); $table->tinyInteger('attempts')->unsigned(); $table->unsignedInteger('reserved_at')->nullable(); $table->unsignedInteger('available_at'); $table->unsignedInteger('created_at'); }); } if (! $schema->hasTable('failed_jobs')) { 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(); }); } if (! $schema->hasTable('job_batches')) { Schema::create('job_batches', function (Blueprint $table) { $table->string('id')->primary(); $table->string('name'); $table->integer('total_jobs'); $table->integer('pending_jobs'); $table->integer('failed_jobs'); $table->text('failed_job_ids'); $table->mediumText('options')->nullable(); $table->integer('cancelled_at')->nullable(); $table->integer('created_at'); $table->integer('finished_at')->nullable(); }); } } /** * Reverse the migrations. */ public function down(): void { Schema::dropIfExists('jobs'); Schema::dropIfExists('failed_jobs'); Schema::dropIfExists('job_batches'); } };
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/database/migrations/2025_08_14_092916_add_performance_indexes.php
database/migrations/2025_08_14_092916_add_performance_indexes.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. */ public function up(): void { // Add indexes for monitor_histories table Schema::table('monitor_histories', function (Blueprint $table) { $table->index('monitor_id'); $table->index('created_at'); $table->index(['monitor_id', 'created_at']); }); // Add indexes for monitors table Schema::table('monitors', function (Blueprint $table) { $table->index('uptime_check_enabled'); $table->index('is_public'); $table->index('uptime_last_check_date'); $table->index('uptime_status'); $table->index(['uptime_check_enabled', 'is_public']); }); // Add indexes for user_monitor table Schema::table('user_monitor', function (Blueprint $table) { $table->index('is_active'); $table->index('created_at'); $table->index(['user_id', 'is_active']); $table->index(['monitor_id', 'is_active']); }); // Add indexes for status_page_monitor table Schema::table('status_page_monitor', function (Blueprint $table) { $table->index('order'); $table->index(['status_page_id', 'order']); }); // Add indexes for sessions table (performance for auth queries) Schema::table('sessions', function (Blueprint $table) { $table->index(['user_id', 'last_activity']); }); } /** * Reverse the migrations. */ public function down(): void { // Remove indexes for monitor_histories table Schema::table('monitor_histories', function (Blueprint $table) { $table->dropIndex(['monitor_id']); $table->dropIndex(['created_at']); $table->dropIndex(['monitor_id', 'created_at']); }); // Remove indexes for monitors table Schema::table('monitors', function (Blueprint $table) { $table->dropIndex(['uptime_check_enabled']); $table->dropIndex(['is_public']); $table->dropIndex(['uptime_last_check_date']); $table->dropIndex(['uptime_status']); $table->dropIndex(['uptime_check_enabled', 'is_public']); }); // Remove indexes for user_monitor table Schema::table('user_monitor', function (Blueprint $table) { $table->dropIndex(['is_active']); $table->dropIndex(['created_at']); $table->dropIndex(['user_id', 'is_active']); $table->dropIndex(['monitor_id', 'is_active']); }); // Remove indexes for status_page_monitor table Schema::table('status_page_monitor', function (Blueprint $table) { $table->dropIndex(['order']); $table->dropIndex(['status_page_id', 'order']); }); // Remove indexes for sessions table Schema::table('sessions', function (Blueprint $table) { $table->dropIndex(['user_id', 'last_activity']); }); } };
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/database/migrations/2025_12_09_194859_create_telemetry_pings_table.php
database/migrations/2025_12_09_194859_create_telemetry_pings_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. */ public function up(): void { Schema::create('telemetry_pings', function (Blueprint $table) { $table->id(); $table->string('instance_id', 64)->unique()->index(); $table->string('app_version')->nullable(); $table->string('php_version')->nullable(); $table->string('laravel_version')->nullable(); $table->unsignedInteger('monitors_total')->default(0); $table->unsignedInteger('monitors_public')->default(0); $table->unsignedInteger('users_total')->default(0); $table->unsignedInteger('status_pages_total')->default(0); $table->string('os_family')->nullable(); $table->string('os_type')->nullable(); $table->string('database_driver')->nullable(); $table->string('queue_driver')->nullable(); $table->string('cache_driver')->nullable(); $table->date('install_date')->nullable(); $table->timestamp('first_seen_at')->nullable(); $table->timestamp('last_ping_at')->nullable(); $table->unsignedInteger('ping_count')->default(1); $table->json('raw_data')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. */ public function down(): void { Schema::dropIfExists('telemetry_pings'); } };
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/database/seeders/DemoStatusPageSeeder.php
database/seeders/DemoStatusPageSeeder.php
<?php namespace Database\Seeders; use App\Models\Monitor; use App\Models\StatusPage; use App\Models\User; use Illuminate\Database\Seeder; class DemoStatusPageSeeder extends Seeder { /** * Run the database seeds. */ public function run(): void { // Find or create a user for the demo status page $user = User::first(); if (! $user) { $this->command->warn('No users found. Please run UserSeeder first.'); return; } // Check if demo status page already exists $existingDemo = StatusPage::query()->where('path', 'demo')->first(); if ($existingDemo) { $this->command->info('Demo status page already exists. Skipping...'); return; } // Create the demo status page $statusPage = StatusPage::create([ 'user_id' => $user->id, 'title' => 'Demo Status Page', 'description' => 'Example status page showcasing Uptime Kita features. Monitor your services and share their status with your users.', 'icon' => 'activity', 'path' => 'demo', ]); $this->command->info('Demo status page created successfully.'); // Get some public monitors to attach $publicMonitors = Monitor::query() ->where('is_public', true) ->where('uptime_check_enabled', true) ->limit(5) ->get(); if ($publicMonitors->isEmpty()) { $this->command->warn('No public monitors found to attach to demo status page.'); return; } // Attach monitors with order $order = 1; foreach ($publicMonitors as $monitor) { $statusPage->monitors()->attach($monitor->id, ['order' => $order]); $order++; } $this->command->info("Attached {$publicMonitors->count()} monitors to demo status page."); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/database/seeders/NotificationChannelSeeder.php
database/seeders/NotificationChannelSeeder.php
<?php namespace Database\Seeders; use App\Models\NotificationChannel; use App\Models\User; use Illuminate\Database\Seeder; class NotificationChannelSeeder extends Seeder { public function run(): void { $user = User::first(); if (! $user) { $this->command->info('No users found, skipping notification channel seeding.'); return; } NotificationChannel::firstOrCreate([ 'user_id' => $user->id, ], [ 'type' => 'telegram', 'destination' => env('TELEGRAM_DEFAULT_CHAT_ID', '-1002075830228'), // chat ID Telegram 'metadata' => ['note' => 'Telegram utama'], ]); NotificationChannel::firstOrCreate([ 'user_id' => $user->id, ], [ 'type' => 'email', 'destination' => $user->email, 'metadata' => ['preferred' => true], ]); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/database/seeders/DatabaseSeeder.php
database/seeders/DatabaseSeeder.php
<?php namespace Database\Seeders; use App\Models\User; // use Illuminate\Database\Console\Seeds\WithoutModelEvents; use Illuminate\Database\Seeder; class DatabaseSeeder extends Seeder { /** * Seed the application's database. */ public function run(): void { // User::factory(10)->create(); User::firstOrCreate([ 'email' => config('app.admin_credentials.email'), ], [ 'name' => 'Syofyan Zuhad', 'password' => bcrypt(config('app.admin_credentials.password')), 'email_verified_at' => now(), 'is_admin' => true, ]); $this->call([ MonitorSeeder::class, // NotificationChannelSeeder::class, ]); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/database/seeders/MonitorSeeder.php
database/seeders/MonitorSeeder.php
<?php namespace Database\Seeders; use App\Models\Monitor; use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; class MonitorSeeder extends Seeder { /** * Run the database seeds. */ public function run(): void { $monitors = require database_path('seeders/monitors/monitors.php'); $collages = require database_path('seeders/monitors/collage.php'); $goverments = require database_path('seeders/monitors/goverments.php'); // merge monitors and collages $allMonitors = array_merge($monitors, $collages, $goverments); // create an array from monitor strings // and convert them to an array of associative arrays // with url, name, status, and uptime_check_interval_in_minutes // map each monitor to an associative array $allMonitors = array_map(function ($monitor) { // If it's a string, treat as URL return [ 'url' => $monitor, 'uptime_check_enabled' => 1, 'certificate_check_enabled' => 1, 'is_public' => 1, 'uptime_check_interval_in_minutes' => 1, ]; }, $allMonitors); // add 5 minute key to each monitor // $fiveMinuteMonitors = array_map(function ($monitor) { // $monitor['uptime_check_interval_in_minutes'] = 5; // return $monitor; // }, $monitors); // $monitors = array_merge( // $oneMinuteMonitors, // // $fiveMinuteMonitors // ); // upsert DB::table('monitors')->upsert( $allMonitors, [ 'url', ], // unique by url [ 'certificate_check_enabled', 'is_public', 'uptime_check_interval_in_minutes', ] ); } }
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/database/seeders/monitors/monitors.php
database/seeders/monitors/monitors.php
<?php return [ 'https://syofyanzuhad.dev', 'https://www.google.com', 'https://facebook.com', 'https://x.com', 'https://instagram.com', 'https://linkedin.com', 'https://youtube.com', 'https://reddit.com', 'https://github.com', 'https://stackoverflow.com', 'https://medium.com', 'https://dev.to', 'https://chatgpt.com', 'https://openai.com', 'https://claude.ai', 'https://perplexity.ai', 'https://grok.com', 'https://bing.com', 'https://yahoo.com', 'https://duckduckgo.com', 'https://baidu.com', 'https://yandex.com', 'https://naver.com', 'https://seznam.cz', 'https://ask.com', 'https://wolframalpha.com', 'https://quora.com', 'https://wikipedia.org', 'https://amazon.com', 'https://ebay.com', 'https://aliexpress.com', 'https://etsy.com', 'https://craigslist.org', 'https://walmart.com', 'https://target.com', 'https://bestbuy.com', 'https://costco.com', 'https://homeDepot.com', 'https://lowes.com', 'https://target.com', 'https://aldi.com', 'https://lidl.com', 'https://traderjoes.com', 'https://wholefoodsmarket.com', 'https://tokopedia.com', 'https://bukalapak.com', 'https://shopee.co.id', 'https://blibli.com', 'https://lazada.co.id', 'https://jd.id', 'https://sociolla.com', 'https://zalora.co.id', 'https://orami.co.id', 'https://fabelio.com', 'https://ruparupa.com', 'https://blanja.com', 'https://elevenia.co.id', 'https://tiktok.com', 'https://pinterest.com', 'https://snapchat.com', 'https://tumblr.com', 'https://flickr.com', 'https://vimeo.com', 'https://dailymotion.com', 'https://twitch.tv', 'https://spotify.com', 'https://soundcloud.com', 'https://apple.com', 'https://microsoft.com', 'https://adobe.com', 'https://oracle.com', 'https://ibm.com', 'https://salesforce.com', 'https://paypal.com', 'https://stripe.com', 'https://squareup.com', 'https://github.io', 'https://gitlab.com', 'https://bitbucket.org', 'https://sourceforge.net', 'https://codepen.io', 'https://jsfiddle.net', 'https://codesandbox.io', 'https://replit.com', 'https://glitch.com', 'https://heroku.com', 'https://netlify.com', 'https://vercel.com', 'https://firebase.google.com', 'https://aws.amazon.com', 'https://azure.microsoft.com', 'https://cloud.google.com', 'https://digitalocean.com', 'https://linode.com', 'https://vultr.com', 'https://herokuapp.com', 'https://render.com', 'https://fly.io', 'https://railway.app', 'https://supabase.io', 'https://hasura.io', 'https://strapi.io', 'https://ghost.org', 'https://wordpress.com', 'https://drupal.org', 'https://joomla.org', 'https://magento.com', 'https://shopify.com', 'https://bigcommerce.com', 'https://wix.com', 'https://weebly.com', 'https://squarespace.com', 'https://laravel.com', 'https://symfony.com', 'https://django.com', 'https://flask.com', 'https://rubyontheweb.com', 'https://rails.com', 'https://expressjs.com', 'https://nodejs.org', 'https://reactjs.org', 'https://vuejs.org', 'https://angular.io', 'https://svelte.dev', 'https://nextjs.org', 'https://nuxtjs.org', 'https://gatsbyjs.com', 'https://emberjs.com', 'https://backbonejs.org', 'https://jquery.com', 'https://bootstrap.com', 'https://tailwindcss.com', 'https://bulma.io', 'https://foundation.zurb.com', 'https://materializecss.com', 'https://semantic-ui.com', 'https://ant.design', 'https://element.eleme.io', 'https://vuetifyjs.com', 'https://trendshift.io/', ];
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/database/seeders/monitors/goverments.php
database/seeders/monitors/goverments.php
<?php return [ 'https://indonesia.go.id', 'https://www.kemenkeu.go.id', 'https://www.kemdikbud.go.id', 'https://www.kemlu.go.id', 'https://www.kemenkumham.go.id', 'https://www.kemenag.go.id', 'https://www.kemendagri.go.id', 'https://www.kemenhub.go.id', 'https://www.kemenperin.go.id', 'https://www.kemenkes.go.id', 'https://www.kemnaker.go.id', 'https://www.kemendag.go.id', 'https://www.kemenpora.go.id', 'https://www.kemenparekraf.go.id', 'https://www.kemenkopukm.go.id', 'https://www.kementerianpanrb.go.id', 'https://www.kementerianlhk.go.id', 'https://www.kemenpppa.go.id', 'https://www.kementerianesdm.go.id', 'https://www.kementan.go.id', 'https://www.kemristekbrin.go.id', 'https://www.bpk.go.id', 'https://www.bpkp.go.id', 'https://www.bps.go.id', 'https://www.bkn.go.id', 'https://www.bnpb.go.id', 'https://www.bnn.go.id', 'https://www.basarnas.go.id', 'https://www.lapan.go.id', 'https://www.bapanas.go.id', 'https://www.lipi.go.id', 'https://www.bi.go.id', 'https://www.ojk.go.id', 'https://www.lkpp.go.id', 'https://www.djkn.kemenkeu.go.id', 'https://www.djpb.kemenkeu.go.id', 'https://www.djpbn.kemenkeu.go.id', 'https://www.pajak.go.id', 'https://www.beacukai.go.id', 'https://www.kemenkeu-learningcenter.org', 'https://www.djp.go.id', 'https://www.mahkamahagung.go.id', 'https://www.mahkamahkonstitusi.go.id', 'https://www.kejaksaan.go.id', 'https://www.komnasham.go.id', 'https://www.komisiombudsman.go.id', 'https://www.kpk.go.id', 'https://www.polri.go.id', 'https://www.dpr.go.id', 'https://www.dpd.go.id', 'https://www.setneg.go.id', 'https://www.kominfo.go.id', 'https://www.bssn.go.id', 'https://www.bakti.kominfo.go.id', 'https://www.ais.kominfo.go.id', 'https://www.idsertifikasi.id', 'https://www.ristekbrin.go.id', 'https://www.brin.go.id', 'https://www.kemdikbudristek.go.id', 'https://www.puspendik.kemdikbud.go.id', 'https://www.kampusmerdeka.kemdikbud.go.id', 'https://www.bpjsketenagakerjaan.go.id', 'https://www.kemensos.go.id', 'https://www.kemnakertrans.go.id', 'https://www.jamsostek.co.id', 'https://www.kemlu.go.id/protokol', 'https://www.menlhk.go.id', 'https://www.marineandfisheries.go.id', 'https://www.kkp.go.id', 'https://www.bmkg.go.id', 'https://www.bpdashl.org', 'https://www.jakarta.go.id', 'https://www.jabarprov.go.id', 'https://www.jatengprov.go.id', 'https://www.jatimprov.go.id', 'https://www.sumutprov.go.id', 'https://www.sumbarprov.go.id', 'https://www.riau.go.id', 'https://www.lampungprov.go.id', 'https://www.bantenprov.go.id', 'https://www.bali.go.id', 'https://www.bandung.go.id', 'https://www.surabaya.go.id', 'https://www.semarangkota.go.id', 'https://www.yogyakarta.go.id', 'https://www.denpasarkota.go.id', 'https://www.malang.go.id', 'https://www.bogorkota.go.id', 'https://www.tangerangkota.go.id', 'https://www.bekasikota.go.id', 'https://www.depok.go.id', 'https://www.kpu.go.id', 'https://www.bawaslu.go.id', 'https://www.kpai.go.id', 'https://www.lnsldp.go.id', 'https://www.komnasperempuan.go.id', 'https://www.komisiinformasi.go.id', 'https://www.kpk.go.id', 'https://www.bnn.go.id', 'https://www.ombudsman.go.id', 'https://www.bp2mi.go.id', ];
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/database/seeders/monitors/collage.php
database/seeders/monitors/collage.php
<?php return [ 'https://gontor.ac.id', 'https://unida.gontor.ac.id', 'https://ui.ac.id', 'https://unair.ac.id', 'https://ugm.ac.id', 'https://itb.ac.id', 'https://ipb.ac.id', 'https://its.ac.id', 'https://undip.ac.id', 'https://uns.ac.id', 'https://unpad.ac.id', 'https://ub.ac.id', 'https://www.usu.ac.id', 'https://unp.ac.id', 'https://um.ac.id', 'https://uho.ac.id', 'https://uinsa.ac.id', 'https://uinjkt.ac.id', 'https://uin-suka.ac.id', 'https://telkomuniversity.ac.id', 'https://binus.ac.id', 'https://unpar.ac.id', 'https://umn.ac.id', 'https://ums.ac.id', 'https://www.umy.ac.id', 'https://uad.ac.id', 'https://amikom.ac.id', 'https://gunadarma.ac.id', 'https://trisakti.ac.id', 'https://mercubuana.ac.id', 'https://unpam.ac.id', 'https://unisma.ac.id', 'https://unsoed.ac.id', 'https://www.polinema.ac.id', 'https://polban.ac.id', 'https://polines.ac.id', 'https://pnb.ac.id', 'https://stis.ac.id', 'https://stikom.edu', 'https://stikom-bali.ac.id', 'https://stiki.ac.id', 'https://universitaspertamina.ac.id', 'https://president.ac.id', 'https://ut.ac.id', 'https://myut.ut.ac.id', 'https://admisi-sia.ut.ac.id', 'https://elearning.ut.ac.id', 'https://tmk.ut.ac.id', 'https://untan.ac.id', 'https://untirta.ac.id', 'https://untag-sby.ac.id', 'https://untag-smd.ac.id', 'https://ukdw.ac.id', 'https://uksw.edu', 'https://widyatama.ac.id', 'https://widyagama.ac.id', 'https://unmul.ac.id', 'https://unsri.ac.id', 'https://unib.ac.id', 'https://web.upri.ac.id', 'https://untad.ac.id', 'https://unram.ac.id', 'https://unud.ac.id', ];
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/resources/views/app.blade.php
resources/views/app.blade.php
<!DOCTYPE html> <html lang="{{ str_replace('_', '-', app()->getLocale()) }}" @class(['dark' => ($appearance ?? 'system') == 'dark'])> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> {{-- Inline script to detect system dark mode preference and apply it immediately --}} <script> (function() { const appearance = '{{ $appearance ?? "system" }}'; if (appearance === 'system') { const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches; if (prefersDark) { document.documentElement.classList.add('dark'); } } })(); </script> {{-- Inline style to set the HTML background color based on our theme in app.css --}} <style> html { background-color: oklch(1 0 0); } html.dark { background-color: oklch(0.145 0 0); } </style> <title inertia>Uptime Kita</title> <meta name="description" content="{{ config('app.description', 'Uptime Kita - Simple Uptime Monitoring (open-source)') }}"> <meta name="author" content="syofyanzuhad"> <meta name="keywords" content="uptime monitoring, status page, website monitoring, server monitoring, open source"> {{-- Open Graph / Facebook --}} <meta property="og:site_name" content="Uptime Kita"> <meta property="og:locale" content="id_ID"> <meta property="og:type" content="website"> <meta property="og:title" content="{{ $ogTitle ?? config('app.name', 'Uptime Kita') }}"> <meta property="og:description" content="{{ $ogDescription ?? config('app.description', 'Uptime Kita - Simple Uptime Monitoring (open-source)') }}"> <meta property="og:image" content="{{ $ogImage ?? config('app.url').'/og/monitors.png' }}"> <meta property="og:url" content="{{ $ogUrl ?? url()->current() }}"> {{-- Twitter --}} <meta name="twitter:card" content="summary_large_image"> <meta name="twitter:site" content="@syofyanzuhad"> <meta name="twitter:title" content="{{ $ogTitle ?? config('app.name', 'Uptime Kita') }}"> <meta name="twitter:description" content="{{ $ogDescription ?? config('app.description', 'Uptime Kita - Simple Uptime Monitoring (open-source)') }}"> <meta name="twitter:image" content="{{ $ogImage ?? config('app.url').'/og/monitors.png' }}"> {{-- Canonical URL --}} <link rel="canonical" href="{{ $ogUrl ?? url()->current() }}"> <link rel="icon" href="/favicon.ico" sizes="any"> <link rel="icon" href="/favicon.svg" type="image/svg+xml"> <link rel="apple-touch-icon" href="/apple-touch-icon.png"> <link rel="preconnect" href="https://fonts.bunny.net"> <link href="https://fonts.bunny.net/css?family=instrument-sans:400,500,600" rel="stylesheet" /> @if(config('app.env') !== 'local') <script defer src="https://umami.syofyanzuhad.dev/script.js" data-website-id="803a4f91-04d8-43be-9302-82df6ff14481"></script> <script defer src="https://cloud.umami.is/script.js" data-website-id="27ccc29a-1870-4f9f-9d22-9fd9f91e9b12"></script> @endif @routes @vite(['resources/js/app.ts', "resources/js/pages/{$page['component']}.vue"]) @inertiaHead </head> <body class="font-sans antialiased"> @inertia </body> </html>
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
syofyanzuhad/uptime-kita
https://github.com/syofyanzuhad/uptime-kita/blob/d60b7c16c3cc55d022da9562da63f4f6d29a4588/resources/views/vendor/log-viewer/index.blade.php
resources/views/vendor/log-viewer/index.blade.php
<!DOCTYPE html> <html lang="{{ str_replace('_', '-', app()->getLocale()) }}" class="h-full"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <meta name="csrf-token" content="{{ csrf_token() }}"> <link rel="shortcut icon" href="{{ asset(mix('img/log-viewer-32.png', 'vendor/log-viewer')) }}"> <title>Log Viewer{{ config('app.name') ? ' - ' . config('app.name') : '' }}</title> <!-- Style sheets--> <link href="{{ asset(mix('app.css', 'vendor/log-viewer')) }}" rel="stylesheet" onerror="alert('app.css failed to load. Please refresh the page, re-publish Log Viewer assets, or fix routing for vendor assets.')"> </head> <body class="h-full px-3 lg:px-5 bg-gray-100 dark:bg-gray-900"> <div id="log-viewer" class="flex h-full max-h-screen max-w-full"> <router-view></router-view> </div> <!-- Global LogViewer Object --> <script> window.LogViewer = @json($logViewerScriptVariables); // Add additional headers for LogViewer requests like so: // window.LogViewer.headers['Authorization'] = 'Bearer xxxxxxx'; </script> <script src="{{ asset(mix('app.js', 'vendor/log-viewer')) }}" onerror="alert('app.js failed to load. Please refresh the page, re-publish Log Viewer assets, or fix routing for vendor assets.')"></script> </body> </html>
php
Apache-2.0
d60b7c16c3cc55d022da9562da63f4f6d29a4588
2026-01-05T04:47:43.726909Z
false
engrnvd/laravel-crud-generator
https://github.com/engrnvd/laravel-crud-generator/blob/48ac7e879221c22e1ca8435b7edee7b621975ecc/src/Db.php
src/Db.php
<?php /** * Created by naveedulhassan. * Date: 1/22/16 * Time: 2:55 PM */ namespace Nvd\Crud; class Db { public static function fields($table) { $columns = \DB::select('show fields from '.$table); $tableFields = array(); // return value foreach ($columns as $column) { $column = (array)$column; $field = new \stdClass(); $field->name = $column['Field']; $field->defValue = $column['Default']; $field->required = $column['Null'] == 'NO'; $field->key = $column['Key']; // type and length $field->maxLength = 0;// get field and type from $res['Type'] $type_length = explode( "(", $column['Type'] ); $field->type = $type_length[0]; if( count($type_length) > 1 ) { // some times there is no "(" $field->maxLength = (int)$type_length[1]; if( $field->type == 'enum' ) { // enum has some values 'Male','Female') $matches = explode( "'", $type_length[1] ); foreach($matches as $match) { if( $match && $match != "," && $match != ")" ){ $field->enumValues[] = $match; } } } } // everything decided for the field, add it to the array $tableFields[$field->name] = $field; } return $tableFields; } public static function getConditionStr($field) { if( in_array( $field->type, ['varchar','text'] ) ) return "'{$field->name}','like','%'.\Request::input('{$field->name}').'%'"; return "'{$field->name}',\Request::input('{$field->name}')"; } public static function getValidationRule($field) { // skip certain fields if ( in_array( $field->name, static::skippedFields() ) ) return ""; $rules = []; // required fields if( $field->required ) $rules[] = "required"; // strings if( in_array( $field->type, ['varchar','text'] ) ) { $rules[] = "string"; if ( $field->maxLength ) $rules[] = "max:".$field->maxLength; } // dates if( in_array( $field->type, ['date','datetime'] ) ) $rules[] = "date"; // numbers if ( in_array( $field->type, ['int','unsigned_int'] ) ) $rules [] = "integer"; // emails if( preg_match("/email/", $field->name) ){ $rules[] = "email"; } // enums if ( $field->type == 'enum' ) $rules [] = "in:".join( ",", $field->enumValues ); return "'".$field->name."' => '".join( "|", $rules )."',"; } protected static function skippedFields() { return ['id','created_at','updated_at']; } public static function isGuarded($fieldName) { return in_array( $fieldName, static::skippedFields() ); } public static function getSearchInputStr ( $field ) { // selects if ( $field->type == 'enum' ) { $output = "{!!\Nvd\Crud\Html::selectRequested(\n"; $output .= "\t\t\t\t\t'".$field->name."',\n"; $output .= "\t\t\t\t\t[ '', '".join("', '",$field->enumValues)."' ],\n"; //Yes', 'No $output .= "\t\t\t\t\t['class'=>'form-control']\n"; $output .= "\t\t\t\t)!!}"; return $output; } // input type: $type = 'text'; if ( $field->type == 'date' ) $type = $field->type; $output = '<input type="'.$type.'" class="form-control" name="'.$field->name.'" value="{{Request::input("'.$field->name.'")}}">'; return $output; } public static function getFormInputMarkup ( $field, $modelName = '' ) { // skip certain fields if ( in_array( $field->name, static::skippedFields() ) ) return ""; // string that binds the model $modelStr = $modelName ? '->model($'.$modelName.')' : ''; // selects if ( $field->type == 'enum' ) { return "{!! \Nvd\Crud\Form::select( '{$field->name}', [ '".join("', '",$field->enumValues)."' ] ){$modelStr}->show() !!}"; } if ( $field->type == 'text' ) { return "{!! \Nvd\Crud\Form::textarea( '{$field->name}' ){$modelStr}->show() !!}"; } // input type: $type = 'text'; if ( $field->type == 'date' ) $type = $field->type; return "{!! \Nvd\Crud\Form::input('{$field->name}','{$type}'){$modelStr}->show() !!}"; } }
php
MIT
48ac7e879221c22e1ca8435b7edee7b621975ecc
2026-01-05T04:47:55.233116Z
false
engrnvd/laravel-crud-generator
https://github.com/engrnvd/laravel-crud-generator/blob/48ac7e879221c22e1ca8435b7edee7b621975ecc/src/Html.php
src/Html.php
<?php namespace Nvd\Crud; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Request; class Html { /** * @param $record Model * @param $field * @return string */ public static function editable($record, $field ) { $attributes = [ 'class' => "editable", 'data-type' => "select", 'data-name' => $field->name, 'data-value' => $record->{$field->name}, 'data-pk' => $record->{$record->getKeyName()}, 'data-url' => "/person/".$record->{$record->getKeyName()}, ]; // source for enum if ( $field->type == 'enum' ) // "[{'Male':'Male'},{'Female':'Female'}]" { $items = []; foreach ( $field->enumValues as $value ) $items[] = "{'$value':'$value'}"; $attributes['data-source'] = 'data-source="['.join( ',', $items ).']"'; } $output = static::startTag('span', $attributes); $output .= $record->{$field->name}; $output .= static::endTag('span'); return $output; } public static function getSourceForEnum($field) { if ( $field->type == 'enum' ) // "[{'Male':'Male'},{'Female':'Female'}]" { $items = []; foreach ( $field->enumValues as $value ) $items[] = "{'$value':'$value'}"; return 'data-source="['.join( ',', $items ).']"'; } return ""; } public static function getInputType($field) { // textarea if( in_array( $field->type, ['text'] ) ) return 'textarea'; // dates if( $field->type == 'date' ) return "date"; // date-time if( $field->type == 'datetime' ) return "datetime"; // numbers if ( in_array( $field->type, ['int','unsigned_int'] ) ) return "number"; // emails if( preg_match("/email/", $field->name) ) return "email"; // enums if ( $field->type == 'enum' ) return 'select'; // default type return 'text'; } public static function sortableTh($fieldName, $route, $label=null ) { $output = "<th>"; $sortType = "asc"; if( Request::input("sort") == $fieldName and Request::input("sortType") == "asc" ) $sortType = "desc"; $params = array_merge(Request::query(),['sort' => $fieldName, 'sortType' => $sortType]); $href = route($route,$params); $output .= "<a href='{$href}'>"; $label = $label?:ucwords( str_replace( "_", " ", $fieldName ) ); $output .= $label; if( Request::input("sort") == $fieldName ) $output .= " <i class='fa fa-sort-alpha-".Request::input("sortType")."'></i>"; $output .= "</a>"; $output .= "</th>"; return $output; } public static function selectRequested($name, $options, $attributes = [], $useKeysAsValues = false) { return static::select($name, $options, $attributes, \Request::input($name), $useKeysAsValues); } public static function select( $name, $options, $attributes = [], $selectedValue = null, $useKeysAsValues = false ) { $output = static::startTag( "select", array_merge( ['name'=>$name], $attributes ) ); foreach ( $options as $key => $value ){ if( $useKeysAsValues ) { $selectedAttr = $key === $selectedValue ? " selected" : ""; $valueAttr = " value='{$key}'"; } else { $selectedAttr = $value === $selectedValue ? " selected" : ""; $valueAttr = ""; } $output .= "<option{$selectedAttr}{$valueAttr}>{$value}</option>"; } $output .= static::endTag("select"); return $output; } public static function startTag( $tag, $attributes = [], $inline = false ) { $output = "<{$tag}"; foreach ( $attributes as $attr => $value ){ $output .= " {$attr}='{$value}'"; } $output .= $inline ? "/" : ""; $output .= ">"; return $output; } public static function endTag( $tag ) { return "</{$tag}>"; } }
php
MIT
48ac7e879221c22e1ca8435b7edee7b621975ecc
2026-01-05T04:47:55.233116Z
false
engrnvd/laravel-crud-generator
https://github.com/engrnvd/laravel-crud-generator/blob/48ac7e879221c22e1ca8435b7edee7b621975ecc/src/Form.php
src/Form.php
<?php /** * Created by naveedulhassan. * Date: 1/21/16 * Time: 3:08 PM */ namespace Nvd\Crud; use Illuminate\Support\MessageBag; /** * Class Form * @package Nvd\Crud * * @property $name; * @property $value; * * @method Form label($label = "") * @method Form model($value = "") * @method Form type($value = "") * @method Form helpBlock($value = false) * @method Form options($value = false) * @method Form useOptionKeysForValues($value = false) */ class Form { protected $_name; protected $_value; protected $attributes = []; protected $label; protected $helpBlock = true; // show help block or not protected $model; // model to be bound protected $type; // element type: select, input, textarea protected $options; // only for select element protected $useOptionKeysForValues; // only for select element public static function input( $name, $type = 'text' ) { $elem = static::createElement($name,'input'); $elem->attributes['type'] = $type; return $elem; } public static function select( $name, $options, $useOptionKeysForValues = false ) { $elem = static::createElement($name,"select"); $elem->options = $options; $elem->useOptionKeysForValues = $useOptionKeysForValues; return $elem; } public static function textarea($name) { return static::createElement($name,"textarea"); } public function attributes($value = null) { if($value and !is_array($value)) throw new \Exception("Attributes should be an array."); if($value) { $this->attributes = array_merge($this->attributes, $value); return $this; } return $this->attributes; } public function show() { $this->setValue(); $errors = \Session::get('errors', new MessageBag()); $hasError = ($errors and $errors->has($this->name)) ? " has-error" : ""; $output = '<div class="form-group'.$hasError.'">'; $output .= $this->label? "<label for='{$this->name}'>{$this->label}" : ""; $output .= $this->label? "</label>" : ""; $output .= call_user_func([$this, "show".ucfirst($this->type)]); if ( $this->helpBlock and $errors and $errors->has($this->name) ) { $output .= '<span class="help-block text-danger">'; $output .= $errors->first($this->name); $output .= '</span>'; } $output .= "</div>"; return $output; } protected function showInput() { $output = Html::startTag("input", $this->attributes, true ); return $output; } protected function showSelect() { return Html::select( $this->name, $this->options, $this->attributes, $this->useOptionKeysForValues ); } protected function showTextarea() { $output = Html::startTag( "textarea", $this->attributes ); $output .= $this->value; $output .= Html::endTag("textarea"); return $output; } protected static function createElement( $name, $type ) { $elem = new self; $elem->type = $type; $elem->name = $name; $elem->attributes['id'] = $name; $elem->attributes['class'] = 'form-control'; $elem->label = ucwords( str_replace( "_"," ", $name ) ); return $elem; } protected function setValue() { $this->value = old($this->name); if( empty($this->value) and $this->model ) { $this->value = $this->model->{$this->name}; } return $this; } public function __call( $attr, $args = null ) { if( !property_exists($this, $attr) ) throw new \Exception("Method {$attr} does not exist."); if(count($args)){ $this->$attr = $args[0]; return $this; } return $this->$attr; } public function __set($property, $value) { if( in_array( $property, ['name','value'] ) ) { $this->{"_".$property} = $value; if( $property != 'value' or $this->type == 'input' ) // textarea and select should not have a value attribute { $this->attributes[$property] = $value; } } } public function __get($property) { return $this->{"_".$property}; } }
php
MIT
48ac7e879221c22e1ca8435b7edee7b621975ecc
2026-01-05T04:47:55.233116Z
false
engrnvd/laravel-crud-generator
https://github.com/engrnvd/laravel-crud-generator/blob/48ac7e879221c22e1ca8435b7edee7b621975ecc/src/Config/config.php
src/Config/config.php
<?php $config = [ /* * Views that will be generated. If you wish to add your own view, * make sure to create a template first in the * '/resources/views/crud-templates/views' directory. * */ 'views' => [ 'index', 'edit', 'show', 'create', ], /* * Directory containing the templates * If you want to use your custom templates, specify them here * */ 'templates' => 'vendor.crud.single-page-templates', ]; /* * Layout template used when generating views * */ $config['layout'] = $config['templates'].'.common.app'; return $config;
php
MIT
48ac7e879221c22e1ca8435b7edee7b621975ecc
2026-01-05T04:47:55.233116Z
false
engrnvd/laravel-crud-generator
https://github.com/engrnvd/laravel-crud-generator/blob/48ac7e879221c22e1ca8435b7edee7b621975ecc/src/classic-templates/controller.blade.php
src/classic-templates/controller.blade.php
<?php /* @var $gen \Nvd\Crud\Commands\Crud */ ?> <?='<?php'?> namespace App\Http\Controllers; use App\{{$gen->modelClassName()}}; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; class {{$gen->controllerClassName()}} extends Controller { public $viewDir = "{{$gen->viewsDirName()}}"; public function index() { $records = {{$gen->modelClassName()}}::findRequested(); return $this->view( "index", ['records' => $records] ); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return $this->view("create"); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store( Request $request ) { $this->validate($request, {{$gen->modelClassName()}}::validationRules()); {{$gen->modelClassName()}}::create($request->all()); return redirect('/{{$gen->route()}}'); } /** * Display the specified resource. * * @return \Illuminate\Http\Response */ public function show(Request $request, {{$gen->modelClassName()}} ${{$gen->modelVariableName()}}) { return $this->view("show",['{{$gen->modelVariableName()}}' => ${{$gen->modelVariableName()}}]); } /** * Show the form for editing the specified resource. * * @return \Illuminate\Http\Response */ public function edit(Request $request, {{$gen->modelClassName()}} ${{$gen->modelVariableName()}}) { return $this->view( "edit", ['{{$gen->modelVariableName()}}' => ${{$gen->modelVariableName()}}] ); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function update(Request $request, {{$gen->modelClassName()}} ${{$gen->modelVariableName()}}) { $this->validate($request, {{$gen->modelClassName()}}::validationRules()); ${{$gen->modelVariableName()}}->update($request->all()); return redirect('/{{$gen->route()}}'); } /** * Remove the specified resource from storage. * * @return \Illuminate\Http\Response */ public function destroy(Request $request, {{$gen->modelClassName()}} ${{$gen->modelVariableName()}}) { ${{$gen->modelVariableName()}}->delete(); return redirect('/{{$gen->route()}}'); } protected function view($view, $data = []) { return view($this->viewDir.".".$view, $data); } }
php
MIT
48ac7e879221c22e1ca8435b7edee7b621975ecc
2026-01-05T04:47:55.233116Z
false
engrnvd/laravel-crud-generator
https://github.com/engrnvd/laravel-crud-generator/blob/48ac7e879221c22e1ca8435b7edee7b621975ecc/src/classic-templates/model.blade.php
src/classic-templates/model.blade.php
<?php /* @var $gen \Nvd\Crud\Commands\Crud */ /* @var $fields [] */ ?> <?='<?php'?> namespace App; use Illuminate\Database\Eloquent\Model; class <?=$gen->modelClassName()?> extends Model { public $guarded = ["id","created_at","updated_at"]; public static function findRequested() { $query = <?=$gen->modelClassName()?>::query(); // search results based on user input @foreach ( $fields as $field ) \Request::input('{{$field->name}}') and $query->where({!! \Nvd\Crud\Db::getConditionStr($field) !!}); @endforeach // sort results \Request::input("sort") and $query->orderBy(\Request::input("sort"),\Request::input("sortType","asc")); // paginate results return $query->paginate(15); } public static function validationRules( $attributes = null ) { $rules = [ @foreach ( $fields as $field ) @if( $rule = \Nvd\Crud\Db::getValidationRule( $field ) ) {!! $rule !!} @endif @endforeach ]; // no list is provided if(!$attributes) return $rules; // a single attribute is provided if(!is_array($attributes)) return [ $attributes => $rules[$attributes] ]; // a list of attributes is provided $newRules = []; foreach ( $attributes as $attr ) $newRules[$attr] = $rules[$attr]; return $newRules; } }
php
MIT
48ac7e879221c22e1ca8435b7edee7b621975ecc
2026-01-05T04:47:55.233116Z
false
engrnvd/laravel-crud-generator
https://github.com/engrnvd/laravel-crud-generator/blob/48ac7e879221c22e1ca8435b7edee7b621975ecc/src/classic-templates/views/show.php
src/classic-templates/views/show.php
<?php /* @var $gen \Nvd\Crud\Commands\Crud */ /* @var $fields [] */ ?> @extends('<?=config('crud.layout')?>') @section('content') <h2><?= $gen->titleSingular() ?>: {{$<?= $gen->modelVariableName() ?>-><?=array_values($fields)[1]->name?>}}</h2> <ul class="list-group"> <?php foreach ( $fields as $field ) { ?> <li class="list-group-item"> <h4><?=ucwords(str_replace('_',' ',$field->name))?></h4> <h5>{{$<?= $gen->modelVariableName() ?>-><?=$field->name?>}}</h5> </li> <?php } ?> </ul> @endsection
php
MIT
48ac7e879221c22e1ca8435b7edee7b621975ecc
2026-01-05T04:47:55.233116Z
false
engrnvd/laravel-crud-generator
https://github.com/engrnvd/laravel-crud-generator/blob/48ac7e879221c22e1ca8435b7edee7b621975ecc/src/classic-templates/views/edit.php
src/classic-templates/views/edit.php
<?php /* @var $gen \Nvd\Crud\Commands\Crud */ /* @var $fields [] */ ?> @extends('<?=config('crud.layout')?>') @section('content') <h2>Update <?=$gen->titleSingular()?>: {{$<?=$gen->modelVariableName()?>-><?=array_values($fields)[1]->name?>}}</h2> <form action="/<?=$gen->route()?>/{{$<?=$gen->modelVariableName()?>->id}}" method="post"> {{ csrf_field() }} {{ method_field("PUT") }} <?php foreach ( $fields as $field ) { ?> <?php if( $str = \Nvd\Crud\Db::getFormInputMarkup( $field, $gen->modelVariableName() ) ) { ?> <?=$str?> <?php } ?> <?php } ?> <button type="submit" class="btn btn-default">Submit</button> </form> @endsection
php
MIT
48ac7e879221c22e1ca8435b7edee7b621975ecc
2026-01-05T04:47:55.233116Z
false
engrnvd/laravel-crud-generator
https://github.com/engrnvd/laravel-crud-generator/blob/48ac7e879221c22e1ca8435b7edee7b621975ecc/src/classic-templates/views/index.php
src/classic-templates/views/index.php
<?php /* @var $gen \Nvd\Crud\Commands\Crud */ /* @var $fields [] */ ?> @extends('<?=config('crud.layout')?>') @section('content') <h2><?= $gen->titlePlural() ?></h2> @include('<?=$gen->templatesDir()?>.common.create-new-link', ['url' => '<?= $gen->route() ?>']) <table class="table table-striped grid-view-tbl"> <thead> <tr class="header-row"> <?php foreach ( $fields as $field ) { ?> {!!\Nvd\Crud\Html::sortableTh('<?=$field->name?>','<?= $gen->route() ?>.index','<?=ucwords(str_replace('_',' ',$field->name))?>')!!} <?php } ?> <th></th> </tr> <tr class="search-row"> <form class="search-form"> <?php foreach ( $fields as $field ) { ?> <td><?=\Nvd\Crud\Db::getSearchInputStr($field)?></td> <?php } ?> <td style="min-width: 6.1em;">@include('<?=$gen->templatesDir()?>.common.search-btn')</td> </form> </tr> </thead> <tbody> @forelse ( $records as $record ) <tr> <?php foreach ( $fields as $field ) { ?> <td>{{$record['<?=$field->name?>']}}</td> <?php } ?> @include( '<?=$gen->templatesDir()?>.common.actions', [ 'url' => '<?= $gen->route() ?>', 'record' => $record ] ) </tr> @empty @include ('<?=$gen->templatesDir()?>.common.not-found-tr',['colspan' => <?=count($fields)+1?>]) @endforelse </tbody> </table> @include('<?=$gen->templatesDir()?>.common.pagination', [ 'records' => $records ] ) @endsection
php
MIT
48ac7e879221c22e1ca8435b7edee7b621975ecc
2026-01-05T04:47:55.233116Z
false
engrnvd/laravel-crud-generator
https://github.com/engrnvd/laravel-crud-generator/blob/48ac7e879221c22e1ca8435b7edee7b621975ecc/src/classic-templates/views/create.php
src/classic-templates/views/create.php
<?php /* @var $gen \Nvd\Crud\Commands\Crud */ /* @var $fields [] */ ?> @extends('<?=config('crud.layout')?>') @section('content') <h2>Create a New <?=$gen->titleSingular()?></h2> <form action="/<?=$gen->route()?>" method="post"> {{ csrf_field() }} <?php foreach ( $fields as $field ) { ?> <?php if( $str = \Nvd\Crud\Db::getFormInputMarkup($field) ) { ?> <?=$str?> <?php } ?> <?php } ?> <button type="submit" class="btn btn-default">Submit</button> </form> @endsection
php
MIT
48ac7e879221c22e1ca8435b7edee7b621975ecc
2026-01-05T04:47:55.233116Z
false
engrnvd/laravel-crud-generator
https://github.com/engrnvd/laravel-crud-generator/blob/48ac7e879221c22e1ca8435b7edee7b621975ecc/src/classic-templates/common/pagination.blade.php
src/classic-templates/common/pagination.blade.php
<?php /* @var $records */ ?> @if(count($records)) {!! $records->appends(Request::query())->render() !!} @endif
php
MIT
48ac7e879221c22e1ca8435b7edee7b621975ecc
2026-01-05T04:47:55.233116Z
false
engrnvd/laravel-crud-generator
https://github.com/engrnvd/laravel-crud-generator/blob/48ac7e879221c22e1ca8435b7edee7b621975ecc/src/classic-templates/common/actions.blade.php
src/classic-templates/common/actions.blade.php
<?php /* @var $url */ /* @var $record */ ?> <td class="actions-cell"> <form class="form-inline" action="/{{$url}}/{{$record->id}}" method="POST"> <a href="/{{$url}}/{{$record->id}}"><i class="fa fa-eye"></i></a>&nbsp;&nbsp; <a href="/{{$url}}/{{$record->id}}/edit"><i class="fa fa-pencil"></i></a>&nbsp; {{ csrf_field() }} {{ method_field('DELETE') }} <button style="outline: none;background: transparent;border: none;" onclick="return confirm('Are You Sure?')" type="submit" class="fa fa-remove text-danger"></button> </form> </td>
php
MIT
48ac7e879221c22e1ca8435b7edee7b621975ecc
2026-01-05T04:47:55.233116Z
false
engrnvd/laravel-crud-generator
https://github.com/engrnvd/laravel-crud-generator/blob/48ac7e879221c22e1ca8435b7edee7b621975ecc/src/classic-templates/common/search-btn.blade.php
src/classic-templates/common/search-btn.blade.php
<button type="submit" class="fa fa-search form-control btn btn-primary"></button>
php
MIT
48ac7e879221c22e1ca8435b7edee7b621975ecc
2026-01-05T04:47:55.233116Z
false
engrnvd/laravel-crud-generator
https://github.com/engrnvd/laravel-crud-generator/blob/48ac7e879221c22e1ca8435b7edee7b621975ecc/src/classic-templates/common/not-found-tr.blade.php
src/classic-templates/common/not-found-tr.blade.php
<tr class="alert alert-warning"><td colspan="{{$colspan}}">No records found.</td></tr>
php
MIT
48ac7e879221c22e1ca8435b7edee7b621975ecc
2026-01-05T04:47:55.233116Z
false
engrnvd/laravel-crud-generator
https://github.com/engrnvd/laravel-crud-generator/blob/48ac7e879221c22e1ca8435b7edee7b621975ecc/src/classic-templates/common/create-new-link.blade.php
src/classic-templates/common/create-new-link.blade.php
<?php /* @var $url */ /* @var $label */ ?> <p> <a href="/{{$url}}/create" class="create-link"> <i class="fa fa-plus"></i> Add a New {{$label or ucwords(str_replace("-"," ", $url))}} </a> </p>
php
MIT
48ac7e879221c22e1ca8435b7edee7b621975ecc
2026-01-05T04:47:55.233116Z
false
engrnvd/laravel-crud-generator
https://github.com/engrnvd/laravel-crud-generator/blob/48ac7e879221c22e1ca8435b7edee7b621975ecc/src/classic-templates/common/app.blade.php
src/classic-templates/common/app.blade.php
<!DOCTYPE html> <html> <head> <title>Laravel Sandbox</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css"> <script src="https://code.jquery.com/jquery-2.2.0.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script> </head> <body> <div class="container"> <div class="content"> @yield("content") </div> </div> </body> </html>
php
MIT
48ac7e879221c22e1ca8435b7edee7b621975ecc
2026-01-05T04:47:55.233116Z
false
engrnvd/laravel-crud-generator
https://github.com/engrnvd/laravel-crud-generator/blob/48ac7e879221c22e1ca8435b7edee7b621975ecc/src/Commands/Crud.php
src/Commands/Crud.php
<?php namespace Nvd\Crud\Commands; use Illuminate\Console\Command; use Nvd\Crud\Db; class Crud extends Command { public $tableName; /** * The name and signature of the console command. * * @var string */ protected $signature = 'nvd:crud {tableName : The name of the table you want to generate crud for.}'; /** * The console command description. * * @var string */ protected $description = 'Generate crud for a specific table in the database'; /** * Create a new command instance. */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { $this->tableName = $this->argument('tableName'); $this->generateModel(); $this->generateRouteModelBinding(); $this->generateRoute(); $this->generateController(); $this->generateViews(); } public function generateRouteModelBinding() { $declaration = "\$router->model('".$this->route()."', 'App\\".$this->modelClassName()."');"; $providerFile = app_path('Providers/RouteServiceProvider.php'); $fileContent = file_get_contents($providerFile); if ( strpos( $fileContent, $declaration ) == false ) { $regex = "/(public\s*function\s*boot\s*\(\s*Router\s*.router\s*\)\s*\{)/"; if( preg_match( $regex, $fileContent ) ) { $fileContent = preg_replace( $regex, "$1\n\t\t".$declaration, $fileContent ); file_put_contents($providerFile, $fileContent); $this->info("Route model binding inserted successfully in ".$providerFile); return true; } // match was not found for some reason $this->warn("Could not add route model binding for the route '".$this->route()."'."); $this->warn("Please add the following line manually in {$providerFile}:"); $this->warn($declaration); return false; } // already exists $this->info("Model binding for the route: '".$this->route()."' already exists."); $this->info("Skipping..."); return false; } public function generateRoute() { $route = "Route::resource('{$this->route()}','{$this->controllerClassName()}');"; $routesFile = app_path('Http/routes.php'); $routesFileContent = file_get_contents($routesFile); if ( strpos( $routesFileContent, $route ) == false ) { $routesFileContent = $this->getUpdatedContent($routesFileContent, $route); file_put_contents($routesFile,$routesFileContent); $this->info("created route: ".$route); return true; } $this->info("Route: '".$route."' already exists."); $this->info("Skipping..."); return false; } protected function getUpdatedContent ( $existingContent, $route ) { // check if the user has directed to add routes $str = "nvd-crud routes go here"; if( strpos( $existingContent, $str ) !== false ) return str_replace( $str, "{$str}\n\t".$route, $existingContent ); // check for 'web' middleware group $regex = "/(Route\s*\:\:\s*group\s*\(\s*\[\s*\'middleware\'\s*\=\>\s*\[\s*\'web\'\s*\]\s*\]\s*\,\s*function\s*\(\s*\)\s*\{)/"; if( preg_match( $regex, $existingContent ) ) return preg_replace( $regex, "$1\n\t".$route, $existingContent ); // if there is no 'web' middleware group return $existingContent."\n".$route; } public function generateController() { $controllerFile = $this->controllersDir().'/'.$this->controllerClassName().".php"; if($this->confirmOverwrite($controllerFile)) { $content = view($this->templatesDir().'.controller',['gen' => $this]); file_put_contents($controllerFile, $content); $this->info( $this->controllerClassName()." generated successfully." ); } } public function generateModel() { $modelFile = $this->modelsDir().'/'.$this->modelClassName().".php"; if($this->confirmOverwrite($modelFile)) { $content = view( $this->templatesDir().'.model', [ 'gen' => $this, 'fields' => Db::fields($this->tableName) ]); file_put_contents($modelFile, $content); $this->info( "Model class ".$this->modelClassName()." generated successfully." ); } } public function generateViews() { if( !file_exists($this->viewsDir()) ) mkdir($this->viewsDir()); foreach ( config('crud.views') as $view ){ $viewFile = $this->viewsDir()."/".$view.".blade.php"; if($this->confirmOverwrite($viewFile)) { $content = view( $this->templatesDir().'.views.'.$view, [ 'gen' => $this, 'fields' => Db::fields($this->tableName) ]); file_put_contents($viewFile, $content); $this->info( "View file ".$view." generated successfully." ); } } } protected function confirmOverwrite($file) { // if file does not already exist, return if( !file_exists($file) ) return true; // file exists, get confirmation if ($this->confirm($file.' already exists! Do you wish to overwrite this file? [y|N]')) { $this->info("overwriting..."); return true; } else{ $this->info("Using existing file ..."); return false; } } public function route() { return str_slug(str_replace("_"," ", str_singular($this->tableName))); } public function controllerClassName() { return studly_case(str_singular($this->tableName))."Controller"; } public function viewsDir() { return base_path('resources/views/'.$this->viewsDirName()); } public function viewsDirName() { return str_singular($this->tableName); } public function controllersDir() { return app_path('Http/Controllers'); } public function modelsDir() { return app_path(); } public function modelClassName() { return studly_case(str_singular($this->tableName)); } public function modelVariableName() { return camel_case(str_singular($this->tableName)); } public function titleSingular() { return ucwords(str_singular(str_replace("_", " ", $this->tableName))); } public function titlePlural() { return ucwords(str_replace("_", " ", $this->tableName)); } public function templatesDir() { return config('crud.templates'); } }
php
MIT
48ac7e879221c22e1ca8435b7edee7b621975ecc
2026-01-05T04:47:55.233116Z
false
engrnvd/laravel-crud-generator
https://github.com/engrnvd/laravel-crud-generator/blob/48ac7e879221c22e1ca8435b7edee7b621975ecc/src/Providers/NvdCrudServiceProvider.php
src/Providers/NvdCrudServiceProvider.php
<?php namespace Nvd\Crud\Providers; use Illuminate\Support\ServiceProvider; use Nvd\Crud\Commands\Crud; class NvdCrudServiceProvider extends ServiceProvider { /** * Bootstrap the application services. * * @return void */ public function boot() { $this->commands([Crud::class]); $this->publishes([ __DIR__.'/../Config/config.php' => config_path('crud.php'), __DIR__.'/../classic-templates' => base_path('resources/views/vendor/crud/classic-templates'), __DIR__.'/../single-page-templates' => base_path('resources/views/vendor/crud/single-page-templates'), ],'nvd'); } /** * Register the application services. * * @return void */ public function register() { // } }
php
MIT
48ac7e879221c22e1ca8435b7edee7b621975ecc
2026-01-05T04:47:55.233116Z
false
engrnvd/laravel-crud-generator
https://github.com/engrnvd/laravel-crud-generator/blob/48ac7e879221c22e1ca8435b7edee7b621975ecc/src/single-page-templates/controller.blade.php
src/single-page-templates/controller.blade.php
<?php /* @var $gen \Nvd\Crud\Commands\Crud */ ?> <?='<?php'?> namespace App\Http\Controllers; use App\{{$gen->modelClassName()}}; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; class {{$gen->controllerClassName()}} extends Controller { public $viewDir = "{{$gen->viewsDirName()}}"; public function index() { $records = {{$gen->modelClassName()}}::findRequested(); return $this->view( "index", ['records' => $records] ); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return $this->view("create"); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store( Request $request ) { $this->validate($request, {{$gen->modelClassName()}}::validationRules()); {{$gen->modelClassName()}}::create($request->all()); return redirect('/{{$gen->route()}}'); } /** * Display the specified resource. * * @return \Illuminate\Http\Response */ public function show(Request $request, {{$gen->modelClassName()}} ${{$gen->modelVariableName()}}) { return $this->view("show",['{{$gen->modelVariableName()}}' => ${{$gen->modelVariableName()}}]); } /** * Show the form for editing the specified resource. * * @return \Illuminate\Http\Response */ public function edit(Request $request, {{$gen->modelClassName()}} ${{$gen->modelVariableName()}}) { return $this->view( "edit", ['{{$gen->modelVariableName()}}' => ${{$gen->modelVariableName()}}] ); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function update(Request $request, {{$gen->modelClassName()}} ${{$gen->modelVariableName()}}) { if( $request->isXmlHttpRequest() ) { $data = [$request->name => $request->value]; $validator = \Validator::make( $data, {{$gen->modelClassName()}}::validationRules( $request->name ) ); if($validator->fails()) return response($validator->errors()->first( $request->name),403); ${{$gen->modelVariableName()}}->update($data); return "Record updated"; } $this->validate($request, {{$gen->modelClassName()}}::validationRules()); ${{$gen->modelVariableName()}}->update($request->all()); return redirect('/{{$gen->route()}}'); } /** * Remove the specified resource from storage. * * @return \Illuminate\Http\Response */ public function destroy(Request $request, {{$gen->modelClassName()}} ${{$gen->modelVariableName()}}) { ${{$gen->modelVariableName()}}->delete(); return redirect('/{{$gen->route()}}'); } protected function view($view, $data = []) { return view($this->viewDir.".".$view, $data); } }
php
MIT
48ac7e879221c22e1ca8435b7edee7b621975ecc
2026-01-05T04:47:55.233116Z
false
engrnvd/laravel-crud-generator
https://github.com/engrnvd/laravel-crud-generator/blob/48ac7e879221c22e1ca8435b7edee7b621975ecc/src/single-page-templates/model.blade.php
src/single-page-templates/model.blade.php
<?php /* @var $gen \Nvd\Crud\Commands\Crud */ /* @var $fields [] */ ?> <?='<?php'?> namespace App; use Illuminate\Database\Eloquent\Model; class <?=$gen->modelClassName()?> extends Model { public $guarded = ["id","created_at","updated_at"]; public static function findRequested() { $query = <?=$gen->modelClassName()?>::query(); // search results based on user input @foreach ( $fields as $field ) \Request::input('{{$field->name}}') and $query->where({!! \Nvd\Crud\Db::getConditionStr($field) !!}); @endforeach // sort results \Request::input("sort") and $query->orderBy(\Request::input("sort"),\Request::input("sortType","asc")); // paginate results return $query->paginate(15); } public static function validationRules( $attributes = null ) { $rules = [ @foreach ( $fields as $field ) @if( $rule = \Nvd\Crud\Db::getValidationRule( $field ) ) {!! $rule !!} @endif @endforeach ]; // no list is provided if(!$attributes) return $rules; // a single attribute is provided if(!is_array($attributes)) return [ $attributes => $rules[$attributes] ]; // a list of attributes is provided $newRules = []; foreach ( $attributes as $attr ) $newRules[$attr] = $rules[$attr]; return $newRules; } }
php
MIT
48ac7e879221c22e1ca8435b7edee7b621975ecc
2026-01-05T04:47:55.233116Z
false
engrnvd/laravel-crud-generator
https://github.com/engrnvd/laravel-crud-generator/blob/48ac7e879221c22e1ca8435b7edee7b621975ecc/src/single-page-templates/views/show.php
src/single-page-templates/views/show.php
<?php /* @var $gen \Nvd\Crud\Commands\Crud */ /* @var $fields [] */ ?> @extends('<?=config('crud.layout')?>') @section('content') <h2><?= $gen->titleSingular() ?>: {{$<?= $gen->modelVariableName() ?>-><?=array_values($fields)[1]->name?>}}</h2> <ul class="list-group"> <?php foreach ( $fields as $field ) { ?> <li class="list-group-item"> <h4><?=ucwords(str_replace('_',' ',$field->name))?></h4> <h5>{{$<?= $gen->modelVariableName() ?>-><?=$field->name?>}}</h5> </li> <?php } ?> </ul> @endsection
php
MIT
48ac7e879221c22e1ca8435b7edee7b621975ecc
2026-01-05T04:47:55.233116Z
false
engrnvd/laravel-crud-generator
https://github.com/engrnvd/laravel-crud-generator/blob/48ac7e879221c22e1ca8435b7edee7b621975ecc/src/single-page-templates/views/edit.php
src/single-page-templates/views/edit.php
<?php /* @var $gen \Nvd\Crud\Commands\Crud */ /* @var $fields [] */ ?> @extends('<?=config('crud.layout')?>') @section('content') <h2>Update <?=$gen->titleSingular()?>: {{$<?=$gen->modelVariableName()?>-><?=array_values($fields)[1]->name?>}}</h2> <form action="/<?=$gen->route()?>/{{$<?=$gen->modelVariableName()?>->id}}" method="post"> {{ csrf_field() }} {{ method_field("PUT") }} <?php foreach ( $fields as $field ) { ?> <?php if( $str = \Nvd\Crud\Db::getFormInputMarkup( $field, $gen->modelVariableName() ) ) { ?> <?=$str?> <?php } ?> <?php } ?> <button type="submit" class="btn btn-default">Submit</button> </form> @endsection
php
MIT
48ac7e879221c22e1ca8435b7edee7b621975ecc
2026-01-05T04:47:55.233116Z
false
engrnvd/laravel-crud-generator
https://github.com/engrnvd/laravel-crud-generator/blob/48ac7e879221c22e1ca8435b7edee7b621975ecc/src/single-page-templates/views/index.php
src/single-page-templates/views/index.php
<?php /* @var $gen \Nvd\Crud\Commands\Crud */ /* @var $fields [] */ ?> @extends('<?=config('crud.layout')?>') @section('content') <h2><?= $gen->titlePlural() ?></h2> @include('<?=$gen->viewsDirName()?>.create') <table class="table table-striped grid-view-tbl"> <thead> <tr class="header-row"> <?php foreach ( $fields as $field ) { ?> {!!\Nvd\Crud\Html::sortableTh('<?=$field->name?>','<?= $gen->route() ?>.index','<?=ucwords(str_replace('_',' ',$field->name))?>')!!} <?php } ?> <th></th> </tr> <tr class="search-row"> <form class="search-form"> <?php foreach ( $fields as $field ) { ?> <td><?=\Nvd\Crud\Db::getSearchInputStr($field)?></td> <?php } ?> <td style="min-width: 6em;">@include('<?=$gen->templatesDir()?>.common.search-btn')</td> </form> </tr> </thead> <tbody> @forelse ( $records as $record ) <tr> <?php foreach ( $fields as $field ) { ?> <td> <?php if( !\Nvd\Crud\Db::isGuarded($field->name) ) {?> <span class="editable" data-type="<?=\Nvd\Crud\Html::getInputType($field)?>" data-name="<?=$field->name?>" data-value="{{ $record-><?=$field->name?> }}" data-pk="{{ $record->{$record->getKeyName()} }}" data-url="/<?=$gen->route()?>/{{ $record->{$record->getKeyName()} }}" <?=\Nvd\Crud\Html::getSourceForEnum($field)?>>{{ $record-><?=$field->name?> }}</span> <?php } else { ?> {{ $record-><?=$field->name?> }} <?php } ?> </td> <?php } ?> @include( '<?=$gen->templatesDir()?>.common.actions', [ 'url' => '<?= $gen->route() ?>', 'record' => $record ] ) </tr> @empty @include ('<?=$gen->templatesDir()?>.common.not-found-tr',['colspan' => <?=count($fields)+1?>]) @endforelse </tbody> </table> @include('<?=$gen->templatesDir()?>.common.pagination', [ 'records' => $records ] ) <script> $(".editable").editable({ajaxOptions:{method:'PUT'}}); </script> @endsection
php
MIT
48ac7e879221c22e1ca8435b7edee7b621975ecc
2026-01-05T04:47:55.233116Z
false
engrnvd/laravel-crud-generator
https://github.com/engrnvd/laravel-crud-generator/blob/48ac7e879221c22e1ca8435b7edee7b621975ecc/src/single-page-templates/views/create.php
src/single-page-templates/views/create.php
<?php /* @var $gen \Nvd\Crud\Commands\Crud */ /* @var $fields [] */ ?> <div class="panel-group col-md-6 col-sm-12" id="accordion" style="padding-left: 0"> <div class="panel panel-primary"> <div class="panel-heading"> <h4 class="panel-title"> <a data-toggle="collapse" data-parent="#accordion" href="#collapseOne"> <i class="fa fa-plus"></i> Add a New <?=$gen->titleSingular()?> </a> </h4> </div> <div id="collapseOne" class="panel-collapse collapse"> <div class="panel-body"> <form action="/<?=$gen->route()?>" method="post"> {{ csrf_field() }} <?php foreach ( $fields as $field ) { ?> <?php if( $str = \Nvd\Crud\Db::getFormInputMarkup($field) ) { ?> <?=$str?> <?php } ?> <?php } ?> <button type="submit" class="btn btn-primary">Create</button> </form> </div> </div> </div> </div>
php
MIT
48ac7e879221c22e1ca8435b7edee7b621975ecc
2026-01-05T04:47:55.233116Z
false
engrnvd/laravel-crud-generator
https://github.com/engrnvd/laravel-crud-generator/blob/48ac7e879221c22e1ca8435b7edee7b621975ecc/src/single-page-templates/common/pagination.blade.php
src/single-page-templates/common/pagination.blade.php
<?php /* @var $records */ ?> @if(count($records)) {!! $records->appends(Request::query())->render() !!} @endif
php
MIT
48ac7e879221c22e1ca8435b7edee7b621975ecc
2026-01-05T04:47:55.233116Z
false
engrnvd/laravel-crud-generator
https://github.com/engrnvd/laravel-crud-generator/blob/48ac7e879221c22e1ca8435b7edee7b621975ecc/src/single-page-templates/common/actions.blade.php
src/single-page-templates/common/actions.blade.php
<?php /* @var $url */ /* @var $record */ ?> <td class="actions-cell"> <form class="form-inline" action="/{{$url}}/{{$record->id}}" method="POST"> <a href="/{{$url}}/{{$record->id}}"><i class="fa fa-eye"></i></a>&nbsp;&nbsp; <a href="/{{$url}}/{{$record->id}}/edit"><i class="fa fa-pencil-square-o"></i></a> {{ csrf_field() }} {{ method_field('DELETE') }} <button style="outline: none;background: transparent;border: none;" onclick="return confirm('Are You Sure?')" type="submit" class="fa fa-trash text-danger"></button> </form> </td>
php
MIT
48ac7e879221c22e1ca8435b7edee7b621975ecc
2026-01-05T04:47:55.233116Z
false
engrnvd/laravel-crud-generator
https://github.com/engrnvd/laravel-crud-generator/blob/48ac7e879221c22e1ca8435b7edee7b621975ecc/src/single-page-templates/common/search-btn.blade.php
src/single-page-templates/common/search-btn.blade.php
<button type="submit" class="fa fa-search form-control btn btn-primary"></button>
php
MIT
48ac7e879221c22e1ca8435b7edee7b621975ecc
2026-01-05T04:47:55.233116Z
false
engrnvd/laravel-crud-generator
https://github.com/engrnvd/laravel-crud-generator/blob/48ac7e879221c22e1ca8435b7edee7b621975ecc/src/single-page-templates/common/not-found-tr.blade.php
src/single-page-templates/common/not-found-tr.blade.php
<tr class="alert alert-warning"><td colspan="{{$colspan}}">No records found.</td></tr>
php
MIT
48ac7e879221c22e1ca8435b7edee7b621975ecc
2026-01-05T04:47:55.233116Z
false
engrnvd/laravel-crud-generator
https://github.com/engrnvd/laravel-crud-generator/blob/48ac7e879221c22e1ca8435b7edee7b621975ecc/src/single-page-templates/common/create-new-link.blade.php
src/single-page-templates/common/create-new-link.blade.php
<?php /* @var $url */ /* @var $label */ ?> <p> <a href="/{{$url}}/create" class="create-link"> <i class="fa fa-plus"></i> Add a New {{$label or ucwords(str_replace("-"," ", $url))}} </a> </p>
php
MIT
48ac7e879221c22e1ca8435b7edee7b621975ecc
2026-01-05T04:47:55.233116Z
false
engrnvd/laravel-crud-generator
https://github.com/engrnvd/laravel-crud-generator/blob/48ac7e879221c22e1ca8435b7edee7b621975ecc/src/single-page-templates/common/app.blade.php
src/single-page-templates/common/app.blade.php
<!DOCTYPE html> <html> <head> <title>Laravel Sandbox</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css"> <link href="//cdnjs.cloudflare.com/ajax/libs/x-editable/1.5.0/bootstrap3-editable/css/bootstrap-editable.css" rel="stylesheet"/> <script src="https://code.jquery.com/jquery-2.2.0.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/x-editable/1.5.0/bootstrap3-editable/js/bootstrap-editable.min.js"></script> <meta name="csrf-token" content="{{ csrf_token() }}" /> <script> $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); </script> </head> <body> <div class="container"> <div class="content"> @yield("content") </div> </div> </body> </html>
php
MIT
48ac7e879221c22e1ca8435b7edee7b621975ecc
2026-01-05T04:47:55.233116Z
false
Bacon/BaconPdf
https://github.com/Bacon/BaconPdf/blob/5f2e6b4eea079d5311111b80a53f6e5d3d3d4630/benchmark/ObjectWriterEvent.php
benchmark/ObjectWriterEvent.php
<?php /** * BaconPdf * * @link http://github.com/Bacon/BaconPdf For the canonical source repository * @copyright 2015 Ben Scholzen (DASPRiD) * @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License */ namespace Bacon\PdfBenchmark; use Athletic\AthleticEvent; use Bacon\Pdf\Writer\ObjectWriter; use SplFileObject; class ObjectWriterEvent extends AthleticEvent { /** * @var ObjectWriter */ private $objectWriter; /** * {@inheritdoc} */ public function setUp() { $this->objectWriter = new ObjectWriter(new SplFileObject('php://memory', 'w+')); } /** * @iterations 10000 */ public function writeRawLine() { $this->objectWriter->writeRawLine('foo'); } /** * @iterations 10000 */ public function startDictionary() { $this->objectWriter->startDictionary(); } /** * @iterations 10000 */ public function endDictionary() { $this->objectWriter->endDictionary(); } /** * @iterations 10000 */ public function startArray() { $this->objectWriter->startArray(); } /** * @iterations 10000 */ public function endArray() { $this->objectWriter->endArray(); } /** * @iterations 10000 */ public function writeNull() { $this->objectWriter->writeNull(); } /** * @iterations 10000 */ public function writeBoolean() { $this->objectWriter->writeBoolean(true); } /** * @iterations 10000 */ public function writeIntegerNumber() { $this->objectWriter->writeNumber(1); } /** * @iterations 10000 */ public function writeFloatNumber() { $this->objectWriter->writeNumber(1.1); } /** * @iterations 10000 */ public function writeName() { $this->objectWriter->writeName('foo'); } /** * @iterations 10000 */ public function writeLiteralString() { $this->objectWriter->writeLiteralString('foo'); } /** * @iterations 10000 */ public function writeHexadecimalString() { $this->objectWriter->writeHexadecimalString('foo'); } }
php
BSD-2-Clause
5f2e6b4eea079d5311111b80a53f6e5d3d3d4630
2026-01-05T04:48:03.848172Z
false
Bacon/BaconPdf
https://github.com/Bacon/BaconPdf/blob/5f2e6b4eea079d5311111b80a53f6e5d3d3d4630/src/Page.php
src/Page.php
<?php /** * BaconPdf * * @link http://github.com/Bacon/BaconPdf For the canonical source repository * @copyright 2015 Ben Scholzen (DASPRiD) * @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License */ namespace Bacon\Pdf; use Bacon\Pdf\Writer\PageWriter; final class Page { /** * @var PageWriter */ private $pageWriter; /** * @param PageWriter $pageWriter * @param float $width * @param float $height */ public function __construct(PageWriter $pageWriter, $width, $height) { $this->pageWriter = $pageWriter; $this->pageWriter->setBox('MediaBox', new Rectangle(0, 0, $width, $height)); } /** * Sets the crop box to which the page should be cropped to for displaying or printing. * * @param Rectangle $cropBox */ public function setCropBox(Rectangle $cropBox) { $this->pageWriter->setBox('CropBox', $cropBox); } /** * Sets the bleed box to which the page should be clipped in a production environment. * * @param Rectangle $bleedBox */ public function setBleedBox(Rectangle $bleedBox) { $this->pageWriter->setBox('BleedBox', $bleedBox); } /** * Sets the trim box to which the finished page should be trimmed. * * @param Rectangle $trimBox */ public function setTrimBox(Rectangle $trimBox) { $this->pageWriter->setBox('TrimBox', $trimBox); } /** * Sets the art box which contains the meaningful content of the page. * * @param Rectangle $artBox */ public function setArtBox(Rectangle $artBox) { $this->pageWriter->setBox('ArtBox', $artBox); } /** * Rotates the page for output. * * The supplied value must be a multiple of 90, so either 0, 90, 180 oder 270. * * @param int $degrees */ public function rotate($degrees) { $this->pageWriter->setRotation($degrees); } }
php
BSD-2-Clause
5f2e6b4eea079d5311111b80a53f6e5d3d3d4630
2026-01-05T04:48:03.848172Z
false
Bacon/BaconPdf
https://github.com/Bacon/BaconPdf/blob/5f2e6b4eea079d5311111b80a53f6e5d3d3d4630/src/Rectangle.php
src/Rectangle.php
<?php /** * BaconPdf * * @link http://github.com/Bacon/BaconPdf For the canonical source repository * @copyright 2015 Ben Scholzen (DASPRiD) * @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License */ namespace Bacon\Pdf; use Bacon\Pdf\Writer\ObjectWriter; /** * Rectangle data structure as defiend in section 3.8.4. */ final class Rectangle { /** * @var float */ private $x1; /** * @var float */ private $y1; /** * @var float */ private $x2; /** * @var float */ private $y2; /** * Creates a new rectangle. * * It doesn't matter in which way you specify the corners, as they will internally be normalized. * * @param float $x1 * @param float $y1 * @param float $x2 * @param float $y2 */ public function __construct($x1, $y1, $x2, $y2) { $this->x1 = min($x1, $x2); $this->y1 = min($y1, $y2); $this->x2 = max($x1, $x2); $this->y2 = max($y1, $y2); } /** * Writes the rectangle object to a writer. * * @param ObjectWriter $objectWriter * @internal */ public function writeRectangleArray(ObjectWriter $objectWriter) { $objectWriter->startArray(); $objectWriter->writeNumber($this->x1); $objectWriter->writeNumber($this->y1); $objectWriter->writeNumber($this->x2); $objectWriter->writeNumber($this->y2); $objectWriter->endArray(); } }
php
BSD-2-Clause
5f2e6b4eea079d5311111b80a53f6e5d3d3d4630
2026-01-05T04:48:03.848172Z
false
Bacon/BaconPdf
https://github.com/Bacon/BaconPdf/blob/5f2e6b4eea079d5311111b80a53f6e5d3d3d4630/src/DocumentInformation.php
src/DocumentInformation.php
<?php /** * BaconPdf * * @link http://github.com/Bacon/BaconPdf For the canonical source repository * @copyright 2015 Ben Scholzen (DASPRiD) * @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License */ namespace Bacon\Pdf; use Bacon\Pdf\Exception\DomainException; use Bacon\Pdf\Utils\StringUtils; use Bacon\Pdf\Writer\ObjectWriter; use DateTimeImmutable; use OutOfBoundsException; final class DocumentInformation { /** * @var array */ private $data = ['Producer' => 'BaconPdf']; /** * Sets an entry in the information dictionary. * * The CreationData and ModDate values are restricted for internal use, so trying to set them will trigger an * exception. Setting the "Trapped" value is allowed, but it must be one of the values "True", "False" or "Unknown". * You can set any key in here, but the following are the standard keys recognized by the PDF standard. Keep in mind * that the keys are case-sensitive: * * Title, Author, Subject, Keywords, Creator, Producer and Trapped. * * @param string $key * @param string $value * @throws DomainException */ public function set($key, $value) { if ('CreationDate' === $key || 'ModDate' === $key) { throw new DomainException('CreationDate and ModDate must not be set manually'); } if ('Trapped' === $key) { if (!in_array($value, ['True', 'False', 'Unknown'])) { throw new DomainException('Value for "Trapped" must be either "True", "False" or "Unknown"'); } $this->data['Trapped'] = $value; return; } $this->data[$key] = $value; } /** * Removes an entry from the information dictionary. * * @param string $key */ public function remove($key) { unset($this->data[$key]); } /** * Checks whether an entry exists in the information dictionary. * * @param string $key * @return bool */ public function has($key) { return array_key_exists($key, $this->data); } /** * Retrieves the value for a specific entry in the information dictionary. * * You may retrieve any entry from the information dictionary through this method, except for "CreationData" and * "ModDate". Those two entries have their own respective methods to be retrieved. * * @param string $key * @return string * @throws DomainException * @throws OutOfBoundsException */ public function get($key) { if ('CreationDate' === $key || 'ModDate' === $key) { throw new DomainException('CreationDate and ModDate must be retrieved through their respective methods'); } if (!array_key_exists($key, $this->data)) { throw new OutOfBoundsException(sprintf('Entry for key "%s" not found', $key)); } return $this->data[$key]; } /** * @return DateTimeImmutable */ public function getCreationDate() { return $this->retrieveDate('CreationDate'); } /** * @return DateTimeImmutable */ public function getModificationDate() { return $this->retrieveDate('ModDate'); } /** * Writes the info dictionary. * * @param ObjectWriter $objectWriter * @internal */ public function writeInfoDictionary(ObjectWriter $objectWriter) { $objectWriter->startDictionary(); foreach ($this->data as $key => $value) { $objectWriter->writeName($key); switch ($key) { case 'CreationDate': case 'ModDate': $objectWriter->writeLiteralString(StringUtils::formatDateTime($value)); break; case 'Trapped': $objectWriter->writeName($value); break; default: $objectWriter->writeLiteralString(StringUtils::encodeString($value)); } } $objectWriter->endDictionary(); } /** * @param string $key * @return DateTimeImmutable * @throws OutOfBoundsException */ private function retrieveDate($key) { if (!array_key_exists($key, $this->data)) { throw new OutOfBoundsException(sprintf('Entry for key "%s" not found', $key)); } return $this->data[$key]; } }
php
BSD-2-Clause
5f2e6b4eea079d5311111b80a53f6e5d3d3d4630
2026-01-05T04:48:03.848172Z
false
Bacon/BaconPdf
https://github.com/Bacon/BaconPdf/blob/5f2e6b4eea079d5311111b80a53f6e5d3d3d4630/src/RasterImage.php
src/RasterImage.php
<?php /** * BaconPdf * * @link http://github.com/Bacon/BaconPdf For the canonical source repository * @copyright 2015 Ben Scholzen (DASPRiD) * @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License */ namespace Bacon\Pdf; use Bacon\Pdf\Exception\DomainException; use Bacon\Pdf\Writer\ObjectWriter; use Imagick; use Symfony\Component\Yaml\Exception\RuntimeException; final class RasterImage { /** * @var int */ private $id; /** * @var int */ private $width; /** * @var int */ private $height; /** * @param ObjectWriter $objectWriter * @param string $filename * @param string $pdfVersion * @param bool $useLossyCompression * @param int $compressionQuality * @throws DomainException * @throws RuntimeException */ public function __construct( ObjectWriter $objectWriter, $filename, $pdfVersion, $useLossyCompression, $compressionQuality ) { if ($compressionQuality < 0 || $compressionQuality > 100) { throw new DomainException('Compression quality must be a value between 0 and 100'); } $image = new Imagick($filename); $image->stripImage(); $this->width = $image->getImageWidth(); $this->height = $image->getImageHeight(); $filter = $this->determineFilter($useLossyCompression, $pdfVersion); $colorSpace = $this->determineColorSpace($image); $this->setFitlerParameters($image, $filter, $colorSpace, $compressionQuality); $shadowMaskInData = null; $shadowMaskId = null; if (Imagick::ALPHACHANNEL_UNDEFINED !== $image->getImageAlphaChannel()) { if (version_compare($pdfVersion, '1.4', '>=')) { throw new RuntimeException('Transparent images require PDF version 1.4 or higher'); } if ($filter === 'JPXDecode') { $shadowMaskInData = 1; } else { $shadowMaskId = $this->createShadowMask($objectWriter, $image, $filter); } } $streamData = $image->getImageBlob(); $image->clear(); $this->id = $objectWriter->startObject(); $objectWriter->startDictionary(); $this->writeCommonDictionaryEntries($objectWriter, $colorSpace, strlen($streamData), $filter); if (null !== $shadowMaskInData) { $objectWriter->writeName('SMaskInData'); $objectWriter->writeNumber($shadowMaskInData); } elseif (null !== $shadowMaskId) { $objectWriter->writeName('SMask'); $objectWriter->writeIndirectReference($shadowMaskId); } $objectWriter->startStream(); $objectWriter->writeRaw($streamData); $objectWriter->endStream(); $objectWriter->endObject(); } /** * Returns the object number of the imported image. * * @return int */ public function getId() { return $this->id; } /** * Returns the width of the image in pixels. * * @return int */ public function getWidth() { return $this->width; } /** * Returns the height of the image in pixels. * * @return int */ public function getHeight() { return $this->height; } /** * @param bool $useLossyCompression * @param string $pdfVersion * @return string */ private function determineFilter($useLossyCompression, $pdfVersion) { if (!$useLossyCompression) { return 'FlateDecode'; } if (version_compare($pdfVersion, '1.5', '>=')) { return 'JPXDecode'; } return 'DCTDecode'; } /** * Determines the color space of an image. * * @param Imagick $image * @return string * @throws DomainException */ private function determineColorSpace(Imagick $image) { switch ($image->getColorSpace()) { case Imagick::COLORSPACE_GRAY: return 'DeviceGray'; case Imagick::COLORSPACE_RGB: return 'DeviceRGB'; case Imagick::COLORSPACE_CMYK: return 'DeviceCMYK'; } throw new DomainException('Image has an unsupported colorspace, must be gray, RGB or CMYK'); } /** * Creates a shadow mask from an image's alpha channel. * * @param ObjectWriter $objectWriter * @param Imagick $image * @param string $filter * @return int */ private function createShadowMask(ObjectWriter $objectWriter, Imagick $image, $filter) { $shadowMask = clone $image; $shadowMask->separateImageChannel(Imagick::CHANNEL_ALPHA); if ('FlateDecode' === $filter) { $image->setImageFormat('GRAY'); } $streamData = $shadowMask->getImageBlob(); $shadowMask->clear(); $id = $objectWriter->startObject(); $objectWriter->startDictionary(); $this->writeCommonDictionaryEntries($objectWriter, 'DeviceGray', strlen($streamData), $filter); $objectWriter->endDictionary(); $objectWriter->startStream(); $objectWriter->writeRaw($streamData); $objectWriter->endStream(); $objectWriter->endObject(); return $id; } /** * Writes common dictionary entries shared between actual images and their soft masks. * * @param ObjectWriter $objectWriter * @param string $colorSpace * @param int $length * @param string $filter * @param int|null $shadowMaskId */ private function writeCommonDictionaryEntries(ObjectWriter $objectWriter, $colorSpace, $length, $filter) { $objectWriter->writeName('Type'); $objectWriter->writeName('XObject'); $objectWriter->writeName('Subtype'); $objectWriter->writeName('Image'); $objectWriter->writeName('Width'); $objectWriter->writeNumber($this->width); $objectWriter->writeName('Height'); $objectWriter->writeNumber($this->height); $objectWriter->writeName('ColorSpace'); $objectWriter->writeName($colorSpace); $objectWriter->writeName('BitsPerComponent'); $objectWriter->writeNumber(8); $objectWriter->writeName('Length'); $objectWriter->writeNumber($length); $objectWriter->writeName('Filter'); $objectWriter->writeName($filter); } /** * Sets the filter parameters for the image. * * @param Imagick $image * @param string $filter * @param string $colorSpace * @param int $compressionQuality */ private function setFitlerParameters(Imagick $image, $filter, $colorSpace, $compressionQuality) { switch ($filter) { case 'JPXDecode': $image->setImageFormat('J2K'); $image->setImageCompression(Imagick::COMPRESSION_JPEG2000); break; case 'DCTDecode': $image->setImageFormat('JPEG'); $image->setImageCompression(Imagick::COMPRESSION_JPEG); break; case 'FlateDecode': $image->setImageFormat([ 'DeviceGray' => 'GRAY', 'DeviceRGB' => 'RGB', 'DeviceCMYK' => 'CMYK', ][$colorSpace]); $image->setImageCompression(Imagick::COMPRESSION_ZIP); break; } $image->setImageCompressionQuality($compressionQuality); } }
php
BSD-2-Clause
5f2e6b4eea079d5311111b80a53f6e5d3d3d4630
2026-01-05T04:48:03.848172Z
false
Bacon/BaconPdf
https://github.com/Bacon/BaconPdf/blob/5f2e6b4eea079d5311111b80a53f6e5d3d3d4630/src/PdfWriter.php
src/PdfWriter.php
<?php /** * BaconPdf * * @link http://github.com/Bacon/BaconPdf For the canonical source repository * @copyright 2015 Ben Scholzen (DASPRiD) * @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License */ namespace Bacon\Pdf; use Bacon\Pdf\Encryption\EncryptionInterface; use Bacon\Pdf\Options\PdfWriterOptions; use Bacon\Pdf\Writer\DocumentWriter; use Bacon\Pdf\Writer\ObjectWriter; use Bacon\Pdf\Writer\PageWriter; use SplFileObject; class PdfWriter { /** * @var PdfWriterOptions */ private $options; /** * @var ObjectWriter */ private $objectWriter; /** * @var DocumentWriter */ private $documentWriter; /** * @var EncryptionInterface */ private $encryption; /** * @param SplFileObject $fileObject * @param PdfWriterOptions $options */ public function __construct(SplFileObject $fileObject, PdfWriterOptions $options = null) { if (null === $options) { $options = new PdfWriterOptions(); } $this->options = $options; $fileIdentifier = md5(microtime(), true); $this->objectWriter = new ObjectWriter($fileObject); $this->documentWriter = new DocumentWriter($this->objectWriter, $options, $fileIdentifier); $this->encryption = $options->getEncryption($fileIdentifier); } /** * Returns the document information object. * * @return DocumentInformation */ public function getDocumentInformation() { return $this->documentWriter->getDocumentInformation(); } /** * Adds a page to the document. * * @param float $width * @param float $height * @return Page */ public function addPage($width, $height) { $pageWriter = new PageWriter($this->objectWriter); $this->documentWriter->addPageWriter($pageWriter); return new Page($pageWriter, $width, $height); } /** * Imports a raster image into the document. * * @param strings $filename * @param bool $useLossyCompression * @param int $compressionQuality * @return Image */ public function importRasterImage($filename, $useLossyCompression = false, $compressionQuality = 80) { return new RasterImage( $this->objectWriter, $filename, $this->options->getPdfVersion(), $useLossyCompression, $compressionQuality ); } /** * Ends the document by writing all pending data. * * While the PDF writer will remove all references to the passed in file object in itself to avoid further writing * and to allow the file pointer to be closed, the callee may still have a reference to it. If that is the case, * make sure to unset it if you don't need it. * * Any further attempts to append data to the PDF writer will result in an exception. */ public function endDocument() { $this->documentWriter->endDocument($this->encryption); } /** * Creates a PDF writer which writes everything to a file. * * @param string $filename * @param PdfWriterOptions|null $options * @return static */ public static function toFile($filename, PdfWriterOptions $options = null) { return new static(new SplFileObject($filename, 'wb'), $options); } /** * Creates a PDF writer which outputs everything to the STDOUT. * * Make sure to send the appropriate headers beforehand if you are in a web environment. * * @param PdfWriterOptions|null $options * @return static */ public static function output(PdfWriterOptions $options = null) { return new static(new SplFileObject('php://stdout', 'wb'), $options); } }
php
BSD-2-Clause
5f2e6b4eea079d5311111b80a53f6e5d3d3d4630
2026-01-05T04:48:03.848172Z
false
Bacon/BaconPdf
https://github.com/Bacon/BaconPdf/blob/5f2e6b4eea079d5311111b80a53f6e5d3d3d4630/src/Options/RasterImageOptions.php
src/Options/RasterImageOptions.php
<?php /** * BaconPdf * * @link http://github.com/Bacon/BaconPdf For the canonical source repository * @copyright 2015 Ben Scholzen (DASPRiD) * @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License */ namespace Bacon\Pdf\Options; final class RasterImageOptions { /** * @var bool */ private $useLossyCompression; /** * @var int */ private $lossyCompressionQuality; private function __construct($useLossyCompression = false, $lossyCompressionQuality = 100) { $this->useLossyCompression = $useLossyCompression; $this->lossyCompressionQuality = $lossyCompressionQuality; } public function useLossyCompression() { return $this->useLossyCompression; } public function getLossyCompressionQuality() { return $this->lossyCompressionQuality; } }
php
BSD-2-Clause
5f2e6b4eea079d5311111b80a53f6e5d3d3d4630
2026-01-05T04:48:03.848172Z
false
Bacon/BaconPdf
https://github.com/Bacon/BaconPdf/blob/5f2e6b4eea079d5311111b80a53f6e5d3d3d4630/src/Options/PdfWriterOptions.php
src/Options/PdfWriterOptions.php
<?php /** * BaconPdf * * @link http://github.com/Bacon/BaconPdf For the canonical source repository * @copyright 2015 Ben Scholzen (DASPRiD) * @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License */ namespace Bacon\Pdf\Options; use Bacon\Pdf\Encryption\AbstractEncryption; use Bacon\Pdf\Encryption\EncryptionInterface; use Bacon\Pdf\Encryption\NullEncryption; use Bacon\Pdf\Exception\DomainException; final class PdfWriterOptions { /** * @var string */ private $pdfVersion; /** * @var EncryptionOptions|null */ private $encryptionOptions; /** * @param string $pdfVersion * @throws DomainException */ public function __construct($pdfVersion = '1.7') { if (!in_array($pdfVersion, ['1.3', '1.4', '1.5', '1.6', '1.7'])) { throw new DomainException('PDF version is not in the supported range (1.3 - 1.7)'); } $this->pdfVersion = $pdfVersion; } /** * Returns the PDF version to use for the document. * * @return string */ public function getPdfVersion() { return $this->pdfVersion; } /** * Sets encryption options. * * @param EncryptionOptions $encryptionOptions */ public function setEncryptionOptions(EncryptionOptions $encryptionOptions) { $this->encryptionOptions = $encryptionOptions; } /** * @param string $permanentFileIdentifier * @return EncryptionInterface */ public function getEncryption($permanentFileIdentifier) { if (null === $this->encryptionOptions) { return new NullEncryption(); } return AbstractEncryption::forPdfVersion($this->pdfVersion, $permanentFileIdentifier, $this->encryptionOptions); } }
php
BSD-2-Clause
5f2e6b4eea079d5311111b80a53f6e5d3d3d4630
2026-01-05T04:48:03.848172Z
false
Bacon/BaconPdf
https://github.com/Bacon/BaconPdf/blob/5f2e6b4eea079d5311111b80a53f6e5d3d3d4630/src/Options/EncryptionOptions.php
src/Options/EncryptionOptions.php
<?php /** * BaconPdf * * @link http://github.com/Bacon/BaconPdf For the canonical source repository * @copyright 2015 Ben Scholzen (DASPRiD) * @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License */ namespace Bacon\Pdf\Options; use Bacon\Pdf\Encryption\Permissions; final class EncryptionOptions { /** * @var string */ private $userPassword; /** * @var string */ private $ownerPassword; /** * @var Permissions */ private $userPermissions; /** * @param string $userPassword * @param string|null $ownerPassword * @param Permissions|null $userPermissions */ public function __construct($userPassword, $ownerPassword = null, Permissions $userPermissions = null) { $this->userPassword = $userPassword; $this->ownerPassword = (null !== $ownerPassword ? $ownerPassword : $userPassword); $this->userPermissions = (null !== $userPermissions ? $userPermissions : Permissions::allowEverything()); } /** * @return string */ public function getUserPassword() { return $this->userPassword; } /** * @return string */ public function getOwnerPassword() { return $this->ownerPassword; } /** * @return Permissions */ public function getUserPermissions() { return $this->userPermissions; } }
php
BSD-2-Clause
5f2e6b4eea079d5311111b80a53f6e5d3d3d4630
2026-01-05T04:48:03.848172Z
false
Bacon/BaconPdf
https://github.com/Bacon/BaconPdf/blob/5f2e6b4eea079d5311111b80a53f6e5d3d3d4630/src/Utils/StringUtils.php
src/Utils/StringUtils.php
<?php /** * BaconPdf * * @link http://github.com/Bacon/BaconPdf For the canonical source repository * @copyright 2015 Ben Scholzen (DASPRiD) * @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License */ namespace Bacon\Pdf\Utils; use DateTimeInterface; final class StringUtils { public function __construct() { } /** * Encodes a string according to section 3.8.1. * * @param string $string * @return string */ public static function encodeString($string) { return "\xfe\xff" . iconv('UTF-8', 'UTF-16BE', $string); } /** * Formats a date according to section 3.8.3. * * @param DateTimeInterface $dateTime * @return string */ public static function formatDateTime(DateTimeInterface $dateTime) { $timeString = $dateTime->format('\D\:YmdHis'); if (0 === $dateTime->getTimezone()->getOffset()) { return $timeString . 'Z'; } return $timeString . strtr(':', "'", $dateTime->format('P')) . "'"; } }
php
BSD-2-Clause
5f2e6b4eea079d5311111b80a53f6e5d3d3d4630
2026-01-05T04:48:03.848172Z
false
Bacon/BaconPdf
https://github.com/Bacon/BaconPdf/blob/5f2e6b4eea079d5311111b80a53f6e5d3d3d4630/src/Encryption/Pdf11Encryption.php
src/Encryption/Pdf11Encryption.php
<?php /** * BaconPdf * * @link http://github.com/Bacon/BaconPdf For the canonical source repository * @copyright 2015 Ben Scholzen (DASPRiD) * @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License */ namespace Bacon\Pdf\Encryption; /** * Encryption for handling PDF version 1.1 and above. */ class Pdf11Encryption extends AbstractEncryption { /** * {@inheritdoc} */ public function encrypt($plaintext, $objectNumber, $generationNumber) { return openssl_encrypt( $plaintext, 'rc4', $this->computeIndividualEncryptionKey($objectNumber, $generationNumber), true ); } /** * {@inheritdoc} */ protected function getRevision() { return 2; } /** * {@inheritdoc} */ protected function getAlgorithm() { return 1; } /** * {@inheritdoc} */ protected function getKeyLength() { return 40; } }
php
BSD-2-Clause
5f2e6b4eea079d5311111b80a53f6e5d3d3d4630
2026-01-05T04:48:03.848172Z
false
Bacon/BaconPdf
https://github.com/Bacon/BaconPdf/blob/5f2e6b4eea079d5311111b80a53f6e5d3d3d4630/src/Encryption/NullEncryption.php
src/Encryption/NullEncryption.php
<?php /** * BaconPdf * * @link http://github.com/Bacon/BaconPdf For the canonical source repository * @copyright 2015 Ben Scholzen (DASPRiD) * @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License */ namespace Bacon\Pdf\Encryption; use Bacon\Pdf\Writer\ObjectWriter; /** * Null encryption which will just return plaintext. */ final class NullEncryption implements EncryptionInterface { /** * {@inheritdoc} */ public function encrypt($plaintext, $objectNumber, $generationNumber) { return $plaintext; } /** * {@inheritdoc} */ public function writeEncryptEntry(ObjectWriter $objectWriter) { } }
php
BSD-2-Clause
5f2e6b4eea079d5311111b80a53f6e5d3d3d4630
2026-01-05T04:48:03.848172Z
false
Bacon/BaconPdf
https://github.com/Bacon/BaconPdf/blob/5f2e6b4eea079d5311111b80a53f6e5d3d3d4630/src/Encryption/Permissions.php
src/Encryption/Permissions.php
<?php /** * BaconPdf * * @link http://github.com/Bacon/BaconPdf For the canonical source repository * @copyright 2015 Ben Scholzen (DASPRiD) * @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License */ namespace Bacon\Pdf\Encryption; /** * Permissions as defined in table 3.20 in section 3.5. */ final class Permissions { /** * @var bool */ private $mayPrint; /** * @var bool */ private $mayPrintHighResolution; /** * @var bool */ private $mayModify; /** * @var bool */ private $mayCopy; /** * @var bool */ private $mayAnnotate; /** * @var bool */ private $mayFillInForms; /** * @var bool */ private $mayExtractForAccessibility; /** * @var bool */ private $mayAssemble; /** * @param bool $mayPrint * @param bool $mayPrintHighResolution * @param bool $mayModify * @param bool $mayCopy * @param bool $mayAnnotate * @param bool $mayFillInForms * @param bool $mayExtractForAccessibility * @param bool $mayAssemble */ public function __construct( $mayPrint, $mayPrintHighResolution, $mayModify, $mayCopy, $mayAnnotate, $mayFillInForms, $mayExtractForAccessibility, $mayAssemble ) { $this->mayPrint = $mayPrint; $this->mayPrintHighResolution = $mayPrintHighResolution; $this->mayModify = $mayModify; $this->mayCopy = $mayCopy; $this->mayAnnotate = $mayAnnotate; $this->mayFillInForms = $mayFillInForms; $this->mayExtractForAccessibility = $mayExtractForAccessibility; $this->mayAssemble = $mayAssemble; } /** * Creates permissions which allow nothing. * * @return self */ public static function allowNothing() { return new self(false, false, false, false, false, false, false, false); } /** * Creates permissions which allow everything. * * @return self */ public static function allowEverything() { return new self(true, true, true, true, true, true, true, true); } /** * Convert the permissions to am integer bit mask. * * {@internal Keep in mind that the bit positions named in the PDF reference are counted from 1, while in here they * are counted from 0.}} * * @param int $revision * @return int */ public function toInt($revision) { $bitMask = new BitMask(); $bitMask->set(2, $this->mayPrint); $bitMask->set(3, $this->mayModify); $bitMask->set(4, $this->mayCopy); $bitMask->set(5, $this->mayAnnotate); if ($revision >= 3) { $bitMask->set(8, $this->mayFillInForms); $bitMask->set(9, $this->mayExtractForAccessibility); $bitMask->set(10, $this->mayAssemble); $bitMask->set(11, $this->mayPrintHighResolution); } return $bitMask->toInt(); } }
php
BSD-2-Clause
5f2e6b4eea079d5311111b80a53f6e5d3d3d4630
2026-01-05T04:48:03.848172Z
false
Bacon/BaconPdf
https://github.com/Bacon/BaconPdf/blob/5f2e6b4eea079d5311111b80a53f6e5d3d3d4630/src/Encryption/EncryptionInterface.php
src/Encryption/EncryptionInterface.php
<?php /** * BaconPdf * * @link http://github.com/Bacon/BaconPdf For the canonical source repository * @copyright 2015 Ben Scholzen (DASPRiD) * @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License */ namespace Bacon\Pdf\Encryption; use Bacon\Pdf\Writer\ObjectWriter; interface EncryptionInterface { /** * Encrypts a string. * * @param string $plaintext * @param int $objectNumber * @param int $generationNumber * @return string */ public function encrypt($plaintext, $objectNumber, $generationNumber); /** * Writes the encrypt dictionary prefixed by the "/Encrypt" name. * * @param ObjectWriter $objectWriter */ public function writeEncryptEntry(ObjectWriter $objectWriter); }
php
BSD-2-Clause
5f2e6b4eea079d5311111b80a53f6e5d3d3d4630
2026-01-05T04:48:03.848172Z
false
Bacon/BaconPdf
https://github.com/Bacon/BaconPdf/blob/5f2e6b4eea079d5311111b80a53f6e5d3d3d4630/src/Encryption/AbstractEncryption.php
src/Encryption/AbstractEncryption.php
<?php /** * BaconPdf * * @link http://github.com/Bacon/BaconPdf For the canonical source repository * @copyright 2015 Ben Scholzen (DASPRiD) * @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License */ namespace Bacon\Pdf\Encryption; use Bacon\Pdf\Exception\RuntimeException; use Bacon\Pdf\Exception\UnexpectedValueException; use Bacon\Pdf\Exception\UnsupportedPasswordException; use Bacon\Pdf\Options\EncryptionOptions; use Bacon\Pdf\Writer\ObjectWriter; abstract class AbstractEncryption implements EncryptionInterface { // @codingStandardsIgnoreStart const ENCRYPTION_PADDING = "\x28\xbf\x4e\x5e\x4e\x75\x8a\x41\x64\x00\x4e\x56\xff\xfa\x01\x08\x2e\x2e\x00\xb6\xd0\x68\x3e\x80\x2f\x0c\xa9\xfe\x64\x53\x69\x7a"; // @codingStandardsIgnoreEnd /** * @var string */ private $encryptionKey; /** * @var string */ private $userEntry; /** * @var string */ private $ownerEntry; /** * @var Permissions */ private $userPermissions; /** * @param string $permanentFileIdentifier * @param string $userPassword * @param string $ownerPassword * @param Permissions $userPermissions * @throws UnexpectedValueException */ public function __construct( $permanentFileIdentifier, $userPassword, $ownerPassword, Permissions $userPermissions ) { // @codeCoverageIgnoreStart if (!extension_loaded('openssl')) { throw new RuntimeException('The OpenSSL extension is required for encryption'); } // @codeCoverageIgnoreEnd $encodedUserPassword = $this->encodePassword($userPassword); $encodedOwnerPassword = $this->encodePassword($ownerPassword); $revision = $this->getRevision(); $keyLength = $this->getKeyLength() / 8; if (!in_array($keyLength, [40 / 8, 128 / 8])) { throw new UnexpectedValueException('Key length must be either 40 or 128'); } $this->ownerEntry = $this->computeOwnerEntry( $encodedOwnerPassword, $encodedUserPassword, $revision, $keyLength ); if (2 === $revision) { list($this->userEntry, $this->encryptionKey) = $this->computeUserEntryRev2( $encodedUserPassword, $this->ownerEntry, $revision, $permanentFileIdentifier ); } else { list($this->userEntry, $this->encryptionKey) = $this->computeUserEntryRev3OrGreater( $encodedUserPassword, $revision, $keyLength, $this->ownerEntry, $userPermissions->toInt($revision), $permanentFileIdentifier ); } $this->userPermissions = $userPermissions; } /** * Returns an encryption fitting for a specific PDF version. * * @param string $pdfVersion * @param string $permanentFileIdentifier * @param EncryptionOptions $options * @return EncryptionInterface */ public static function forPdfVersion($pdfVersion, $permanentFileIdentifier, EncryptionOptions $options) { if (version_compare($pdfVersion, '1.6', '>=')) { $encryptionClassName = Pdf16Encryption::class; } elseif (version_compare($pdfVersion, '1.4', '>=')) { $encryptionClassName = Pdf14Encryption::class; } else { $encryptionClassName = Pdf11Encryption::class; } return new $encryptionClassName( $permanentFileIdentifier, $options->getUserPassword(), $options->getOwnerPassword(), $options->getUserPermissions() ); } /** * {@inheritdoc} */ public function writeEncryptEntry(ObjectWriter $objectWriter) { $objectWriter->writeName('Encrypt'); $objectWriter->startDictionary(); $objectWriter->writeName('Filter'); $objectWriter->writeName('Standard'); $objectWriter->writeName('V'); $objectWriter->writeNumber($this->getAlgorithm()); $objectWriter->writeName('R'); $objectWriter->writeNumber($this->getRevision()); $objectWriter->writeName('O'); $objectWriter->writeHexadecimalString($this->ownerEntry); $objectWriter->writeName('U'); $objectWriter->writeHexadecimalString($this->userEntry); $objectWriter->writeName('P'); $objectWriter->writeNumber($this->userPermissions->toInt($this->getRevision())); $this->writeAdditionalEncryptDictionaryEntries($objectWriter); $objectWriter->endDictionary(); } /** * Adds additional entries to the encrypt dictionary if required. * * @param ObjectWriter $objectWriter */ protected function writeAdditionalEncryptDictionaryEntries(ObjectWriter $objectWriter) { } /** * Returns the revision number of the encryption. * * @return int */ abstract protected function getRevision(); /** * Returns the algorithm number of the encryption. * * @return int */ abstract protected function getAlgorithm(); /** * Returns the key length to be used. * * The returned value must be either 40 or 128. * * @return int */ abstract protected function getKeyLength(); /** * Computes an individual ecryption key for an object. * * @param string $objectNumber * @param string $generationNumber * @return string */ protected function computeIndividualEncryptionKey($objectNumber, $generationNumber) { return substr(md5( $this->encryptionKey . substr(pack('V', $objectNumber), 0, 3) . substr(pack('V', $generationNumber), 0, 2), true ), 0, min(16, strlen($this->encryptionKey) + 5)); } /** * Encodes a given password into latin-1 and performs length check. * * @param string $password * @return string * @throws UnsupportedPasswordException */ private function encodePassword($password) { set_error_handler(function () { }, E_NOTICE); $encodedPassword = iconv('UTF-8', 'ISO-8859-1', $password); restore_error_handler(); if (false === $encodedPassword) { throw new UnsupportedPasswordException('Password contains non-latin-1 characters'); } if (strlen($encodedPassword) > 32) { throw new UnsupportedPasswordException('Password is longer than 32 characters'); } return $encodedPassword; } /** * Computes the encryption key as defined by algorithm 3.2 in 3.5.2. * * @param string $password * @param int $revision * @param int $keyLength * @param string $ownerEntry * @param int $permissions * @param string $permanentFileIdentifier * @param bool $encryptMetadata * @return string */ private function computeEncryptionKey( $password, $revision, $keyLength, $ownerEntry, $permissions, $permanentFileIdentifier, $encryptMetadata = true ) { $string = substr($password . self::ENCRYPTION_PADDING, 0, 32) . $ownerEntry . pack('V', $permissions) . $permanentFileIdentifier; if ($revision >= 4 && $encryptMetadata) { $string .= "\0xff\0xff\0xff\0xff"; } $hash = md5($string, true); if ($revision >= 3) { for ($i = 0; $i < 50; ++$i) { $hash = md5(substr($hash, 0, $keyLength), true); } return substr($hash, 0, $keyLength); } return substr($hash, 0, 5); } /** * Computes the owner entry as defined by algorithm 3.3 in 3.5.2. * * @param string $ownerPassword * @param string $userPassword * @param int $revision * @param int $keyLength * @return string */ private function computeOwnerEntry($ownerPassword, $userPassword, $revision, $keyLength) { $hash = md5(substr($ownerPassword . self::ENCRYPTION_PADDING, 0, 32), true); if ($revision >= 3) { for ($i = 0; $i < 50; ++$i) { $hash = md5($hash, true); } $key = substr($hash, 0, $keyLength); } else { $key = substr($hash, 0, 5); } $value = openssl_encrypt(substr($userPassword . self::ENCRYPTION_PADDING, 0, 32), 'rc4', $key, true); if ($revision >= 3) { $value = self::applyRc4Loop($value, $key, $keyLength); } return $value; } /** * Computes the user entry (rev 2) as defined by algorithm 3.4 in 3.5.2. * * @param string $userPassword * @param string $ownerEntry * @param int $userPermissionFlags * @param string $permanentFileIdentifier * @return string[] */ private function computeUserEntryRev2($userPassword, $ownerEntry, $userPermissionFlags, $permanentFileIdentifier) { $key = self::computeEncryptionKey( $userPassword, 2, 5, $ownerEntry, $userPermissionFlags, $permanentFileIdentifier ); return [ openssl_encrypt(self::ENCRYPTION_PADDING, 'rc4', $key, true), $key ]; } /** * Computes the user entry (rev 3 or greater) as defined by algorithm 3.5 in 3.5.2. * * @param string $userPassword * @param int $revision * @param int $keyLength * @param string $ownerEntry * @param int $permissions * @param string $permanentFileIdentifier * @return string[] */ private function computeUserEntryRev3OrGreater( $userPassword, $revision, $keyLength, $ownerEntry, $permissions, $permanentFileIdentifier ) { $key = self::computeEncryptionKey( $userPassword, $revision, $keyLength, $ownerEntry, $permissions, $permanentFileIdentifier ); $hash = md5(self::ENCRYPTION_PADDING . $permanentFileIdentifier, true); $value = self::applyRc4Loop(openssl_encrypt($hash, 'rc4', $key, true), $key, $keyLength); $value .= openssl_random_pseudo_bytes(16); return [ $value, $key ]; } /** * Applies loop RC4 encryption. * * @param string $value * @param string $key * @param int $keyLength * @return string */ private function applyRc4Loop($value, $key, $keyLength) { for ($i = 1; $i <= 19; ++$i) { $newKey = ''; for ($j = 0; $j < $keyLength; ++$j) { $newKey .= chr(ord($key[$j]) ^ $i); } $value = openssl_encrypt($value, 'rc4', $newKey, true); } return $value; } }
php
BSD-2-Clause
5f2e6b4eea079d5311111b80a53f6e5d3d3d4630
2026-01-05T04:48:03.848172Z
false
Bacon/BaconPdf
https://github.com/Bacon/BaconPdf/blob/5f2e6b4eea079d5311111b80a53f6e5d3d3d4630/src/Encryption/Pdf16Encryption.php
src/Encryption/Pdf16Encryption.php
<?php /** * BaconPdf * * @link http://github.com/Bacon/BaconPdf For the canonical source repository * @copyright 2015 Ben Scholzen (DASPRiD) * @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License */ namespace Bacon\Pdf\Encryption; use Bacon\Pdf\Writer\ObjectWriter; /** * Encryption for handling PDF version 1.6 and above. */ class Pdf16Encryption extends Pdf14Encryption { /** * {@inheritdoc} */ protected function writeAdditionalEncryptDictionaryEntries(ObjectWriter $objectWriter) { parent::writeAdditionalEncryptDictionaryEntries($objectWriter); $objectWriter->writeName('CF'); $objectWriter->startDictionary(); $objectWriter->writeName('StdCF'); $objectWriter->startDictionary(); $objectWriter->writeName('Type'); $objectWriter->writeName('CryptFilter'); $objectWriter->writeName('CFM'); $objectWriter->writeName('AESV2'); $objectWriter->writeName('Length'); $objectWriter->writeNumber(128); $objectWriter->endDictionary(); $objectWriter->endDictionary(); $objectWriter->writeName('StrF'); $objectWriter->writeName('StdCF'); $objectWriter->writeName('StmF'); $objectWriter->writeName('StdCF'); } /** * {@inheritdoc} */ public function encrypt($plaintext, $objectNumber, $generationNumber) { $initializationVector = openssl_random_pseudo_bytes(16); return $initializationVector . openssl_encrypt( $plaintext, 'aes-128-cbc', $this->computeIndividualEncryptionKey($objectNumber, $generationNumber) . "\x73\x41\x6c\x54", true, $initializationVector ); } /** * {@inheritdoc} */ protected function getRevision() { return 4; } /** * {@inheritdoc} */ protected function getAlgorithm() { return 4; } }
php
BSD-2-Clause
5f2e6b4eea079d5311111b80a53f6e5d3d3d4630
2026-01-05T04:48:03.848172Z
false
Bacon/BaconPdf
https://github.com/Bacon/BaconPdf/blob/5f2e6b4eea079d5311111b80a53f6e5d3d3d4630/src/Encryption/Pdf14Encryption.php
src/Encryption/Pdf14Encryption.php
<?php /** * BaconPdf * * @link http://github.com/Bacon/BaconPdf For the canonical source repository * @copyright 2015 Ben Scholzen (DASPRiD) * @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License */ namespace Bacon\Pdf\Encryption; use Bacon\Pdf\Writer\ObjectWriter; /** * Encryption for handling PDF version 1.4 and above. */ class Pdf14Encryption extends Pdf11Encryption { /** * {@inheritdoc} */ protected function writeAdditionalEncryptDictionaryEntries(ObjectWriter $objectWriter) { parent::writeAdditionalEncryptDictionaryEntries($objectWriter); $objectWriter->writeName('Length'); $objectWriter->writeNumber(128); } /** * {@inheritdoc} */ protected function getRevision() { return 3; } /** * {@inheritdoc} */ protected function getAlgorithm() { return 2; } /** * {@inheritdoc} */ protected function getKeyLength() { return 128; } }
php
BSD-2-Clause
5f2e6b4eea079d5311111b80a53f6e5d3d3d4630
2026-01-05T04:48:03.848172Z
false
Bacon/BaconPdf
https://github.com/Bacon/BaconPdf/blob/5f2e6b4eea079d5311111b80a53f6e5d3d3d4630/src/Encryption/BitMask.php
src/Encryption/BitMask.php
<?php /** * BaconPdf * * @link http://github.com/Bacon/BaconPdf For the canonical source repository * @copyright 2015 Ben Scholzen (DASPRiD) * @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License */ namespace Bacon\Pdf\Encryption; /** * Bit mask for representing permissions. */ final class BitMask { /** * @var int */ private $value = 0; /** * Sets * * @param int $bit * @param bool $value */ public function set($bit, $value) { if ($value) { $this->value |= (1 << $bit); return; } $this->value &= ~(1 << $bit); } /** * @return int */ public function toInt() { return $this->value; } }
php
BSD-2-Clause
5f2e6b4eea079d5311111b80a53f6e5d3d3d4630
2026-01-05T04:48:03.848172Z
false
Bacon/BaconPdf
https://github.com/Bacon/BaconPdf/blob/5f2e6b4eea079d5311111b80a53f6e5d3d3d4630/src/Exception/OutOfBoundsException.php
src/Exception/OutOfBoundsException.php
<?php /** * BaconPdf * * @link http://github.com/Bacon/BaconPdf For the canonical source repository * @copyright 2015 Ben Scholzen (DASPRiD) * @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License */ namespace Bacon\Pdf\Exception; class OutOfBoundsException extends \OutOfBoundsException implements ExceptionInterface { }
php
BSD-2-Clause
5f2e6b4eea079d5311111b80a53f6e5d3d3d4630
2026-01-05T04:48:03.848172Z
false
Bacon/BaconPdf
https://github.com/Bacon/BaconPdf/blob/5f2e6b4eea079d5311111b80a53f6e5d3d3d4630/src/Exception/UnsupportedPasswordException.php
src/Exception/UnsupportedPasswordException.php
<?php /** * BaconPdf * * @link http://github.com/Bacon/BaconPdf For the canonical source repository * @copyright 2015 Ben Scholzen (DASPRiD) * @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License */ namespace Bacon\Pdf\Exception; class UnsupportedPasswordException extends \DomainException implements ExceptionInterface { }
php
BSD-2-Clause
5f2e6b4eea079d5311111b80a53f6e5d3d3d4630
2026-01-05T04:48:03.848172Z
false
Bacon/BaconPdf
https://github.com/Bacon/BaconPdf/blob/5f2e6b4eea079d5311111b80a53f6e5d3d3d4630/src/Exception/OutOfRangeException.php
src/Exception/OutOfRangeException.php
<?php /** * BaconPdf * * @link http://github.com/Bacon/BaconPdf For the canonical source repository * @copyright 2015 Ben Scholzen (DASPRiD) * @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License */ namespace Bacon\Pdf\Exception; class OutOfRangeException extends \OutOfRangeException implements ExceptionInterface { }
php
BSD-2-Clause
5f2e6b4eea079d5311111b80a53f6e5d3d3d4630
2026-01-05T04:48:03.848172Z
false
Bacon/BaconPdf
https://github.com/Bacon/BaconPdf/blob/5f2e6b4eea079d5311111b80a53f6e5d3d3d4630/src/Exception/ExceptionInterface.php
src/Exception/ExceptionInterface.php
<?php /** * BaconPdf * * @link http://github.com/Bacon/BaconPdf For the canonical source repository * @copyright 2015 Ben Scholzen (DASPRiD) * @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License */ namespace Bacon\Pdf\Exception; interface ExceptionInterface { }
php
BSD-2-Clause
5f2e6b4eea079d5311111b80a53f6e5d3d3d4630
2026-01-05T04:48:03.848172Z
false
Bacon/BaconPdf
https://github.com/Bacon/BaconPdf/blob/5f2e6b4eea079d5311111b80a53f6e5d3d3d4630/src/Exception/RuntimeException.php
src/Exception/RuntimeException.php
<?php /** * BaconPdf * * @link http://github.com/Bacon/BaconPdf For the canonical source repository * @copyright 2015 Ben Scholzen (DASPRiD) * @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License */ namespace Bacon\Pdf\Exception; class RuntimeException extends \RuntimeException implements ExceptionInterface { }
php
BSD-2-Clause
5f2e6b4eea079d5311111b80a53f6e5d3d3d4630
2026-01-05T04:48:03.848172Z
false
Bacon/BaconPdf
https://github.com/Bacon/BaconPdf/blob/5f2e6b4eea079d5311111b80a53f6e5d3d3d4630/src/Exception/UnexpectedValueException.php
src/Exception/UnexpectedValueException.php
<?php /** * BaconPdf * * @link http://github.com/Bacon/BaconPdf For the canonical source repository * @copyright 2015 Ben Scholzen (DASPRiD) * @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License */ namespace Bacon\Pdf\Exception; class UnexpectedValueException extends \UnexpectedValueException implements ExceptionInterface { }
php
BSD-2-Clause
5f2e6b4eea079d5311111b80a53f6e5d3d3d4630
2026-01-05T04:48:03.848172Z
false
Bacon/BaconPdf
https://github.com/Bacon/BaconPdf/blob/5f2e6b4eea079d5311111b80a53f6e5d3d3d4630/src/Exception/InvalidArgumentException.php
src/Exception/InvalidArgumentException.php
<?php /** * BaconPdf * * @link http://github.com/Bacon/BaconPdf For the canonical source repository * @copyright 2015 Ben Scholzen (DASPRiD) * @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License */ namespace Bacon\Pdf\Exception; class InvalidArgumentException extends \InvalidArgumentException implements ExceptionInterface { }
php
BSD-2-Clause
5f2e6b4eea079d5311111b80a53f6e5d3d3d4630
2026-01-05T04:48:03.848172Z
false
Bacon/BaconPdf
https://github.com/Bacon/BaconPdf/blob/5f2e6b4eea079d5311111b80a53f6e5d3d3d4630/src/Exception/WriterClosedException.php
src/Exception/WriterClosedException.php
<?php /** * BaconPdf * * @link http://github.com/Bacon/BaconPdf For the canonical source repository * @copyright 2015 Ben Scholzen (DASPRiD) * @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License */ namespace Bacon\Pdf\Exception; class WriterClosedException extends \RuntimeException implements ExceptionInterface { }
php
BSD-2-Clause
5f2e6b4eea079d5311111b80a53f6e5d3d3d4630
2026-01-05T04:48:03.848172Z
false
Bacon/BaconPdf
https://github.com/Bacon/BaconPdf/blob/5f2e6b4eea079d5311111b80a53f6e5d3d3d4630/src/Exception/DomainException.php
src/Exception/DomainException.php
<?php /** * BaconPdf * * @link http://github.com/Bacon/BaconPdf For the canonical source repository * @copyright 2015 Ben Scholzen (DASPRiD) * @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License */ namespace Bacon\Pdf\Exception; class DomainException extends \DomainException implements ExceptionInterface { }
php
BSD-2-Clause
5f2e6b4eea079d5311111b80a53f6e5d3d3d4630
2026-01-05T04:48:03.848172Z
false
Bacon/BaconPdf
https://github.com/Bacon/BaconPdf/blob/5f2e6b4eea079d5311111b80a53f6e5d3d3d4630/src/Writer/PageWriter.php
src/Writer/PageWriter.php
<?php /** * BaconPdf * * @link http://github.com/Bacon/BaconPdf For the canonical source repository * @copyright 2015 Ben Scholzen (DASPRiD) * @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License */ namespace Bacon\Pdf\Writer; use Bacon\Pdf\Rectangle; use DomainException; class PageWriter { /** * @var ObjectWriter */ private $objectWriter; /** * @var int */ private $pageId; /** * @var Rectangle[] */ private $boxes = []; /** * @var int|null */ private $rotation; /** * @var string */ private $contentStream = ''; /** * @param ObjectWriter $objectWriter */ public function __construct(ObjectWriter $objectWriter) { $this->objectWriter = $objectWriter; $this->pageId = $this->objectWriter->allocateObjectId(); } /** * Sets a box for the page. * * @param string $name * @param Rectangle $box */ public function setBox($name, Rectangle $box) { $this->boxes[$name] = $box; } /** * Sets the rotation of the page. * * @param int $degrees * @throws DomainException */ public function setRotation($degrees) { if (!in_array($degrees, [0, 90, 180, 270])) { throw new DomainException('Degrees value must be a multiple of 90'); } $this->rotation = $degrees; } /** * Appends data to the content stream. * * @param string $data */ public function appendContentStream($data) { $this->contentStream .= $data; } /** * Writes the page contents and definition to the writer. * * @param ObjectWriter $objectWriter * @param int $pageTreeId * @return int */ public function writePage(ObjectWriter $objectWriter, $pageTreeId) { $objectWriter->startObject($this->pageId); $objectWriter->startDictionary(); $objectWriter->writeName('Type'); $objectWriter->writeName('Page'); $objectWriter->writeName('Parent'); $objectWriter->writeIndirectReference($pageTreeId); $objectWriter->writeName('Resources'); $objectWriter->startDictionary(); $objectWriter->endDictionary(); $objectWriter->writeName('Contents'); $objectWriter->startArray(); $objectWriter->endArray(); foreach ($this->boxes as $name => $box) { $objectWriter->writeName($name); $box->writeRectangleArray($objectWriter); } if (null !== $this->rotation) { $objectWriter->writeName('Rotate'); $objectWriter->writeNumber($this->rotation); } $objectWriter->endDictionary(); $objectWriter->endObject(); return $this->pageId; } }
php
BSD-2-Clause
5f2e6b4eea079d5311111b80a53f6e5d3d3d4630
2026-01-05T04:48:03.848172Z
false
Bacon/BaconPdf
https://github.com/Bacon/BaconPdf/blob/5f2e6b4eea079d5311111b80a53f6e5d3d3d4630/src/Writer/DocumentWriter.php
src/Writer/DocumentWriter.php
<?php /** * BaconPdf * * @link http://github.com/Bacon/BaconPdf For the canonical source repository * @copyright 2015 Ben Scholzen (DASPRiD) * @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License */ namespace Bacon\Pdf\Writer; use Bacon\Pdf\DocumentInformation; use Bacon\Pdf\Encryption\EncryptionInterface; use Bacon\Pdf\Options\PdfWriterOptions; class DocumentWriter { /** * @var ObjectWriter */ private $objectWriter; /** * @var PdfWriterOptions */ private $options; /** * @var string */ private $permanentFileIdentifier; /** * @var string */ private $changingFileIdentifier; /** * @var int */ private $pageTreeId; /** * @var PageWriter[] */ private $pageWriters = []; /** * @var int[] */ private $pageIds = []; /** * @var DocumentInformation */ private $documentInformation; /** * @param ObjectWriter $objectWriter * @param string $fileIdentifier */ public function __construct(ObjectWriter $objectWriter, PdfWriterOptions $options, $fileIdentifier) { $this->objectWriter = $objectWriter; $this->options = $options; $this->objectWriter->writeRawLine(sprintf("%%PDF-%s", $this->options->getPdfVersion())); $this->objectWriter->writeRawLine("%\xff\xff\xff\xff"); $this->permanentFileIdentifier = $this->changingFileIdentifier = $fileIdentifier; $this->pageTreeId = $this->objectWriter->allocateObjectId(); $this->documentInformation = new DocumentInformation(); } /** * Returns the document information object. * * @return DocumentInformation */ public function getDocumentInformation() { return $this->documentInformation; } /** * Adds a page writer for the page tree. * * @param PageWriter $pageWriter */ public function addPageWriter(PageWriter $pageWriter) { $this->pageWriters[] = $pageWriter; } /** * Ends the document. * * @param EncryptionInterface $encryption */ public function endDocument(EncryptionInterface $encryption) { $this->closeRemainingPages(); $this->writePageTree(); $documentInformationId = $this->writeDocumentInformation(); $documentCatalogId = $this->writeDocumentCatalog(); $xrefOffset = $this->writeCrossReferenceTable(); $this->writeTrailer($documentInformationId, $documentCatalogId, $encryption); $this->writeFooter($xrefOffset); } /** * Closes pages which haven't been explicitly closed yet. */ private function closeRemainingPages() { foreach ($this->pageWriters as $key => $pageWriter) { $this->pageIds[] = $pageWriter->writePage($this->objectWriter, $this->pageTreeId); unset($this->pageWriters[$key]); } } /** * Writes the page tree. */ private function writePageTree() { $this->objectWriter->startObject($this->pageTreeId); $this->objectWriter->startDictionary(); $this->objectWriter->writeName('Type'); $this->objectWriter->writeName('Pages'); $this->objectWriter->writeName('Kids'); $this->objectWriter->startArray(); sort($this->pageIds, SORT_NUMERIC); foreach ($this->pageIds as $pageId) { $this->objectWriter->writeIndirectReference($pageId); } $this->objectWriter->endArray(); $this->objectWriter->writeName('Count'); $this->objectWriter->writeNumber(count($this->pageIds)); $this->objectWriter->endDictionary(); $this->objectWriter->endObject(); } /** * Writes the document information. * * @return int */ private function writeDocumentInformation() { $id = $this->objectWriter->startObject(); $this->documentInformation->writeInfoDictionary($this->objectWriter); $this->objectWriter->endObject(); return $id; } /** * Writes the document catalog. * * @return int */ private function writeDocumentCatalog() { $id = $this->objectWriter->startObject(); $this->objectWriter->startDictionary(); $this->objectWriter->writeName('Type'); $this->objectWriter->writeName('Catalog'); $this->objectWriter->writeName('Pages'); $this->objectWriter->writeIndirectReference($this->pageTreeId); $this->objectWriter->endDictionary(); $this->objectWriter->endObject(); return $id; } /** * Writes the cross-reference table. * * @return int */ private function writeCrossReferenceTable() { $xrefOffset = $this->objectWriter->getCurrentOffset(); $objectOffsets = $this->objectWriter->getObjectOffsets(); ksort($objectOffsets, SORT_NUMERIC); $this->objectWriter->writeRawLine('xref'); $this->objectWriter->writeRawLine(sprintf('0 %d', count($objectOffsets) + 1)); $this->objectWriter->writeRawLine(sprintf('%010d %05d f ', 0, 65535)); foreach ($objectOffsets as $offset) { $this->objectWriter->writeRawLine(sprintf('%010d %05d n ', $offset, 0)); } return $xrefOffset; } /** * Writes the trailer. * * @param int $documentInformationId * @param int $documentCatalogId * @param EncryptionInterface $encryption */ private function writeTrailer($documentInformationId, $documentCatalogId, EncryptionInterface $encryption) { $this->objectWriter->writeRawLine('trailer'); $this->objectWriter->startDictionary(); $this->objectWriter->writeName('Id'); $this->objectWriter->startArray(); $this->objectWriter->writeHexadecimalString($this->permanentFileIdentifier); $this->objectWriter->writeHexadecimalString($this->changingFileIdentifier); $this->objectWriter->endArray(); $this->objectWriter->writeName('Info'); $this->objectWriter->writeIndirectReference($documentInformationId); $this->objectWriter->writeName('Root'); $this->objectWriter->writeIndirectReference($documentCatalogId); $encryption->writeEncryptEntry($this->objectWriter); $this->objectWriter->endDictionary(); } /** * Writes the footer. * * @param int $xrefOffset */ private function writeFooter($xrefOffset) { $this->objectWriter->writeRawLine(''); $this->objectWriter->writeRawLine('startxref'); $this->objectWriter->writeRawLine((string) $xrefOffset); $this->objectWriter->writeRawLine("%%%EOF"); } }
php
BSD-2-Clause
5f2e6b4eea079d5311111b80a53f6e5d3d3d4630
2026-01-05T04:48:03.848172Z
false
Bacon/BaconPdf
https://github.com/Bacon/BaconPdf/blob/5f2e6b4eea079d5311111b80a53f6e5d3d3d4630/src/Writer/ObjectWriter.php
src/Writer/ObjectWriter.php
<?php /** * BaconPdf * * @link http://github.com/Bacon/BaconPdf For the canonical source repository * @copyright 2015 Ben Scholzen (DASPRiD) * @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License */ namespace Bacon\Pdf\Writer; use Bacon\Pdf\Exception\InvalidArgumentException; use SplFileObject; /** * Writer responsible for writing objects to a stream. * * While the PDF specification tells that there is a line limit of 255 characters, not even Adobe's own PDF library * respects this limit. We ignore it as well, as it imposes a huge impact on the performance of the writer. * * {@internal This is a very performance sensitive class, which is why some code may look duplicated. Before thinking * about refactoring these parts, take a good look and the supplied benchmarks and verify that your changes * do not affect the performance in a bad way. Keep in mind that the methods in this writer are called quite * often.}} */ class ObjectWriter { /** * @var SplFileObject */ private $fileObject; /** * @var bool */ private $requiresWhitespace = false; /** * @var int */ private $lastAllocatedObjectId = 0; /** * @var int[] */ private $objectOffsets = []; /** * @param SplFileObject $fileObject */ public function __construct(SplFileObject $fileObject) { $this->fileObject = $fileObject; } /** * Returns the current position in the file. * * @return int */ public function getCurrentOffset() { return $this->fileObject->ftell(); } /** * Writes a raw data line to the stream. * * A newline character is appended after the data. Keep in mind that you may still be after a token which requires * a following whitespace, depending on the context you are in. * * @param string $data */ public function writeRawLine($data) { $this->fileObject->fwrite($data . "\n"); } /** * Writes raw data to the stream. * * @param string $data */ public function writeRaw($data) { $this->fileObject->fwrite($data); } /** * Returns all object offsets. * * @return int */ public function getObjectOffsets() { return $this->objectOffsets; } /** * Allocates a new ID for an object. * * @return int */ public function allocateObjectId() { return ++$this->lastAllocatedObjectId; } /** * Starts an object. * * If the object ID is omitted, a new one is allocated. * * @param int|null $objectId * @return int */ public function startObject($objectId = null) { if (null === $objectId) { $objectId = ++$this->lastAllocatedObjectId; } $this->objectOffsets[$objectId] = $this->fileObject->ftell(); $this->fileObject->fwrite(sprintf("%d 0 obj\n", $objectId)); return $objectId; } /** * Ends an object. */ public function endObject() { $this->fileObject->fwrite("\nendobj\n"); } /** * Starts a stream. */ public function startStream() { $this->fileObject->fwrite("stream\n"); } public function endStream() { $this->fileObject->fwrite("\nendstream\n"); } /** * Writes an indirect reference * * @param int $objectId */ public function writeIndirectReference($objectId) { if ($this->requiresWhitespace) { $this->fileObject->fwrite(sprintf(' %d 0 R', $objectId)); } else { $this->fileObject->fwrite(sprintf('%d 0 R', $objectId)); } $this->requiresWhitespace = true; } /** * Starts a dictionary. */ public function startDictionary() { $this->fileObject->fwrite('<<'); $this->requiresWhitespace = false; } /** * Ends a dictionary. */ public function endDictionary() { $this->fileObject->fwrite('>>'); $this->requiresWhitespace = false; } /** * Starts an array. */ public function startArray() { $this->fileObject->fwrite('['); $this->requiresWhitespace = false; } /** * Ends an array. */ public function endArray() { $this->fileObject->fwrite(']'); $this->requiresWhitespace = false; } /** * Writes a null value. */ public function writeNull() { if ($this->requiresWhitespace) { $this->fileObject->fwrite(' null'); } else { $this->fileObject->fwrite('null'); } $this->requiresWhitespace = true; } /** * Writes a boolean. * * @param bool $boolean */ public function writeBoolean($boolean) { if ($this->requiresWhitespace) { $this->fileObject->fwrite($boolean ? ' true' : ' false'); } else { $this->fileObject->fwrite($boolean ? 'true' : 'false'); } $this->requiresWhitespace = true; } /** * Writes a number. * * @param int|float $number * @throws InvalidArgumentException */ public function writeNumber($number) { if ($this->requiresWhitespace) { $this->fileObject->fwrite(' ' . (rtrim(sprintf('%.6F', $number), '0.') ?: '0')); } else { $this->fileObject->fwrite(rtrim(sprintf('%.6F', $number), '0.') ?: '0'); } $this->requiresWhitespace = true; } /** * Writes a name. * * @param string $name */ public function writeName($name) { $this->fileObject->fwrite('/' . $name); $this->requiresWhitespace = true; } /** * Writes a literal string. * * The string itself is splitted into multiple lines after 248 characters. We chose that specific limit to avoid * splitting mutli-byte characters in half. * * @param string $string */ public function writeLiteralString($string) { $this->fileObject->fwrite('(' . strtr($string, ['(' => '\\(', ')' => '\\)', '\\' => '\\\\']) . ')'); $this->requiresWhitespace = false; } /** * Writes a hexadecimal string. * * @param string $string */ public function writeHexadecimalString($string) { $this->fileObject->fwrite('<' . bin2hex($string) . '>'); $this->requiresWhitespace = false; } }
php
BSD-2-Clause
5f2e6b4eea079d5311111b80a53f6e5d3d3d4630
2026-01-05T04:48:03.848172Z
false
Bacon/BaconPdf
https://github.com/Bacon/BaconPdf/blob/5f2e6b4eea079d5311111b80a53f6e5d3d3d4630/test/Encryption/PermissionsTest.php
test/Encryption/PermissionsTest.php
<?php /** * BaconPdf * * @link http://github.com/Bacon/BaconPdf For the canonical source repository * @copyright 2015 Ben Scholzen (DASPRiD) * @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License */ namespace Bacon\PdfTest\Encryption; use Bacon\Pdf\Encryption\Permissions; use PHPUnit_Framework_TestCase as TestCase; use ReflectionClass; /** * @covers \Bacon\Pdf\Encryption\Permissions */ class PermissionsTest extends TestCase { public function testZeroPermissions() { $permissions = Permissions::allowNothing(); $this->assertSame(0, $permissions->toInt(2)); $this->assertSame(0, $permissions->toInt(3)); } public function testFullPermissions() { $permissions = Permissions::allowEverything(); $this->assertSame(60, $permissions->toInt(2)); $this->assertSame(3900, $permissions->toInt(3)); } /** * @dataProvider individualPermissions */ public function testIndividualPermissions($flagPosition, $rev2Value, $rev3Value) { $args = array_fill(0, 8, false); $args[$flagPosition] = true; $reflectionClass = new ReflectionClass(Permissions::class); $permissions = $reflectionClass->newInstanceArgs($args); $this->assertSame($rev2Value, $permissions->toInt(2)); $this->assertSame($rev3Value, $permissions->toInt(3)); } /** * @return array */ public function individualPermissions() { return [ 'may-print' => [0, 4, 4], 'may-print-high-resolution' => [1, 0, 2048], 'may-modify' => [2, 8, 8], 'may-copy' => [3, 16, 16], 'may-annotate' => [4, 32, 32], 'may-fill-in-forms' => [5, 0, 256], 'may-extract-for-accessibility' => [6, 0, 512], 'may-assemble' => [7, 0, 1024], ]; } }
php
BSD-2-Clause
5f2e6b4eea079d5311111b80a53f6e5d3d3d4630
2026-01-05T04:48:03.848172Z
false
Bacon/BaconPdf
https://github.com/Bacon/BaconPdf/blob/5f2e6b4eea079d5311111b80a53f6e5d3d3d4630/test/Encryption/Pdf14EncryptionTest.php
test/Encryption/Pdf14EncryptionTest.php
<?php /** * BaconPdf * * @link http://github.com/Bacon/BaconPdf For the canonical source repository * @copyright 2015 Ben Scholzen (DASPRiD) * @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License */ namespace Bacon\PdfTest\Encryption; use Bacon\Pdf\Encryption\Pdf14Encryption; use Bacon\Pdf\Encryption\Permissions; /** * @covers \Bacon\Pdf\Encryption\AbstractEncryption * @covers \Bacon\Pdf\Encryption\Pdf14Encryption */ class Pdf14EncryptionTest extends AbstractEncryptionTestCase { /** * {@inheritdoc} */ public function encryptionTestData() { return [ 'same-numbers' => ['test', 'foo', null, 1, 1], 'changed-generation-number' => ['test', 'foo', null, 1, 2], 'changed-object-number' => ['test', 'foo', null, 2, 1], 'both-numbers-changed' => ['test', 'foo', null, 2, 2], 'changed-user-password' => ['test', 'bar', null, 1, 1], 'added-owner-password' => ['test', 'bar', 'baz', 1, 1], ]; } /** * {@inheritdoc} */ protected function createEncryption( $userPassword, $ownerPassword = null, Permissions $userPermissions = null ) { return new Pdf14Encryption( md5('test', true), $userPassword, $ownerPassword ?: $userPassword, $userPermissions ?: Permissions::allowNothing() ); } /** * {@inheritdoc} */ protected function decrypt($encryptedText, $key) { return openssl_decrypt($encryptedText, 'rc4', $key, OPENSSL_RAW_DATA); } /** * {@inheritdoc} */ protected function getExpectedEntry() { return file_get_contents(__DIR__ . '/_files/pdf14-encrypt-entry.txt'); } }
php
BSD-2-Clause
5f2e6b4eea079d5311111b80a53f6e5d3d3d4630
2026-01-05T04:48:03.848172Z
false
Bacon/BaconPdf
https://github.com/Bacon/BaconPdf/blob/5f2e6b4eea079d5311111b80a53f6e5d3d3d4630/test/Encryption/Pdf11EncryptionTest.php
test/Encryption/Pdf11EncryptionTest.php
<?php /** * BaconPdf * * @link http://github.com/Bacon/BaconPdf For the canonical source repository * @copyright 2015 Ben Scholzen (DASPRiD) * @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License */ namespace Bacon\PdfTest\Encryption; use Bacon\Pdf\Encryption\Pdf11Encryption; use Bacon\Pdf\Encryption\Permissions; /** * @covers \Bacon\Pdf\Encryption\AbstractEncryption * @covers \Bacon\Pdf\Encryption\Pdf11Encryption */ class Pdf11EncryptionTest extends AbstractEncryptionTestCase { /** * {@inheritdoc} */ public function encryptionTestData() { return [ 'same-numbers' => ['test', 'foo', null, 1, 1], 'changed-generation-number' => ['test', 'foo', null, 1, 2], 'changed-object-number' => ['test', 'foo', null, 2, 1], 'both-numbers-changed' => ['test', 'foo', null, 2, 2], 'changed-user-password' => ['test', 'bar', null, 1, 1], 'added-owner-password' => ['test', 'bar', 'baz', 1, 1], ]; } /** * {@inheritdoc} */ protected function createEncryption( $userPassword, $ownerPassword = null, Permissions $userPermissions = null ) { return new Pdf11Encryption( md5('test', true), $userPassword, $ownerPassword ?: $userPassword, $userPermissions ?: Permissions::allowNothing() ); } /** * {@inheritdoc} */ protected function decrypt($encryptedText, $key) { return openssl_decrypt($encryptedText, 'rc4', $key, OPENSSL_RAW_DATA); } /** * {@inheritdoc} */ protected function getExpectedEntry() { return file_get_contents(__DIR__ . '/_files/pdf11-encrypt-entry.txt'); } }
php
BSD-2-Clause
5f2e6b4eea079d5311111b80a53f6e5d3d3d4630
2026-01-05T04:48:03.848172Z
false
Bacon/BaconPdf
https://github.com/Bacon/BaconPdf/blob/5f2e6b4eea079d5311111b80a53f6e5d3d3d4630/test/Encryption/AbstractEncryptionTestCase.php
test/Encryption/AbstractEncryptionTestCase.php
<?php /** * BaconPdf * * @link http://github.com/Bacon/BaconPdf For the canonical source repository * @copyright 2015 Ben Scholzen (DASPRiD) * @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License */ namespace Bacon\PdfTest\Encryption; use Bacon\Pdf\Encryption\AbstractEncryption; use Bacon\Pdf\Encryption\Permissions; use Bacon\PdfTest\TestHelper\MemoryObjectWriter; use PHPUnit_Framework_TestCase as TestCase; use ReflectionClass; /** * @covers \Bacon\Pdf\Encryption\AbstractEncryption */ abstract class AbstractEncryptionTestCase extends TestCase { /** * @dataProvider encryptionTestData * @param string $plaintext * @param string $userPassword * @param string|null $ownerPassword * @param int $objectNumber * @param int $generationNumber */ public function testEncrypt( $plaintext, $userPassword, $ownerPassword, $objectNumber, $generationNumber ) { $encryption = $this->createEncryption($userPassword, $ownerPassword); $reflectionClass = new ReflectionClass($encryption); $reflectionMethod = $reflectionClass->getMethod('computeIndividualEncryptionKey'); $reflectionMethod->setAccessible(true); $key = $reflectionMethod->invoke($encryption, $objectNumber, $generationNumber); $encryptedText = $encryption->encrypt($plaintext, $objectNumber, $generationNumber); $decryptedText = $this->decrypt($encryptedText, $key); $this->assertSame($plaintext, $decryptedText); } public function testWriteEncryptEntry() { $encryption = $this->createEncryption('foo', 'bar'); $memoryObjectWriter = new MemoryObjectWriter(); $encryption->writeEncryptEntry($memoryObjectWriter); $this->assertStringMatchesFormat($this->getExpectedEntry(), $memoryObjectWriter->getData()); } /** * @return array */ abstract public function encryptionTestData(); /** * @param string $userPassword * @param string|null $ownerPassword * @param Permissions|null $userPermissions * @return AbstractEncryption */ abstract protected function createEncryption( $userPassword, $ownerPassword = null, Permissions $userPermissions = null ); /** * @param string $encryptedText * @param string $key * @return string */ abstract protected function decrypt($encryptedText, $key); /** * @return string */ abstract protected function getExpectedEntry(); }
php
BSD-2-Clause
5f2e6b4eea079d5311111b80a53f6e5d3d3d4630
2026-01-05T04:48:03.848172Z
false
Bacon/BaconPdf
https://github.com/Bacon/BaconPdf/blob/5f2e6b4eea079d5311111b80a53f6e5d3d3d4630/test/Encryption/BitMaskTest.php
test/Encryption/BitMaskTest.php
<?php /** * BaconPdf * * @link http://github.com/Bacon/BaconPdf For the canonical source repository * @copyright 2015 Ben Scholzen (DASPRiD) * @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License */ namespace Bacon\PdfTest\Encryption; use Bacon\Pdf\Encryption\BitMask; use PHPUnit_Framework_TestCase as TestCase; /** * @covers \Bacon\Pdf\Encryption\BitMask */ class BitMaskTest extends TestCase { public function testDefault() { $bitMask = new BitMask(); $this->assertSame(0, $bitMask->toInt()); } public function testSetBit() { $bitMask = new BitMask(); $bitMask->set(0, true); $bitMask->set(1, true); $this->assertSame(3, $bitMask->toInt()); $bitMask->set(0, false); $this->assertSame(2, $bitMask->toInt()); } }
php
BSD-2-Clause
5f2e6b4eea079d5311111b80a53f6e5d3d3d4630
2026-01-05T04:48:03.848172Z
false