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 |
|---|---|---|---|---|---|---|---|---|
danielgsims/php-collections | https://github.com/danielgsims/php-collections/blob/199355733ba12ac17cf1958dee1a4370a320120b/tests/Collection/ClearTest.php | tests/Collection/ClearTest.php | <?php
use Collections\Collection;
use PHPUnit\Framework\TestCase;
class ClearTest extends TestCase
{
public function test_clear_returns_an_empty_collection()
{
$col = new Collection('TestClassA', [ new TestClassA(1) ]);
//col will have one
$this->assertEquals(1, $col->count());
//empty should have no items
$empty = $col->clear();
$this->assertEquals(0, $empty->count());
//col should remain unchanged
$this->assertEquals(1, $col->count());
}
} | php | MIT | 199355733ba12ac17cf1958dee1a4370a320120b | 2026-01-05T04:46:12.589480Z | false |
danielgsims/php-collections | https://github.com/danielgsims/php-collections/blob/199355733ba12ac17cf1958dee1a4370a320120b/tests/Collection/TailTest.php | tests/Collection/TailTest.php | <?php
use Collections\Collection;
use PHPUnit\Framework\TestCase;
class TailTest extends TestCase
{
public function test_that_tail_gives_you_everything_but_head()
{
$col = new Collection('int', [1,2,3,]);
$tail = $col->tail();
$this->assertEquals(2, $tail->count());
//col shouldn't be changed and should have 3 items
$this->assertEquals(3, $col->count());
//check that tail has two and three
$this->assertEquals(2, $tail->at(0));
$this->assertEquals(3, $tail->at(1));
}
} | php | MIT | 199355733ba12ac17cf1958dee1a4370a320120b | 2026-01-05T04:46:12.589480Z | false |
danielgsims/php-collections | https://github.com/danielgsims/php-collections/blob/199355733ba12ac17cf1958dee1a4370a320120b/tests/Collection/ReduceTest.php | tests/Collection/ReduceTest.php | <?php
use Collections\Collection;
use PHPUnit\Framework\TestCase;
class ReduceTest extends TestCase
{
public function testReduce()
{
$t = new TestClassA(1);
$t2 = new TestClassA(2);
$t3 = new TestClassA(3);
$this->c = new Collection('TestClassA');
$this->c = $this->c->add($t);
$this->c = $this->c->add($t2);
$this->c = $this->c->add($t3);
$result = $this->c->reduce(function ($total, $item) {
return $total + $item->getValue();
});
$this->assertEquals(6, $result);
$result = $this->c->reduce(function ($total, $item) {
return $total + $item->getValue();
}, 2);
$this->assertEquals(8, $result);
}
} | php | MIT | 199355733ba12ac17cf1958dee1a4370a320120b | 2026-01-05T04:46:12.589480Z | false |
danielgsims/php-collections | https://github.com/danielgsims/php-collections/blob/199355733ba12ac17cf1958dee1a4370a320120b/tests/Collection/FindAllTest.php | tests/Collection/FindAllTest.php | <?php
use Collections\Collection;
use PHPUnit\Framework\TestCase;
class FindAllTest extends TestCase
{
public function testFindAll()
{
$this->c = new Collection('TestClassA');
$this->c = $this->c->add(new TestClassA(54));
$this->c = $this->c->add(new TestClassA(32));
$this->c = $this->c->add(new TestClassA(32));
$this->c = $this->c->add(new TestClassA(32));
$condition = function ($item) {
return $item->getValue() == 32;
};
$subset = $this->c->filter($condition);
$c = (new Collection("TestClassA"))
->add(new TestClassA(32))
->add(new TestClassA(32))
->add(new TestClassA(32));
$this->assertEquals(3, $subset->count());
$this->assertEquals($c, $subset);
}
} | php | MIT | 199355733ba12ac17cf1958dee1a4370a320120b | 2026-01-05T04:46:12.589480Z | false |
danielgsims/php-collections | https://github.com/danielgsims/php-collections/blob/199355733ba12ac17cf1958dee1a4370a320120b/tests/Collection/AccessTest.php | tests/Collection/AccessTest.php | <?php
use Collections\Collection;
use PHPUnit\Framework\TestCase;
class AccessTest extends TestCase
{
/**
* @expectedException Collections\Exceptions\InvalidArgumentException
*/
public function test_bad_index_throws_ex()
{
$col = new Collection('TestClassA', [ new TestClassA(1)]);
$col->at("one");
}
/**
* @expectedException Collections\Exceptions\OutOfRangeException
*/
public function test_out_of_range_throws_ex()
{
$col = new Collection('TestClassA', [ new TestClassA(1)]);
$col->at(1);
}
/**
* @expectedException Collections\Exceptions\InvalidArgumentException
*/
public function test_negative_index_throws_value()
{
$col = new Collection('TestClassA', [ new TestClassA(1)]);
$col->at(-1);
}
public function test_index_returns_value()
{
$col = new Collection('TestClassA', [ new TestClassA(1)]);
$res = $col->at(0);
$this->assertEquals(new TestClassA(1), $res);
}
} | php | MIT | 199355733ba12ac17cf1958dee1a4370a320120b | 2026-01-05T04:46:12.589480Z | false |
danielgsims/php-collections | https://github.com/danielgsims/php-collections/blob/199355733ba12ac17cf1958dee1a4370a320120b/tests/Collection/GetIteratorTest.php | tests/Collection/GetIteratorTest.php | <?php
use Collections\Collection;
use PHPUnit\Framework\TestCase;
class GetIteratorTest extends TestCase
{
public function testIterator()
{
$col = new Collection('TestClassA');
$iterator = $col->getIterator();
$class = get_class($iterator);
$this->assertEquals($class, "ArrayIterator");
}
} | php | MIT | 199355733ba12ac17cf1958dee1a4370a320120b | 2026-01-05T04:46:12.589480Z | false |
danielgsims/php-collections | https://github.com/danielgsims/php-collections/blob/199355733ba12ac17cf1958dee1a4370a320120b/tests/Collection/ReverseTest.php | tests/Collection/ReverseTest.php | <?php
use Collections\Collection;
use PHPUnit\Framework\TestCase;
class ReverseTest extends TestCase
{
public function testReverse()
{
$c = new Collection('int', [1,2,3]);
$r = $c->reverse();
$this->assertEquals([3,2,1], $r->toArray());
$this->assertEquals([1,2,3], $c->toArray());
}
} | php | MIT | 199355733ba12ac17cf1958dee1a4370a320120b | 2026-01-05T04:46:12.589480Z | false |
danielgsims/php-collections | https://github.com/danielgsims/php-collections/blob/199355733ba12ac17cf1958dee1a4370a320120b/tests/Collection/MergeTest.php | tests/Collection/MergeTest.php | <?php
use Collections\Collection;
use Collections\Exceptions\InvalidArgumentException;
use PHPUnit\Framework\TestCase;
class MergeTest extends TestCase
{
public function test_merge()
{
$c = new Collection('int');
$c = $c->add(1);
$c = $c->add(2);
$c = $c->add(3);
$c = $c->add(4);
$c1 = new Collection('int');
$c1 = $c1->add(5);
$c1 = $c1->add(6);
$c1 = $c1->add(7);
$c1 = $c1->add(8);
$result = $c->merge($c1);
$expected = new Collection('int');
$expected = $expected->add(1);
$expected = $expected->add(2);
$expected = $expected->add(3);
$expected = $expected->add(4);
$expected = $expected->add(5);
$expected = $expected->add(6);
$expected = $expected->add(7);
$expected = $expected->add(8);
$this->assertEquals($expected, $result);
}
public function test_add_range_adds_new_collection_with_items()
{
$col = new Collection('TestClassA');
$range = [ new TestClassA(0), new TestClassA(1) ];
$withRange = $col->merge($range);
$this->assertEquals(0, $col->count());
$this->assertEquals(2, $withRange->count());
$this->assertEquals($range, $withRange->toArray());
}
/**
* @expectedException Collections\Exceptions\InvalidArgumentException
*/
public function test_range_with_incorrect_types_throws_ex()
{
$badItems = array();
$badItems[] = new TestClassB();
$badItems[] = new TestClassB();
$col = new Collection('TestClassA');
$col->merge($badItems);
}
/**
* @expectedException Collections\Exceptions\InvalidArgumentException
*/
public function test_non_array_or_col_throws_ex()
{
$col = new Collection('TestClassA');
$col->merge(new TestClassA(1));
}
}
| php | MIT | 199355733ba12ac17cf1958dee1a4370a320120b | 2026-01-05T04:46:12.589480Z | false |
danielgsims/php-collections | https://github.com/danielgsims/php-collections/blob/199355733ba12ac17cf1958dee1a4370a320120b/tests/Collection/EveryTest.php | tests/Collection/EveryTest.php | <?php
use Collections\Collection;
use PHPUnit\Framework\TestCase;
class EveryTest extends TestCase
{
public function testEvery()
{
$t = new TestClassA(2);
$t2 = new TestClassA(4);
$t3 = new TestClassA(6);
$this->c = new Collection('TestClassA');
$this->c = $this->c->add($t);
$this->c = $this->c->add($t2);
$this->c = $this->c->add($t3);
$result = $this->c->every(function ($item) {
return $item->getValue() % 2 == 0;
});
$this->assertTrue($result);
$result = $this->c->every(function ($item) {
return $item->getValue() % 2 != 0;
});
$this->assertFalse($result);
}
} | php | MIT | 199355733ba12ac17cf1958dee1a4370a320120b | 2026-01-05T04:46:12.589480Z | false |
danielgsims/php-collections | https://github.com/danielgsims/php-collections/blob/199355733ba12ac17cf1958dee1a4370a320120b/tests/Collection/ToArrayTest.php | tests/Collection/ToArrayTest.php | <?php
use Collections\Collection;
use PHPUnit\Framework\TestCase;
class ToArrayTest extends TestCase
{
public function testToArray()
{
$items = array();
$items[] = new TestClassA(1);
$items[] = new TestClassA(2);
$items[] = new TestClassA(3);
$col = new Collection('TestClassA', $items);
$this->assertEquals($items, $col->toArray());
}
} | php | MIT | 199355733ba12ac17cf1958dee1a4370a320120b | 2026-01-05T04:46:12.589480Z | false |
danielgsims/php-collections | https://github.com/danielgsims/php-collections/blob/199355733ba12ac17cf1958dee1a4370a320120b/tests/Collection/InsertTest.php | tests/Collection/InsertTest.php | <?php
use Collections\Collection;
use PHPUnit\Framework\TestCase;
class InsertTest extends TestCase
{
public function testInsert()
{
$c = new Collection('TestClassA');
$c = $c->add(new TestClassA(1));
$c = $c->add(new TestClassA(2));
$result = $c->insert(1, new TestClassA(3));
$this->assertEquals(3, $result->at(1)->getValue());
}
/**
* @expectedException Collections\Exceptions\OutOfRangeException
* @expectedExceptionMessage Index out of bounds of collection
*/
public function testInsertThrowsOutOfRangeException()
{
$c = new Collection('TestClassA');
$c->insert(100, new TestClassA(5));
}
/**
* @expectedException Collections\Exceptions\InvalidArgumentException
* @expectedExceptionMessage Index must be a non-negative integer
*/
public function testInsertThrowsInvalidArgumentException()
{
$c = new Collection('TestClassA');
$c->insert(-1, new TestClassA(5));
}
}
| php | MIT | 199355733ba12ac17cf1958dee1a4370a320120b | 2026-01-05T04:46:12.589480Z | false |
danielgsims/php-collections | https://github.com/danielgsims/php-collections/blob/199355733ba12ac17cf1958dee1a4370a320120b/tests/Collection/TakeRightTest.php | tests/Collection/TakeRightTest.php | <?php
use Collections\Collection;
use PHPUnit\Framework\TestCase;
class TakeRightTest extends TestCase
{
public function testTakeRight()
{
$t = new TestClassA(2);
$t2 = new TestClassA(4);
$t3 = new TestClassA(6);
$this->c = new Collection('TestClassA');
$this->c = $this->c->add($t);
$this->c = $this->c->add($t2);
$this->c = $this->c->add($t3);
$c1 = $this->c->takeRight(1);
$c2 = $this->c->takeRight(2);
$c3 = $this->c->takeRight(3);
$this->assertEquals(1, $c1->count());
$this->assertEquals(2, $c2->count());
$this->assertEquals(3, $c3->count());
$this->assertEquals($t3, $c1->at(0));
$this->assertEquals($t2, $c2->at(0));
$this->assertEquals($t3, $c2->at(1));
$this->assertEquals($t, $c3->at(0));
$this->assertEquals($t2, $c3->at(1));
$this->assertEquals($t3, $c3->at(2));
}
public function test_take_right_takes_remainder_if_count_too_large()
{
$c = new Collection('int',[0,1,2,3]);
$c2 = $c->takeRight(10);
$this->assertEquals(4, $c2->count());
}
} | php | MIT | 199355733ba12ac17cf1958dee1a4370a320120b | 2026-01-05T04:46:12.589480Z | false |
danielgsims/php-collections | https://github.com/danielgsims/php-collections/blob/199355733ba12ac17cf1958dee1a4370a320120b/tests/Collection/ShuffleTest.php | tests/Collection/ShuffleTest.php | <?php
use Collections\Collection;
use PHPUnit\Framework\TestCase;
class ShuffleTest extends TestCase
{
public function test_shuffle()
{
$col = new Collection('int');
$col = $col->add(1);
$col = $col->add(2);
$col = $col->add(3);
$col = $col->add(4);
$col = $col->add(5);
$col = $col->add(6);
$col = $col->add(7);
$col = $col->add(8);
$col = $col->add(9);
$col = $col->add(10);
$shuffled = $col->shuffle();
$this->assertTrue($shuffled->contains(function ($a) { return $a == 1; }));
$this->assertTrue($shuffled->contains(function ($a) { return $a == 2; }));
$this->assertTrue($shuffled->contains(function ($a) { return $a == 3; }));
$this->assertTrue($shuffled->contains(function ($a) { return $a == 4; }));
$this->assertTrue($shuffled->contains(function ($a) { return $a == 5; }));
$this->assertTrue($shuffled->contains(function ($a) { return $a == 6; }));
$this->assertTrue($shuffled->contains(function ($a) { return $a == 7; }));
$this->assertTrue($shuffled->contains(function ($a) { return $a == 8; }));
$this->assertTrue($shuffled->contains(function ($a) { return $a == 9; }));
$this->assertTrue($shuffled->contains(function ($a) { return $a == 10; }));
$this->assertNotEquals($col, $shuffled);
}
}
| php | MIT | 199355733ba12ac17cf1958dee1a4370a320120b | 2026-01-05T04:46:12.589480Z | false |
danielgsims/php-collections | https://github.com/danielgsims/php-collections/blob/199355733ba12ac17cf1958dee1a4370a320120b/tests/Collection/RemoveAtTest.php | tests/Collection/RemoveAtTest.php | <?php
use Collections\Collection;
use PHPUnit\Framework\TestCase;
class RemoveAtTest extends TestCase
{
public function testRemoveAt()
{
$items = array();
$items[] = new TestClassA(3);
$items[] = new TestClassA(2);
$items[] = new TestClassA(1);
$this->c = new Collection('TestClassA');
$this->c = $this->c->merge($items);
$this->assertEquals(3, $this->c->count());
$this->c = $this->c->removeAt(1);
$this->assertEquals(2, $this->c->count());
$this->assertEquals(1, $this->c->at(1)->getValue());
}
} | php | MIT | 199355733ba12ac17cf1958dee1a4370a320120b | 2026-01-05T04:46:12.589480Z | false |
danielgsims/php-collections | https://github.com/danielgsims/php-collections/blob/199355733ba12ac17cf1958dee1a4370a320120b/tests/Collection/MapTest.php | tests/Collection/MapTest.php | <?php
use Collections\Collection;
use PHPUnit\Framework\TestCase;
class MapTest extends TestCase
{
public function test_map_ints()
{
$c = (new Collection('int'))
->add(1)
->add(2)
->add(3)
->add(4);
$result = $c->map(function ($a) { return $a * 3; });
$expected = (new Collection('int'))
->add(3)
->add(6)
->add(9)
->add(12);
$this->assertEquals($expected, $result);
}
public function test_map_strings()
{
$c = (new Collection('string'))
->add('a')
->add('b')
->add('c')
->add('d');
$result = $c->map(function ($a) { return strtoupper($a); });
$expected = (new Collection('string'))
->add('A')
->add('B')
->add('C')
->add('D');
$this->assertEquals($expected, $result);
}
public function test_map_object()
{
$c = (new Collection('string'))
->add('05/01/2016')
->add('05/02/2016')
->add('05/03/2016')
->add('05/04/2016');
$result = $c->map(function ($a) { return new \DateTime($a); });
$expected = (new Collection('DateTime'))
->add(new \DateTime('05/01/2016'))
->add(new \DateTime('05/02/2016'))
->add(new \DateTime('05/03/2016'))
->add(new \DateTime('05/04/2016'));
$this->assertEquals($expected, $result);
$count = 0;
$result = $c->map(function ($a) use (&$count) { return $count++; });
$expected = (new Collection('integer'))
->add(0)
->add(1)
->add(2)
->add(3);
$this->assertEquals($expected, $result);
}
public function test_map_empty_collection()
{
$c = new Collection('string');
$result = $c->map(function ($a) {
return $a;
});
$expected = new Collection('string');
$this->assertEquals($expected, $result);
}
}
| php | MIT | 199355733ba12ac17cf1958dee1a4370a320120b | 2026-01-05T04:46:12.589480Z | false |
danielgsims/php-collections | https://github.com/danielgsims/php-collections/blob/199355733ba12ac17cf1958dee1a4370a320120b/tests/Collection/InsertRangeTest.php | tests/Collection/InsertRangeTest.php | <?php
use Collections\Collection;
use PHPUnit\Framework\TestCase;
class InsertRangeTest extends TestCase
{
public function testInsert()
{
$c = (new Collection('TestClassA'))
->add(new TestClassA(1))
->add(new TestClassA(2));
$items = array();
$items[] = new TestClassA(3);
$items[] = new TestClassA(4);
$result = $c->insertRange(1, $items);
$expected = (new Collection('TestClassA'))
->add(new TestClassA(1))
->add(new TestClassA(3))
->add(new TestClassA(4))
->add(new TestClassA(2));
$this->assertEquals($expected, $result);
$expected1 = (new Collection('TestClassA'))
->add(new TestClassA(1))
->add(new TestClassA(2));
$this->assertEquals($expected1, $c);
}
}
| php | MIT | 199355733ba12ac17cf1958dee1a4370a320120b | 2026-01-05T04:46:12.589480Z | false |
danielgsims/php-collections | https://github.com/danielgsims/php-collections/blob/199355733ba12ac17cf1958dee1a4370a320120b/templates/FooCollection.php | templates/FooCollection.php | <?php
use Collections\Collection;
/**
* A collection of {{foo}} objects with a specified class or interface
*/
class FooCollection extends Collections\Collection
{
/**
* Instantiates the collection by specifying what type of Object will be used.
*
* @param string $objectName Name of the class or interface used in the Collection
*/
public function __construct($objectName = "{{foo}}")
{
parent::__construct($objectName);
}
/**
* Fetches the item at the specified index
*
* @param integer $index The index of an item to fetch
* @throws InvalidArgumentException
* @throws OutOfRangeException
* @return {{foo}} The item at the specified index
*/
public function at($index)
{
return parent::at($index);
}
/**
* Finds and returns the first item in the collection that satisfies the callback.
*
* @param callback $condition The condition critera to test each item, requires one argument that represents the Collection item during iteration.
* @return {{foo}} The first item that satisfied the condition or false if no object was found
*/
public function find(callable $condition)
{
return parent::find($condition);
}
/**
* Finds and returns the last item in the collection that satisfies the callback.
*
* @param callback $condition The condition criteria to test each item, requires one argument that represents the Collection item during an iteration.
* @return {{foo}} The last item that matched condition or -1 if no item was found matching the condition.
*/
public function findLast(callable $condition)
{
return parent::findLast($condition);
}
/**
* Returns a collection of all items that satisfy the callback function. If nothing is found, returns an empty
* Collection
*
* @param calback $condition The condition critera to test each item, requires one argument that represents the Collection item during iteration.
* @return {{FooCollection}} A collection of all of the items that satisfied the condition
*/
public function findAll(callable $condition)
{
return parent::findAll($condition);
}
/**
* Get a range of items in the collection
*
* @param integer $start The starting index of the range
* @param integer $end The ending index of the range
* @return {{FooCollection}} A collection of items matching the range
*/
public function getRange($start, $end)
{
return parent::getRange($start,$end);
}
}
| php | MIT | 199355733ba12ac17cf1958dee1a4370a320120b | 2026-01-05T04:46:12.589480Z | false |
mikebronner/laravel-pivot-events | https://github.com/mikebronner/laravel-pivot-events/blob/aeeceb7672c2ac359472fedba75349710572e72f/src/Relations/BelongsToManyCustom.php | src/Relations/BelongsToManyCustom.php | <?php namespace GeneaLabs\LaravelPivotEvents\Relations;
use GeneaLabs\LaravelPivotEvents\Traits\FiresPivotEventsTrait;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
class BelongsToManyCustom extends BelongsToMany
{
use FiresPivotEventsTrait;
}
| php | MIT | aeeceb7672c2ac359472fedba75349710572e72f | 2026-01-05T04:46:21.677391Z | false |
mikebronner/laravel-pivot-events | https://github.com/mikebronner/laravel-pivot-events/blob/aeeceb7672c2ac359472fedba75349710572e72f/src/Relations/MorphToManyCustom.php | src/Relations/MorphToManyCustom.php | <?php namespace GeneaLabs\LaravelPivotEvents\Relations;
use Illuminate\Database\Eloquent\Relations\MorphToMany;
use GeneaLabs\LaravelPivotEvents\Traits\FiresPivotEventsTrait;
class MorphToManyCustom extends MorphToMany
{
use FiresPivotEventsTrait;
}
| php | MIT | aeeceb7672c2ac359472fedba75349710572e72f | 2026-01-05T04:46:21.677391Z | false |
mikebronner/laravel-pivot-events | https://github.com/mikebronner/laravel-pivot-events/blob/aeeceb7672c2ac359472fedba75349710572e72f/src/Traits/ExtendFireModelEventTrait.php | src/Traits/ExtendFireModelEventTrait.php | <?php namespace GeneaLabs\LaravelPivotEvents\Traits;
use Illuminate\Contracts\Broadcasting\Factory as BroadcastingFactory;
use Illuminate\Support\Arr;
trait ExtendFireModelEventTrait
{
/**
* Fire the given event for the model.
*
* @param string $event
* @param bool $halt
*
* @return mixed
*/
public function fireModelEvent(
$event,
$halt = true,
$relationName = null,
$ids = [],
$idsAttributes = []
) {
if (!isset(static::$dispatcher)) {
return true;
}
$method = $halt
? 'until'
: 'dispatch';
$result = $this->filterModelEventResults(
$this->fireCustomModelEvent($event, $method)
);
if (false === $result) {
return false;
}
$payload = [
'model' => $this,
'relation' => $relationName,
'pivotIds' => $ids,
'pivotIdsAttributes' => $idsAttributes,
0 => $this,
];
$result = $result
?: static::$dispatcher
->{$method}("eloquent.{$event}: " . static::class, $payload);
$this->broadcastPivotEvent($event, $payload);
return $result;
}
protected function broadcastPivotEvent(string $event, array $payload): void
{
$events = [
"pivotAttached",
"pivotDetached",
"pivotSynced",
"pivotUpdated",
];
if (! in_array($event, $events)) {
return;
}
$className = explode("\\", get_class($this));
$name = method_exists($this, "broadcastAs")
? $this->broadcastAs()
: array_pop($className) . ucwords($event);
$channels = method_exists($this, "broadcastOn")
? Arr::wrap($this->broadcastOn($event))
: [];
if (empty($channels)) {
return;
}
$connections = method_exists($this, "broadcastConnections")
? $this->broadcastConnections()
: [null];
$manager = app(BroadcastingFactory::class);
foreach ($connections as $connection) {
$manager->connection($connection)
->broadcast($channels, $name, $payload);
}
}
}
| php | MIT | aeeceb7672c2ac359472fedba75349710572e72f | 2026-01-05T04:46:21.677391Z | false |
mikebronner/laravel-pivot-events | https://github.com/mikebronner/laravel-pivot-events/blob/aeeceb7672c2ac359472fedba75349710572e72f/src/Traits/PivotEventTrait.php | src/Traits/PivotEventTrait.php | <?php namespace GeneaLabs\LaravelPivotEvents\Traits;
trait PivotEventTrait
{
use ExtendRelationsTrait;
use ExtendFireModelEventTrait;
/**
* Get the observable event names.
*
* @return array
*/
public function getObservableEvents()
{
return array_merge(
parent::getObservableEvents(),
[
'pivotSyncing', 'pivotSynced',
'pivotAttaching', 'pivotAttached',
'pivotDetaching', 'pivotDetached',
'pivotUpdating', 'pivotUpdated',
],
$this->observables
);
}
public static function pivotSyncing($callback, $priority = 0)
{
static::registerModelEvent('pivotSyncing', $callback, $priority);
}
public static function pivotSynced($callback, $priority = 0)
{
static::registerModelEvent('pivotSynced', $callback, $priority);
}
public static function pivotAttaching($callback, $priority = 0)
{
static::registerModelEvent('pivotAttaching', $callback, $priority);
}
public static function pivotAttached($callback, $priority = 0)
{
static::registerModelEvent('pivotAttached', $callback, $priority);
}
public static function pivotDetaching($callback, $priority = 0)
{
static::registerModelEvent('pivotDetaching', $callback, $priority);
}
public static function pivotDetached($callback, $priority = 0)
{
static::registerModelEvent('pivotDetached', $callback, $priority);
}
public static function pivotUpdating($callback, $priority = 0)
{
static::registerModelEvent('pivotUpdating', $callback, $priority);
}
public static function pivotUpdated($callback, $priority = 0)
{
static::registerModelEvent('pivotUpdated', $callback, $priority);
}
}
| php | MIT | aeeceb7672c2ac359472fedba75349710572e72f | 2026-01-05T04:46:21.677391Z | false |
mikebronner/laravel-pivot-events | https://github.com/mikebronner/laravel-pivot-events/blob/aeeceb7672c2ac359472fedba75349710572e72f/src/Traits/ExtendRelationsTrait.php | src/Traits/ExtendRelationsTrait.php | <?php namespace GeneaLabs\LaravelPivotEvents\Traits;
use GeneaLabs\LaravelPivotEvents\Relations\BelongsToManyCustom;
use GeneaLabs\LaravelPivotEvents\Relations\MorphToManyCustom;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
trait ExtendRelationsTrait
{
protected function newMorphToMany(
Builder $query,
Model $parent,
$name,
$table,
$foreignPivotKey,
$relatedPivotKey,
$parentKey,
$relatedKey,
$relationName = null,
$inverse = false
) {
return new MorphToManyCustom(
$query,
$parent,
$name,
$table,
$foreignPivotKey,
$relatedPivotKey,
$parentKey,
$relatedKey,
$relationName,
$inverse
);
}
protected function newBelongsToMany(
Builder $query,
Model $parent,
$table,
$foreignPivotKey,
$relatedPivotKey,
$parentKey,
$relatedKey,
$relationName = null
) {
return new BelongsToManyCustom(
$query,
$parent,
$table,
$foreignPivotKey,
$relatedPivotKey,
$parentKey,
$relatedKey,
$relationName
);
}
}
| php | MIT | aeeceb7672c2ac359472fedba75349710572e72f | 2026-01-05T04:46:21.677391Z | false |
mikebronner/laravel-pivot-events | https://github.com/mikebronner/laravel-pivot-events/blob/aeeceb7672c2ac359472fedba75349710572e72f/src/Traits/FiresPivotEventsTrait.php | src/Traits/FiresPivotEventsTrait.php | <?php namespace GeneaLabs\LaravelPivotEvents\Traits;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Collection;
trait FiresPivotEventsTrait
{
/**
* Sync the intermediate tables with a list of IDs or collection of models.
*
* @param mixed $ids
* @param bool $detaching
*
* @return array
*/
public function sync($ids, $detaching = true)
{
if (false === $this->parent->fireModelEvent('pivotSyncing', true, $this->getRelationName())) {
return false;
}
$parentResult = [];
$this->parent->withoutEvents(function () use ($ids, $detaching, &$parentResult) {
$parentResult = parent::sync($ids, $detaching);
});
$this->parent->fireModelEvent('pivotSynced', false, $this->getRelationName(), $parentResult);
return $parentResult;
}
/**
* Attach a model to the parent.
*
* @param mixed $id
* @param array $attributes
* @param bool $touch
*/
public function attach($ids, array $attributes = [], $touch = true)
{
list($idsOnly, $idsAttributes) = $this->getIdsWithAttributes($ids, $attributes);
$this->parent->fireModelEvent('pivotAttaching', true, $this->getRelationName(), $idsOnly, $idsAttributes);
$parentResult = parent::attach($ids, $attributes, $touch);
$this->parent->fireModelEvent('pivotAttached', false, $this->getRelationName(), $idsOnly, $idsAttributes);
return $parentResult;
}
/**
* Detach models from the relationship.
*
* @param mixed $ids
* @param bool $touch
*
* @return int
*/
public function detach($ids = null, $touch = true)
{
if (is_null($ids)) {
$ids = $this->query->pluck($this->query->qualifyColumn($this->relatedKey))->toArray();
}
list($idsOnly) = $this->getIdsWithAttributes($ids);
$this->parent->fireModelEvent('pivotDetaching', true, $this->getRelationName(), $idsOnly);
$parentResult = parent::detach($ids, $touch);
$this->parent->fireModelEvent('pivotDetached', false, $this->getRelationName(), $idsOnly);
return $parentResult;
}
/**
* Update an existing pivot record on the table.
*
* @param mixed $id
* @param array $attributes
* @param bool $touch
*
* @return int
*/
public function updateExistingPivot($id, array $attributes, $touch = true)
{
list($idsOnly, $idsAttributes) = $this->getIdsWithAttributes($id, $attributes);
$this->parent->fireModelEvent('pivotUpdating', true, $this->getRelationName(), $idsOnly, $idsAttributes);
$parentResult = parent::updateExistingPivot($id, $attributes, $touch);
$this->parent->fireModelEvent('pivotUpdated', false, $this->getRelationName(), $idsOnly, $idsAttributes);
return $parentResult;
}
/**
* Cleans the ids and ids with attributes
* Returns an array with and array of ids and array of id => attributes.
*
* @param mixed $id
* @param array $attributes
*
* @return array
*/
private function getIdsWithAttributes($id, $attributes = [])
{
$ids = [];
if ($id instanceof Model) {
$ids[$id->getKey()] = $attributes;
} elseif ($id instanceof Collection) {
foreach ($id as $model) {
$ids[$model->getKey()] = $attributes;
}
} elseif (is_array($id)) {
foreach ($id as $key => $attributesArray) {
if (is_array($attributesArray)) {
$ids[$key] = array_merge($attributes, $attributesArray);
} else {
$ids[$attributesArray] = $attributes;
}
}
} elseif (is_int($id) || is_string($id)) {
$ids[$id] = $attributes;
}
$idsOnly = array_keys($ids);
return [$idsOnly, $ids];
}
}
| php | MIT | aeeceb7672c2ac359472fedba75349710572e72f | 2026-01-05T04:46:21.677391Z | false |
mikebronner/laravel-pivot-events | https://github.com/mikebronner/laravel-pivot-events/blob/aeeceb7672c2ac359472fedba75349710572e72f/tests/ObservableEventsTest.php | tests/ObservableEventsTest.php | <?php
namespace GeneaLabs\LaravelPivotEvents\Tests;
use GeneaLabs\LaravelPivotEvents\Tests\Models\User;
class ObservableEventsTest extends TestCase
{
public function setUp(): void
{
parent::setUp();
}
public function test_events()
{
$user = User::find(1);
$events = $user->getObservableEvents();
$this->assertTrue(in_array('pivotAttaching', $events));
}
}
| php | MIT | aeeceb7672c2ac359472fedba75349710572e72f | 2026-01-05T04:46:21.677391Z | false |
mikebronner/laravel-pivot-events | https://github.com/mikebronner/laravel-pivot-events/blob/aeeceb7672c2ac359472fedba75349710572e72f/tests/PivotEventTraitTest.php | tests/PivotEventTraitTest.php | <?php namespace GeneaLabs\LaravelPivotEvents\Tests;
use GeneaLabs\LaravelPivotEvents\Tests\Models\Tag;
use GeneaLabs\LaravelPivotEvents\Tests\Models\Post;
use GeneaLabs\LaravelPivotEvents\Tests\Models\Role;
use GeneaLabs\LaravelPivotEvents\Tests\Models\User;
use GeneaLabs\LaravelPivotEvents\Tests\Models\Video;
use GeneaLabs\LaravelPivotEvents\Tests\Models\Seller;
class PivotEventTraitTest extends TestCase
{
public function setUp(): void
{
parent::setUp();
}
private function startListening()
{
self::$events = [];
}
public function test_attach_int()
{
$this->startListening();
$user = User::find(1);
$user->roles()->attach(1, ['value' => 123]);
$this->check_events(['eloquent.pivotAttaching: '.User::class, 'eloquent.pivotAttached: '.User::class]);
$this->check_variables(0, [1], [1 => ['value' => 123]]);
$this->check_database(1, 123, 0, 'value');
}
public function test_polymorphic_attach_int()
{
$this->startListening();
$post = Post::find(1);
$post->tags()->attach(1, ['value' => 123]);
$this->check_events(['eloquent.pivotAttaching: '.Post::class, 'eloquent.pivotAttached: '.Post::class]);
$this->check_variables(0, [1], [1 => ['value' => 123]], 'tags');
$this->check_database(1, 123, 0, 'value', 'taggables');
}
public function test_attach_string()
{
$this->startListening();
$user = User::find(1);
$seller = Seller::first();
$user->sellers()->attach($seller->id, ['value' => 123]);
$this->check_events(['eloquent.pivotAttaching: '.User::class, 'eloquent.pivotAttached: '.User::class]);
$this->check_variables(0, [$seller->id], [$seller->id => ['value' => 123]], 'sellers');
$this->check_database(1, 123, 0, 'value', 'seller_user');
}
public function test_attach_array()
{
$this->startListening();
$user = User::find(1);
$user->roles()->attach([1 => ['value' => 123], 2 => ['value' => 456]], ['value2' => 789]);
$this->assertEquals(2, \DB::table('role_user')->count());
$this->check_events(['eloquent.pivotAttaching: '.User::class, 'eloquent.pivotAttached: '.User::class]);
$this->check_variables(0, [1, 2], [1 => ['value' => 123, 'value2' => 789], 2 => ['value' => 456, 'value2' => 789]]);
$this->check_database(2, 123);
$this->check_database(2, 789, 0, 'value2');
}
public function test_polymorphic_attach_array()
{
$this->startListening();
$video = Video::find(1);
$video->tags()->attach([1 => ['value' => 123], 2 => ['value' => 456]], ['value2' => 789]);
$this->assertEquals(2, \DB::table('taggables')->count());
$this->check_events(['eloquent.pivotAttaching: '.Video::class, 'eloquent.pivotAttached: '.Video::class]);
$this->check_variables(0, [1, 2], [1 => ['value' => 123, 'value2' => 789], 2 => ['value' => 456, 'value2' => 789]], 'tags');
$this->check_database(2, 123, 0, 'value', 'taggables');
$this->check_database(2, 789, 0, 'value2', 'taggables');
}
public function test_attach_model()
{
$this->startListening();
$user = User::find(1);
$role = Role::find(1);
$user->roles()->attach($role, ['value' => 123]);
$this->assertEquals(1, \DB::table('role_user')->count());
$this->check_events(['eloquent.pivotAttaching: '.User::class, 'eloquent.pivotAttached: '.User::class]);
$this->check_variables(0, [1], [1 => ['value' => 123]]);
$this->check_database(1, 123);
}
public function test_polymorphic_attach_model()
{
$this->startListening();
$tag = Tag::find(1);
$video = Video::find(1);
$tag->videos()->attach($video, ['value' => 123]);
$this->assertEquals(1, \DB::table('taggables')->count());
$this->check_events(['eloquent.pivotAttaching: '.Tag::class, 'eloquent.pivotAttached: '.Tag::class]);
$this->check_variables(0, [1], [1 => ['value' => 123]], 'videos');
$this->check_database(1, 123, 0, 'value', 'taggables');
}
public function test_attach_collection()
{
$this->startListening();
$user = User::find(1);
$roles = Role::take(2)->get();
$user->roles()->attach($roles, ['value' => 123]);
$this->assertEquals(2, \DB::table('role_user')->count());
$this->check_events(['eloquent.pivotAttaching: '.User::class, 'eloquent.pivotAttached: '.User::class]);
$this->check_variables(0, [1, 2], [1 => ['value' => 123], 2 => ['value' => 123]]);
$this->check_database(2, 123);
$this->check_database(2, 123, 1);
}
public function test_polymorphic_attach_collection()
{
$this->startListening();
$post = Post::find(1);
$tags = Tag::take(2)->get();
$post->tags()->attach($tags, ['value' => 123]);
$this->assertEquals(2, \DB::table('taggables')->count());
$this->check_events(['eloquent.pivotAttaching: '.Post::class, 'eloquent.pivotAttached: '.Post::class]);
$this->check_variables(0, [1, 2], [1 => ['value' => 123], 2 => ['value' => 123]], 'tags');
$this->check_database(2, 123, 0, 'value', 'taggables');
$this->check_database(2, 123, 1, 'value', 'taggables');
}
public function test_detach_int()
{
$this->startListening();
$user = User::find(1);
$user->roles()->attach([1, 2, 3]);
$this->assertEquals(3, \DB::table('role_user')->count());
$this->startListening();
$user->roles()->detach(2);
$this->assertEquals(2, \DB::table('role_user')->count());
$this->check_events(['eloquent.pivotDetaching: '.User::class, 'eloquent.pivotDetached: '.User::class]);
$this->check_variables(0, [2]);
}
public function test_polymorphic_detach_int()
{
$this->startListening();
$video = Video::find(1);
$video->tags()->attach([1, 2, 3]);
$this->assertEquals(3, \DB::table('taggables')->count());
$this->startListening();
$video->tags()->detach(2);
$this->assertEquals(2, \DB::table('taggables')->count());
$this->check_events(['eloquent.pivotDetaching: '.Video::class, 'eloquent.pivotDetached: '.Video::class]);
$this->check_variables(0, [2], [], 'tags');
}
public function test_detach_array()
{
$this->startListening();
$user = User::find(1);
$user->roles()->attach([1, 2, 3]);
$this->assertEquals(3, \DB::table('role_user')->count());
$this->startListening();
$user->roles()->detach([2, 3]);
$this->assertEquals(1, \DB::table('role_user')->count());
$this->check_events(['eloquent.pivotDetaching: '.User::class, 'eloquent.pivotDetached: '.User::class]);
$this->check_variables(0, [2, 3]);
}
public function test_polymorphic_detach_array()
{
$this->startListening();
$post = Post::find(1);
$post->tags()->attach([1, 2, 3]);
$this->assertEquals(3, \DB::table('taggables')->count());
$this->startListening();
$post->tags()->detach([2, 3]);
$this->assertEquals(1, \DB::table('taggables')->count());
$this->check_events(['eloquent.pivotDetaching: '.Post::class, 'eloquent.pivotDetached: '.Post::class]);
$this->check_variables(0, [2, 3], [], 'tags');
}
public function test_detach_model()
{
$this->startListening();
$user = User::find(1);
$user->roles()->attach([1, 2, 3]);
$this->assertEquals(3, \DB::table('role_user')->count());
$this->startListening();
$role = Role::find(1);
$user->roles()->detach($role);
$this->assertEquals(2, \DB::table('role_user')->count());
$this->check_events(['eloquent.pivotDetaching: '.User::class, 'eloquent.pivotDetached: '.User::class]);
$this->check_variables(0, [1]);
}
public function test_polymorphic_detach_model()
{
$this->startListening();
$post = Post::find(1);
$video = Video::find(1);
$post->tags()->attach([1, 2]);
$video->tags()->attach([2]);
$this->assertEquals(3, \DB::table('taggables')->count());
$this->startListening();
$tag = Tag::find(2);
$tag->videos()->detach($video);
$this->assertEquals(2, \DB::table('taggables')->count());
$this->check_events(['eloquent.pivotDetaching: '.Tag::class, 'eloquent.pivotDetached: '.Tag::class]);
$this->check_variables(0, [1], [], 'videos');
}
public function test_detach_collection()
{
$this->startListening();
$user = User::find(1);
$user->roles()->attach([1, 2, 3]);
$this->assertEquals(3, \DB::table('role_user')->count());
$this->startListening();
$roles = Role::take(2)->get();
$user->roles()->detach($roles);
$this->assertEquals(1, \DB::table('role_user')->count());
$this->check_events(['eloquent.pivotDetaching: '.User::class, 'eloquent.pivotDetached: '.User::class]);
$this->check_variables(0, [1, 2]);
}
public function test_polymorphic_detach_collection()
{
$this->startListening();
$post = Post::find(1);
$post->tags()->attach([1, 2, 3]);
$this->assertEquals(3, \DB::table('taggables')->count());
$this->startListening();
$tags = Tag::take(2)->get();
$post->tags()->detach($tags);
$this->assertEquals(1, \DB::table('taggables')->count());
$this->check_events(['eloquent.pivotDetaching: '.Post::class, 'eloquent.pivotDetached: '.Post::class]);
$this->check_variables(0, [1, 2], [], 'tags');
}
public function test_detach_null()
{
$this->startListening();
$user = User::find(1);
$user->roles()->attach([1, 2, 3]);
$this->assertEquals(3, \DB::table('role_user')->count());
$this->startListening();
$user->roles()->detach();
$this->assertEquals(0, \DB::table('role_user')->count());
$this->check_events(['eloquent.pivotDetaching: '.User::class, 'eloquent.pivotDetached: '.User::class]);
$this->check_variables(0, [1, 2, 3]);
}
public function test_polymorphic_detach_null()
{
$this->startListening();
$post = Post::find(1);
$post->tags()->attach([1, 2]);
$video = Video::find(2);
$video->tags()->attach([2, 3]);
$this->assertEquals(4, \DB::table('taggables')->count());
$this->startListening();
$post->tags()->detach();
$this->assertEquals(2, \DB::table('taggables')->count());
$this->check_events(['eloquent.pivotDetaching: '.Post::class, 'eloquent.pivotDetached: '.Post::class]);
$this->check_variables(0, [1, 2], [], 'tags');
}
public function test_update()
{
$this->startListening();
$user = User::find(1);
$user->roles()->attach([1, 2, 3]);
$this->startListening();
$user->roles()->updateExistingPivot(1, ['value' => 123]);
$this->assertEquals(3, \DB::table('role_user')->count());
$this->check_events(['eloquent.pivotUpdating: '.User::class, 'eloquent.pivotUpdated: '.User::class]);
$this->check_variables(0, [1], [1 => ['value' => 123]]);
$this->check_database(3, 123, 0);
$this->check_database(3, null, 2);
}
public function test_polymorphic_update()
{
$this->startListening();
$video = Video::find(1);
$video->tags()->attach([1, 2, 3]);
$this->startListening();
$video->tags()->updateExistingPivot(1, ['value' => 123]);
$this->assertEquals(3, \DB::table('taggables')->count());
$this->check_events(['eloquent.pivotUpdating: '.Video::class, 'eloquent.pivotUpdated: '.Video::class]);
$this->check_variables(0, [1], [1 => ['value' => 123]], 'tags');
$this->check_database(3, 123, 0, 'value', 'taggables');
$this->check_database(3, null, 2, 'value', 'taggables');
}
public function test_sync_int()
{
$this->startListening();
$user = User::find(1);
$user->roles()->attach([2, 3]);
$this->assertEquals(2, \DB::table('role_user')->count());
$this->startListening();
$user->roles()->sync(1);
$this->assertEquals(1, \DB::table('role_user')->count());
$this->check_events([
'eloquent.pivotSyncing: '.User::class,
'eloquent.pivotSynced: '.User::class,
]);
}
/** @group test */
public function test_polymorphic_sync_int()
{
$this->startListening();
$post = Post::find(1);
$post->tags()->attach([2, 3]);
$this->assertEquals(2, \DB::table('taggables')->count());
$this->startListening();
$post->tags()->sync(1);
$this->assertEquals(1, \DB::table('taggables')->count());
$this->check_events([
'eloquent.pivotSyncing: '.Post::class,
'eloquent.pivotSynced: '.Post::class,
]);
}
public function test_sync_array()
{
$this->startListening();
$user = User::find(1);
$user->roles()->attach([2, 3]);
$this->assertEquals(2, \DB::table('role_user')->count());
$this->startListening();
$user->roles()->sync([1]);
$this->assertEquals(1, \DB::table('role_user')->count());
$this->check_events([
'eloquent.pivotSyncing: '.User::class,
'eloquent.pivotSynced: '.User::class,
]);
}
public function test_polymorphic_sync_array()
{
$this->startListening();
$video = Video::find(1);
$video->tags()->attach([2, 3]);
$this->assertEquals(2, \DB::table('taggables')->count());
$this->startListening();
$video->tags()->sync([1]);
$this->assertEquals(1, \DB::table('taggables')->count());
$this->check_events([
'eloquent.pivotSyncing: '.Video::class,
'eloquent.pivotSynced: '.Video::class,
]);
}
public function test_sync_model()
{
$this->startListening();
$user = User::find(1);
$user->roles()->attach([2, 3]);
$this->assertEquals(2, \DB::table('role_user')->count());
$this->startListening();
$role = Role::find(1);
$user->roles()->sync($role);
$this->check_events([
'eloquent.pivotSyncing: '.User::class,
'eloquent.pivotSynced: '.User::class,
]);
$this->assertEquals(2, count(self::$events));
}
public function test_polymorphic_sync_model()
{
$this->startListening();
$video = Video::find(1);
$video->tags()->attach([2, 3]);
$this->assertEquals(2, \DB::table('taggables')->count());
$this->startListening();
$tag = Tag::find(1);
$video->tags()->sync($tag);
$this->assertEquals(1, \DB::table('taggables')->count());
$this->check_events([
'eloquent.pivotSyncing: '.Video::class,
'eloquent.pivotSynced: '.Video::class,
]);
$this->assertEquals(2, count(self::$events));
}
public function test_sync_collection()
{
$this->startListening();
$user = User::find(1);
$user->roles()->attach([1, 2]);
$this->assertEquals(2, \DB::table('role_user')->count());
$this->startListening();
$roles = Role::whereIn('id', [3, 4])->get();
$user->roles()->sync($roles);
$this->check_events([
'eloquent.pivotSyncing: '.User::class,
'eloquent.pivotSynced: '.User::class,
]);
}
public function test_polymorphic_sync_collection()
{
$this->startListening();
$tag = Tag::find(1);
$tag->posts()->attach([1]);
$tag->videos()->attach([2]);
$this->assertEquals(2, \DB::table('taggables')->count());
$this->startListening();
$posts = Post::where('id', 2)->get();
$tag->posts()->sync($posts);
$this->check_events([
'eloquent.pivotSyncing: '.Tag::class,
'eloquent.pivotSynced: '.Tag::class,
]);
}
public function test_standard_update()
{
$this->startListening();
$user = User::find(1);
$this->startListening();
$user->update(['name' => 'different']);
$this->check_events([
'eloquent.saving: '.User::class,
'eloquent.updating: '.User::class,
'eloquent.updated: '.User::class,
'eloquent.saved: '.User::class,
]);
}
public function test_relation_is_null()
{
$this->startListening();
$user = User::find(1);
$user->update(['name' => 'new_name']);
$eventName = 'eloquent.updating: '.User::class;
$this->check_variables(0, [], [], null);
}
private function check_events($events)
{
$i = 0;
foreach ($events as $event) {
$this->assertEquals(self::$events[$i]['name'], $event);
++$i;
}
$this->assertEquals(count($events), count(self::$events));
}
private function check_variables($number, $ids, $idsAttributes = [], $relation = 'roles')
{
$this->assertEquals(self::$events[$number]['pivotIds'], $ids);
$this->assertEquals(self::$events[$number]['pivotIdsAttributes'], $idsAttributes);
$this->assertEquals(self::$events[$number]['relation'], $relation);
}
private function check_database($count, $value, $number = 0, $attribute = 'value', $table = 'role_user')
{
$this->assertEquals($value, \DB::table($table)->get()->get($number)->$attribute);
$this->assertEquals($count, \DB::table($table)->count());
}
}
| php | MIT | aeeceb7672c2ac359472fedba75349710572e72f | 2026-01-05T04:46:21.677391Z | false |
mikebronner/laravel-pivot-events | https://github.com/mikebronner/laravel-pivot-events/blob/aeeceb7672c2ac359472fedba75349710572e72f/tests/TestCase.php | tests/TestCase.php | <?php namespace GeneaLabs\LaravelPivotEvents\Tests;
use GeneaLabs\LaravelPivotEvents\Tests\Models\Tag;
use GeneaLabs\LaravelPivotEvents\Tests\Models\Post;
use GeneaLabs\LaravelPivotEvents\Tests\Models\Role;
use GeneaLabs\LaravelPivotEvents\Tests\Models\User;
use GeneaLabs\LaravelPivotEvents\Tests\Models\Video;
use GeneaLabs\LaravelPivotEvents\Tests\Models\Seller;
abstract class TestCase extends \Orchestra\Testbench\TestCase
{
public static $events = [];
public function setUp(): void
{
parent::setUp();
User::create(['name' => 'example@example.com']);
User::create(['name' => 'example2@example.com']);
Seller::create(['name' => 'seller 1']);
Role::create(['name' => 'admin']);
Role::create(['name' => 'manager']);
Role::create(['name' => 'customer']);
Role::create(['name' => 'driver']);
Post::create(['name' => 'Learn Laravel in 30 days']);
Post::create(['name' => 'Vue.js for Dummies']);
Video::create(['name' => 'Laravel from Scratch']);
Video::create(['name' => 'ES2015 Fundamentals']);
Tag::create(['name' => 'technology']);
Tag::create(['name' => 'laravel']);
Tag::create(['name' => 'java-script']);
$this->assertEquals(0, \DB::table('role_user')->count());
$this->assertEquals(0, \DB::table('seller_user')->count());
$this->assertEquals(0, \DB::table('taggables')->count());
\Event::listen('eloquent.*', function ($eventName, array $data) {
if (0 !== strpos($eventName, 'eloquent.retrieved')
&& array_key_exists("model", $data)
) {
self::$events[] = [0 => $data['model'], 'name' => $eventName, 'model' => $data['model'], 'relation' => $data['relation'], 'pivotIds' => $data['pivotIds'], 'pivotIdsAttributes' => $data['pivotIdsAttributes']];
}
});
}
protected function getEnvironmentSetUp($app)
{
// Setup default database to use sqlite :memory:
$app['config']->set('database.default', 'testbench');
$app['config']->set('database.connections.testbench', [
'driver' => 'sqlite',
'database' => ':memory:',
'prefix' => '',
]);
}
protected function getPackageProviders($app)
{
return [ServiceProvider::class];
}
}
| php | MIT | aeeceb7672c2ac359472fedba75349710572e72f | 2026-01-05T04:46:21.677391Z | false |
mikebronner/laravel-pivot-events | https://github.com/mikebronner/laravel-pivot-events/blob/aeeceb7672c2ac359472fedba75349710572e72f/tests/ServiceProvider.php | tests/ServiceProvider.php | <?php namespace GeneaLabs\LaravelPivotEvents\Tests;
class ServiceProvider extends \Illuminate\Support\ServiceProvider
{
public function register()
{
//register
}
public function boot()
{
$this->loadMigrationsFrom(__DIR__.'/database/migrations/');
}
protected function loadMigrationsFrom($path)
{
\Artisan::call('migrate', ['--database' => 'testbench']);
$migrator = $this->app->make('migrator');
$migrator->run($path);
}
}
| php | MIT | aeeceb7672c2ac359472fedba75349710572e72f | 2026-01-05T04:46:21.677391Z | false |
mikebronner/laravel-pivot-events | https://github.com/mikebronner/laravel-pivot-events/blob/aeeceb7672c2ac359472fedba75349710572e72f/tests/Models/Seller.php | tests/Models/Seller.php | <?php
namespace GeneaLabs\LaravelPivotEvents\Tests\Models;
use GeneaLabs\LaravelPivotEvents\Traits\PivotEventTrait;
use Illuminate\Support\Str;
class Seller extends BaseModel
{
use PivotEventTrait;
public $incrementing = false;
protected $table = 'sellers';
protected $fillable = ['name'];
/**
* Boot the String Id for the model.
*/
protected static function boot()
{
parent::boot();
static::creating(function ($model) {
$model->{$model->getKeyName()} = Str::random(16);
});
}
public function users()
{
return $this->belongsToMany(User::class)
->withPivot(['value']);
}
}
| php | MIT | aeeceb7672c2ac359472fedba75349710572e72f | 2026-01-05T04:46:21.677391Z | false |
mikebronner/laravel-pivot-events | https://github.com/mikebronner/laravel-pivot-events/blob/aeeceb7672c2ac359472fedba75349710572e72f/tests/Models/Video.php | tests/Models/Video.php | <?php
namespace GeneaLabs\LaravelPivotEvents\Tests\Models;
use GeneaLabs\LaravelPivotEvents\Traits\PivotEventTrait;
class Video extends BaseModel
{
use PivotEventTrait;
protected $table = 'videos';
protected $fillable = ['name'];
public function tags()
{
return $this->morphToMany(Tag::class, 'taggable');
}
}
| php | MIT | aeeceb7672c2ac359472fedba75349710572e72f | 2026-01-05T04:46:21.677391Z | false |
mikebronner/laravel-pivot-events | https://github.com/mikebronner/laravel-pivot-events/blob/aeeceb7672c2ac359472fedba75349710572e72f/tests/Models/Tag.php | tests/Models/Tag.php | <?php
namespace GeneaLabs\LaravelPivotEvents\Tests\Models;
use GeneaLabs\LaravelPivotEvents\Traits\PivotEventTrait;
class Tag extends BaseModel
{
use PivotEventTrait;
protected $table = 'videos';
protected $fillable = ['name'];
public function posts()
{
return $this->morphedByMany(Post::class, 'taggable');
}
public function videos()
{
return $this->morphedByMany(Video::class, 'taggable');
}
}
| php | MIT | aeeceb7672c2ac359472fedba75349710572e72f | 2026-01-05T04:46:21.677391Z | false |
mikebronner/laravel-pivot-events | https://github.com/mikebronner/laravel-pivot-events/blob/aeeceb7672c2ac359472fedba75349710572e72f/tests/Models/User.php | tests/Models/User.php | <?php
namespace GeneaLabs\LaravelPivotEvents\Tests\Models;
use GeneaLabs\LaravelPivotEvents\Traits\PivotEventTrait;
class User extends BaseModel
{
use PivotEventTrait;
protected $table = 'users';
protected $fillable = ['name'];
public function roles()
{
return $this->belongsToMany(Role::class)
->withPivot(['value']);
}
public function sellers()
{
return $this->belongsToMany(Seller::class)
->withPivot(['value']);
}
}
| php | MIT | aeeceb7672c2ac359472fedba75349710572e72f | 2026-01-05T04:46:21.677391Z | false |
mikebronner/laravel-pivot-events | https://github.com/mikebronner/laravel-pivot-events/blob/aeeceb7672c2ac359472fedba75349710572e72f/tests/Models/Role.php | tests/Models/Role.php | <?php
namespace GeneaLabs\LaravelPivotEvents\Tests\Models;
class Role extends BaseModel
{
protected $table = 'roles';
protected $fillable = ['name'];
}
| php | MIT | aeeceb7672c2ac359472fedba75349710572e72f | 2026-01-05T04:46:21.677391Z | false |
mikebronner/laravel-pivot-events | https://github.com/mikebronner/laravel-pivot-events/blob/aeeceb7672c2ac359472fedba75349710572e72f/tests/Models/BaseModel.php | tests/Models/BaseModel.php | <?php
namespace GeneaLabs\LaravelPivotEvents\Tests\Models;
use Illuminate\Database\Eloquent\Model;
class BaseModel extends Model
{
}
| php | MIT | aeeceb7672c2ac359472fedba75349710572e72f | 2026-01-05T04:46:21.677391Z | false |
mikebronner/laravel-pivot-events | https://github.com/mikebronner/laravel-pivot-events/blob/aeeceb7672c2ac359472fedba75349710572e72f/tests/Models/Post.php | tests/Models/Post.php | <?php
namespace GeneaLabs\LaravelPivotEvents\Tests\Models;
use GeneaLabs\LaravelPivotEvents\Traits\PivotEventTrait;
class Post extends BaseModel
{
use PivotEventTrait;
protected $table = 'posts';
protected $fillable = ['name'];
public function tags()
{
return $this->morphToMany(Tag::class, 'taggable');
}
}
| php | MIT | aeeceb7672c2ac359472fedba75349710572e72f | 2026-01-05T04:46:21.677391Z | false |
mikebronner/laravel-pivot-events | https://github.com/mikebronner/laravel-pivot-events/blob/aeeceb7672c2ac359472fedba75349710572e72f/tests/database/migrations/2017_11_04_163552_create_database.php | tests/database/migrations/2017_11_04_163552_create_database.php | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
/**
* Class CreateDatabase.
*/
class CreateDatabase extends Migration
{
/**
* Run the migrations.
*/
public function up()
{
Schema::create('sellers', function (Blueprint $table) {
$table->string('id');
$table->string('name');
$table->timestamps();
});
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
Schema::create('roles', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
Schema::create('role_user', function (Blueprint $table) {
$table->integer('role_id')->unsigned()->index();
$table->integer('user_id')->unsigned()->index();
$table->primary(['role_id', 'user_id']);
$table->foreign('role_id')->references('id')->on('roles')
->onUpdate('cascade')->onDelete('cascade');
$table->foreign('user_id')->references('id')->on('users')
->onUpdate('cascade')->onDelete('cascade');
$table->integer('value')->nullable();
$table->integer('value2')->nullable();
$table->timestamps();
});
Schema::create('seller_user', function (Blueprint $table) {
$table->string('seller_id')->index();
$table->integer('user_id')->unsigned()->index();
$table->primary(['seller_id', 'user_id']);
$table->foreign('seller_id')->references('id')->on('sellers')
->onUpdate('cascade')->onDelete('cascade');
$table->foreign('user_id')->references('id')->on('users')
->onUpdate('cascade')->onDelete('cascade');
$table->integer('value')->nullable();
$table->timestamps();
});
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
Schema::create('videos', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
Schema::create('tags', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
Schema::create('taggables', function (Blueprint $table) {
$table->unsignedInteger('tag_id');
$table->unsignedInteger('taggable_id');
$table->string('taggable_type');
$table->integer('value')->nullable();
$table->integer('value2')->nullable();
});
}
/**
* Reverse the migrations.
*/
public function down()
{
Schema::drop('role_user');
Schema::drop('user_seller');
Schema::drop('users');
Schema::drop('roles');
Schema::drop('sellers');
Schema::drop('posts');
Schema::drop('videos');
Schema::drop('tags');
Schema::drop('taggables');
}
}
| php | MIT | aeeceb7672c2ac359472fedba75349710572e72f | 2026-01-05T04:46:21.677391Z | false |
fuko-php/masked | https://github.com/fuko-php/masked/blob/fd2e3c173e249da0ead4088428083fe0be74b626/src/Masked/Redact.php | src/Masked/Redact.php | <?php /**
* Fuko\Masked: uncover and mask sensitive data
*
* @category Fuko
* @package Fuko\Masked
*
* @author Kaloyan Tsvetkov (KT) <kaloyan@kaloyan.info>
* @link https://github.com/fuko-php/masked/
* @license https://opensource.org/licenses/MIT
*/
namespace Fuko\Masked;
use InvalidArgumentException;
use const FILTER_SANITIZE_FULL_SPECIAL_CHARS;
use function abs;
use function array_unshift;
use function call_user_func_array;
use function filter_var;
use function is_callable;
use function round;
use function mb_strlen;
use function str_repeat;
use function mb_substr;
/**
* Masks sensitive data: replaces blacklisted elements with redacted values
*
* @package Fuko\Masked
*/
class Redact
{
/**
* @var array callback used in {@link Fuko\Masked\Redact::redact()};
* format is actually an array with two elements, first being
* the actual callback, and the second being an array with any
* extra arguments that are needed.
*/
protected static $redactCallback = array(
array(__CLASS__, 'disguise'),
array(0, '█')
);
/**
* Redacts provided string by masking it
*
* @param string $value
* @return string
*/
public static function redact($value)
{
$args = self::$redactCallback[1];
array_unshift($args, $value);
return call_user_func_array(
self::$redactCallback[0],
$args
);
}
/**
* Set a new callback to be used by {@link Fuko\Masked\Redact::redact()}
*
* First callback argument will be the value that needs to be
* masked/redacted; optionally you can provide more $arguments
*
* @param callable $callback
* @param array $arguments (optional) extra arguments for the callback
* @throws \InvalidArgumentException
*/
public static function setRedactCallback($callback, array $arguments = null)
{
if (!is_callable($callback))
{
throw new InvalidArgumentException(
'First argument to '
. __METHOD__
. '() must be a valid callback'
);
}
self::$redactCallback = array(
$callback,
!empty($arguments)
? array_values($arguments)
: array()
);
}
/**
* Get a masked version of a string
*
* This is the default callback used by {@link Fuko\Masked\Redact::redact()}
*
* @param string $value
* @param integer $unmaskedChars number of chars to mask; having
* positive number will leave the unmasked symbols at the
* end of the value; using negative number will leave the
* unmasked chars at the start of the value
* @param string $maskSymbol
* @return string
*/
public static function disguise($value, $unmaskedChars = 4, $maskSymbol = '*')
{
$value = filter_var($value, FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$unmaskedChars = (int) $unmaskedChars;
$maskSymbol = filter_var($maskSymbol, FILTER_SANITIZE_FULL_SPECIAL_CHARS);
// not enough chars to unmask ?
//
if (abs($unmaskedChars) >= mb_strlen($value))
{
$unmaskedChars = 0;
}
// at least half must be masked ?
//
if (abs($unmaskedChars) > mb_strlen($value)/2)
{
$unmaskedChars = round($unmaskedChars/2);
}
// leading unmasked chars
//
if ($unmaskedChars < 0)
{
$unmasked = mb_substr($value, 0, -$unmaskedChars);
return $unmasked . str_repeat($maskSymbol,
mb_strlen($value) - mb_strlen($unmasked)
);
}
// trailing unmasked chars
//
$unmasked = $unmaskedChars
? mb_substr($value, -$unmaskedChars)
: '';
return str_repeat($maskSymbol,
mb_strlen($value) - mb_strlen($unmasked)
) . $unmasked;
}
}
| php | MIT | fd2e3c173e249da0ead4088428083fe0be74b626 | 2026-01-05T04:46:32.600454Z | false |
fuko-php/masked | https://github.com/fuko-php/masked/blob/fd2e3c173e249da0ead4088428083fe0be74b626/src/Masked/InputCollection.php | src/Masked/InputCollection.php | <?php /**
* Fuko\Masked: uncover and mask sensitive data
*
* @category Fuko
* @package Fuko\Masked
*
* @author Kaloyan Tsvetkov (KT) <kaloyan@kaloyan.info>
* @link https://github.com/fuko-php/masked/
* @license https://opensource.org/licenses/MIT
*/
namespace Fuko\Masked;
use const FILTER_SANITIZE_STRING;
use const E_USER_WARNING;
use const INPUT_ENV;
use const INPUT_SERVER;
use const INPUT_COOKIE;
use const INPUT_GET;
use const INPUT_POST;
use const INPUT_SESSION;
use const INPUT_REQUEST;
use function array_keys;
use function define;
use function defined;
use function gettype;
use function filter_var;
use function in_array;
use function is_array;
use function is_callable;
use function is_object;
use function is_scalar;
use function sprintf;
use function strpos;
use function str_replace;
use function trigger_error;
if (!defined('INPUT_SESSION'))
{
define('INPUT_SESSION', 6);
}
if (!defined('INPUT_REQUEST'))
{
define('INPUT_REQUEST', 99);
}
/**
* Collects inputs for scanning to find values for redacting with {@link Fuko\Masked\Protect}
*
* @package Fuko\Masked
*/
class InputCollection
{
/**
* @var array default inputs to scan
*/
const DEFAULT_INPUTS = array(
INPUT_SERVER => array(
'PHP_AUTH_PW' => true
),
INPUT_POST => array(
'password' => true
),
);
/**
* @var array collection of inputs for scanning to find values for redacting
*/
protected $hideInputs = self::DEFAULT_INPUTS;
/**
* Clear accumulated inputs to hide
*/
function clearInputs()
{
$this->hideInputs = self::DEFAULT_INPUTS;
}
/**
* Get list of accumulated inputs to hide
*
* @return array
*/
function getInputs()
{
return $this->hideInputs;
}
/**
* Get the actual input values to hide
*
* @return array
*/
function getInputsValues()
{
$hideInputValues = array();
foreach ($this->hideInputs as $type => $inputs)
{
// the input names are the keys
//
foreach (array_keys($inputs) as $name)
{
$input = $this->filterInput($type, $name);
if (!$input)
{
continue;
}
$hideInputValues[] = $input;
}
}
return $hideInputValues;
}
/**
* Gets a specific external variable by name and filter it as a string
*
* @param integer $type input type, must be one of INPUT_REQUEST,
* INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SESSION,
* INPUT_SERVER or INPUT_ENV
* @param string $name name of the input variable to get
* @return string
*/
protected function filterInput($type, $name)
{
switch ($type)
{
case INPUT_ENV :
return !empty($_ENV)
? $this->filterInputVar($_ENV, $name)
: '';
case INPUT_SERVER :
return !empty($_SERVER)
? $this->filterInputVar($_SERVER, $name)
: '';
case INPUT_COOKIE :
return !empty($_COOKIE)
? $this->filterInputVar($_COOKIE, $name)
: '';
case INPUT_GET :
return !empty($_GET)
? $this->filterInputVar($_GET, $name)
: '';
case INPUT_POST :
return !empty($_POST)
? $this->filterInputVar($_POST, $name)
: '';
case INPUT_SESSION :
return !empty($_SESSION)
? $this->filterInputVar($_SESSION, $name)
: '';
case INPUT_REQUEST :
return !empty($_REQUEST)
? $this->filterInputVar($_REQUEST, $name)
: '';
}
return '';
}
/**
* Filters a variable as a string
*
* @param array $input
* @param string $name name of the input variable to get
* @return string
*/
protected function filterInputVar(array $input, $name)
{
if (empty($input[$name]))
{
return '';
}
return filter_var(
$input[$name],
FILTER_SANITIZE_STRING
);
}
/**
* Introduce new inputs to hide
*
* @param array $inputs array keys are input types(INPUT_REQUEST,
* INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SESSION,
* INPUT_SERVER, INPUT_ENV), array values are arrays with
* input names
*/
function hideInputs(array $inputs)
{
foreach ($inputs as $type => $names)
{
if (empty($names))
{
trigger_error('Fuko\Masked\Protect::hideInputs'
. '() empty input names for "'
. $type . '" input type',
E_USER_WARNING
);
continue;
}
if (is_scalar($names))
{
$names = array(
$names
);
}
if (!is_array($names))
{
trigger_error('Fuko\Masked\Protect::hideInputs'
. '() input names must be string or array, '
. gettype($names) . ' provided instead',
E_USER_WARNING
);
continue;
}
foreach ($names as $name)
{
$this->addInput($name, $type, 'Fuko\Masked\Protect::hideInputs');
}
}
}
/**
* Introduce a new input to hide
*
* @param string $name input name, e.g. "password" if you are
* targeting $_POST['password']
* @param integer $type input type, must be one of these: INPUT_REQUEST,
* INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SESSION, INPUT_SERVER,
* INPUT_ENV; default value is INPUT_REQUEST
* @return boolean|NULL TRUE if added, FALSE if wrong
* name or type, NULL if already added
*/
function hideInput($name, $type = INPUT_REQUEST)
{
return $this->addInput($name, $type, 'Fuko\Masked\Protect::hideInput');
}
/**
* Validates input:
* - if $name is empty
* - if $name is scalar
* - if $type is scalar
* - if $type is one of these: INPUT_REQUEST,
* INPUT_GET, INPUT_POST, INPUT_COOKIE,
* INPUT_SESSION, INPUT_SERVER, INPUT_ENV
* @param string $name
* @param integer $type
* @param string $method method to use to report the validation errors
* @return boolean
*/
protected function validateInput($name, &$type, $method)
{
if (empty($name))
{
trigger_error(
$method . '() $name argument is empty',
E_USER_WARNING
);
return false;
}
if (!is_scalar($name))
{
trigger_error(
$method . '() $name argument is not scalar, it is '
. gettype($name),
E_USER_WARNING
);
return false;
}
if (!is_scalar($type))
{
trigger_error(
$method . '() $type argument is not scalar, it is '
. gettype($type),
E_USER_WARNING
);
return false;
}
$type = (int) $type;
if (!in_array($type, array(
INPUT_REQUEST,
INPUT_GET,
INPUT_POST,
INPUT_COOKIE,
INPUT_SESSION,
INPUT_SERVER,
INPUT_ENV)))
{
$type = INPUT_REQUEST;
}
return true;
}
/**
* Add $input as of $type to the list of inputs to hide
*
* @param string $name input name, e.g. "password" if you are
* targeting $_POST['password']
* @param integer $type input type, must be one of these: INPUT_REQUEST,
* INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SESSION, INPUT_SERVER,
* INPUT_ENV; default value is INPUT_REQUEST
* @param string $method method to use to report the validation errors
* @return boolean|NULL TRUE if added, FALSE if wrong
* name or type, NULL if already added
*/
protected function addInput($name, $type, $method)
{
if (!$this->validateInput($name, $type, $method))
{
return false;
}
if (isset($this->hideInputs[$type][$name]))
{
return null;
}
return $this->hideInputs[$type][$name] = true;
}
}
| php | MIT | fd2e3c173e249da0ead4088428083fe0be74b626 | 2026-01-05T04:46:32.600454Z | false |
fuko-php/masked | https://github.com/fuko-php/masked/blob/fd2e3c173e249da0ead4088428083fe0be74b626/src/Masked/ValueCollection.php | src/Masked/ValueCollection.php | <?php /**
* Fuko\Masked: uncover and mask sensitive data
*
* @category Fuko
* @package Fuko\Masked
*
* @author Kaloyan Tsvetkov (KT) <kaloyan@kaloyan.info>
* @link https://github.com/fuko-php/masked/
* @license https://opensource.org/licenses/MIT
*/
namespace Fuko\Masked;
use const E_USER_WARNING;
use function gettype;
use function in_array;
use function is_array;
use function is_callable;
use function is_object;
use function is_scalar;
use function sprintf;
use function trigger_error;
/**
* Collects values to uncover and mask with {@link Fuko\Masked\Protect}
*
* @package Fuko\Masked
*/
class ValueCollection
{
/**
* @var array collection of values to hide redacting
*/
protected $hideValues = array();
/**
* Get the collected values to hide
*
* @return array
*/
function getValues()
{
return $this->hideValues;
}
/**
* Clear accumulated values to hide
*/
function clearValues()
{
$this->hideValues = array();
}
/**
* Introduce new values to hide
*
* @param array $values array with values of scalars or
* objects that have __toString() methods
*/
function hideValues(array $values)
{
foreach ($values as $k => $value)
{
$this->addValue(
$value, 'Fuko\Masked\Protect::hideValues'
. '() received %s as a hide value (key "'
. $k . '" of the $values argument)');
}
}
/**
* Introduce a new value to hide
*
* @param mixed $value scalar values (strings, numbers)
* or objects with __toString() method added
* @return boolean|NULL TRUE if added, FALSE if wrong
* type, NULL if already added
*/
function hideValue($value)
{
return $this->addValue(
$value,
'Fuko\Masked\Protect::hideValue() received %s as a hide value'
);
}
/**
* Validate $value:
* - check if it is empty,
* - if it is string or if an object with __toString() method
* @param mixed $value
* @param string $error error message placeholder
* @return boolean
*/
protected function validateValue($value, $error)
{
if (empty($value))
{
$wrongType = 'an empty value';
} else
if (is_scalar($value))
{
$wrongType = '';
} else
if (is_array($value))
{
$wrongType = 'an array';
} else
if (is_object($value))
{
$wrongType = !is_callable(array($value, '__toString'))
? 'an object'
: '';
} else
{
/* resources ? */
$wrongType = 'unexpected type (' . (string) $value . ')';
}
if ($wrongType)
{
trigger_error(
sprintf($error, $wrongType),
E_USER_WARNING
);
return false;
}
return true;
}
/**
* Add $value to the list of values to hide
*
* @param mixed $value
* @param string $error error message placeholder
* @return boolean|NULL TRUE if added, FALSE if wrong
* type, NULL if already added
*/
protected function addValue($value, $error = '%s')
{
if (!$this->validateValue($value, $error))
{
return false;
}
if (in_array($value, $this->hideValues))
{
return null;
}
$this->hideValues[] = $value;
return true;
}
}
| php | MIT | fd2e3c173e249da0ead4088428083fe0be74b626 | 2026-01-05T04:46:32.600454Z | false |
fuko-php/masked | https://github.com/fuko-php/masked/blob/fd2e3c173e249da0ead4088428083fe0be74b626/src/Masked/Protect.php | src/Masked/Protect.php | <?php /**
* Fuko\Masked: uncover and mask sensitive data
*
* @category Fuko
* @package Fuko\Masked
*
* @author Kaloyan Tsvetkov (KT) <kaloyan@kaloyan.info>
* @link https://github.com/fuko-php/masked/
* @license https://opensource.org/licenses/MIT
*/
namespace Fuko\Masked;
use Fuko\Masked\InputCollection;
use Fuko\Masked\ValueCollection;
use const FILTER_DEFAULT;
use function filter_var;
use function is_array;
use function is_object;
use function is_scalar;
use function strpos;
use function str_replace;
/**
* Protect sensitive data and redacts it using {@link Fuko\Masked\Redact::redact()}
*
* @package Fuko\Masked
*/
final class Protect
{
/**
* @var ValueCollection collection of values to hide redacting
*/
private static $hideValueCollection;
/**
* Clear accumulated values to hide
*/
static function clearValues()
{
if (!empty(self::$hideValueCollection))
{
self::$hideValueCollection->clearValues();
}
}
/**
* Introduce new values to hide
*
* @param array $values array with values of scalars or
* objects that have __toString() methods
*/
static function hideValues(array $values)
{
(self::$hideValueCollection
?? (self::$hideValueCollection =
new ValueCollection))->hideValues($values);
}
/**
* Introduce a new value to hide
*
* @param mixed $value scalar values (strings, numbers)
* or objects with __toString() method added
* @return boolean|NULL TRUE if added, FALSE if wrong
* type, NULL if already added
*/
static function hideValue($value)
{
return (self::$hideValueCollection
?? (self::$hideValueCollection =
new ValueCollection))->hideValue($value);
}
/////////////////////////////////////////////////////////////////////
/**
* @var InputCollection collection of inputs for scanning to find
* values for redacting
*/
private static $hideInputCollection;
/**
* Clear accumulated inputs to hide
*/
static function clearInputs()
{
if (!empty(self::$hideInputCollection))
{
self::$hideInputCollection->clearInputs();
}
}
/**
* Introduce new inputs to hide
*
* @param array $inputs array keys are input types(INPUT_REQUEST,
* INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SESSION,
* INPUT_SERVER, INPUT_ENV), array values are arrays with
* input names
*/
static function hideInputs(array $inputs)
{
(self::$hideInputCollection
?? (self::$hideInputCollection =
new InputCollection))->hideInputs($inputs);
}
/**
* Introduce a new input to hide
*
* @param string $name input name, e.g. "password" if you are
* targeting $_POST['password']
* @param integer $type input type, must be one of these: INPUT_REQUEST,
* INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SESSION, INPUT_SERVER,
* INPUT_ENV; default value is INPUT_REQUEST
* @return boolean|NULL TRUE if added, FALSE if wrong
* name or type, NULL if already added
*/
static function hideInput($name, $type = INPUT_REQUEST)
{
return (self::$hideInputCollection
?? (self::$hideInputCollection =
new InputCollection))->hideInput($name, $type);
}
/////////////////////////////////////////////////////////////////////
/**
* Protects a variable by replacing sensitive data inside it
*
* @param mixed $var only strings and arrays will be processed,
* objects will be "stringified", other types (resources?)
* will be returned as empty strings
* @return string|array
*/
static function protect($var)
{
if (is_scalar($var))
{
return self::protectScalar($var);
} else
if (is_array($var))
{
foreach ($var as $k => $v)
{
$var[$k] = self::protect($v);
}
return $var;
} else
if (is_object($var))
{
return self::protectScalar(
filter_var($var, FILTER_DEFAULT)
);
} else
{
return '';
}
}
/**
* Protects a scalar value by replacing sensitive data inside it
*
* @param string $var
* @return string
*/
static function protectScalar($var)
{
// hide values
//
if (!empty(self::$hideValueCollection))
{
if ($hideValues = self::$hideValueCollection->getValues())
{
$var = self::_redact($var, $hideValues);
}
}
// hide inputs
//
$hideInputValues = array();
if (!empty(self::$hideInputCollection))
{
$hideInputValues = self::$hideInputCollection->getInputsValues();
if (!empty($hideInputValues))
{
$var = self::_redact($var, $hideInputValues);
}
}
return $var;
}
/**
* Redacts $values inside the $var string
* @param string $var
* @param array $values
* @return string
*/
private static function _redact($var, array $values)
{
foreach ($values as $value)
{
$value = (string) $value;
if (false === strpos($var, $value))
{
continue;
}
$var = str_replace($value, Redact::redact($value), $var);
}
return $var;
}
}
| php | MIT | fd2e3c173e249da0ead4088428083fe0be74b626 | 2026-01-05T04:46:32.600454Z | false |
fuko-php/masked | https://github.com/fuko-php/masked/blob/fd2e3c173e249da0ead4088428083fe0be74b626/tests/Masked/ProtectHideValuesTest.php | tests/Masked/ProtectHideValuesTest.php | <?php
namespace Fuko\Masked\Tests;
use Fuko\Masked\Protect;
use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\Error\Warning;
class ProtectHideValuesTest extends TestCase
{
function tearDown(): void
{
Protect::clearValues();
}
/**
* @covers Fuko\Masked\Protect::hideValue
*/
function test_hideValue()
{
$this->assertTrue(Protect::hideValue('password'));
$this->assertNull(Protect::hideValue('password'));
$this->assertTrue(Protect::hideValue($this));
}
function __toString(): string
{
return self::class;
}
/**
* @dataProvider provider_hideValue_empty
* @covers Fuko\Masked\Protect::hideValue
*/
function test_hideValue_empty($value)
{
$this->expectException(Warning::class);
$this->expectExceptionMessage(
'Fuko\Masked\Protect::hideValue() received an empty value as a hide value'
);
Protect::hideValue($value);
}
function provider_hideValue_empty()
{
return array(
array(''),
array(0),
array(null),
array(array()),
);
}
/**
* @covers Fuko\Masked\Protect::hideValue
*/
function test_hideValue_array()
{
$this->expectException(Warning::class);
$this->expectExceptionMessage(
'Fuko\Masked\Protect::hideValue() received an array as a hide value'
);
Protect::hideValue($_SERVER);
}
/**
* @covers Fuko\Masked\Protect::hideValue
*/
function test_hideValue_object()
{
$this->expectException(Warning::class);
$this->expectExceptionMessage(
'Fuko\Masked\Protect::hideValue() received an object as a hide value'
);
Protect::hideValue((object) $_SERVER);
}
/**
* @covers Fuko\Masked\Protect::hideValue
*/
function test_hideValue_other()
{
$this->expectException(Warning::class);
$this->expectExceptionMessageMatches(
'~^Fuko\\\\Masked\\\\Protect\:\:hideValue\(\) received unexpected type \(Resource id #\d+\) as a hide value$~'
);
Protect::hideValue(opendir(__DIR__));
}
/**
* @covers Fuko\Masked\Protect::hideValues
*/
function test_hideValues_emptyString()
{
$this->expectException(Warning::class);
$this->expectExceptionMessage(
'Fuko\Masked\Protect::hideValues() received an empty value as a hide value (key "1" of the $values argument)'
);
Protect::hideValues( array('password', '') );
}
/**
* @covers Fuko\Masked\Protect::hideValues
*/
function test_hideValues_emptyArray()
{
$this->expectException(Warning::class);
$this->expectExceptionMessage(
'Fuko\Masked\Protect::hideValues() received an empty value as a hide value (key "0" of the $values argument)'
);
Protect::hideValues( array(array()) );
}
/**
* @covers Fuko\Masked\Protect::hideValues
*/
function test_hideValues_Zero()
{
$this->expectException(Warning::class);
$this->expectExceptionMessage(
'Fuko\Masked\Protect::hideValues() received an empty value as a hide value (key "4" of the $values argument)'
);
Protect::hideValues( array(1,2,3,4,0) );
}
/**
* @covers Fuko\Masked\Protect::hideValues
*/
function test_hideValues_Null()
{
$this->expectException(Warning::class);
$this->expectExceptionMessage(
'Fuko\Masked\Protect::hideValues() received an empty value as a hide value (key "0" of the $values argument)'
);
Protect::hideValues( array(null, 'null') );
}
/**
* @covers Fuko\Masked\Protect::hideValues
*/
function test_hideValues_withArray()
{
$this->expectException(Warning::class);
$this->expectExceptionMessage(
'Fuko\Masked\Protect::hideValues() received an array as a hide value (key "0" of the $values argument)'
);
Protect::hideValues( array($_SERVER) );
}
/**
* @covers Fuko\Masked\Protect::hideValues
*/
function test_hideValues_withObject()
{
$this->expectException(Warning::class);
$this->expectExceptionMessage(
'Fuko\Masked\Protect::hideValues() received an object as a hide value (key "0" of the $values argument)'
);
Protect::hideValues( array( (object) $_SERVER) );
}
/**
* @covers Fuko\Masked\Protect::hideValues
*/
function test_hideValues_withOther()
{
$this->expectException(Warning::class);
$this->expectExceptionMessageMatches(
'~^Fuko\\\\Masked\\\\Protect\:\:hideValues\(\) received unexpected type \(Resource id #\d+\) as a hide value \(key "0" of the \$values argument\)$~'
);
Protect::hideValues(array(opendir(__DIR__)));
}
}
| php | MIT | fd2e3c173e249da0ead4088428083fe0be74b626 | 2026-01-05T04:46:32.600454Z | false |
fuko-php/masked | https://github.com/fuko-php/masked/blob/fd2e3c173e249da0ead4088428083fe0be74b626/tests/Masked/ProtectValueTest.php | tests/Masked/ProtectValueTest.php | <?php
namespace Fuko\Masked\Tests;
use Fuko\Masked\Protect;
use Fuko\Masked\Redact;
use PHPUnit\Framework\TestCase;
class ProtectValueTest extends TestCase
{
function tearDown(): void
{
Protect::clearValues();
}
/**
* @dataProvider provider_protect_value
* @covers Fuko\Masked\Protect::protect
* @covers Fuko\Masked\Protect::protectScalar
*/
function test_protect_value($haystack, $needle, $redacted)
{
is_scalar($needle)
? Protect::hideValue($needle)
: Protect::hideValues($needle);
$this->assertEquals(
Protect::protect($haystack),
$redacted
);
}
function provider_protect_value()
{
return array(
array(
'This is my password!',
'password',
'This is my ████████!'
),
array(
'His name is John Doe and he is a spy',
array('Doe', 'John'),
'His name is ████ ███ and he is a spy'
),
array(
'I\'ve had it with these motherfucking snakes on this motherfucking plane!',
'fuck',
'I\'ve had it with these mother████ing snakes on this mother████ing plane!'
),
array(
'Your username is "condor" and your password is "NewmanSucks!"',
array('NewmanSucks!', 'condor'),
'Your username is "██████" and your password is "████████████"'
),
array(
array(),
array(),
array()
),
array(
array('password' => 'RedfordRulz!'),
'RedfordRulz!',
array('password' => '████████████')
),
array(
array(
'first' => 'Robert',
'last' => 'Redford',
'password' => 'RedfordRulz!',
'email' => 'bobby@sundance.org',
),
'RedfordRulz!',
array(
'first' => 'Robert',
'last' => 'Redford',
'password' => '████████████',
'email' => 'bobby@sundance.org',
)
),
);
}
function test_protect_backtrace()
{
Protect::hideValue($username = 'u53rn4m3');
Protect::hideValue($password = 'P422wOrd');
$dummy = $this->uno($username, $password);
$this->assertBacktrace(
var_export(Protect::protect($dummy), true),
$username,
$password);
}
function assertBacktrace($redacted, $username, $password)
{
$this->assertFalse(
strpos($redacted, $username)
);
$this->assertFalse(
strpos($redacted, $password)
);
$this->assertIsInt(
strpos($redacted, Redact::redact( $username ))
);
$this->assertIsInt(
strpos($redacted, Redact::redact( $password ))
);
}
function uno($username, $password)
{
return $this->due($username, $password);
}
function due($username, $password)
{
unset($username, $password);
return debug_backtrace();
}
}
| php | MIT | fd2e3c173e249da0ead4088428083fe0be74b626 | 2026-01-05T04:46:32.600454Z | false |
fuko-php/masked | https://github.com/fuko-php/masked/blob/fd2e3c173e249da0ead4088428083fe0be74b626/tests/Masked/ValueCollectionTest.php | tests/Masked/ValueCollectionTest.php | <?php
namespace Fuko\Masked\Tests;
use Fuko\Masked\ValueCollection;
use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\Error\Warning;
class ValueCollectionTest extends TestCase
{
/**
* @covers Fuko\Masked\ValueCollection::hideValue()
*/
function testHideEmptyValue()
{
$this->expectException(Warning::class);
$this->expectExceptionMessage('Fuko\Masked\Protect::hideValue() received an empty value as a hide value');
$c = new ValueCollection;
$c->hideValue([]);
}
/**
* @covers Fuko\Masked\ValueCollection::hideValue()
*/
function testHideEmptyString()
{
$this->expectException(Warning::class);
$this->expectExceptionMessage('Fuko\Masked\Protect::hideValue() received an empty value as a hide value');
$c = new ValueCollection;
$c->hideValue('');
}
/**
* @covers Fuko\Masked\ValueCollection::hideValue()
*/
function testHideArray()
{
$this->expectException(Warning::class);
$this->expectExceptionMessage('Fuko\Masked\Protect::hideValue() received an array as a hide value');
$c = new ValueCollection;
$c->hideValue([123, 234]);
}
/**
* @covers Fuko\Masked\ValueCollection::hideValue()
*/
function testHideStdClass()
{
$this->expectException(Warning::class);
$this->expectExceptionMessage('Fuko\Masked\Protect::hideValue() received an object as a hide value');
$c = new ValueCollection;
$c->hideValue( (object) ['a' => 123] );
}
/**
* @covers Fuko\Masked\ValueCollection::hideValue()
* @covers Fuko\Masked\ValueCollection::getValues()
*/
function testHideException()
{
$c = new ValueCollection;
$this->assertTrue( $c->hideValue( $e = new \Exception ) );
$this->assertEquals( $c->getValues(), [$e->__toString()] );
}
/**
* @covers Fuko\Masked\ValueCollection::hideValue()
*/
function testHideFileHandler()
{
$this->expectException(Warning::class);
$this->expectExceptionMessageMatches(
'~^Fuko\\\\Masked\\\\Protect\:\:hideValue\(\) received unexpected type \(Resource id #\d+\) as a hide value$~'
);
$c = new ValueCollection;
$c->hideValue( fopen(__FILE__, 'r') );
}
/**
* @covers Fuko\Masked\ValueCollection::hideValue()
* @covers Fuko\Masked\ValueCollection::getValues()
*/
function testHideDuplicateValue()
{
$c = new ValueCollection;
$this->assertTrue( $c->hideValue( 'secret' ) );
$this->assertNull( $c->hideValue( 'secret' ) );
$this->assertEquals( $c->getValues(), ['secret'] );
}
/**
* @covers Fuko\Masked\ValueCollection::hideValues()
*/
function testHideEmptyValues()
{
$this->expectException(Warning::class);
$this->expectExceptionMessage(
'Fuko\Masked\Protect::hideValues() received an empty value as a hide value (key "0" of the $values argument)'
);
$c = new ValueCollection;
$c->hideValues( [''] );
}
/**
* @covers Fuko\Masked\ValueCollection::hideValues()
* @covers Fuko\Masked\ValueCollection::getValues()
* @covers Fuko\Masked\ValueCollection::clearValues()
*/
function testHideValues()
{
$c = new ValueCollection;
$c->hideValues( $hide = ['secret', 'parola'] );
$this->assertEquals( $c->getValues(), $hide );
$c->clearValues();
$this->assertEquals( $c->getValues(), [] );
}
}
| php | MIT | fd2e3c173e249da0ead4088428083fe0be74b626 | 2026-01-05T04:46:32.600454Z | false |
fuko-php/masked | https://github.com/fuko-php/masked/blob/fd2e3c173e249da0ead4088428083fe0be74b626/tests/Masked/ProtectInputTest.php | tests/Masked/ProtectInputTest.php | <?php
namespace Fuko\Masked\Tests;
use Fuko\Masked\Protect;
use Fuko\Masked\Redact;
use PHPUnit\Framework\TestCase;
use const INPUT_POST;
use const INPUT_SERVER;
use const INPUT_SESSION;
if (!defined('INPUT_SESSION'))
{
define('INPUT_SESSION', 6);
}
use function strpos;
use function var_export;
class ProtectInputTest extends TestCase
{
function tearDown(): void
{
Protect::clearInputs();
}
/**
* @dataProvider provider_protect_input
* @covers Fuko\Masked\Protect::protect
* @covers Fuko\Masked\Protect::protectScalar
*/
function test_protect_input($name, $type, array $input)
{
Protect::hideInput($name, $type);
$this->assertProtected($name, $input);
}
function assertProtected($name, array $input)
{
$redacted = var_export(Protect::protect($input), true);
$this->assertFalse(
strpos($redacted, $input[$name])
);
$this->assertIsInt(
strpos($redacted, Redact::redact( $input[$name] ))
);
}
function provider_protect_input()
{
return array(
array('PHP_SELF', INPUT_SERVER, $_SERVER),
array('USER', INPUT_SERVER, $_SERVER),
array('user_id', INPUT_SESSION, $_SESSION = array(
'user_id' => 4918,
'name' => 'Waldo Pepper',
)),
array('password', INPUT_POST, $_POST = array(
'username' => 'Martin.Bishop',
'password' => 'Martin.Brice!',
)),
);
}
function test_protect_default_input()
{
$_SERVER['PHP_AUTH_PW'] = 'Joseph.Turner!';
$this->assertProtected('PHP_AUTH_PW', $_SERVER);
}
}
| php | MIT | fd2e3c173e249da0ead4088428083fe0be74b626 | 2026-01-05T04:46:32.600454Z | false |
fuko-php/masked | https://github.com/fuko-php/masked/blob/fd2e3c173e249da0ead4088428083fe0be74b626/tests/Masked/setRedactCallbackTest.php | tests/Masked/setRedactCallbackTest.php | <?php
namespace Fuko\Masked\Tests;
use Fuko\Masked\Redact;
use PHPUnit\Framework\TestCase;
use InvalidArgumentException;
use function strlen;
class setRedactCallbackTest extends TestCase
{
function tearDown(): void
{
Redact::setRedactCallback(
array(Redact::class, 'disguise'),
array(0, '█')
);
}
protected $mask_flag = false;
function mask_even($value, $symbol)
{
for ($i = 0; $i < strlen($value); $i++)
{
if ($i%2)
{
$value[ $i ] = $symbol;
}
}
$this->mask_flag = true;
return $value;
}
/**
* @covers Fuko\Masked\Redact::setRedactCallback
* @covers Fuko\Masked\Redact::redact
*/
function test_mask()
{
Redact::setRedactCallback(
array($this, 'mask_even'),
array('-')
);
$this->mask_flag = false;
$this->assertEquals(
Redact::redact('12345'),
'1-3-5'
);
$this->assertTrue($this->mask_flag);
}
function dudu()
{
return '💩';
}
/**
* @covers Fuko\Masked\Redact::setRedactCallback
* @covers Fuko\Masked\Redact::redact
*/
function test_dudu()
{
Redact::setRedactCallback(
array($this, 'dudu'),
array('-')
);
$this->assertEquals(
Redact::redact('12345'),
'💩'
);
}
/**
* @covers Fuko\Masked\Redact::setRedactCallback
*/
function test_setRedactUnknownCallback()
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage(
'First argument to Fuko\Masked\Redact::setRedactCallback() must be a valid callback'
);
Redact::setRedactCallback(
array($this, '_')
);
}
private function poop() {}
/**
* @covers Fuko\Masked\Redact::setRedactCallback
*/
function test_setRedactPrivateCallback()
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage(
'First argument to Fuko\Masked\Redact::setRedactCallback() must be a valid callback'
);
$this->poop();
Redact::setRedactCallback(
array($this, 'poop')
);
}
}
| php | MIT | fd2e3c173e249da0ead4088428083fe0be74b626 | 2026-01-05T04:46:32.600454Z | false |
fuko-php/masked | https://github.com/fuko-php/masked/blob/fd2e3c173e249da0ead4088428083fe0be74b626/tests/Masked/RedactTest.php | tests/Masked/RedactTest.php | <?php
namespace Fuko\Masked\Tests;
use Fuko\Masked\Redact;
use PHPUnit\Framework\TestCase;
class RedactTest extends TestCase
{
/**
* @dataProvider provider_disguise_masking
* @covers Fuko\Masked\Redact::redact
*/
function test_disguise_masking($source, $masked)
{
$this->assertEquals(
Redact::redact($source),
$masked
);
}
function provider_disguise_masking()
{
return array(
array(-123, '████'),
array(-1234, '█████'),
array(1234, '████'),
array(null, ''),
array('', ''),
array(0, '█'),
array(00, '█'),
array('41111111111111111', '█████████████████'),
array([], ''),
array((object) ['a' => 1], ''),
array($this, ''),
);
}
}
| php | MIT | fd2e3c173e249da0ead4088428083fe0be74b626 | 2026-01-05T04:46:32.600454Z | false |
fuko-php/masked | https://github.com/fuko-php/masked/blob/fd2e3c173e249da0ead4088428083fe0be74b626/tests/Masked/RedactDisguiseTest.php | tests/Masked/RedactDisguiseTest.php | <?php
namespace Fuko\Masked\Tests;
use Fuko\Masked\Redact;
use PHPUnit\Framework\TestCase;
class RedactDisguiseTest extends TestCase
{
/**
* @dataProvider provider_disguise_masking
* @covers Fuko\Masked\Redact::disguise
*/
function test_disguise_masking($source, $masked)
{
$this->assertEquals(
Redact::disguise($source),
$masked
);
}
function provider_disguise_masking()
{
return array(
array(-123, '****'),
array(-1234, '***34'),
array(1234, '****'),
array(null, ''),
array('', ''),
array(0, '*'),
array(00, '*'),
array('41111111111111111', '*************1111'),
array([], ''),
array((object) $_SERVER, ''),
array($this, ''),
);
}
/**
* @dataProvider provider_disguise_unmasked
* @covers Fuko\Masked\Redact::disguise
*/
function test_disguise_unmasked($source, $unmasked, $masked)
{
$this->assertEquals(
Redact::disguise($source, $unmasked),
$masked
);
}
function provider_disguise_unmasked()
{
return array(
array(1234, 0, '****'),
array(1234, 1, '***4'),
array(1234, 4, '****'),
array(1234, -1, '1***'),
array(1234, -4, '****'),
array(1234, 2/3, '****'),
array(1234, 1.9, '***4'),
array(1234, [], '****'),
);
}
/**
* @dataProvider provider_disguise_symbol
* @covers Fuko\Masked\Redact::disguise
*/
function test_disguise_symbol($source, $unmasked, $symbol, $masked)
{
$this->assertEquals(
Redact::disguise($source, $unmasked, $symbol),
$masked
);
}
function provider_disguise_symbol()
{
return array(
array('1234', 0, '█', '████'),
array('1234', 0, 'xX', 'xXxXxXxX'),
array('1234', 0, '', ''),
array('1234', 1, '', '4'),
array('1234', -1, '', '1'),
array('1234', -4, '', ''),
array('12345', 4, '', '45'),
array('12345', -4, '', '12'),
array('1234', 0, null, ''),
array('crap', 0, '💩', '💩💩💩💩'),
array('shit', 3, '💩', '💩💩it'),
array('shit', -2, '💩', 'sh💩💩'),
);
}
}
| php | MIT | fd2e3c173e249da0ead4088428083fe0be74b626 | 2026-01-05T04:46:32.600454Z | false |
fuko-php/masked | https://github.com/fuko-php/masked/blob/fd2e3c173e249da0ead4088428083fe0be74b626/tests/Masked/ProtectHideInputsTest.php | tests/Masked/ProtectHideInputsTest.php | <?php
namespace Fuko\Masked\Tests;
use Fuko\Masked\Protect;
use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\Error\Warning;
use const INPUT_COOKIE;
use const INPUT_POST;
use const INPUT_REQUEST;
use const INPUT_SESSION;
use function fopen;
use function opendir;
class ProtectHideInputsTest extends TestCase
{
function tearDown(): void
{
Protect::clearInputs();
}
/**
* @dataProvider provider_hideInput
* @covers Fuko\Masked\Protect::hideInput
*/
function test_hideInput($name, $type)
{
$this->assertTrue(
Protect::hideInput($name, $type)
);
}
function provider_hideInput()
{
return array(
array('clandestine', INPUT_POST),
array('incognito', 333),
array('OLDPWD', INPUT_ENV),
array('USER', INPUT_SERVER),
array('cipher', ''),
);
}
/**
* @covers Fuko\Masked\Protect::hideInput
*/
function test_hideInput_withEmptyName()
{
$this->expectException(Warning::class);
$this->expectExceptionMessage(
'Fuko\Masked\Protect::hideInput() $name argument is empty'
);
Protect::hideInput('', INPUT_SESSION);
}
/**
* @covers Fuko\Masked\Protect::hideInput
*/
function test_hideInput_withEmptyArray()
{
$this->expectException(Warning::class);
$this->expectExceptionMessage(
'Fuko\Masked\Protect::hideInput() $name argument is empty'
);
Protect::hideInput(array(), INPUT_REQUEST);
}
/**
* @covers Fuko\Masked\Protect::hideInput
*/
function test_hideInput_withNull()
{
$this->expectException(Warning::class);
$this->expectExceptionMessage(
'Fuko\Masked\Protect::hideInput() $name argument is empty'
);
Protect::hideInput(null, INPUT_COOKIE);
}
/**
* @covers Fuko\Masked\Protect::hideInput
*/
function test_hideInput_withObject()
{
$this->expectException(Warning::class);
$this->expectExceptionMessage(
'Fuko\Masked\Protect::hideInput() $name argument is not scalar, it is object'
);
Protect::hideInput($this, INPUT_POST);
}
/**
* @covers Fuko\Masked\Protect::hideInput
*/
function test_hideInput_withNullType()
{
$this->expectException(Warning::class);
$this->expectExceptionMessage(
'Fuko\Masked\Protect::hideInput() $type argument is not scalar, it is NULL'
);
Protect::hideInput('cipher', null);
}
/**
* @covers Fuko\Masked\Protect::hideInput
*/
function test_hideInput_withArrayType()
{
$this->expectException(Warning::class);
$this->expectExceptionMessage(
'Fuko\Masked\Protect::hideInput() $type argument is not scalar, it is array'
);
Protect::hideInput('cipher', array());
}
/**
* @covers Fuko\Masked\Protect::hideInput
*/
function test_hideInput_withObectType()
{
$this->expectException(Warning::class);
$this->expectExceptionMessage(
'Fuko\Masked\Protect::hideInput() $type argument is not scalar, it is object'
);
Protect::hideInput('cipher', $this);
}
/**
* @covers Fuko\Masked\Protect::hideInputs
*/
function test_hideInputs_withNullName()
{
$this->expectException(Warning::class);
$this->expectExceptionMessage(
'Fuko\Masked\Protect::hideInputs() empty input names for "44" input type'
);
Protect::hideInputs( array( 44 => null ) );
}
/**
* @covers Fuko\Masked\Protect::hideInputs
*/
function test_hideInputs_withNullInput()
{
$this->expectException(Warning::class);
$this->expectExceptionMessage(
'Fuko\Masked\Protect::hideInputs() empty input names for "0" input type'
);
Protect::hideInputs( array( null ) );
}
/**
* @covers Fuko\Masked\Protect::hideInputs
*/
function test_hideInputs_withEmptyString()
{
$this->expectException(Warning::class);
$this->expectExceptionMessage(
'Fuko\Masked\Protect::hideInputs() empty input names for "0" input type'
);
Protect::hideInputs( array( '' ) );
}
/**
* @covers Fuko\Masked\Protect::hideInputs
*/
function test_hideInputs_withObjectInput()
{
$this->expectException(Warning::class);
$this->expectExceptionMessage(
'Fuko\Masked\Protect::hideInputs() input names must be string or array, object provided instead'
);
Protect::hideInputs( array( 33 => (object) $_SERVER ) );
}
/**
* @covers Fuko\Masked\Protect::hideInputs
*/
function test_hideInputs_withOtherInput()
{
$this->expectException(Warning::class);
$this->expectExceptionMessage(
'Fuko\Masked\Protect::hideInputs() input names must be string or array, resource provided instead'
);
Protect::hideInputs( array(22 => fopen(__FILE__, 'r') ) );
}
/**
* @covers Fuko\Masked\Protect::hideInputs
*/
function test_hideInputs_withObjectInputName()
{
$this->expectException(Warning::class);
$this->expectExceptionMessage(
'Fuko\Masked\Protect::hideInputs() $name argument is not scalar, it is object'
);
Protect::hideInputs( array( 33 => array( (object) $_SERVER ) ) );
}
/**
* @covers Fuko\Masked\Protect::hideInputs
*/
function test_hideInputs_withOtherInputName()
{
$this->expectException(Warning::class);
$this->expectExceptionMessage(
'Fuko\Masked\Protect::hideInputs() $name argument is not scalar, it is resource'
);
Protect::hideInputs( array( 22 => array( opendir(__DIR__) ) ) );
}
}
| php | MIT | fd2e3c173e249da0ead4088428083fe0be74b626 | 2026-01-05T04:46:32.600454Z | false |
badges/poser | https://github.com/badges/poser/blob/f6f448e27bc676601ffcb9b378e6ce29edeb77a5/.php-cs-fixer.php | .php-cs-fixer.php | <?php
// see https://github.com/FriendsOfPHP/PHP-CS-Fixer
$finder = PhpCsFixer\Finder::create()
->in(__DIR__)
->exclude(['vendor'])
;
return (new PhpCsFixer\Config())
->setRiskyAllowed(true)
->setRules([
'@Symfony' => true,
'@Symfony:risky' => true,
'@PHP81Migration' => true,
'declare_strict_types' => false,
'native_function_invocation' => ['include' => ['@all']],
'concat_space' => ['spacing' => 'one'],
'binary_operator_spaces' => ['operators' => ['=>' => 'align', '=' => 'align']],
'phpdoc_align' => ['align' => 'vertical'],
'phpdoc_summary' => false,
'php_unit_test_annotation' => ['style' => 'annotation'],
])
->setFinder($finder)
;
| php | MIT | f6f448e27bc676601ffcb9b378e6ce29edeb77a5 | 2026-01-05T04:46:38.341609Z | false |
badges/poser | https://github.com/badges/poser/blob/f6f448e27bc676601ffcb9b378e6ce29edeb77a5/src/Image.php | src/Image.php | <?php
/*
* This file is part of the badge-poser package.
*
* (c) PUGX <http://pugx.github.io/>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PUGX\Poser;
/**
* Class Image, an Image value Object.
*
* @author Claudio D'Alicandro <claudio.dalicandro@gmail.com>
* @author Giulio De Donato <liuggio@gmail.com>
*/
class Image
{
private string $content;
private string $style;
private function __construct(string $content, string $style)
{
$this->content = $content;
$this->style = $style;
}
/**
* Returns the image content as binary string.
*/
public function __toString(): string
{
return $this->content;
}
/**
* Factory method.
*/
public static function createFromString(string $content, string $style): self
{
return new self($content, $style);
}
public function getStyle(): string
{
return $this->style;
}
}
| php | MIT | f6f448e27bc676601ffcb9b378e6ce29edeb77a5 | 2026-01-05T04:46:38.341609Z | false |
badges/poser | https://github.com/badges/poser/blob/f6f448e27bc676601ffcb9b378e6ce29edeb77a5/src/Poser.php | src/Poser.php | <?php
namespace PUGX\Poser;
use PUGX\Poser\Render\RenderInterface;
class Poser
{
private array $renders;
/**
* Constructor.
*/
public function __construct(array $renders)
{
$this->renders = [];
foreach ($renders as $render) {
$this->addStyleRender($render);
}
}
/**
* Generate and Render a badge according to the style.
*/
public function generate(string $subject, string $status, string $color, string $style, string $format = Badge::DEFAULT_FORMAT): Image
{
$badge = new Badge($subject, $status, $color, $style, $format);
return $this->getRenderFor($badge->getStyle())->render($badge);
}
/**
* Generate and Render a badge according to the format from an URI,
* eg license-MIT-blue.svg or I_m-liuggio-yellow.svg.
*/
public function generateFromURI(string $string): Image
{
$badge = Badge::fromURI($string);
return $this->getRenderFor($badge->getStyle())->render($badge);
}
/**
* All the styles available.
*/
public function validStyles(): array
{
return \array_keys($this->renders);
}
private function addStyleRender(RenderInterface $render): void
{
$this->renders[$render->getBadgeStyle()] = $render;
}
private function getRenderFor(string $style): RenderInterface
{
if (!isset($this->renders[$style])) {
throw new \InvalidArgumentException(\sprintf('No render founds for this style [%s]', $style));
}
return $this->renders[$style];
}
}
| php | MIT | f6f448e27bc676601ffcb9b378e6ce29edeb77a5 | 2026-01-05T04:46:38.341609Z | false |
badges/poser | https://github.com/badges/poser/blob/f6f448e27bc676601ffcb9b378e6ce29edeb77a5/src/Badge.php | src/Badge.php | <?php
namespace PUGX\Poser;
class Badge
{
public const DEFAULT_STYLE = 'flat';
public const DEFAULT_FORMAT = 'svg';
private static array $colorScheme = [
'brightgreen' => '44cc11',
'green' => '97ca00',
'yellowgreen' => 'a4a61d',
'yellow' => 'dfb317',
'orange' => 'fe7d37',
'red' => 'e05d44',
'blue' => '007ec6',
'lightgray' => '9f9f9f',
'lightgrey' => '9f9f9f',
'gray' => '555555',
'grey' => '555555',
'blueviolet' => '8a2be2',
'success' => '97ca00',
'important' => 'fe7d37',
'critical' => 'e05d44',
'informational' => '007ec6',
'inactive' => '9f9f9f',
];
private string $subject;
private string $status;
private string $color;
private string $style;
private string $format;
public function __construct(string $subject, string $status, string $color, string $style = self::DEFAULT_STYLE, string $format = self::DEFAULT_FORMAT)
{
$this->subject = $this->escapeValue($subject);
$this->status = $this->escapeValue($status);
$this->color = $this->getColorHex($color);
$this->style = $this->escapeValue($style);
$this->format = $this->escapeValue($format);
if (!$this->isValidColorHex($this->color)) {
throw new \InvalidArgumentException(\sprintf('Color not valid %s', $this->color));
}
}
/**
* An array of the color names available.
*/
public static function getColorNamesAvailable(): array
{
return \array_keys(self::$colorScheme);
}
/**
* Factory method the creates a Badge from an URI
* eg. I_m-liuggio-yellow.svg.
*
* @throws \InvalidArgumentException
*/
public static function fromURI(string $URI): self
{
$parsedURI = \parse_url($URI);
if (!isset($parsedURI['path'])) {
throw new \InvalidArgumentException('The URI given is not a valid URI' . $URI);
}
$path = $parsedURI['path'];
\parse_str($parsedURI['query'] ?? '', $query);
$regex = '/^(([^-]|--)+)-(([^-]|--)+)-(([^-.]|--)+)(\.(svg|png|gif|jpg))?$/';
$match = [];
if (1 !== \preg_match($regex, $path, $match) && (6 > \count($match))) {
throw new \InvalidArgumentException('The URI given is not a valid URI' . $URI);
}
$subject = $match[1];
$status = $match[3];
$color = $match[5];
$style = isset($query['style']) && '' !== $query['style'] ? $query['style'] : self::DEFAULT_STYLE;
$format = $match[8] ?? self::DEFAULT_FORMAT;
return new self($subject, $status, $color, $style, $format);
}
/**
* @return string the Hexadecimal #FFFFFF
*/
public function getHexColor(): string
{
return '#' . $this->color;
}
/**
* @return string the style of the image eg. `flat`.
*/
public function getStyle(): string
{
return $this->style;
}
/**
* @return string the format of the image eg. `svg`.
*/
public function getFormat(): string
{
return $this->format;
}
public function getStatus(): string
{
return $this->status;
}
public function getSubject(): string
{
return $this->subject;
}
public function __toString(): string
{
return \sprintf(
'%s-%s-%s.%s',
$this->subject,
$this->status,
$this->color,
$this->format
);
}
private function escapeValue(string $value): string
{
$pattern = [
// '/([^_])_([^_])/g', // damn it global doesn't work in PHP
'/([^_])_$/',
'/^_([^_])/',
'/__/',
'/--+/',
];
$replacement = [
// '$1 $2',
'$1 ',
' $1',
'°§*¼',
'-',
];
$ret = \preg_replace($pattern, $replacement, $value);
$ret = \str_replace('_', ' ', $ret); // this fix the php pgrep_replace is not global :(
$ret = \str_replace('°§*¼', '_', $ret); // this fix the php pgrep_replace is not global :(
return $ret;
}
private function getColorHex(string $color): string
{
return \array_key_exists($color, self::$colorScheme) ? self::$colorScheme[$color] : $color;
}
/**
* @return false|int
*/
private function isValidColorHex(string $color)
{
$color = \ltrim($color, '#');
$regex = '/^[0-9a-fA-F]{6}$/';
return \preg_match($regex, $color);
}
}
| php | MIT | f6f448e27bc676601ffcb9b378e6ce29edeb77a5 | 2026-01-05T04:46:38.341609Z | false |
badges/poser | https://github.com/badges/poser/blob/f6f448e27bc676601ffcb9b378e6ce29edeb77a5/src/UI/Command.php | src/UI/Command.php | <?php
namespace PUGX\Poser\UI;
use PUGX\Poser\Badge;
use PUGX\Poser\Poser;
use PUGX\Poser\Render\SvgFlatRender;
use PUGX\Poser\Render\SvgFlatSquareRender;
use PUGX\Poser\Render\SvgForTheBadgeRenderer;
use PUGX\Poser\Render\SvgPlasticRender;
use PUGX\Poser\ValueObject\InputRequest;
use Symfony\Component\Console\Command\Command as BaseCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class Command extends BaseCommand
{
public const HEADER = " ________________
<bg=black;options=reverse> |_ _ _| _ _ </bg=black;options=reverse> _ _ _ _ _ |
<bg=black;options=reverse> |_)(_|(_|(_|(/_ </bg=black;options=reverse> |_)(_)_\(/_| |
<bg=black;options=reverse> _| </bg=black;options=reverse>_|______________|
https://poser.pugx.org/
";
private Poser $poser;
protected string $header;
public function __construct(?string $name = null)
{
parent::__construct($name);
$this->poser = new Poser([
new SvgPlasticRender(),
new SvgFlatRender(),
new SvgFlatSquareRender(),
new SvgForTheBadgeRenderer(),
]);
$this->header = self::HEADER;
}
private function init(): void
{
$this->poser = new Poser([
new SvgPlasticRender(),
new SvgFlatRender(),
new SvgFlatSquareRender(),
new SvgForTheBadgeRenderer(),
]);
$this->header = self::HEADER;
}
protected function configure(): void
{
$this->init();
$this
->setName('generate')
->setDescription('Create a badge you are a Poser.')
->addArgument(
'subject',
InputArgument::OPTIONAL,
'The subject eg. `license`'
)
->addArgument(
'status',
InputArgument::OPTIONAL,
'The status example `MIT`'
)
->addArgument(
'color',
InputArgument::OPTIONAL,
'The hexadecimal color eg. `97CA00` or the name [' . \implode(', ', Badge::getColorNamesAvailable()) . ']'
)
->addOption(
'style',
's',
InputOption::VALUE_REQUIRED,
'The style of the image eg. `flat`, styles available [' . \implode(', ', $this->poser->validStyles()) . ']',
Badge::DEFAULT_STYLE
)
->addOption(
'format',
'f',
InputOption::VALUE_REQUIRED,
'The format of the image eg. `svg`, formats available [' . \implode(', ', $this->poser->validStyles()) . ']',
Badge::DEFAULT_FORMAT
)
->addOption(
'path',
'p',
InputOption::VALUE_REQUIRED,
'The path of the file to save the create eg. `/tmp/license.svg`'
);
}
/**
* @throws \Exception
* @throws \InvalidArgumentException
*/
protected function execute(InputInterface $input, OutputInterface $output): int
{
$inputRequest = InputRequest::createFromInput($input);
try {
$imageContent = $this->poser->generate(
$inputRequest->getSubject(),
$inputRequest->getStatus(),
$inputRequest->getColor(),
$inputRequest->getStyle(),
$inputRequest->getFormat()
);
$path = $input->getOption('path');
if ($path && \is_string($path)) {
$this->storeImage($output, $path, (string) $imageContent);
} else {
$this->flushImage($output, (string) $imageContent);
}
} catch (\Exception $e) {
$this->printHeaderOnce($output);
throw $e;
}
return 0;
}
protected function flushImage(OutputInterface $output, string $imageContent): void
{
$output->write($imageContent);
$this->header = '';
}
/**
* @throws \Exception
*/
protected function storeImage(OutputInterface $output, string $path, string $imageContent): void
{
$this->printHeaderOnce($output);
try {
$fp = @\fopen($path, 'x');
} catch (\Exception $e) {
$fp = false;
}
if (false == $fp) {
throw new \Exception("Error on creating the file maybe file [$path] already exists?");
}
$written = @\fwrite($fp, $imageContent);
if ($written < 1 || $written != \strlen($imageContent)) {
throw new \Exception('Error on writing to file.');
}
@\fclose($fp);
$output->write(\sprintf('Image created at %s', $path));
}
protected function printHeaderOnce(OutputInterface $output): void
{
if (!empty($this->header)) {
$output->write($this->header);
}
$this->header = '';
}
}
| php | MIT | f6f448e27bc676601ffcb9b378e6ce29edeb77a5 | 2026-01-05T04:46:38.341609Z | false |
badges/poser | https://github.com/badges/poser/blob/f6f448e27bc676601ffcb9b378e6ce29edeb77a5/src/UI/SingleCommandApplication.php | src/UI/SingleCommandApplication.php | <?php
namespace PUGX\Poser\UI;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
/**
* Application providing access to just one command.
*
* When a console application only consists of one
* command, having to specify this command's name as first
* argument is superfluous.
* This class simplifies creating and using this
* kind of applications.
*
* Usage:
*
* $cmd = new SimpleCommand();
* $app = new SingleCommandApplication($cmd, '1.2');
* $app->run();
*
* @author Stefaan Lippens <soxofaan@gmail.com>
*/
class SingleCommandApplication extends Application
{
/**
* Name of the single accessible command of this application.
*/
private ?string $commandName = null;
/**
* Constructor to build a "single command" application, given a command.
*
* The application will adopt the same name as the command.
*
* @param Command $command The single (accessible) command for this application
* @param string $version The version of the application
*
* @throws \InvalidArgumentException
*/
public function __construct(Command $command, string $version = 'UNKNOWN')
{
$commandName = $command->getName();
if (null === $commandName) {
throw new \InvalidArgumentException('command cannot be null');
}
parent::__construct($commandName, $version);
// Add the given command as single (accessible) command.
$this->add($command);
$this->commandName = $commandName;
// Override the Application's definition so that it does not
// require a command name as first argument.
$this->getDefinition()->setArguments();
}
protected function getCommandName(InputInterface $input): ?string
{
return $this->commandName;
}
/**
* Adds a command object.
*
* This function overrides (public) Application::add()
* but should should only be used internally.
* Will raise \LogicException when called
* after the single accessible command is set up
* (from the constructor).
*
* @param Command $command A Command object
*
* @return Command The registered command
*
* @throws \LogicException
*/
public function add(Command $command): ?Command
{
// Fail if we already set up the single accessible command.
if ($this->commandName) {
throw new \LogicException('You should not add additional commands to a SingleCommandApplication instance.');
}
return parent::add($command);
}
}
| php | MIT | f6f448e27bc676601ffcb9b378e6ce29edeb77a5 | 2026-01-05T04:46:38.341609Z | false |
badges/poser | https://github.com/badges/poser/blob/f6f448e27bc676601ffcb9b378e6ce29edeb77a5/src/ValueObject/InputRequest.php | src/ValueObject/InputRequest.php | <?php
declare(strict_types=1);
namespace PUGX\Poser\ValueObject;
use PUGX\Poser\Badge;
use Symfony\Component\Console\Input\InputInterface;
class InputRequest
{
private string $subject;
private string $status;
private string $color;
private string $style;
private string $format;
private function __construct(string $subject, string $status, string $color, string $style, string $format)
{
$this->subject = $subject;
$this->status = $status;
$this->color = $color;
$this->style = $style;
$this->format = $format;
}
public static function createFromInput(InputInterface $input): self
{
$subject = $input->getArgument('subject');
$status = $input->getArgument('status');
$color = $input->getArgument('color');
$style = $input->getOption('style');
$format = $input->getOption('format');
if (!\is_string($subject)) {
throw new \InvalidArgumentException('subject is not a string');
}
if (!\is_string($status)) {
throw new \InvalidArgumentException('status is not a string');
}
if (!\is_string($color)) {
throw new \InvalidArgumentException('color is not a string');
}
if (!\is_string($style)) {
throw new \InvalidArgumentException('style is not a string');
}
if (!\is_string($format)) {
$format = Badge::DEFAULT_FORMAT;
}
return new self($subject, $status, $color, $style, $format);
}
public function getSubject(): string
{
return $this->subject;
}
public function getStatus(): string
{
return $this->status;
}
public function getColor(): string
{
return $this->color;
}
public function getStyle(): string
{
return $this->style;
}
public function getFormat(): string
{
return $this->format;
}
}
| php | MIT | f6f448e27bc676601ffcb9b378e6ce29edeb77a5 | 2026-01-05T04:46:38.341609Z | false |
badges/poser | https://github.com/badges/poser/blob/f6f448e27bc676601ffcb9b378e6ce29edeb77a5/src/Render/SvgFlatSquareRender.php | src/Render/SvgFlatSquareRender.php | <?php
/*
* This file is part of the badge-poser package.
*
* (c) PUGX <http://pugx.github.io/>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PUGX\Poser\Render;
/**
* Class SvgFlatSquareRender.
*
* @author Giulio De Donato <liuggio@gmail.com>
*/
class SvgFlatSquareRender extends LocalSvgRenderer
{
public function getBadgeStyle(): string
{
return 'flat-square';
}
protected function getTemplateName(): string
{
return $this->getBadgeStyle();
}
}
| php | MIT | f6f448e27bc676601ffcb9b378e6ce29edeb77a5 | 2026-01-05T04:46:38.341609Z | false |
badges/poser | https://github.com/badges/poser/blob/f6f448e27bc676601ffcb9b378e6ce29edeb77a5/src/Render/SvgForTheBadgeRenderer.php | src/Render/SvgForTheBadgeRenderer.php | <?php
/*
* This file is part of the badge-poser package.
*
* (c) PUGX <http://pugx.github.io/>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PUGX\Poser\Render;
use PUGX\Poser\Badge;
use PUGX\Poser\Calculator\TextSizeCalculatorInterface;
class SvgForTheBadgeRenderer extends LocalSvgRenderer
{
public const VENDOR_TEXT_FONT = __DIR__ . '/../Calculator/Font/Verdana.svg';
public const VALUE_TEXT_FONT = __DIR__ . '/../Calculator/Font/Verdana-Bold.svg';
public const TEXT_FONT_SIZE = 10;
public const TEXT_FONT_COLOR = '#FFFFFF';
public const TEXT_LETTER_SPACING = 0.1;
public const PADDING_X = 10;
private \EasySVG $easy;
public function __construct(
?\EasySVG $easySVG = null,
?TextSizeCalculatorInterface $textSizeCalculator = null,
?string $templatesDirectory = null
) {
parent::__construct($textSizeCalculator, $templatesDirectory);
if (null === $easySVG) {
$easySVG = new \EasySVG();
}
$this->easy = $easySVG;
}
public function getBadgeStyle(): string
{
return 'for-the-badge';
}
protected function getTemplateName(): string
{
return $this->getBadgeStyle();
}
protected function buildParameters(Badge $badge): array
{
$parameters = parent::buildParameters($badge);
$parameters['vendor'] = \mb_strtoupper($parameters['vendor']);
$parameters['value'] = \mb_strtoupper($parameters['value']);
$this->easy->clearSVG();
$this->easy->setLetterSpacing(self::TEXT_LETTER_SPACING);
$this->easy->setFont(self::VENDOR_TEXT_FONT, self::TEXT_FONT_SIZE, self::TEXT_FONT_COLOR);
$vendorDimensions = $this->easy->textDimensions($parameters['vendor']);
$parameters['vendorWidth'] = $vendorDimensions[0] + 2 * self::PADDING_X;
$parameters['vendorStartPosition'] = \round($parameters['vendorWidth'] / 2, 1) + 1;
$this->easy->clearSVG();
$this->easy->setLetterSpacing(self::TEXT_LETTER_SPACING);
$this->easy->setFont(self::VALUE_TEXT_FONT, self::TEXT_FONT_SIZE, self::TEXT_FONT_COLOR);
$valueDimensions = $this->easy->textDimensions($parameters['value']);
$parameters['valueWidth'] = $valueDimensions[0] + 2 * self::PADDING_X;
$parameters['valueStartPosition'] = $parameters['vendorWidth'] + \round($parameters['valueWidth'] / 2, 1) - 1;
$parameters['totalWidth'] = $parameters['valueWidth'] + $parameters['vendorWidth'];
return $parameters;
}
}
| php | MIT | f6f448e27bc676601ffcb9b378e6ce29edeb77a5 | 2026-01-05T04:46:38.341609Z | false |
badges/poser | https://github.com/badges/poser/blob/f6f448e27bc676601ffcb9b378e6ce29edeb77a5/src/Render/LocalSvgRenderer.php | src/Render/LocalSvgRenderer.php | <?php
/*
* This file is part of the badge-poser package.
*
* (c) PUGX <http://pugx.github.io/>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PUGX\Poser\Render;
use PUGX\Poser\Badge;
use PUGX\Poser\Calculator\GDTextSizeCalculator;
use PUGX\Poser\Calculator\TextSizeCalculatorInterface;
use PUGX\Poser\Image;
/**
* Local SVG renderer.
* Generate SVG badges from local templates.
*
* @author JM Leroux <jmleroux.pro@gmail.com>
*/
abstract class LocalSvgRenderer implements RenderInterface
{
public const VENDOR_COLOR = '#555';
private TextSizeCalculatorInterface $textSizeCalculator;
private string $templatesDirectory;
public function __construct(?TextSizeCalculatorInterface $textSizeCalculator = null, ?string $templatesDirectory = null)
{
$this->textSizeCalculator = $textSizeCalculator ?? new GDTextSizeCalculator();
$this->templatesDirectory = $templatesDirectory ?? (__DIR__ . '/../Resources/templates');
}
public function render(Badge $badge): Image
{
$template = $this->getTemplate($this->getTemplateName());
$parameters = $this->buildParameters($badge);
return $this->renderSvg($template, $parameters, $badge->getStyle());
}
abstract protected function getTemplateName(): string;
/**
* @return string SVG content of the template
*/
private function getTemplate(string $style): string
{
if (null === $this->templatesDirectory) {
throw new \InvalidArgumentException('TemplateDirectory cannot be null');
}
$filepath = \sprintf('%s/%s.svg', $this->templatesDirectory, $style);
if (!\file_exists($filepath)) {
throw new \InvalidArgumentException(\sprintf('No template for style %s', $style));
}
return \file_get_contents($filepath);
}
private function stringWidth(string $text): float
{
if (null === $this->textSizeCalculator) {
throw new \InvalidArgumentException('TextSizeCalculator cannot be null');
}
return $this->textSizeCalculator->calculateWidth($text);
}
private function renderSvg(string $render, array $parameters, string $style): Image
{
foreach ($parameters as $key => $variable) {
$render = \str_replace(\sprintf('{{ %s }}', $key), $variable, $render);
}
try {
$xml = new \SimpleXMLElement($render);
} catch (\Exception $e) {
throw new \RuntimeException('Generated string is not a valid XML');
}
if ('svg' !== $xml->getName()) {
throw new \RuntimeException('Generated xml is not a SVG');
}
return Image::createFromString($render, $style);
}
protected function buildParameters(Badge $badge): array
{
$parameters = [];
$parameters['vendorWidth'] = $this->stringWidth($badge->getSubject());
$parameters['valueWidth'] = $this->stringWidth($badge->getStatus());
$parameters['totalWidth'] = $parameters['valueWidth'] + $parameters['vendorWidth'];
$parameters['vendorColor'] = static::VENDOR_COLOR;
$parameters['valueColor'] = $badge->getHexColor();
$parameters['vendor'] = $badge->getSubject();
$parameters['value'] = $badge->getStatus();
$parameters['vendorStartPosition'] = \round($parameters['vendorWidth'] / 2, 1) + 1;
$parameters['valueStartPosition'] = $parameters['vendorWidth'] + \round($parameters['valueWidth'] / 2, 1) - 1;
return $parameters;
}
}
| php | MIT | f6f448e27bc676601ffcb9b378e6ce29edeb77a5 | 2026-01-05T04:46:38.341609Z | false |
badges/poser | https://github.com/badges/poser/blob/f6f448e27bc676601ffcb9b378e6ce29edeb77a5/src/Render/SvgFlatRender.php | src/Render/SvgFlatRender.php | <?php
/*
* This file is part of the badge-poser package.
*
* (c) PUGX <http://pugx.github.io/>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PUGX\Poser\Render;
/**
* Class SvgFlatRender.
*
* @author Giulio De Donato <liuggio@gmail.com>
*/
class SvgFlatRender extends LocalSvgRenderer
{
public function getBadgeStyle(): string
{
return 'flat';
}
protected function getTemplateName(): string
{
return $this->getBadgeStyle();
}
}
| php | MIT | f6f448e27bc676601ffcb9b378e6ce29edeb77a5 | 2026-01-05T04:46:38.341609Z | false |
badges/poser | https://github.com/badges/poser/blob/f6f448e27bc676601ffcb9b378e6ce29edeb77a5/src/Render/RenderInterface.php | src/Render/RenderInterface.php | <?php
/*
* This file is part of the badge-poser package.
*
* (c) PUGX <http://pugx.github.io/>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PUGX\Poser\Render;
use PUGX\Poser\Badge;
use PUGX\Poser\Image;
interface RenderInterface
{
/**
* Render a badge
*/
public function render(Badge $badge): Image;
/**
* @return string the style of the badge image eg. `flat`.
*/
public function getBadgeStyle(): string;
}
| php | MIT | f6f448e27bc676601ffcb9b378e6ce29edeb77a5 | 2026-01-05T04:46:38.341609Z | false |
badges/poser | https://github.com/badges/poser/blob/f6f448e27bc676601ffcb9b378e6ce29edeb77a5/src/Render/SvgPlasticRender.php | src/Render/SvgPlasticRender.php | <?php
/*
* This file is part of the badge-poser package.
*
* (c) PUGX <http://pugx.github.io/>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PUGX\Poser\Render;
/**
* Class SvgPlasticRender.
*
* @author Claudio D'Alicandro <claudio.dalicandro@gmail.com>
* @author Giulio De Donato <liuggio@gmail.com>
*/
class SvgPlasticRender extends LocalSvgRenderer
{
public function getBadgeStyle(): string
{
return 'plastic';
}
protected function getTemplateName(): string
{
return $this->getBadgeStyle();
}
}
| php | MIT | f6f448e27bc676601ffcb9b378e6ce29edeb77a5 | 2026-01-05T04:46:38.341609Z | false |
badges/poser | https://github.com/badges/poser/blob/f6f448e27bc676601ffcb9b378e6ce29edeb77a5/src/Calculator/TextSizeCalculatorInterface.php | src/Calculator/TextSizeCalculatorInterface.php | <?php
/*
* This file is part of the badge-poser package.
*
* (c) PUGX <http://pugx.github.io/>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PUGX\Poser\Calculator;
interface TextSizeCalculatorInterface
{
public const TEXT_SIZE = 11;
public const SHIELD_PADDING_EXTERNAL = 6;
public const SHIELD_PADDING_INTERNAL = 4;
/**
* Calculate the width of the text box.
*/
public function calculateWidth(string $text, int $size = self::TEXT_SIZE): float;
}
| php | MIT | f6f448e27bc676601ffcb9b378e6ce29edeb77a5 | 2026-01-05T04:46:38.341609Z | false |
badges/poser | https://github.com/badges/poser/blob/f6f448e27bc676601ffcb9b378e6ce29edeb77a5/src/Calculator/GDTextSizeCalculator.php | src/Calculator/GDTextSizeCalculator.php | <?php
/*
* This file is part of the badge-poser package.
*
* (c) PUGX <http://pugx.github.io/>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PUGX\Poser\Calculator;
class GDTextSizeCalculator implements TextSizeCalculatorInterface
{
public const TEXT_FONT = '/Font/DejaVuSans.ttf';
protected string $fontPath;
public function __construct()
{
$this->fontPath = __DIR__ . self::TEXT_FONT;
}
/**
* Calculate the width of the text box.
*/
public function calculateWidth(string $text, int $size = self::TEXT_SIZE): float
{
$size = $this->convertToPt($size);
$box = \imagettfbbox($size, 0, $this->fontPath, $text);
return \round(\abs($box[2] - $box[0]) + self::SHIELD_PADDING_EXTERNAL + self::SHIELD_PADDING_INTERNAL, 1);
}
private function convertToPt(int $pixels): float
{
return \round($pixels * 0.75, 1);
}
}
| php | MIT | f6f448e27bc676601ffcb9b378e6ce29edeb77a5 | 2026-01-05T04:46:38.341609Z | false |
badges/poser | https://github.com/badges/poser/blob/f6f448e27bc676601ffcb9b378e6ce29edeb77a5/src/Calculator/SvgTextSizeCalculator.php | src/Calculator/SvgTextSizeCalculator.php | <?php
/*
* This file is part of the badge-poser package.
*
* (c) PUGX <http://pugx.github.io/>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PUGX\Poser\Calculator;
use Cog\SvgFont\FontList;
use Cog\Unicode\UnicodeString;
/**
* @author Anton Komarev <anton@komarev.com>
*/
class SvgTextSizeCalculator implements TextSizeCalculatorInterface
{
/**
* Calculate the width of the text box.
*/
public function calculateWidth(string $text, int $size = self::TEXT_SIZE): float
{
$font = FontList::ofFile(__DIR__ . '/Font/DejaVuSans.svg')->getById('DejaVuSansBook');
$letterSpacing = 0.0;
$width = $font->computeStringWidth(
UnicodeString::of($text),
$size,
$letterSpacing,
);
$shieldPaddingX = self::SHIELD_PADDING_EXTERNAL + self::SHIELD_PADDING_INTERNAL;
return \round($width + $shieldPaddingX, 1);
}
}
| php | MIT | f6f448e27bc676601ffcb9b378e6ce29edeb77a5 | 2026-01-05T04:46:38.341609Z | false |
badges/poser | https://github.com/badges/poser/blob/f6f448e27bc676601ffcb9b378e6ce29edeb77a5/tests/PoserTest.php | tests/PoserTest.php | <?php
declare(strict_types=1);
namespace PUGX\Poser\Tests;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
use PUGX\Poser\Poser;
use PUGX\Poser\Render\SvgFlatRender;
use PUGX\Poser\Render\SvgFlatSquareRender;
class PoserTest extends TestCase
{
private Poser $poser;
protected function setUp(): void
{
$this->poser = new Poser([
new SvgFlatRender(),
new SvgFlatSquareRender(),
]);
}
#[Test]
public function itIsInitializable(): void
{
$this->assertInstanceOf(Poser::class, $this->poser);
}
#[Test]
public function itShouldBeAbleToGenerateAnSvgImage(): void
{
$subject = 'stable';
$status = 'v2.0';
$color = '97CA00';
$style = 'flat';
$format = 'svg';
$image = $this->poser->generate($subject, $status, $color, $style, $format);
$this->assertValidSVGImageContaining((string) $image, $subject, $status);
}
#[Test]
public function itShouldBeAbleToGenerateAnSvgImageFromURI(): void
{
$subject = 'stable-v2.0-97CA00.svg';
$image = $this->poser->generateFromURI($subject);
$this->assertValidSVGImageContaining((string) $image, 'stable', 'v2.0');
}
#[Test]
public function itShouldBeAbleToGenerateAnSvgImageFromURIWithoutFileExtension(): void
{
$subject = 'stable-v2.0-97CA00';
$image = $this->poser->generateFromURI($subject);
$this->assertValidSVGImageContaining((string) $image, 'stable', 'v2.0');
}
#[Test]
public function itShouldBeAbleToGenerateAnSvgImageFromURIWithStyle(): void
{
$subject = 'stable-v2.0-97CA00.svg?style=flat-square';
$image = $this->poser->generateFromURI($subject);
$this->assertValidSVGImageContaining((string) $image, 'stable', 'v2.0');
}
#[Test]
public function itThrowsExceptionWhenGeneratingAnSvgImageWithBadURI(): void
{
$subject = 'stable-v2.0-';
$this->expectException(\InvalidArgumentException::class);
$this->poser->generateFromURI($subject);
}
private function assertValidSVGImageContaining(string $svg, string $subject, string $status): void
{
$regex = '/^<svg.*width="((.|\n)*)' . \preg_quote($subject, '/') . '((.|\n)*)' . \preg_quote($status, '/') . '((.|\n)*)<\/svg>$/';
$this->assertMatchesRegularExpression($regex, $svg);
}
}
| php | MIT | f6f448e27bc676601ffcb9b378e6ce29edeb77a5 | 2026-01-05T04:46:38.341609Z | false |
badges/poser | https://github.com/badges/poser/blob/f6f448e27bc676601ffcb9b378e6ce29edeb77a5/tests/BadgeTest.php | tests/BadgeTest.php | <?php
declare(strict_types=1);
namespace PUGX\Poser\Tests;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
use PUGX\Poser\Badge;
class BadgeTest extends TestCase
{
#[Test]
public function itIsInitializable(): void
{
$badge = new Badge('a', 'b', '97CA00', 'flat');
$this->assertInstanceOf(Badge::class, $badge);
}
#[Test]
public function itShouldBeConstructedByFromURIFactoryMethod(): void
{
$assert = 'version-stable-97CA00.svg';
$badge = Badge::fromURI($assert);
$this->assertEquals($assert, (string) $badge);
}
#[Test]
public function itShouldBeConstructedByFromURIFactoryMethodEscapingCorrectlyUnderscores(): void
{
$input = 'I__m__liugg__io-b-97CA00.svg';
$assertInput = 'I_m_liugg_io-b-97CA00.svg';
$badge = Badge::fromURI($input);
$this->assertEquals($assertInput, (string) $badge);
}
#[Test]
public function itShouldBeConstructedByFromURIFactoryMethodEscapingCorrectlyWithSingleUnderscore(): void
{
$input = 'I_m_liuggio-b-97CA00.svg';
$assertInput = 'I m liuggio-b-97CA00.svg';
$badge = Badge::fromURI($input);
$this->assertEquals($assertInput, (string) $badge);
}
#[Test]
public function itShouldBeConstructedByFromURIFactoryMethodEscapingCorrectlyWithDashes(): void
{
$input = 'I--m--liuggio-b-97CA00.svg';
$assertInput = 'I-m-liuggio-b-97CA00.svg';
$badge = Badge::fromURI($input);
$this->assertEquals($assertInput, (string) $badge);
}
#[Test]
#[DataProvider('positiveConversionExamples')]
public function itShouldValidateAvailableColorSchemes(string $colorName): void
{
$badge = new Badge('a', 'b', $colorName, 'flat');
$this->assertIsString($badge->getHexColor());
}
public static function positiveConversionExamples(): array
{
$colorNames = Badge::getColorNamesAvailable();
$data = [];
foreach ($colorNames as $colorName) {
$data[$colorName] = [$colorName];
}
return $data;
}
}
| php | MIT | f6f448e27bc676601ffcb9b378e6ce29edeb77a5 | 2026-01-05T04:46:38.341609Z | false |
badges/poser | https://github.com/badges/poser/blob/f6f448e27bc676601ffcb9b378e6ce29edeb77a5/tests/Render/SvgFlatSquareRenderTest.php | tests/Render/SvgFlatSquareRenderTest.php | <?php
declare(strict_types=1);
namespace PUGX\Poser\Tests\Render;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
use PUGX\Poser\Badge;
use PUGX\Poser\Calculator\TextSizeCalculatorInterface;
use PUGX\Poser\Render\SvgFlatSquareRender;
class SvgFlatSquareRenderTest extends TestCase
{
private TextSizeCalculatorInterface $calculator;
private SvgFlatSquareRender $render;
protected function setUp(): void
{
$this->calculator = $this->createMock(TextSizeCalculatorInterface::class);
$this->calculator->method('calculateWidth')->willReturn(20.0);
$this->render = new SvgFlatSquareRender($this->calculator);
}
#[Test]
public function itShouldRenderASvg(): void
{
$badge = Badge::fromURI('version-stable-97CA00.svg?style=flat-square');
$image = $this->render->render($badge);
$this->assertValidSVGImage((string) $image);
}
#[Test]
public function itShouldRenderALicenseMitExactlyLikeThisSvg(): void
{
$fixture = __DIR__ . '/../Fixtures/flat-square.svg';
$template = \file_get_contents($fixture);
$badge = Badge::fromURI('license-MIT-blue.svg?style=flat-square');
$image = $this->render->render($badge);
$this->assertEquals($template, (string) $image);
}
#[Test]
public function itShouldReturnCorrectBadgeStyle(): void
{
$this->assertEquals('flat-square', $this->render->getBadgeStyle());
}
private function assertValidSVGImage(string $svg): void
{
$regex = '/^<svg.*width="((.|\n)*)<\/svg>$/';
$this->assertMatchesRegularExpression($regex, $svg);
}
}
| php | MIT | f6f448e27bc676601ffcb9b378e6ce29edeb77a5 | 2026-01-05T04:46:38.341609Z | false |
badges/poser | https://github.com/badges/poser/blob/f6f448e27bc676601ffcb9b378e6ce29edeb77a5/tests/Render/SvgPlasticRenderTest.php | tests/Render/SvgPlasticRenderTest.php | <?php
declare(strict_types=1);
namespace PUGX\Poser\Tests\Render;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
use PUGX\Poser\Badge;
use PUGX\Poser\Calculator\TextSizeCalculatorInterface;
use PUGX\Poser\Render\SvgPlasticRender;
class SvgPlasticRenderTest extends TestCase
{
private TextSizeCalculatorInterface $calculator;
private SvgPlasticRender $render;
protected function setUp(): void
{
$this->calculator = $this->createMock(TextSizeCalculatorInterface::class);
$this->calculator->method('calculateWidth')->willReturn(20.0);
$this->render = new SvgPlasticRender($this->calculator);
}
#[Test]
public function itShouldRenderASvg(): void
{
$badge = Badge::fromURI('version-stable-97CA00.svg?style=plastic');
$image = $this->render->render($badge);
$this->assertValidSVGImage((string) $image);
}
#[Test]
public function itShouldReturnCorrectBadgeStyle(): void
{
$this->assertEquals('plastic', $this->render->getBadgeStyle());
}
#[Test]
public function itThrowsExceptionWhenRenderingInvalidSvg(): void
{
$templatesDir = __DIR__ . '/../Fixtures/invalid_template';
$render = new SvgPlasticRender($this->calculator, $templatesDir);
$badge = Badge::fromURI('version-stable-97CA00.svg?style=plastic');
$this->expectException(\RuntimeException::class);
$this->expectExceptionMessage('Generated string is not a valid XML');
$render->render($badge);
}
#[Test]
public function itThrowsExceptionWhenRenderingNonSvgXml(): void
{
$templatesDir = __DIR__ . '/../Fixtures/xml_template';
$render = new SvgPlasticRender($this->calculator, $templatesDir);
$badge = Badge::fromURI('version-stable-97CA00.svg?style=plastic');
$this->expectException(\RuntimeException::class);
$this->expectExceptionMessage('Generated xml is not a SVG');
$render->render($badge);
}
private function assertValidSVGImage(string $svg): void
{
$regex = '/^<svg.*width="((.|\n)*)<\/svg>$/';
$this->assertMatchesRegularExpression($regex, $svg);
}
}
| php | MIT | f6f448e27bc676601ffcb9b378e6ce29edeb77a5 | 2026-01-05T04:46:38.341609Z | false |
badges/poser | https://github.com/badges/poser/blob/f6f448e27bc676601ffcb9b378e6ce29edeb77a5/tests/Render/SvgFlatRenderTest.php | tests/Render/SvgFlatRenderTest.php | <?php
declare(strict_types=1);
namespace PUGX\Poser\Tests\Render;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
use PUGX\Poser\Badge;
use PUGX\Poser\Calculator\TextSizeCalculatorInterface;
use PUGX\Poser\Render\SvgFlatRender;
class SvgFlatRenderTest extends TestCase
{
private TextSizeCalculatorInterface $calculator;
private SvgFlatRender $render;
protected function setUp(): void
{
$this->calculator = $this->createMock(TextSizeCalculatorInterface::class);
$this->calculator->method('calculateWidth')->willReturn(20.0);
$this->render = new SvgFlatRender($this->calculator);
}
#[Test]
public function itShouldRenderASvg(): void
{
$badge = Badge::fromURI('version-stable-97CA00.svg');
$image = $this->render->render($badge);
$this->assertValidSVGImage((string) $image);
}
#[Test]
public function itShouldRenderALicenseMitExactlyLikeThisSvg(): void
{
$fixture = __DIR__ . '/../Fixtures/flat.svg';
$template = \file_get_contents($fixture);
$badge = Badge::fromURI('license-MIT-blue.svg');
$image = $this->render->render($badge);
$this->assertEquals($template, (string) $image);
}
#[Test]
public function itShouldReturnCorrectBadgeStyle(): void
{
$this->assertEquals('flat', $this->render->getBadgeStyle());
}
private function assertValidSVGImage(string $svg): void
{
$regex = '/^<svg.*width="((.|\n)*)<\/svg>$/';
$this->assertMatchesRegularExpression($regex, $svg);
}
}
| php | MIT | f6f448e27bc676601ffcb9b378e6ce29edeb77a5 | 2026-01-05T04:46:38.341609Z | false |
badges/poser | https://github.com/badges/poser/blob/f6f448e27bc676601ffcb9b378e6ce29edeb77a5/tests/Calculator/GDTextSizeCalculatorTest.php | tests/Calculator/GDTextSizeCalculatorTest.php | <?php
declare(strict_types=1);
namespace PUGX\Poser\Tests\Calculator;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
use PUGX\Poser\Calculator\GDTextSizeCalculator;
class GDTextSizeCalculatorTest extends TestCase
{
private GDTextSizeCalculator $calculator;
protected function setUp(): void
{
$this->calculator = new GDTextSizeCalculator();
}
#[Test]
public function itShouldComputeTextWidthWithSize8(): void
{
$width = $this->calculator->calculateWidth('MIT', 8);
$this->assertEquals(24.0, $width);
}
#[Test]
public function itShouldComputeTextWidthWithSize10(): void
{
$width = $this->calculator->calculateWidth('MIT', 10);
$this->assertEquals(29.0, $width);
}
#[Test]
public function itShouldComputeTextWidthWithSize14(): void
{
$width = $this->calculator->calculateWidth('MIT', 14);
$this->assertEquals(34.0, $width);
}
#[Test]
public function itShouldComputeTextWidthWithDefaultSize(): void
{
$width = $this->calculator->calculateWidth('MIT');
$this->assertIsFloat($width);
$this->assertGreaterThan(0, $width);
}
}
| php | MIT | f6f448e27bc676601ffcb9b378e6ce29edeb77a5 | 2026-01-05T04:46:38.341609Z | false |
badges/poser | https://github.com/badges/poser/blob/f6f448e27bc676601ffcb9b378e6ce29edeb77a5/tests/Calculator/SvgTextSizeCalculatorTest.php | tests/Calculator/SvgTextSizeCalculatorTest.php | <?php
declare(strict_types=1);
namespace PUGX\Poser\Tests\Calculator;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
use PUGX\Poser\Calculator\SvgTextSizeCalculator;
class SvgTextSizeCalculatorTest extends TestCase
{
private SvgTextSizeCalculator $calculator;
protected function setUp(): void
{
$this->calculator = new SvgTextSizeCalculator();
}
#[Test]
public function itShouldComputeTextWidthWithSize8(): void
{
$width = $this->calculator->calculateWidth('MIT', 8);
$this->assertEquals(24.1, $width);
}
#[Test]
public function itShouldComputeTextWidthWithSize10(): void
{
$width = $this->calculator->calculateWidth('MIT', 10);
$this->assertEquals(27.7, $width);
}
#[Test]
public function itShouldComputeTextWidthWithSize14(): void
{
$width = $this->calculator->calculateWidth('MIT', 14);
$this->assertEquals(34.8, $width);
}
#[Test]
public function itShouldComputeTextWidthWithDefaultSize(): void
{
$width = $this->calculator->calculateWidth('MIT');
$this->assertIsFloat($width);
$this->assertGreaterThan(0, $width);
}
}
| php | MIT | f6f448e27bc676601ffcb9b378e6ce29edeb77a5 | 2026-01-05T04:46:38.341609Z | false |
badges/poser | https://github.com/badges/poser/blob/f6f448e27bc676601ffcb9b378e6ce29edeb77a5/features/bootstrap/FeatureContext.php | features/bootstrap/FeatureContext.php | <?php
use Behat\Behat\Context\Context;
/**
* Behat context class.
*/
class FeatureContext implements Context
{
private string $binFolder;
private string $output;
private int $return;
/**
* Initializes context.
*
* Every scenario gets its own context object.
* You can also pass arbitrary arguments to the context constructor through behat.yml.
*/
public function __construct()
{
$this->binFolder = __DIR__ . '/../../bin/';
$this->output = '';
}
/**
* @When I run :command
*/
public function iRun($command): void
{
$poser = $this->binFolder . $command;
$this->return = -1;
\ob_start();
\passthru("cd {$this->binFolder};php $command", $this->return);
$this->output = \ob_get_clean();
}
/**
* @Then the same output should be like the content of :filePath
*/
public function theSameOutputShouldBeLikeTheContentOf($filePath): void
{
$filePath = __DIR__ . '/../' . $filePath;
$content = \file_get_contents($filePath);
$this->assertEquals($content, $this->output);
}
/**
* @Then it should pass
*/
public function itShouldPass(): void
{
if (0 != $this->return) {
throw new Exception('Error executing ' . $this->return);
}
}
/**
* @Then the content of :given should be equal to :expected
*/
public function theContentOfShouldBeEqualTo($given, $expected): void
{
$givenPath = $given;
$given = \file_get_contents($givenPath);
$expectedPath = __DIR__ . '/../' . $expected;
$expected = \file_get_contents($expectedPath);
\unlink($givenPath);
$this->assertEquals($given, $expected);
}
private function assertEquals($given, $expected): void
{
$expected = \preg_replace('/\s+/', '', $expected);
$given = \preg_replace('/\s+/', '', $given);
$perc = 0;
\similar_text($expected, $given, $perc);
if ($perc < 94) {
throw new Exception('String similarity:' . $perc . '%. String expected:' . $expected . \PHP_EOL . ' given:' . $given);
}
}
}
| php | MIT | f6f448e27bc676601ffcb9b378e6ce29edeb77a5 | 2026-01-05T04:46:38.341609Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/index.php | index.php | <?php
/*
*---------------------------------------------------------------
* APPLICATION ENVIRONMENT
*---------------------------------------------------------------
*
* You can load different configurations depending on your
* current environment. Setting the environment also influences
* things like logging and error reporting.
*
* This can be set to anything, but default usage is:
*
* development
* testing
* production
*
* NOTE: If you change these, also change the error_reporting() code below
*
*/
define('ENVIRONMENT', 'development');
/*
*---------------------------------------------------------------
* ERROR REPORTING
*---------------------------------------------------------------
*
* Different environments will require different levels of error reporting.
* By default development will show errors but testing and live will hide them.
*/
if (defined('ENVIRONMENT'))
{
switch (ENVIRONMENT)
{
case 'development':
error_reporting(E_ALL);
break;
case 'testing':
case 'production':
error_reporting(0);
break;
default:
exit('The application environment is not set correctly.');
}
}
/*
*---------------------------------------------------------------
* SYSTEM FOLDER NAME
*---------------------------------------------------------------
*
* This variable must contain the name of your "system" folder.
* Include the path if the folder is not in the same directory
* as this file.
*
*/
$system_path = 'system';
/*
*---------------------------------------------------------------
* APPLICATION FOLDER NAME
*---------------------------------------------------------------
*
* If you want this front controller to use a different "application"
* folder then the default one you can set its name here. The folder
* can also be renamed or relocated anywhere on your server. If
* you do, use a full server path. For more info please see the user guide:
* http://codeigniter.com/user_guide/general/managing_apps.html
*
* NO TRAILING SLASH!
*
*/
$application_folder = 'application';
/*
* --------------------------------------------------------------------
* DEFAULT CONTROLLER
* --------------------------------------------------------------------
*
* Normally you will set your default controller in the routes.php file.
* You can, however, force a custom routing by hard-coding a
* specific controller class/function here. For most applications, you
* WILL NOT set your routing here, but it's an option for those
* special instances where you might want to override the standard
* routing in a specific front controller that shares a common CI installation.
*
* IMPORTANT: If you set the routing here, NO OTHER controller will be
* callable. In essence, this preference limits your application to ONE
* specific controller. Leave the function name blank if you need
* to call functions dynamically via the URI.
*
* Un-comment the $routing array below to use this feature
*
*/
// The directory name, relative to the "controllers" folder. Leave blank
// if your controller is not in a sub-folder within the "controllers" folder
// $routing['directory'] = '';
// The controller class file name. Example: Mycontroller
// $routing['controller'] = '';
// The controller function you wish to be called.
// $routing['function'] = '';
/*
* -------------------------------------------------------------------
* CUSTOM CONFIG VALUES
* -------------------------------------------------------------------
*
* The $assign_to_config array below will be passed dynamically to the
* config class when initialized. This allows you to set custom config
* items or override any default config values found in the config.php file.
* This can be handy as it permits you to share one application between
* multiple front controller files, with each file containing different
* config values.
*
* Un-comment the $assign_to_config array below to use this feature
*
*/
// $assign_to_config['name_of_config_item'] = 'value of config item';
// --------------------------------------------------------------------
// END OF USER CONFIGURABLE SETTINGS. DO NOT EDIT BELOW THIS LINE
// --------------------------------------------------------------------
/*
* ---------------------------------------------------------------
* Resolve the system path for increased reliability
* ---------------------------------------------------------------
*/
// Set the current directory correctly for CLI requests
if (defined('STDIN'))
{
chdir(dirname(__FILE__));
}
if (realpath($system_path) !== FALSE)
{
$system_path = realpath($system_path).'/';
}
// ensure there's a trailing slash
$system_path = rtrim($system_path, '/').'/';
// Is the system path correct?
if ( ! is_dir($system_path))
{
exit("Your system folder path does not appear to be set correctly. Please open the following file and correct this: ".pathinfo(__FILE__, PATHINFO_BASENAME));
}
/*
* -------------------------------------------------------------------
* Now that we know the path, set the main path constants
* -------------------------------------------------------------------
*/
// The name of THIS file
define('SELF', pathinfo(__FILE__, PATHINFO_BASENAME));
// The PHP file extension
// this global constant is deprecated.
define('EXT', '.php');
// Path to the system folder
define('BASEPATH', str_replace("\\", "/", $system_path));
// Path to the front controller (this file)
define('FCPATH', str_replace(SELF, '', __FILE__));
// Name of the "system folder"
define('SYSDIR', trim(strrchr(trim(BASEPATH, '/'), '/'), '/'));
// The path to the "application" folder
if (is_dir($application_folder))
{
define('APPPATH', $application_folder.'/');
}
else
{
if ( ! is_dir(BASEPATH.$application_folder.'/'))
{
exit("Your application folder path does not appear to be set correctly. Please open the following file and correct this: ".SELF);
}
define('APPPATH', BASEPATH.$application_folder.'/');
}
/*
* --------------------------------------------------------------------
* LOAD THE BOOTSTRAP FILE
* --------------------------------------------------------------------
*
* And away we go...
*
*/
require_once BASEPATH.'core/CodeIgniter.php';
/* End of file index.php */
/* Location: ./index.php */ | php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/helpers/html_helper.php | system/helpers/html_helper.php | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 5.1.6 or newer
*
* @package CodeIgniter
* @author ExpressionEngine Dev Team
* @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
* @license http://codeigniter.com/user_guide/license.html
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
// ------------------------------------------------------------------------
/**
* CodeIgniter HTML Helpers
*
* @package CodeIgniter
* @subpackage Helpers
* @category Helpers
* @author ExpressionEngine Dev Team
* @link http://codeigniter.com/user_guide/helpers/html_helper.html
*/
// ------------------------------------------------------------------------
/**
* Heading
*
* Generates an HTML heading tag. First param is the data.
* Second param is the size of the heading tag.
*
* @access public
* @param string
* @param integer
* @return string
*/
if ( ! function_exists('heading'))
{
function heading($data = '', $h = '1', $attributes = '')
{
$attributes = ($attributes != '') ? ' '.$attributes : $attributes;
return "<h".$h.$attributes.">".$data."</h".$h.">";
}
}
// ------------------------------------------------------------------------
/**
* Unordered List
*
* Generates an HTML unordered list from an single or multi-dimensional array.
*
* @access public
* @param array
* @param mixed
* @return string
*/
if ( ! function_exists('ul'))
{
function ul($list, $attributes = '')
{
return _list('ul', $list, $attributes);
}
}
// ------------------------------------------------------------------------
/**
* Ordered List
*
* Generates an HTML ordered list from an single or multi-dimensional array.
*
* @access public
* @param array
* @param mixed
* @return string
*/
if ( ! function_exists('ol'))
{
function ol($list, $attributes = '')
{
return _list('ol', $list, $attributes);
}
}
// ------------------------------------------------------------------------
/**
* Generates the list
*
* Generates an HTML ordered list from an single or multi-dimensional array.
*
* @access private
* @param string
* @param mixed
* @param mixed
* @param integer
* @return string
*/
if ( ! function_exists('_list'))
{
function _list($type = 'ul', $list, $attributes = '', $depth = 0)
{
// If an array wasn't submitted there's nothing to do...
if ( ! is_array($list))
{
return $list;
}
// Set the indentation based on the depth
$out = str_repeat(" ", $depth);
// Were any attributes submitted? If so generate a string
if (is_array($attributes))
{
$atts = '';
foreach ($attributes as $key => $val)
{
$atts .= ' ' . $key . '="' . $val . '"';
}
$attributes = $atts;
}
elseif (is_string($attributes) AND strlen($attributes) > 0)
{
$attributes = ' '. $attributes;
}
// Write the opening list tag
$out .= "<".$type.$attributes.">\n";
// Cycle through the list elements. If an array is
// encountered we will recursively call _list()
static $_last_list_item = '';
foreach ($list as $key => $val)
{
$_last_list_item = $key;
$out .= str_repeat(" ", $depth + 2);
$out .= "<li>";
if ( ! is_array($val))
{
$out .= $val;
}
else
{
$out .= $_last_list_item."\n";
$out .= _list($type, $val, '', $depth + 4);
$out .= str_repeat(" ", $depth + 2);
}
$out .= "</li>\n";
}
// Set the indentation for the closing tag
$out .= str_repeat(" ", $depth);
// Write the closing list tag
$out .= "</".$type.">\n";
return $out;
}
}
// ------------------------------------------------------------------------
/**
* Generates HTML BR tags based on number supplied
*
* @access public
* @param integer
* @return string
*/
if ( ! function_exists('br'))
{
function br($num = 1)
{
return str_repeat("<br />", $num);
}
}
// ------------------------------------------------------------------------
/**
* Image
*
* Generates an <img /> element
*
* @access public
* @param mixed
* @return string
*/
if ( ! function_exists('img'))
{
function img($src = '', $index_page = FALSE)
{
if ( ! is_array($src) )
{
$src = array('src' => $src);
}
// If there is no alt attribute defined, set it to an empty string
if ( ! isset($src['alt']))
{
$src['alt'] = '';
}
$img = '<img';
foreach ($src as $k=>$v)
{
if ($k == 'src' AND strpos($v, '://') === FALSE)
{
$CI =& get_instance();
if ($index_page === TRUE)
{
$img .= ' src="'.$CI->config->site_url($v).'"';
}
else
{
$img .= ' src="'.$CI->config->slash_item('base_url').$v.'"';
}
}
else
{
$img .= " $k=\"$v\"";
}
}
$img .= '/>';
return $img;
}
}
// ------------------------------------------------------------------------
/**
* Doctype
*
* Generates a page document type declaration
*
* Valid options are xhtml-11, xhtml-strict, xhtml-trans, xhtml-frame,
* html4-strict, html4-trans, and html4-frame. Values are saved in the
* doctypes config file.
*
* @access public
* @param string type The doctype to be generated
* @return string
*/
if ( ! function_exists('doctype'))
{
function doctype($type = 'xhtml1-strict')
{
global $_doctypes;
if ( ! is_array($_doctypes))
{
if (defined('ENVIRONMENT') AND is_file(APPPATH.'config/'.ENVIRONMENT.'/doctypes.php'))
{
include(APPPATH.'config/'.ENVIRONMENT.'/doctypes.php');
}
elseif (is_file(APPPATH.'config/doctypes.php'))
{
include(APPPATH.'config/doctypes.php');
}
if ( ! is_array($_doctypes))
{
return FALSE;
}
}
if (isset($_doctypes[$type]))
{
return $_doctypes[$type];
}
else
{
return FALSE;
}
}
}
// ------------------------------------------------------------------------
/**
* Link
*
* Generates link to a CSS file
*
* @access public
* @param mixed stylesheet hrefs or an array
* @param string rel
* @param string type
* @param string title
* @param string media
* @param boolean should index_page be added to the css path
* @return string
*/
if ( ! function_exists('link_tag'))
{
function link_tag($href = '', $rel = 'stylesheet', $type = 'text/css', $title = '', $media = '', $index_page = FALSE)
{
$CI =& get_instance();
$link = '<link ';
if (is_array($href))
{
foreach ($href as $k=>$v)
{
if ($k == 'href' AND strpos($v, '://') === FALSE)
{
if ($index_page === TRUE)
{
$link .= 'href="'.$CI->config->site_url($v).'" ';
}
else
{
$link .= 'href="'.$CI->config->slash_item('base_url').$v.'" ';
}
}
else
{
$link .= "$k=\"$v\" ";
}
}
$link .= "/>";
}
else
{
if ( strpos($href, '://') !== FALSE)
{
$link .= 'href="'.$href.'" ';
}
elseif ($index_page === TRUE)
{
$link .= 'href="'.$CI->config->site_url($href).'" ';
}
else
{
$link .= 'href="'.$CI->config->slash_item('base_url').$href.'" ';
}
$link .= 'rel="'.$rel.'" type="'.$type.'" ';
if ($media != '')
{
$link .= 'media="'.$media.'" ';
}
if ($title != '')
{
$link .= 'title="'.$title.'" ';
}
$link .= '/>';
}
return $link;
}
}
// ------------------------------------------------------------------------
/**
* Generates meta tags from an array of key/values
*
* @access public
* @param array
* @return string
*/
if ( ! function_exists('meta'))
{
function meta($name = '', $content = '', $type = 'name', $newline = "\n")
{
// Since we allow the data to be passes as a string, a simple array
// or a multidimensional one, we need to do a little prepping.
if ( ! is_array($name))
{
$name = array(array('name' => $name, 'content' => $content, 'type' => $type, 'newline' => $newline));
}
else
{
// Turn single array into multidimensional
if (isset($name['name']))
{
$name = array($name);
}
}
$str = '';
foreach ($name as $meta)
{
$type = ( ! isset($meta['type']) OR $meta['type'] == 'name') ? 'name' : 'http-equiv';
$name = ( ! isset($meta['name'])) ? '' : $meta['name'];
$content = ( ! isset($meta['content'])) ? '' : $meta['content'];
$newline = ( ! isset($meta['newline'])) ? "\n" : $meta['newline'];
$str .= '<meta '.$type.'="'.$name.'" content="'.$content.'" />'.$newline;
}
return $str;
}
}
// ------------------------------------------------------------------------
/**
* Generates non-breaking space entities based on number supplied
*
* @access public
* @param integer
* @return string
*/
if ( ! function_exists('nbs'))
{
function nbs($num = 1)
{
return str_repeat(" ", $num);
}
}
/* End of file html_helper.php */
/* Location: ./system/helpers/html_helper.php */ | php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/helpers/url_helper.php | system/helpers/url_helper.php | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 5.1.6 or newer
*
* @package CodeIgniter
* @author ExpressionEngine Dev Team
* @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
* @license http://codeigniter.com/user_guide/license.html
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
// ------------------------------------------------------------------------
/**
* CodeIgniter URL Helpers
*
* @package CodeIgniter
* @subpackage Helpers
* @category Helpers
* @author ExpressionEngine Dev Team
* @link http://codeigniter.com/user_guide/helpers/url_helper.html
*/
// ------------------------------------------------------------------------
/**
* Site URL
*
* Create a local URL based on your basepath. Segments can be passed via the
* first parameter either as a string or an array.
*
* @access public
* @param string
* @return string
*/
if ( ! function_exists('site_url'))
{
function site_url($uri = '')
{
$CI =& get_instance();
return $CI->config->site_url($uri);
}
}
// ------------------------------------------------------------------------
/**
* Base URL
*
* Create a local URL based on your basepath.
* Segments can be passed in as a string or an array, same as site_url
* or a URL to a file can be passed in, e.g. to an image file.
*
* @access public
* @param string
* @return string
*/
if ( ! function_exists('base_url'))
{
function base_url($uri = '')
{
$CI =& get_instance();
return $CI->config->base_url($uri);
}
}
// ------------------------------------------------------------------------
/**
* Current URL
*
* Returns the full URL (including segments) of the page where this
* function is placed
*
* @access public
* @return string
*/
if ( ! function_exists('current_url'))
{
function current_url()
{
$CI =& get_instance();
return $CI->config->site_url($CI->uri->uri_string());
}
}
// ------------------------------------------------------------------------
/**
* URL String
*
* Returns the URI segments.
*
* @access public
* @return string
*/
if ( ! function_exists('uri_string'))
{
function uri_string()
{
$CI =& get_instance();
return $CI->uri->uri_string();
}
}
// ------------------------------------------------------------------------
/**
* Index page
*
* Returns the "index_page" from your config file
*
* @access public
* @return string
*/
if ( ! function_exists('index_page'))
{
function index_page()
{
$CI =& get_instance();
return $CI->config->item('index_page');
}
}
// ------------------------------------------------------------------------
/**
* Anchor Link
*
* Creates an anchor based on the local URL.
*
* @access public
* @param string the URL
* @param string the link title
* @param mixed any attributes
* @return string
*/
if ( ! function_exists('anchor'))
{
function anchor($uri = '', $title = '', $attributes = '')
{
$title = (string) $title;
if ( ! is_array($uri))
{
$site_url = ( ! preg_match('!^\w+://! i', $uri)) ? site_url($uri) : $uri;
}
else
{
$site_url = site_url($uri);
}
if ($title == '')
{
$title = $site_url;
}
if ($attributes != '')
{
$attributes = _parse_attributes($attributes);
}
return '<a href="'.$site_url.'"'.$attributes.'>'.$title.'</a>';
}
}
// ------------------------------------------------------------------------
/**
* Anchor Link - Pop-up version
*
* Creates an anchor based on the local URL. The link
* opens a new window based on the attributes specified.
*
* @access public
* @param string the URL
* @param string the link title
* @param mixed any attributes
* @return string
*/
if ( ! function_exists('anchor_popup'))
{
function anchor_popup($uri = '', $title = '', $attributes = FALSE)
{
$title = (string) $title;
$site_url = ( ! preg_match('!^\w+://! i', $uri)) ? site_url($uri) : $uri;
if ($title == '')
{
$title = $site_url;
}
if ($attributes === FALSE)
{
return "<a href='javascript:void(0);' onclick=\"window.open('".$site_url."', '_blank');\">".$title."</a>";
}
if ( ! is_array($attributes))
{
$attributes = array();
}
foreach (array('width' => '800', 'height' => '600', 'scrollbars' => 'yes', 'status' => 'yes', 'resizable' => 'yes', 'screenx' => '0', 'screeny' => '0', ) as $key => $val)
{
$atts[$key] = ( ! isset($attributes[$key])) ? $val : $attributes[$key];
unset($attributes[$key]);
}
if ($attributes != '')
{
$attributes = _parse_attributes($attributes);
}
return "<a href='javascript:void(0);' onclick=\"window.open('".$site_url."', '_blank', '"._parse_attributes($atts, TRUE)."');\"$attributes>".$title."</a>";
}
}
// ------------------------------------------------------------------------
/**
* Mailto Link
*
* @access public
* @param string the email address
* @param string the link title
* @param mixed any attributes
* @return string
*/
if ( ! function_exists('mailto'))
{
function mailto($email, $title = '', $attributes = '')
{
$title = (string) $title;
if ($title == "")
{
$title = $email;
}
$attributes = _parse_attributes($attributes);
return '<a href="mailto:'.$email.'"'.$attributes.'>'.$title.'</a>';
}
}
// ------------------------------------------------------------------------
/**
* Encoded Mailto Link
*
* Create a spam-protected mailto link written in Javascript
*
* @access public
* @param string the email address
* @param string the link title
* @param mixed any attributes
* @return string
*/
if ( ! function_exists('safe_mailto'))
{
function safe_mailto($email, $title = '', $attributes = '')
{
$title = (string) $title;
if ($title == "")
{
$title = $email;
}
for ($i = 0; $i < 16; $i++)
{
$x[] = substr('<a href="mailto:', $i, 1);
}
for ($i = 0; $i < strlen($email); $i++)
{
$x[] = "|".ord(substr($email, $i, 1));
}
$x[] = '"';
if ($attributes != '')
{
if (is_array($attributes))
{
foreach ($attributes as $key => $val)
{
$x[] = ' '.$key.'="';
for ($i = 0; $i < strlen($val); $i++)
{
$x[] = "|".ord(substr($val, $i, 1));
}
$x[] = '"';
}
}
else
{
for ($i = 0; $i < strlen($attributes); $i++)
{
$x[] = substr($attributes, $i, 1);
}
}
}
$x[] = '>';
$temp = array();
for ($i = 0; $i < strlen($title); $i++)
{
$ordinal = ord($title[$i]);
if ($ordinal < 128)
{
$x[] = "|".$ordinal;
}
else
{
if (count($temp) == 0)
{
$count = ($ordinal < 224) ? 2 : 3;
}
$temp[] = $ordinal;
if (count($temp) == $count)
{
$number = ($count == 3) ? (($temp['0'] % 16) * 4096) + (($temp['1'] % 64) * 64) + ($temp['2'] % 64) : (($temp['0'] % 32) * 64) + ($temp['1'] % 64);
$x[] = "|".$number;
$count = 1;
$temp = array();
}
}
}
$x[] = '<'; $x[] = '/'; $x[] = 'a'; $x[] = '>';
$x = array_reverse($x);
ob_start();
?><script type="text/javascript">
//<![CDATA[
var l=new Array();
<?php
$i = 0;
foreach ($x as $val){ ?>l[<?php echo $i++; ?>]='<?php echo $val; ?>';<?php } ?>
for (var i = l.length-1; i >= 0; i=i-1){
if (l[i].substring(0, 1) == '|') document.write("&#"+unescape(l[i].substring(1))+";");
else document.write(unescape(l[i]));}
//]]>
</script><?php
$buffer = ob_get_contents();
ob_end_clean();
return $buffer;
}
}
// ------------------------------------------------------------------------
/**
* Auto-linker
*
* Automatically links URL and Email addresses.
* Note: There's a bit of extra code here to deal with
* URLs or emails that end in a period. We'll strip these
* off and add them after the link.
*
* @access public
* @param string the string
* @param string the type: email, url, or both
* @param bool whether to create pop-up links
* @return string
*/
if ( ! function_exists('auto_link'))
{
function auto_link($str, $type = 'both', $popup = FALSE)
{
if ($type != 'email')
{
if (preg_match_all("#(^|\s|\()((http(s?)://)|(www\.))(\w+[^\s\)\<]+)#i", $str, $matches))
{
$pop = ($popup == TRUE) ? " target=\"_blank\" " : "";
for ($i = 0; $i < count($matches['0']); $i++)
{
$period = '';
if (preg_match("|\.$|", $matches['6'][$i]))
{
$period = '.';
$matches['6'][$i] = substr($matches['6'][$i], 0, -1);
}
$str = str_replace($matches['0'][$i],
$matches['1'][$i].'<a href="http'.
$matches['4'][$i].'://'.
$matches['5'][$i].
$matches['6'][$i].'"'.$pop.'>http'.
$matches['4'][$i].'://'.
$matches['5'][$i].
$matches['6'][$i].'</a>'.
$period, $str);
}
}
}
if ($type != 'url')
{
if (preg_match_all("/([a-zA-Z0-9_\.\-\+]+)@([a-zA-Z0-9\-]+)\.([a-zA-Z0-9\-\.]*)/i", $str, $matches))
{
for ($i = 0; $i < count($matches['0']); $i++)
{
$period = '';
if (preg_match("|\.$|", $matches['3'][$i]))
{
$period = '.';
$matches['3'][$i] = substr($matches['3'][$i], 0, -1);
}
$str = str_replace($matches['0'][$i], safe_mailto($matches['1'][$i].'@'.$matches['2'][$i].'.'.$matches['3'][$i]).$period, $str);
}
}
}
return $str;
}
}
// ------------------------------------------------------------------------
/**
* Prep URL
*
* Simply adds the http:// part if no scheme is included
*
* @access public
* @param string the URL
* @return string
*/
if ( ! function_exists('prep_url'))
{
function prep_url($str = '')
{
if ($str == 'http://' OR $str == '')
{
return '';
}
$url = parse_url($str);
if ( ! $url OR ! isset($url['scheme']))
{
$str = 'http://'.$str;
}
return $str;
}
}
// ------------------------------------------------------------------------
/**
* Create URL Title
*
* Takes a "title" string as input and creates a
* human-friendly URL string with a "separator" string
* as the word separator.
*
* @access public
* @param string the string
* @param string the separator
* @return string
*/
if ( ! function_exists('url_title'))
{
function url_title($str, $separator = '-', $lowercase = FALSE)
{
if ($separator == 'dash')
{
$separator = '-';
}
else if ($separator == 'underscore')
{
$separator = '_';
}
$q_separator = preg_quote($separator);
$trans = array(
'&.+?;' => '',
'[^a-z0-9 _-]' => '',
'\s+' => $separator,
'('.$q_separator.')+' => $separator
);
$str = strip_tags($str);
foreach ($trans as $key => $val)
{
$str = preg_replace("#".$key."#i", $val, $str);
}
if ($lowercase === TRUE)
{
$str = strtolower($str);
}
return trim($str, $separator);
}
}
// ------------------------------------------------------------------------
/**
* Header Redirect
*
* Header redirect in two flavors
* For very fine grained control over headers, you could use the Output
* Library's set_header() function.
*
* @access public
* @param string the URL
* @param string the method: location or redirect
* @return string
*/
if ( ! function_exists('redirect'))
{
function redirect($uri = '', $method = 'location', $http_response_code = 302)
{
if ( ! preg_match('#^https?://#i', $uri))
{
$uri = site_url($uri);
}
switch($method)
{
case 'refresh' : header("Refresh:0;url=".$uri);
break;
default : header("Location: ".$uri, TRUE, $http_response_code);
break;
}
exit;
}
}
// ------------------------------------------------------------------------
/**
* Parse out the attributes
*
* Some of the functions use this
*
* @access private
* @param array
* @param bool
* @return string
*/
if ( ! function_exists('_parse_attributes'))
{
function _parse_attributes($attributes, $javascript = FALSE)
{
if (is_string($attributes))
{
return ($attributes != '') ? ' '.$attributes : '';
}
$att = '';
foreach ($attributes as $key => $val)
{
if ($javascript == TRUE)
{
$att .= $key . '=' . $val . ',';
}
else
{
$att .= ' ' . $key . '="' . $val . '"';
}
}
if ($javascript == TRUE AND $att != '')
{
$att = substr($att, 0, -1);
}
return $att;
}
}
/* End of file url_helper.php */
/* Location: ./system/helpers/url_helper.php */ | php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/helpers/captcha_helper.php | system/helpers/captcha_helper.php | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 5.1.6 or newer
*
* @package CodeIgniter
* @author ExpressionEngine Dev Team
* @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
* @license http://codeigniter.com/user_guide/license.html
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
// ------------------------------------------------------------------------
/**
* CodeIgniter CAPTCHA Helper
*
* @package CodeIgniter
* @subpackage Helpers
* @category Helpers
* @author ExpressionEngine Dev Team
* @link http://codeigniter.com/user_guide/helpers/xml_helper.html
*/
// ------------------------------------------------------------------------
/**
* Create CAPTCHA
*
* @access public
* @param array array of data for the CAPTCHA
* @param string path to create the image in
* @param string URL to the CAPTCHA image folder
* @param string server path to font
* @return string
*/
if ( ! function_exists('create_captcha'))
{
function create_captcha($data = '', $img_path = '', $img_url = '', $font_path = '')
{
$defaults = array('word' => '', 'img_path' => '', 'img_url' => '', 'img_width' => '150', 'img_height' => '30', 'font_path' => '', 'expiration' => 7200);
foreach ($defaults as $key => $val)
{
if ( ! is_array($data))
{
if ( ! isset($$key) OR $$key == '')
{
$$key = $val;
}
}
else
{
$$key = ( ! isset($data[$key])) ? $val : $data[$key];
}
}
if ($img_path == '' OR $img_url == '')
{
return FALSE;
}
if ( ! @is_dir($img_path))
{
return FALSE;
}
if ( ! is_writable($img_path))
{
return FALSE;
}
if ( ! extension_loaded('gd'))
{
return FALSE;
}
// -----------------------------------
// Remove old images
// -----------------------------------
list($usec, $sec) = explode(" ", microtime());
$now = ((float)$usec + (float)$sec);
$current_dir = @opendir($img_path);
while ($filename = @readdir($current_dir))
{
if ($filename != "." and $filename != ".." and $filename != "index.html")
{
$name = str_replace(".jpg", "", $filename);
if (($name + $expiration) < $now)
{
@unlink($img_path.$filename);
}
}
}
@closedir($current_dir);
// -----------------------------------
// Do we have a "word" yet?
// -----------------------------------
if ($word == '')
{
$pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$str = '';
for ($i = 0; $i < 8; $i++)
{
$str .= substr($pool, mt_rand(0, strlen($pool) -1), 1);
}
$word = $str;
}
// -----------------------------------
// Determine angle and position
// -----------------------------------
$length = strlen($word);
$angle = ($length >= 6) ? rand(-($length-6), ($length-6)) : 0;
$x_axis = rand(6, (360/$length)-16);
$y_axis = ($angle >= 0 ) ? rand($img_height, $img_width) : rand(6, $img_height);
// -----------------------------------
// Create image
// -----------------------------------
// PHP.net recommends imagecreatetruecolor(), but it isn't always available
if (function_exists('imagecreatetruecolor'))
{
$im = imagecreatetruecolor($img_width, $img_height);
}
else
{
$im = imagecreate($img_width, $img_height);
}
// -----------------------------------
// Assign colors
// -----------------------------------
$bg_color = imagecolorallocate ($im, 255, 255, 255);
$border_color = imagecolorallocate ($im, 153, 102, 102);
$text_color = imagecolorallocate ($im, 204, 153, 153);
$grid_color = imagecolorallocate($im, 255, 182, 182);
$shadow_color = imagecolorallocate($im, 255, 240, 240);
// -----------------------------------
// Create the rectangle
// -----------------------------------
ImageFilledRectangle($im, 0, 0, $img_width, $img_height, $bg_color);
// -----------------------------------
// Create the spiral pattern
// -----------------------------------
$theta = 1;
$thetac = 7;
$radius = 16;
$circles = 20;
$points = 32;
for ($i = 0; $i < ($circles * $points) - 1; $i++)
{
$theta = $theta + $thetac;
$rad = $radius * ($i / $points );
$x = ($rad * cos($theta)) + $x_axis;
$y = ($rad * sin($theta)) + $y_axis;
$theta = $theta + $thetac;
$rad1 = $radius * (($i + 1) / $points);
$x1 = ($rad1 * cos($theta)) + $x_axis;
$y1 = ($rad1 * sin($theta )) + $y_axis;
imageline($im, $x, $y, $x1, $y1, $grid_color);
$theta = $theta - $thetac;
}
// -----------------------------------
// Write the text
// -----------------------------------
$use_font = ($font_path != '' AND file_exists($font_path) AND function_exists('imagettftext')) ? TRUE : FALSE;
if ($use_font == FALSE)
{
$font_size = 5;
$x = rand(0, $img_width/($length/3));
$y = 0;
}
else
{
$font_size = 16;
$x = rand(0, $img_width/($length/1.5));
$y = $font_size+2;
}
for ($i = 0; $i < strlen($word); $i++)
{
if ($use_font == FALSE)
{
$y = rand(0 , $img_height/2);
imagestring($im, $font_size, $x, $y, substr($word, $i, 1), $text_color);
$x += ($font_size*2);
}
else
{
$y = rand($img_height/2, $img_height-3);
imagettftext($im, $font_size, $angle, $x, $y, $text_color, $font_path, substr($word, $i, 1));
$x += $font_size;
}
}
// -----------------------------------
// Create the border
// -----------------------------------
imagerectangle($im, 0, 0, $img_width-1, $img_height-1, $border_color);
// -----------------------------------
// Generate the image
// -----------------------------------
$img_name = $now.'.jpg';
ImageJPEG($im, $img_path.$img_name);
$img = "<img src=\"$img_url$img_name\" width=\"$img_width\" height=\"$img_height\" style=\"border:0;\" alt=\" \" />";
ImageDestroy($im);
return array('word' => $word, 'time' => $now, 'image' => $img);
}
}
// ------------------------------------------------------------------------
/* End of file captcha_helper.php */
/* Location: ./system/heleprs/captcha_helper.php */ | php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/helpers/form_helper.php | system/helpers/form_helper.php | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 5.1.6 or newer
*
* @package CodeIgniter
* @author ExpressionEngine Dev Team
* @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
* @license http://codeigniter.com/user_guide/license.html
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
// ------------------------------------------------------------------------
/**
* CodeIgniter Form Helpers
*
* @package CodeIgniter
* @subpackage Helpers
* @category Helpers
* @author ExpressionEngine Dev Team
* @link http://codeigniter.com/user_guide/helpers/form_helper.html
*/
// ------------------------------------------------------------------------
/**
* Form Declaration
*
* Creates the opening portion of the form.
*
* @access public
* @param string the URI segments of the form destination
* @param array a key/value pair of attributes
* @param array a key/value pair hidden data
* @return string
*/
if ( ! function_exists('form_open'))
{
function form_open($action = '', $attributes = '', $hidden = array())
{
$CI =& get_instance();
if ($attributes == '')
{
$attributes = 'method="post"';
}
// If an action is not a full URL then turn it into one
if ($action && strpos($action, '://') === FALSE)
{
$action = $CI->config->site_url($action);
}
// If no action is provided then set to the current url
$action OR $action = $CI->config->site_url($CI->uri->uri_string());
$form = '<form action="'.$action.'"';
$form .= _attributes_to_string($attributes, TRUE);
$form .= '>';
// Add CSRF field if enabled, but leave it out for GET requests and requests to external websites
if ($CI->config->item('csrf_protection') === TRUE AND ! (strpos($action, $CI->config->base_url()) === FALSE OR strpos($form, 'method="get"')))
{
$hidden[$CI->security->get_csrf_token_name()] = $CI->security->get_csrf_hash();
}
if (is_array($hidden) AND count($hidden) > 0)
{
$form .= sprintf("<div style=\"display:none\">%s</div>", form_hidden($hidden));
}
return $form;
}
}
// ------------------------------------------------------------------------
/**
* Form Declaration - Multipart type
*
* Creates the opening portion of the form, but with "multipart/form-data".
*
* @access public
* @param string the URI segments of the form destination
* @param array a key/value pair of attributes
* @param array a key/value pair hidden data
* @return string
*/
if ( ! function_exists('form_open_multipart'))
{
function form_open_multipart($action = '', $attributes = array(), $hidden = array())
{
if (is_string($attributes))
{
$attributes .= ' enctype="multipart/form-data"';
}
else
{
$attributes['enctype'] = 'multipart/form-data';
}
return form_open($action, $attributes, $hidden);
}
}
// ------------------------------------------------------------------------
/**
* Hidden Input Field
*
* Generates hidden fields. You can pass a simple key/value string or an associative
* array with multiple values.
*
* @access public
* @param mixed
* @param string
* @return string
*/
if ( ! function_exists('form_hidden'))
{
function form_hidden($name, $value = '', $recursing = FALSE)
{
static $form;
if ($recursing === FALSE)
{
$form = "\n";
}
if (is_array($name))
{
foreach ($name as $key => $val)
{
form_hidden($key, $val, TRUE);
}
return $form;
}
if ( ! is_array($value))
{
$form .= '<input type="hidden" name="'.$name.'" value="'.form_prep($value, $name).'" />'."\n";
}
else
{
foreach ($value as $k => $v)
{
$k = (is_int($k)) ? '' : $k;
form_hidden($name.'['.$k.']', $v, TRUE);
}
}
return $form;
}
}
// ------------------------------------------------------------------------
/**
* Text Input Field
*
* @access public
* @param mixed
* @param string
* @param string
* @return string
*/
if ( ! function_exists('form_input'))
{
function form_input($data = '', $value = '', $extra = '')
{
$defaults = array('type' => 'text', 'name' => (( ! is_array($data)) ? $data : ''), 'value' => $value);
return "<input "._parse_form_attributes($data, $defaults).$extra." />";
}
}
// ------------------------------------------------------------------------
/**
* Password Field
*
* Identical to the input function but adds the "password" type
*
* @access public
* @param mixed
* @param string
* @param string
* @return string
*/
if ( ! function_exists('form_password'))
{
function form_password($data = '', $value = '', $extra = '')
{
if ( ! is_array($data))
{
$data = array('name' => $data);
}
$data['type'] = 'password';
return form_input($data, $value, $extra);
}
}
// ------------------------------------------------------------------------
/**
* Upload Field
*
* Identical to the input function but adds the "file" type
*
* @access public
* @param mixed
* @param string
* @param string
* @return string
*/
if ( ! function_exists('form_upload'))
{
function form_upload($data = '', $value = '', $extra = '')
{
if ( ! is_array($data))
{
$data = array('name' => $data);
}
$data['type'] = 'file';
return form_input($data, $value, $extra);
}
}
// ------------------------------------------------------------------------
/**
* Textarea field
*
* @access public
* @param mixed
* @param string
* @param string
* @return string
*/
if ( ! function_exists('form_textarea'))
{
function form_textarea($data = '', $value = '', $extra = '')
{
$defaults = array('name' => (( ! is_array($data)) ? $data : ''), 'cols' => '40', 'rows' => '10');
if ( ! is_array($data) OR ! isset($data['value']))
{
$val = $value;
}
else
{
$val = $data['value'];
unset($data['value']); // textareas don't use the value attribute
}
$name = (is_array($data)) ? $data['name'] : $data;
return "<textarea "._parse_form_attributes($data, $defaults).$extra.">".form_prep($val, $name)."</textarea>";
}
}
// ------------------------------------------------------------------------
/**
* Multi-select menu
*
* @access public
* @param string
* @param array
* @param mixed
* @param string
* @return type
*/
if ( ! function_exists('form_multiselect'))
{
function form_multiselect($name = '', $options = array(), $selected = array(), $extra = '')
{
if ( ! strpos($extra, 'multiple'))
{
$extra .= ' multiple="multiple"';
}
return form_dropdown($name, $options, $selected, $extra);
}
}
// --------------------------------------------------------------------
/**
* Drop-down Menu
*
* @access public
* @param string
* @param array
* @param string
* @param string
* @return string
*/
if ( ! function_exists('form_dropdown'))
{
function form_dropdown($name = '', $options = array(), $selected = array(), $extra = '')
{
if ( ! is_array($selected))
{
$selected = array($selected);
}
// If no selected state was submitted we will attempt to set it automatically
if (count($selected) === 0)
{
// If the form name appears in the $_POST array we have a winner!
if (isset($_POST[$name]))
{
$selected = array($_POST[$name]);
}
}
if ($extra != '') $extra = ' '.$extra;
$multiple = (count($selected) > 1 && strpos($extra, 'multiple') === FALSE) ? ' multiple="multiple"' : '';
$form = '<select name="'.$name.'"'.$extra.$multiple.">\n";
foreach ($options as $key => $val)
{
$key = (string) $key;
if (is_array($val) && ! empty($val))
{
$form .= '<optgroup label="'.$key.'">'."\n";
foreach ($val as $optgroup_key => $optgroup_val)
{
$sel = (in_array($optgroup_key, $selected)) ? ' selected="selected"' : '';
$form .= '<option value="'.$optgroup_key.'"'.$sel.'>'.(string) $optgroup_val."</option>\n";
}
$form .= '</optgroup>'."\n";
}
else
{
$sel = (in_array($key, $selected)) ? ' selected="selected"' : '';
$form .= '<option value="'.$key.'"'.$sel.'>'.(string) $val."</option>\n";
}
}
$form .= '</select>';
return $form;
}
}
// ------------------------------------------------------------------------
/**
* Checkbox Field
*
* @access public
* @param mixed
* @param string
* @param bool
* @param string
* @return string
*/
if ( ! function_exists('form_checkbox'))
{
function form_checkbox($data = '', $value = '', $checked = FALSE, $extra = '')
{
$defaults = array('type' => 'checkbox', 'name' => (( ! is_array($data)) ? $data : ''), 'value' => $value);
if (is_array($data) AND array_key_exists('checked', $data))
{
$checked = $data['checked'];
if ($checked == FALSE)
{
unset($data['checked']);
}
else
{
$data['checked'] = 'checked';
}
}
if ($checked == TRUE)
{
$defaults['checked'] = 'checked';
}
else
{
unset($defaults['checked']);
}
return "<input "._parse_form_attributes($data, $defaults).$extra." />";
}
}
// ------------------------------------------------------------------------
/**
* Radio Button
*
* @access public
* @param mixed
* @param string
* @param bool
* @param string
* @return string
*/
if ( ! function_exists('form_radio'))
{
function form_radio($data = '', $value = '', $checked = FALSE, $extra = '')
{
if ( ! is_array($data))
{
$data = array('name' => $data);
}
$data['type'] = 'radio';
return form_checkbox($data, $value, $checked, $extra);
}
}
// ------------------------------------------------------------------------
/**
* Submit Button
*
* @access public
* @param mixed
* @param string
* @param string
* @return string
*/
if ( ! function_exists('form_submit'))
{
function form_submit($data = '', $value = '', $extra = '')
{
$defaults = array('type' => 'submit', 'name' => (( ! is_array($data)) ? $data : ''), 'value' => $value);
return "<input "._parse_form_attributes($data, $defaults).$extra." />";
}
}
// ------------------------------------------------------------------------
/**
* Reset Button
*
* @access public
* @param mixed
* @param string
* @param string
* @return string
*/
if ( ! function_exists('form_reset'))
{
function form_reset($data = '', $value = '', $extra = '')
{
$defaults = array('type' => 'reset', 'name' => (( ! is_array($data)) ? $data : ''), 'value' => $value);
return "<input "._parse_form_attributes($data, $defaults).$extra." />";
}
}
// ------------------------------------------------------------------------
/**
* Form Button
*
* @access public
* @param mixed
* @param string
* @param string
* @return string
*/
if ( ! function_exists('form_button'))
{
function form_button($data = '', $content = '', $extra = '')
{
$defaults = array('name' => (( ! is_array($data)) ? $data : ''), 'type' => 'button');
if ( is_array($data) AND isset($data['content']))
{
$content = $data['content'];
unset($data['content']); // content is not an attribute
}
return "<button "._parse_form_attributes($data, $defaults).$extra.">".$content."</button>";
}
}
// ------------------------------------------------------------------------
/**
* Form Label Tag
*
* @access public
* @param string The text to appear onscreen
* @param string The id the label applies to
* @param string Additional attributes
* @return string
*/
if ( ! function_exists('form_label'))
{
function form_label($label_text = '', $id = '', $attributes = array())
{
$label = '<label';
if ($id != '')
{
$label .= " for=\"$id\"";
}
if (is_array($attributes) AND count($attributes) > 0)
{
foreach ($attributes as $key => $val)
{
$label .= ' '.$key.'="'.$val.'"';
}
}
$label .= ">$label_text</label>";
return $label;
}
}
// ------------------------------------------------------------------------
/**
* Fieldset Tag
*
* Used to produce <fieldset><legend>text</legend>. To close fieldset
* use form_fieldset_close()
*
* @access public
* @param string The legend text
* @param string Additional attributes
* @return string
*/
if ( ! function_exists('form_fieldset'))
{
function form_fieldset($legend_text = '', $attributes = array())
{
$fieldset = "<fieldset";
$fieldset .= _attributes_to_string($attributes, FALSE);
$fieldset .= ">\n";
if ($legend_text != '')
{
$fieldset .= "<legend>$legend_text</legend>\n";
}
return $fieldset;
}
}
// ------------------------------------------------------------------------
/**
* Fieldset Close Tag
*
* @access public
* @param string
* @return string
*/
if ( ! function_exists('form_fieldset_close'))
{
function form_fieldset_close($extra = '')
{
return "</fieldset>".$extra;
}
}
// ------------------------------------------------------------------------
/**
* Form Close Tag
*
* @access public
* @param string
* @return string
*/
if ( ! function_exists('form_close'))
{
function form_close($extra = '')
{
return "</form>".$extra;
}
}
// ------------------------------------------------------------------------
/**
* Form Prep
*
* Formats text so that it can be safely placed in a form field in the event it has HTML tags.
*
* @access public
* @param string
* @return string
*/
if ( ! function_exists('form_prep'))
{
function form_prep($str = '', $field_name = '')
{
static $prepped_fields = array();
// if the field name is an array we do this recursively
if (is_array($str))
{
foreach ($str as $key => $val)
{
$str[$key] = form_prep($val);
}
return $str;
}
if ($str === '')
{
return '';
}
// we've already prepped a field with this name
// @todo need to figure out a way to namespace this so
// that we know the *exact* field and not just one with
// the same name
if (isset($prepped_fields[$field_name]))
{
return $str;
}
$str = htmlspecialchars($str);
// In case htmlspecialchars misses these.
$str = str_replace(array("'", '"'), array("'", """), $str);
if ($field_name != '')
{
$prepped_fields[$field_name] = $field_name;
}
return $str;
}
}
// ------------------------------------------------------------------------
/**
* Form Value
*
* Grabs a value from the POST array for the specified field so you can
* re-populate an input field or textarea. If Form Validation
* is active it retrieves the info from the validation class
*
* @access public
* @param string
* @return mixed
*/
if ( ! function_exists('set_value'))
{
function set_value($field = '', $default = '')
{
if (FALSE === ($OBJ =& _get_validation_object()))
{
if ( ! isset($_POST[$field]))
{
return $default;
}
return form_prep($_POST[$field], $field);
}
return form_prep($OBJ->set_value($field, $default), $field);
}
}
// ------------------------------------------------------------------------
/**
* Set Select
*
* Let's you set the selected value of a <select> menu via data in the POST array.
* If Form Validation is active it retrieves the info from the validation class
*
* @access public
* @param string
* @param string
* @param bool
* @return string
*/
if ( ! function_exists('set_select'))
{
function set_select($field = '', $value = '', $default = FALSE)
{
$OBJ =& _get_validation_object();
if ($OBJ === FALSE)
{
if ( ! isset($_POST[$field]))
{
if (count($_POST) === 0 AND $default == TRUE)
{
return ' selected="selected"';
}
return '';
}
$field = $_POST[$field];
if (is_array($field))
{
if ( ! in_array($value, $field))
{
return '';
}
}
else
{
if (($field == '' OR $value == '') OR ($field != $value))
{
return '';
}
}
return ' selected="selected"';
}
return $OBJ->set_select($field, $value, $default);
}
}
// ------------------------------------------------------------------------
/**
* Set Checkbox
*
* Let's you set the selected value of a checkbox via the value in the POST array.
* If Form Validation is active it retrieves the info from the validation class
*
* @access public
* @param string
* @param string
* @param bool
* @return string
*/
if ( ! function_exists('set_checkbox'))
{
function set_checkbox($field = '', $value = '', $default = FALSE)
{
$OBJ =& _get_validation_object();
if ($OBJ === FALSE)
{
if ( ! isset($_POST[$field]))
{
if (count($_POST) === 0 AND $default == TRUE)
{
return ' checked="checked"';
}
return '';
}
$field = $_POST[$field];
if (is_array($field))
{
if ( ! in_array($value, $field))
{
return '';
}
}
else
{
if (($field == '' OR $value == '') OR ($field != $value))
{
return '';
}
}
return ' checked="checked"';
}
return $OBJ->set_checkbox($field, $value, $default);
}
}
// ------------------------------------------------------------------------
/**
* Set Radio
*
* Let's you set the selected value of a radio field via info in the POST array.
* If Form Validation is active it retrieves the info from the validation class
*
* @access public
* @param string
* @param string
* @param bool
* @return string
*/
if ( ! function_exists('set_radio'))
{
function set_radio($field = '', $value = '', $default = FALSE)
{
$OBJ =& _get_validation_object();
if ($OBJ === FALSE)
{
if ( ! isset($_POST[$field]))
{
if (count($_POST) === 0 AND $default == TRUE)
{
return ' checked="checked"';
}
return '';
}
$field = $_POST[$field];
if (is_array($field))
{
if ( ! in_array($value, $field))
{
return '';
}
}
else
{
if (($field == '' OR $value == '') OR ($field != $value))
{
return '';
}
}
return ' checked="checked"';
}
return $OBJ->set_radio($field, $value, $default);
}
}
// ------------------------------------------------------------------------
/**
* Form Error
*
* Returns the error for a specific form field. This is a helper for the
* form validation class.
*
* @access public
* @param string
* @param string
* @param string
* @return string
*/
if ( ! function_exists('form_error'))
{
function form_error($field = '', $prefix = '', $suffix = '')
{
if (FALSE === ($OBJ =& _get_validation_object()))
{
return '';
}
return $OBJ->error($field, $prefix, $suffix);
}
}
// ------------------------------------------------------------------------
/**
* Validation Error String
*
* Returns all the errors associated with a form submission. This is a helper
* function for the form validation class.
*
* @access public
* @param string
* @param string
* @return string
*/
if ( ! function_exists('validation_errors'))
{
function validation_errors($prefix = '', $suffix = '')
{
if (FALSE === ($OBJ =& _get_validation_object()))
{
return '';
}
return $OBJ->error_string($prefix, $suffix);
}
}
// ------------------------------------------------------------------------
/**
* Parse the form attributes
*
* Helper function used by some of the form helpers
*
* @access private
* @param array
* @param array
* @return string
*/
if ( ! function_exists('_parse_form_attributes'))
{
function _parse_form_attributes($attributes, $default)
{
if (is_array($attributes))
{
foreach ($default as $key => $val)
{
if (isset($attributes[$key]))
{
$default[$key] = $attributes[$key];
unset($attributes[$key]);
}
}
if (count($attributes) > 0)
{
$default = array_merge($default, $attributes);
}
}
$att = '';
foreach ($default as $key => $val)
{
if ($key == 'value')
{
$val = form_prep($val, $default['name']);
}
$att .= $key . '="' . $val . '" ';
}
return $att;
}
}
// ------------------------------------------------------------------------
/**
* Attributes To String
*
* Helper function used by some of the form helpers
*
* @access private
* @param mixed
* @param bool
* @return string
*/
if ( ! function_exists('_attributes_to_string'))
{
function _attributes_to_string($attributes, $formtag = FALSE)
{
if (is_string($attributes) AND strlen($attributes) > 0)
{
if ($formtag == TRUE AND strpos($attributes, 'method=') === FALSE)
{
$attributes .= ' method="post"';
}
if ($formtag == TRUE AND strpos($attributes, 'accept-charset=') === FALSE)
{
$attributes .= ' accept-charset="'.strtolower(config_item('charset')).'"';
}
return ' '.$attributes;
}
if (is_object($attributes) AND count($attributes) > 0)
{
$attributes = (array)$attributes;
}
if (is_array($attributes) AND count($attributes) > 0)
{
$atts = '';
if ( ! isset($attributes['method']) AND $formtag === TRUE)
{
$atts .= ' method="post"';
}
if ( ! isset($attributes['accept-charset']) AND $formtag === TRUE)
{
$atts .= ' accept-charset="'.strtolower(config_item('charset')).'"';
}
foreach ($attributes as $key => $val)
{
$atts .= ' '.$key.'="'.$val.'"';
}
return $atts;
}
}
}
// ------------------------------------------------------------------------
/**
* Validation Object
*
* Determines what the form validation class was instantiated as, fetches
* the object and returns it.
*
* @access private
* @return mixed
*/
if ( ! function_exists('_get_validation_object'))
{
function &_get_validation_object()
{
$CI =& get_instance();
// We set this as a variable since we're returning by reference.
$return = FALSE;
if (FALSE !== ($object = $CI->load->is_loaded('form_validation')))
{
if ( ! isset($CI->$object) OR ! is_object($CI->$object))
{
return $return;
}
return $CI->$object;
}
return $return;
}
}
/* End of file form_helper.php */
/* Location: ./system/helpers/form_helper.php */
| php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/helpers/inflector_helper.php | system/helpers/inflector_helper.php | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 5.1.6 or newer
*
* @package CodeIgniter
* @author ExpressionEngine Dev Team
* @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
* @license http://codeigniter.com/user_guide/license.html
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
// ------------------------------------------------------------------------
/**
* CodeIgniter Inflector Helpers
*
* @package CodeIgniter
* @subpackage Helpers
* @category Helpers
* @author ExpressionEngine Dev Team
* @link http://codeigniter.com/user_guide/helpers/directory_helper.html
*/
// --------------------------------------------------------------------
/**
* Singular
*
* Takes a plural word and makes it singular
*
* @access public
* @param string
* @return str
*/
if ( ! function_exists('singular'))
{
function singular($str)
{
$result = strval($str);
$singular_rules = array(
'/(matr)ices$/' => '\1ix',
'/(vert|ind)ices$/' => '\1ex',
'/^(ox)en/' => '\1',
'/(alias)es$/' => '\1',
'/([octop|vir])i$/' => '\1us',
'/(cris|ax|test)es$/' => '\1is',
'/(shoe)s$/' => '\1',
'/(o)es$/' => '\1',
'/(bus|campus)es$/' => '\1',
'/([m|l])ice$/' => '\1ouse',
'/(x|ch|ss|sh)es$/' => '\1',
'/(m)ovies$/' => '\1\2ovie',
'/(s)eries$/' => '\1\2eries',
'/([^aeiouy]|qu)ies$/' => '\1y',
'/([lr])ves$/' => '\1f',
'/(tive)s$/' => '\1',
'/(hive)s$/' => '\1',
'/([^f])ves$/' => '\1fe',
'/(^analy)ses$/' => '\1sis',
'/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/' => '\1\2sis',
'/([ti])a$/' => '\1um',
'/(p)eople$/' => '\1\2erson',
'/(m)en$/' => '\1an',
'/(s)tatuses$/' => '\1\2tatus',
'/(c)hildren$/' => '\1\2hild',
'/(n)ews$/' => '\1\2ews',
'/([^u])s$/' => '\1',
);
foreach ($singular_rules as $rule => $replacement)
{
if (preg_match($rule, $result))
{
$result = preg_replace($rule, $replacement, $result);
break;
}
}
return $result;
}
}
// --------------------------------------------------------------------
/**
* Plural
*
* Takes a singular word and makes it plural
*
* @access public
* @param string
* @param bool
* @return str
*/
if ( ! function_exists('plural'))
{
function plural($str, $force = FALSE)
{
$result = strval($str);
$plural_rules = array(
'/^(ox)$/' => '\1\2en', // ox
'/([m|l])ouse$/' => '\1ice', // mouse, louse
'/(matr|vert|ind)ix|ex$/' => '\1ices', // matrix, vertex, index
'/(x|ch|ss|sh)$/' => '\1es', // search, switch, fix, box, process, address
'/([^aeiouy]|qu)y$/' => '\1ies', // query, ability, agency
'/(hive)$/' => '\1s', // archive, hive
'/(?:([^f])fe|([lr])f)$/' => '\1\2ves', // half, safe, wife
'/sis$/' => 'ses', // basis, diagnosis
'/([ti])um$/' => '\1a', // datum, medium
'/(p)erson$/' => '\1eople', // person, salesperson
'/(m)an$/' => '\1en', // man, woman, spokesman
'/(c)hild$/' => '\1hildren', // child
'/(buffal|tomat)o$/' => '\1\2oes', // buffalo, tomato
'/(bu|campu)s$/' => '\1\2ses', // bus, campus
'/(alias|status|virus)/' => '\1es', // alias
'/(octop)us$/' => '\1i', // octopus
'/(ax|cris|test)is$/' => '\1es', // axis, crisis
'/s$/' => 's', // no change (compatibility)
'/$/' => 's',
);
foreach ($plural_rules as $rule => $replacement)
{
if (preg_match($rule, $result))
{
$result = preg_replace($rule, $replacement, $result);
break;
}
}
return $result;
}
}
// --------------------------------------------------------------------
/**
* Camelize
*
* Takes multiple words separated by spaces or underscores and camelizes them
*
* @access public
* @param string
* @return str
*/
if ( ! function_exists('camelize'))
{
function camelize($str)
{
$str = 'x'.strtolower(trim($str));
$str = ucwords(preg_replace('/[\s_]+/', ' ', $str));
return substr(str_replace(' ', '', $str), 1);
}
}
// --------------------------------------------------------------------
/**
* Underscore
*
* Takes multiple words separated by spaces and underscores them
*
* @access public
* @param string
* @return str
*/
if ( ! function_exists('underscore'))
{
function underscore($str)
{
return preg_replace('/[\s]+/', '_', strtolower(trim($str)));
}
}
// --------------------------------------------------------------------
/**
* Humanize
*
* Takes multiple words separated by underscores and changes them to spaces
*
* @access public
* @param string
* @return str
*/
if ( ! function_exists('humanize'))
{
function humanize($str)
{
return ucwords(preg_replace('/[_]+/', ' ', strtolower(trim($str))));
}
}
/* End of file inflector_helper.php */
/* Location: ./system/helpers/inflector_helper.php */ | php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/helpers/string_helper.php | system/helpers/string_helper.php | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 5.1.6 or newer
*
* @package CodeIgniter
* @author ExpressionEngine Dev Team
* @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
* @license http://codeigniter.com/user_guide/license.html
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
// ------------------------------------------------------------------------
/**
* CodeIgniter String Helpers
*
* @package CodeIgniter
* @subpackage Helpers
* @category Helpers
* @author ExpressionEngine Dev Team
* @link http://codeigniter.com/user_guide/helpers/string_helper.html
*/
// ------------------------------------------------------------------------
/**
* Trim Slashes
*
* Removes any leading/trailing slashes from a string:
*
* /this/that/theother/
*
* becomes:
*
* this/that/theother
*
* @access public
* @param string
* @return string
*/
if ( ! function_exists('trim_slashes'))
{
function trim_slashes($str)
{
return trim($str, '/');
}
}
// ------------------------------------------------------------------------
/**
* Strip Slashes
*
* Removes slashes contained in a string or in an array
*
* @access public
* @param mixed string or array
* @return mixed string or array
*/
if ( ! function_exists('strip_slashes'))
{
function strip_slashes($str)
{
if (is_array($str))
{
foreach ($str as $key => $val)
{
$str[$key] = strip_slashes($val);
}
}
else
{
$str = stripslashes($str);
}
return $str;
}
}
// ------------------------------------------------------------------------
/**
* Strip Quotes
*
* Removes single and double quotes from a string
*
* @access public
* @param string
* @return string
*/
if ( ! function_exists('strip_quotes'))
{
function strip_quotes($str)
{
return str_replace(array('"', "'"), '', $str);
}
}
// ------------------------------------------------------------------------
/**
* Quotes to Entities
*
* Converts single and double quotes to entities
*
* @access public
* @param string
* @return string
*/
if ( ! function_exists('quotes_to_entities'))
{
function quotes_to_entities($str)
{
return str_replace(array("\'","\"","'",'"'), array("'",""","'","""), $str);
}
}
// ------------------------------------------------------------------------
/**
* Reduce Double Slashes
*
* Converts double slashes in a string to a single slash,
* except those found in http://
*
* http://www.some-site.com//index.php
*
* becomes:
*
* http://www.some-site.com/index.php
*
* @access public
* @param string
* @return string
*/
if ( ! function_exists('reduce_double_slashes'))
{
function reduce_double_slashes($str)
{
return preg_replace("#(^|[^:])//+#", "\\1/", $str);
}
}
// ------------------------------------------------------------------------
/**
* Reduce Multiples
*
* Reduces multiple instances of a particular character. Example:
*
* Fred, Bill,, Joe, Jimmy
*
* becomes:
*
* Fred, Bill, Joe, Jimmy
*
* @access public
* @param string
* @param string the character you wish to reduce
* @param bool TRUE/FALSE - whether to trim the character from the beginning/end
* @return string
*/
if ( ! function_exists('reduce_multiples'))
{
function reduce_multiples($str, $character = ',', $trim = FALSE)
{
$str = preg_replace('#'.preg_quote($character, '#').'{2,}#', $character, $str);
if ($trim === TRUE)
{
$str = trim($str, $character);
}
return $str;
}
}
// ------------------------------------------------------------------------
/**
* Create a Random String
*
* Useful for generating passwords or hashes.
*
* @access public
* @param string type of random string. basic, alpha, alunum, numeric, nozero, unique, md5, encrypt and sha1
* @param integer number of characters
* @return string
*/
if ( ! function_exists('random_string'))
{
function random_string($type = 'alnum', $len = 8)
{
switch($type)
{
case 'basic' : return mt_rand();
break;
case 'alnum' :
case 'numeric' :
case 'nozero' :
case 'alpha' :
switch ($type)
{
case 'alpha' : $pool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
break;
case 'alnum' : $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
break;
case 'numeric' : $pool = '0123456789';
break;
case 'nozero' : $pool = '123456789';
break;
}
$str = '';
for ($i=0; $i < $len; $i++)
{
$str .= substr($pool, mt_rand(0, strlen($pool) -1), 1);
}
return $str;
break;
case 'unique' :
case 'md5' :
return md5(uniqid(mt_rand()));
break;
case 'encrypt' :
case 'sha1' :
$CI =& get_instance();
$CI->load->helper('security');
return do_hash(uniqid(mt_rand(), TRUE), 'sha1');
break;
}
}
}
// ------------------------------------------------------------------------
/**
* Add's _1 to a string or increment the ending number to allow _2, _3, etc
*
* @param string $str required
* @param string $separator What should the duplicate number be appended with
* @param string $first Which number should be used for the first dupe increment
* @return string
*/
function increment_string($str, $separator = '_', $first = 1)
{
preg_match('/(.+)'.$separator.'([0-9]+)$/', $str, $match);
return isset($match[2]) ? $match[1].$separator.($match[2] + 1) : $str.$separator.$first;
}
// ------------------------------------------------------------------------
/**
* Alternator
*
* Allows strings to be alternated. See docs...
*
* @access public
* @param string (as many parameters as needed)
* @return string
*/
if ( ! function_exists('alternator'))
{
function alternator()
{
static $i;
if (func_num_args() == 0)
{
$i = 0;
return '';
}
$args = func_get_args();
return $args[($i++ % count($args))];
}
}
// ------------------------------------------------------------------------
/**
* Repeater function
*
* @access public
* @param string
* @param integer number of repeats
* @return string
*/
if ( ! function_exists('repeater'))
{
function repeater($data, $num = 1)
{
return (($num > 0) ? str_repeat($data, $num) : '');
}
}
/* End of file string_helper.php */
/* Location: ./system/helpers/string_helper.php */ | php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/helpers/security_helper.php | system/helpers/security_helper.php | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 5.1.6 or newer
*
* @package CodeIgniter
* @author ExpressionEngine Dev Team
* @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
* @license http://codeigniter.com/user_guide/license.html
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
// ------------------------------------------------------------------------
/**
* CodeIgniter Security Helpers
*
* @package CodeIgniter
* @subpackage Helpers
* @category Helpers
* @author ExpressionEngine Dev Team
* @link http://codeigniter.com/user_guide/helpers/security_helper.html
*/
// ------------------------------------------------------------------------
/**
* XSS Filtering
*
* @access public
* @param string
* @param bool whether or not the content is an image file
* @return string
*/
if ( ! function_exists('xss_clean'))
{
function xss_clean($str, $is_image = FALSE)
{
$CI =& get_instance();
return $CI->security->xss_clean($str, $is_image);
}
}
// ------------------------------------------------------------------------
/**
* Sanitize Filename
*
* @access public
* @param string
* @return string
*/
if ( ! function_exists('sanitize_filename'))
{
function sanitize_filename($filename)
{
$CI =& get_instance();
return $CI->security->sanitize_filename($filename);
}
}
// --------------------------------------------------------------------
/**
* Hash encode a string
*
* @access public
* @param string
* @return string
*/
if ( ! function_exists('do_hash'))
{
function do_hash($str, $type = 'sha1')
{
if ($type == 'sha1')
{
return sha1($str);
}
else
{
return md5($str);
}
}
}
// ------------------------------------------------------------------------
/**
* Strip Image Tags
*
* @access public
* @param string
* @return string
*/
if ( ! function_exists('strip_image_tags'))
{
function strip_image_tags($str)
{
$str = preg_replace("#<img\s+.*?src\s*=\s*[\"'](.+?)[\"'].*?\>#", "\\1", $str);
$str = preg_replace("#<img\s+.*?src\s*=\s*(.+?).*?\>#", "\\1", $str);
return $str;
}
}
// ------------------------------------------------------------------------
/**
* Convert PHP tags to entities
*
* @access public
* @param string
* @return string
*/
if ( ! function_exists('encode_php_tags'))
{
function encode_php_tags($str)
{
return str_replace(array('<?php', '<?PHP', '<?', '?>'), array('<?php', '<?PHP', '<?', '?>'), $str);
}
}
/* End of file security_helper.php */
/* Location: ./system/helpers/security_helper.php */ | php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/helpers/array_helper.php | system/helpers/array_helper.php | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 5.1.6 or newer
*
* @package CodeIgniter
* @author ExpressionEngine Dev Team
* @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
* @license http://codeigniter.com/user_guide/license.html
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
// ------------------------------------------------------------------------
/**
* CodeIgniter Array Helpers
*
* @package CodeIgniter
* @subpackage Helpers
* @category Helpers
* @author ExpressionEngine Dev Team
* @link http://codeigniter.com/user_guide/helpers/array_helper.html
*/
// ------------------------------------------------------------------------
/**
* Element
*
* Lets you determine whether an array index is set and whether it has a value.
* If the element is empty it returns FALSE (or whatever you specify as the default value.)
*
* @access public
* @param string
* @param array
* @param mixed
* @return mixed depends on what the array contains
*/
if ( ! function_exists('element'))
{
function element($item, $array, $default = FALSE)
{
if ( ! isset($array[$item]) OR $array[$item] == "")
{
return $default;
}
return $array[$item];
}
}
// ------------------------------------------------------------------------
/**
* Random Element - Takes an array as input and returns a random element
*
* @access public
* @param array
* @return mixed depends on what the array contains
*/
if ( ! function_exists('random_element'))
{
function random_element($array)
{
if ( ! is_array($array))
{
return $array;
}
return $array[array_rand($array)];
}
}
// --------------------------------------------------------------------
/**
* Elements
*
* Returns only the array items specified. Will return a default value if
* it is not set.
*
* @access public
* @param array
* @param array
* @param mixed
* @return mixed depends on what the array contains
*/
if ( ! function_exists('elements'))
{
function elements($items, $array, $default = FALSE)
{
$return = array();
if ( ! is_array($items))
{
$items = array($items);
}
foreach ($items as $item)
{
if (isset($array[$item]))
{
$return[$item] = $array[$item];
}
else
{
$return[$item] = $default;
}
}
return $return;
}
}
/* End of file array_helper.php */
/* Location: ./system/helpers/array_helper.php */ | php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/helpers/download_helper.php | system/helpers/download_helper.php | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 5.1.6 or newer
*
* @package CodeIgniter
* @author ExpressionEngine Dev Team
* @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
* @license http://codeigniter.com/user_guide/license.html
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
// ------------------------------------------------------------------------
/**
* CodeIgniter Download Helpers
*
* @package CodeIgniter
* @subpackage Helpers
* @category Helpers
* @author ExpressionEngine Dev Team
* @link http://codeigniter.com/user_guide/helpers/download_helper.html
*/
// ------------------------------------------------------------------------
/**
* Force Download
*
* Generates headers that force a download to happen
*
* @access public
* @param string filename
* @param mixed the data to be downloaded
* @return void
*/
if ( ! function_exists('force_download'))
{
function force_download($filename = '', $data = '')
{
if ($filename == '' OR $data == '')
{
return FALSE;
}
// Try to determine if the filename includes a file extension.
// We need it in order to set the MIME type
if (FALSE === strpos($filename, '.'))
{
return FALSE;
}
// Grab the file extension
$x = explode('.', $filename);
$extension = end($x);
// Load the mime types
if (defined('ENVIRONMENT') AND is_file(APPPATH.'config/'.ENVIRONMENT.'/mimes.php'))
{
include(APPPATH.'config/'.ENVIRONMENT.'/mimes.php');
}
elseif (is_file(APPPATH.'config/mimes.php'))
{
include(APPPATH.'config/mimes.php');
}
// Set a default mime if we can't find it
if ( ! isset($mimes[$extension]))
{
$mime = 'application/octet-stream';
}
else
{
$mime = (is_array($mimes[$extension])) ? $mimes[$extension][0] : $mimes[$extension];
}
// Generate the server headers
if (strpos($_SERVER['HTTP_USER_AGENT'], "MSIE") !== FALSE)
{
header('Content-Type: "'.$mime.'"');
header('Content-Disposition: attachment; filename="'.$filename.'"');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header("Content-Transfer-Encoding: binary");
header('Pragma: public');
header("Content-Length: ".strlen($data));
}
else
{
header('Content-Type: "'.$mime.'"');
header('Content-Disposition: attachment; filename="'.$filename.'"');
header("Content-Transfer-Encoding: binary");
header('Expires: 0');
header('Pragma: no-cache');
header("Content-Length: ".strlen($data));
}
exit($data);
}
}
/* End of file download_helper.php */
/* Location: ./system/helpers/download_helper.php */ | php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/helpers/text_helper.php | system/helpers/text_helper.php | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 5.1.6 or newer
*
* @package CodeIgniter
* @author ExpressionEngine Dev Team
* @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
* @license http://codeigniter.com/user_guide/license.html
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
// ------------------------------------------------------------------------
/**
* CodeIgniter Text Helpers
*
* @package CodeIgniter
* @subpackage Helpers
* @category Helpers
* @author ExpressionEngine Dev Team
* @link http://codeigniter.com/user_guide/helpers/text_helper.html
*/
// ------------------------------------------------------------------------
/**
* Word Limiter
*
* Limits a string to X number of words.
*
* @access public
* @param string
* @param integer
* @param string the end character. Usually an ellipsis
* @return string
*/
if ( ! function_exists('word_limiter'))
{
function word_limiter($str, $limit = 100, $end_char = '…')
{
if (trim($str) == '')
{
return $str;
}
preg_match('/^\s*+(?:\S++\s*+){1,'.(int) $limit.'}/', $str, $matches);
if (strlen($str) == strlen($matches[0]))
{
$end_char = '';
}
return rtrim($matches[0]).$end_char;
}
}
// ------------------------------------------------------------------------
/**
* Character Limiter
*
* Limits the string based on the character count. Preserves complete words
* so the character count may not be exactly as specified.
*
* @access public
* @param string
* @param integer
* @param string the end character. Usually an ellipsis
* @return string
*/
if ( ! function_exists('character_limiter'))
{
function character_limiter($str, $n = 500, $end_char = '…')
{
if (strlen($str) < $n)
{
return $str;
}
$str = preg_replace("/\s+/", ' ', str_replace(array("\r\n", "\r", "\n"), ' ', $str));
if (strlen($str) <= $n)
{
return $str;
}
$out = "";
foreach (explode(' ', trim($str)) as $val)
{
$out .= $val.' ';
if (strlen($out) >= $n)
{
$out = trim($out);
return (strlen($out) == strlen($str)) ? $out : $out.$end_char;
}
}
}
}
// ------------------------------------------------------------------------
/**
* High ASCII to Entities
*
* Converts High ascii text and MS Word special characters to character entities
*
* @access public
* @param string
* @return string
*/
if ( ! function_exists('ascii_to_entities'))
{
function ascii_to_entities($str)
{
$count = 1;
$out = '';
$temp = array();
for ($i = 0, $s = strlen($str); $i < $s; $i++)
{
$ordinal = ord($str[$i]);
if ($ordinal < 128)
{
/*
If the $temp array has a value but we have moved on, then it seems only
fair that we output that entity and restart $temp before continuing. -Paul
*/
if (count($temp) == 1)
{
$out .= '&#'.array_shift($temp).';';
$count = 1;
}
$out .= $str[$i];
}
else
{
if (count($temp) == 0)
{
$count = ($ordinal < 224) ? 2 : 3;
}
$temp[] = $ordinal;
if (count($temp) == $count)
{
$number = ($count == 3) ? (($temp['0'] % 16) * 4096) + (($temp['1'] % 64) * 64) + ($temp['2'] % 64) : (($temp['0'] % 32) * 64) + ($temp['1'] % 64);
$out .= '&#'.$number.';';
$count = 1;
$temp = array();
}
}
}
return $out;
}
}
// ------------------------------------------------------------------------
/**
* Entities to ASCII
*
* Converts character entities back to ASCII
*
* @access public
* @param string
* @param bool
* @return string
*/
if ( ! function_exists('entities_to_ascii'))
{
function entities_to_ascii($str, $all = TRUE)
{
if (preg_match_all('/\&#(\d+)\;/', $str, $matches))
{
for ($i = 0, $s = count($matches['0']); $i < $s; $i++)
{
$digits = $matches['1'][$i];
$out = '';
if ($digits < 128)
{
$out .= chr($digits);
}
elseif ($digits < 2048)
{
$out .= chr(192 + (($digits - ($digits % 64)) / 64));
$out .= chr(128 + ($digits % 64));
}
else
{
$out .= chr(224 + (($digits - ($digits % 4096)) / 4096));
$out .= chr(128 + ((($digits % 4096) - ($digits % 64)) / 64));
$out .= chr(128 + ($digits % 64));
}
$str = str_replace($matches['0'][$i], $out, $str);
}
}
if ($all)
{
$str = str_replace(array("&", "<", ">", """, "'", "-"),
array("&","<",">","\"", "'", "-"),
$str);
}
return $str;
}
}
// ------------------------------------------------------------------------
/**
* Word Censoring Function
*
* Supply a string and an array of disallowed words and any
* matched words will be converted to #### or to the replacement
* word you've submitted.
*
* @access public
* @param string the text string
* @param string the array of censoered words
* @param string the optional replacement value
* @return string
*/
if ( ! function_exists('word_censor'))
{
function word_censor($str, $censored, $replacement = '')
{
if ( ! is_array($censored))
{
return $str;
}
$str = ' '.$str.' ';
// \w, \b and a few others do not match on a unicode character
// set for performance reasons. As a result words like über
// will not match on a word boundary. Instead, we'll assume that
// a bad word will be bookeneded by any of these characters.
$delim = '[-_\'\"`(){}<>\[\]|!?@#%&,.:;^~*+=\/ 0-9\n\r\t]';
foreach ($censored as $badword)
{
if ($replacement != '')
{
$str = preg_replace("/({$delim})(".str_replace('\*', '\w*?', preg_quote($badword, '/')).")({$delim})/i", "\\1{$replacement}\\3", $str);
}
else
{
$str = preg_replace("/({$delim})(".str_replace('\*', '\w*?', preg_quote($badword, '/')).")({$delim})/ie", "'\\1'.str_repeat('#', strlen('\\2')).'\\3'", $str);
}
}
return trim($str);
}
}
// ------------------------------------------------------------------------
/**
* Code Highlighter
*
* Colorizes code strings
*
* @access public
* @param string the text string
* @return string
*/
if ( ! function_exists('highlight_code'))
{
function highlight_code($str)
{
// The highlight string function encodes and highlights
// brackets so we need them to start raw
$str = str_replace(array('<', '>'), array('<', '>'), $str);
// Replace any existing PHP tags to temporary markers so they don't accidentally
// break the string out of PHP, and thus, thwart the highlighting.
$str = str_replace(array('<?', '?>', '<%', '%>', '\\', '</script>'),
array('phptagopen', 'phptagclose', 'asptagopen', 'asptagclose', 'backslashtmp', 'scriptclose'), $str);
// The highlight_string function requires that the text be surrounded
// by PHP tags, which we will remove later
$str = '<?php '.$str.' ?>'; // <?
// All the magic happens here, baby!
$str = highlight_string($str, TRUE);
// Prior to PHP 5, the highligh function used icky <font> tags
// so we'll replace them with <span> tags.
if (abs(PHP_VERSION) < 5)
{
$str = str_replace(array('<font ', '</font>'), array('<span ', '</span>'), $str);
$str = preg_replace('#color="(.*?)"#', 'style="color: \\1"', $str);
}
// Remove our artificially added PHP, and the syntax highlighting that came with it
$str = preg_replace('/<span style="color: #([A-Z0-9]+)"><\?php( | )/i', '<span style="color: #$1">', $str);
$str = preg_replace('/(<span style="color: #[A-Z0-9]+">.*?)\?><\/span>\n<\/span>\n<\/code>/is', "$1</span>\n</span>\n</code>", $str);
$str = preg_replace('/<span style="color: #[A-Z0-9]+"\><\/span>/i', '', $str);
// Replace our markers back to PHP tags.
$str = str_replace(array('phptagopen', 'phptagclose', 'asptagopen', 'asptagclose', 'backslashtmp', 'scriptclose'),
array('<?', '?>', '<%', '%>', '\\', '</script>'), $str);
return $str;
}
}
// ------------------------------------------------------------------------
/**
* Phrase Highlighter
*
* Highlights a phrase within a text string
*
* @access public
* @param string the text string
* @param string the phrase you'd like to highlight
* @param string the openging tag to precede the phrase with
* @param string the closing tag to end the phrase with
* @return string
*/
if ( ! function_exists('highlight_phrase'))
{
function highlight_phrase($str, $phrase, $tag_open = '<strong>', $tag_close = '</strong>')
{
if ($str == '')
{
return '';
}
if ($phrase != '')
{
return preg_replace('/('.preg_quote($phrase, '/').')/i', $tag_open."\\1".$tag_close, $str);
}
return $str;
}
}
// ------------------------------------------------------------------------
/**
* Convert Accented Foreign Characters to ASCII
*
* @access public
* @param string the text string
* @return string
*/
if ( ! function_exists('convert_accented_characters'))
{
function convert_accented_characters($str)
{
if (defined('ENVIRONMENT') AND is_file(APPPATH.'config/'.ENVIRONMENT.'/foreign_chars.php'))
{
include(APPPATH.'config/'.ENVIRONMENT.'/foreign_chars.php');
}
elseif (is_file(APPPATH.'config/foreign_chars.php'))
{
include(APPPATH.'config/foreign_chars.php');
}
if ( ! isset($foreign_characters))
{
return $str;
}
return preg_replace(array_keys($foreign_characters), array_values($foreign_characters), $str);
}
}
// ------------------------------------------------------------------------
/**
* Word Wrap
*
* Wraps text at the specified character. Maintains the integrity of words.
* Anything placed between {unwrap}{/unwrap} will not be word wrapped, nor
* will URLs.
*
* @access public
* @param string the text string
* @param integer the number of characters to wrap at
* @return string
*/
if ( ! function_exists('word_wrap'))
{
function word_wrap($str, $charlim = '76')
{
// Se the character limit
if ( ! is_numeric($charlim))
$charlim = 76;
// Reduce multiple spaces
$str = preg_replace("| +|", " ", $str);
// Standardize newlines
if (strpos($str, "\r") !== FALSE)
{
$str = str_replace(array("\r\n", "\r"), "\n", $str);
}
// If the current word is surrounded by {unwrap} tags we'll
// strip the entire chunk and replace it with a marker.
$unwrap = array();
if (preg_match_all("|(\{unwrap\}.+?\{/unwrap\})|s", $str, $matches))
{
for ($i = 0; $i < count($matches['0']); $i++)
{
$unwrap[] = $matches['1'][$i];
$str = str_replace($matches['1'][$i], "{{unwrapped".$i."}}", $str);
}
}
// Use PHP's native function to do the initial wordwrap.
// We set the cut flag to FALSE so that any individual words that are
// too long get left alone. In the next step we'll deal with them.
$str = wordwrap($str, $charlim, "\n", FALSE);
// Split the string into individual lines of text and cycle through them
$output = "";
foreach (explode("\n", $str) as $line)
{
// Is the line within the allowed character count?
// If so we'll join it to the output and continue
if (strlen($line) <= $charlim)
{
$output .= $line."\n";
continue;
}
$temp = '';
while ((strlen($line)) > $charlim)
{
// If the over-length word is a URL we won't wrap it
if (preg_match("!\[url.+\]|://|wwww.!", $line))
{
break;
}
// Trim the word down
$temp .= substr($line, 0, $charlim-1);
$line = substr($line, $charlim-1);
}
// If $temp contains data it means we had to split up an over-length
// word into smaller chunks so we'll add it back to our current line
if ($temp != '')
{
$output .= $temp."\n".$line;
}
else
{
$output .= $line;
}
$output .= "\n";
}
// Put our markers back
if (count($unwrap) > 0)
{
foreach ($unwrap as $key => $val)
{
$output = str_replace("{{unwrapped".$key."}}", $val, $output);
}
}
// Remove the unwrap tags
$output = str_replace(array('{unwrap}', '{/unwrap}'), '', $output);
return $output;
}
}
// ------------------------------------------------------------------------
/**
* Ellipsize String
*
* This function will strip tags from a string, split it at its max_length and ellipsize
*
* @param string string to ellipsize
* @param integer max length of string
* @param mixed int (1|0) or float, .5, .2, etc for position to split
* @param string ellipsis ; Default '...'
* @return string ellipsized string
*/
if ( ! function_exists('ellipsize'))
{
function ellipsize($str, $max_length, $position = 1, $ellipsis = '…')
{
// Strip tags
$str = trim(strip_tags($str));
// Is the string long enough to ellipsize?
if (strlen($str) <= $max_length)
{
return $str;
}
$beg = substr($str, 0, floor($max_length * $position));
$position = ($position > 1) ? 1 : $position;
if ($position === 1)
{
$end = substr($str, 0, -($max_length - strlen($beg)));
}
else
{
$end = substr($str, -($max_length - strlen($beg)));
}
return $beg.$ellipsis.$end;
}
}
/* End of file text_helper.php */
/* Location: ./system/helpers/text_helper.php */ | php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/helpers/email_helper.php | system/helpers/email_helper.php | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 5.1.6 or newer
*
* @package CodeIgniter
* @author ExpressionEngine Dev Team
* @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
* @license http://codeigniter.com/user_guide/license.html
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
// ------------------------------------------------------------------------
/**
* CodeIgniter Email Helpers
*
* @package CodeIgniter
* @subpackage Helpers
* @category Helpers
* @author ExpressionEngine Dev Team
* @link http://codeigniter.com/user_guide/helpers/email_helper.html
*/
// ------------------------------------------------------------------------
/**
* Validate email address
*
* @access public
* @return bool
*/
if ( ! function_exists('valid_email'))
{
function valid_email($address)
{
return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $address)) ? FALSE : TRUE;
}
}
// ------------------------------------------------------------------------
/**
* Send an email
*
* @access public
* @return bool
*/
if ( ! function_exists('send_email'))
{
function send_email($recipient, $subject = 'Test email', $message = 'Hello World')
{
return mail($recipient, $subject, $message);
}
}
/* End of file email_helper.php */
/* Location: ./system/helpers/email_helper.php */ | php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/helpers/path_helper.php | system/helpers/path_helper.php | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 5.1.6 or newer
*
* @package CodeIgniter
* @author ExpressionEngine Dev Team
* @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
* @license http://codeigniter.com/user_guide/license.html
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
// ------------------------------------------------------------------------
/**
* CodeIgniter Path Helpers
*
* @package CodeIgniter
* @subpackage Helpers
* @category Helpers
* @author ExpressionEngine Dev Team
* @link http://codeigniter.com/user_guide/helpers/xml_helper.html
*/
// ------------------------------------------------------------------------
/**
* Set Realpath
*
* @access public
* @param string
* @param bool checks to see if the path exists
* @return string
*/
if ( ! function_exists('set_realpath'))
{
function set_realpath($path, $check_existance = FALSE)
{
// Security check to make sure the path is NOT a URL. No remote file inclusion!
if (preg_match("#^(http:\/\/|https:\/\/|www\.|ftp|[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})#i", $path))
{
show_error('The path you submitted must be a local server path, not a URL');
}
// Resolve the path
if (function_exists('realpath') AND @realpath($path) !== FALSE)
{
$path = realpath($path).'/';
}
// Add a trailing slash
$path = preg_replace("#([^/])/*$#", "\\1/", $path);
// Make sure the path exists
if ($check_existance == TRUE)
{
if ( ! is_dir($path))
{
show_error('Not a valid path: '.$path);
}
}
return $path;
}
}
/* End of file path_helper.php */
/* Location: ./system/helpers/path_helper.php */ | php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/helpers/typography_helper.php | system/helpers/typography_helper.php | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 5.1.6 or newer
*
* @package CodeIgniter
* @author ExpressionEngine Dev Team
* @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
* @license http://codeigniter.com/user_guide/license.html
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
// ------------------------------------------------------------------------
/**
* CodeIgniter Typography Helpers
*
* @package CodeIgniter
* @subpackage Helpers
* @category Helpers
* @author ExpressionEngine Dev Team
* @link http://codeigniter.com/user_guide/helpers/typography_helper.html
*/
// ------------------------------------------------------------------------
/**
* Convert newlines to HTML line breaks except within PRE tags
*
* @access public
* @param string
* @return string
*/
if ( ! function_exists('nl2br_except_pre'))
{
function nl2br_except_pre($str)
{
$CI =& get_instance();
$CI->load->library('typography');
return $CI->typography->nl2br_except_pre($str);
}
}
// ------------------------------------------------------------------------
/**
* Auto Typography Wrapper Function
*
*
* @access public
* @param string
* @param bool whether to allow javascript event handlers
* @param bool whether to reduce multiple instances of double newlines to two
* @return string
*/
if ( ! function_exists('auto_typography'))
{
function auto_typography($str, $strip_js_event_handlers = TRUE, $reduce_linebreaks = FALSE)
{
$CI =& get_instance();
$CI->load->library('typography');
return $CI->typography->auto_typography($str, $strip_js_event_handlers, $reduce_linebreaks);
}
}
// --------------------------------------------------------------------
/**
* HTML Entities Decode
*
* This function is a replacement for html_entity_decode()
*
* @access public
* @param string
* @return string
*/
if ( ! function_exists('entity_decode'))
{
function entity_decode($str, $charset='UTF-8')
{
global $SEC;
return $SEC->entity_decode($str, $charset);
}
}
/* End of file typography_helper.php */
/* Location: ./system/helpers/typography_helper.php */ | php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/helpers/language_helper.php | system/helpers/language_helper.php | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 5.1.6 or newer
*
* @package CodeIgniter
* @author ExpressionEngine Dev Team
* @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
* @license http://codeigniter.com/user_guide/license.html
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
// ------------------------------------------------------------------------
/**
* CodeIgniter Language Helpers
*
* @package CodeIgniter
* @subpackage Helpers
* @category Helpers
* @author ExpressionEngine Dev Team
* @link http://codeigniter.com/user_guide/helpers/language_helper.html
*/
// ------------------------------------------------------------------------
/**
* Lang
*
* Fetches a language variable and optionally outputs a form label
*
* @access public
* @param string the language line
* @param string the id of the form element
* @return string
*/
if ( ! function_exists('lang'))
{
function lang($line, $id = '')
{
$CI =& get_instance();
$line = $CI->lang->line($line);
if ($id != '')
{
$line = '<label for="'.$id.'">'.$line."</label>";
}
return $line;
}
}
// ------------------------------------------------------------------------
/* End of file language_helper.php */
/* Location: ./system/helpers/language_helper.php */ | php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/helpers/smiley_helper.php | system/helpers/smiley_helper.php | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 5.1.6 or newer
*
* @package CodeIgniter
* @author ExpressionEngine Dev Team
* @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
* @license http://codeigniter.com/user_guide/license.html
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
// ------------------------------------------------------------------------
/**
* CodeIgniter Smiley Helpers
*
* @package CodeIgniter
* @subpackage Helpers
* @category Helpers
* @author ExpressionEngine Dev Team
* @link http://codeigniter.com/user_guide/helpers/smiley_helper.html
*/
// ------------------------------------------------------------------------
/**
* Smiley Javascript
*
* Returns the javascript required for the smiley insertion. Optionally takes
* an array of aliases to loosely couple the smiley array to the view.
*
* @access public
* @param mixed alias name or array of alias->field_id pairs
* @param string field_id if alias name was passed in
* @return array
*/
if ( ! function_exists('smiley_js'))
{
function smiley_js($alias = '', $field_id = '', $inline = TRUE)
{
static $do_setup = TRUE;
$r = '';
if ($alias != '' && ! is_array($alias))
{
$alias = array($alias => $field_id);
}
if ($do_setup === TRUE)
{
$do_setup = FALSE;
$m = array();
if (is_array($alias))
{
foreach ($alias as $name => $id)
{
$m[] = '"'.$name.'" : "'.$id.'"';
}
}
$m = '{'.implode(',', $m).'}';
$r .= <<<EOF
var smiley_map = {$m};
function insert_smiley(smiley, field_id) {
var el = document.getElementById(field_id), newStart;
if ( ! el && smiley_map[field_id]) {
el = document.getElementById(smiley_map[field_id]);
if ( ! el)
return false;
}
el.focus();
smiley = " " + smiley;
if ('selectionStart' in el) {
newStart = el.selectionStart + smiley.length;
el.value = el.value.substr(0, el.selectionStart) +
smiley +
el.value.substr(el.selectionEnd, el.value.length);
el.setSelectionRange(newStart, newStart);
}
else if (document.selection) {
document.selection.createRange().text = smiley;
}
}
EOF;
}
else
{
if (is_array($alias))
{
foreach ($alias as $name => $id)
{
$r .= 'smiley_map["'.$name.'"] = "'.$id.'";'."\n";
}
}
}
if ($inline)
{
return '<script type="text/javascript" charset="utf-8">/*<![CDATA[ */'.$r.'// ]]></script>';
}
else
{
return $r;
}
}
}
// ------------------------------------------------------------------------
/**
* Get Clickable Smileys
*
* Returns an array of image tag links that can be clicked to be inserted
* into a form field.
*
* @access public
* @param string the URL to the folder containing the smiley images
* @return array
*/
if ( ! function_exists('get_clickable_smileys'))
{
function get_clickable_smileys($image_url, $alias = '', $smileys = NULL)
{
// For backward compatibility with js_insert_smiley
if (is_array($alias))
{
$smileys = $alias;
}
if ( ! is_array($smileys))
{
if (FALSE === ($smileys = _get_smiley_array()))
{
return $smileys;
}
}
// Add a trailing slash to the file path if needed
$image_url = rtrim($image_url, '/').'/';
$used = array();
foreach ($smileys as $key => $val)
{
// Keep duplicates from being used, which can happen if the
// mapping array contains multiple identical replacements. For example:
// :-) and :) might be replaced with the same image so both smileys
// will be in the array.
if (isset($used[$smileys[$key][0]]))
{
continue;
}
$link[] = "<a href=\"javascript:void(0);\" onclick=\"insert_smiley('".$key."', '".$alias."')\"><img src=\"".$image_url.$smileys[$key][0]."\" width=\"".$smileys[$key][1]."\" height=\"".$smileys[$key][2]."\" alt=\"".$smileys[$key][3]."\" style=\"border:0;\" /></a>";
$used[$smileys[$key][0]] = TRUE;
}
return $link;
}
}
// ------------------------------------------------------------------------
/**
* Parse Smileys
*
* Takes a string as input and swaps any contained smileys for the actual image
*
* @access public
* @param string the text to be parsed
* @param string the URL to the folder containing the smiley images
* @return string
*/
if ( ! function_exists('parse_smileys'))
{
function parse_smileys($str = '', $image_url = '', $smileys = NULL)
{
if ($image_url == '')
{
return $str;
}
if ( ! is_array($smileys))
{
if (FALSE === ($smileys = _get_smiley_array()))
{
return $str;
}
}
// Add a trailing slash to the file path if needed
$image_url = preg_replace("/(.+?)\/*$/", "\\1/", $image_url);
foreach ($smileys as $key => $val)
{
$str = str_replace($key, "<img src=\"".$image_url.$smileys[$key][0]."\" width=\"".$smileys[$key][1]."\" height=\"".$smileys[$key][2]."\" alt=\"".$smileys[$key][3]."\" style=\"border:0;\" />", $str);
}
return $str;
}
}
// ------------------------------------------------------------------------
/**
* Get Smiley Array
*
* Fetches the config/smiley.php file
*
* @access private
* @return mixed
*/
if ( ! function_exists('_get_smiley_array'))
{
function _get_smiley_array()
{
if (defined('ENVIRONMENT') AND file_exists(APPPATH.'config/'.ENVIRONMENT.'/smileys.php'))
{
include(APPPATH.'config/'.ENVIRONMENT.'/smileys.php');
}
elseif (file_exists(APPPATH.'config/smileys.php'))
{
include(APPPATH.'config/smileys.php');
}
if (isset($smileys) AND is_array($smileys))
{
return $smileys;
}
return FALSE;
}
}
// ------------------------------------------------------------------------
/**
* JS Insert Smiley
*
* Generates the javascript function needed to insert smileys into a form field
*
* DEPRECATED as of version 1.7.2, use smiley_js instead
*
* @access public
* @param string form name
* @param string field name
* @return string
*/
if ( ! function_exists('js_insert_smiley'))
{
function js_insert_smiley($form_name = '', $form_field = '')
{
return <<<EOF
<script type="text/javascript">
function insert_smiley(smiley)
{
document.{$form_name}.{$form_field}.value += " " + smiley;
}
</script>
EOF;
}
}
/* End of file smiley_helper.php */
/* Location: ./system/helpers/smiley_helper.php */ | php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/helpers/xml_helper.php | system/helpers/xml_helper.php | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 5.1.6 or newer
*
* @package CodeIgniter
* @author ExpressionEngine Dev Team
* @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
* @license http://codeigniter.com/user_guide/license.html
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
// ------------------------------------------------------------------------
/**
* CodeIgniter XML Helpers
*
* @package CodeIgniter
* @subpackage Helpers
* @category Helpers
* @author ExpressionEngine Dev Team
* @link http://codeigniter.com/user_guide/helpers/xml_helper.html
*/
// ------------------------------------------------------------------------
/**
* Convert Reserved XML characters to Entities
*
* @access public
* @param string
* @return string
*/
if ( ! function_exists('xml_convert'))
{
function xml_convert($str, $protect_all = FALSE)
{
$temp = '__TEMP_AMPERSANDS__';
// Replace entities to temporary markers so that
// ampersands won't get messed up
$str = preg_replace("/&#(\d+);/", "$temp\\1;", $str);
if ($protect_all === TRUE)
{
$str = preg_replace("/&(\w+);/", "$temp\\1;", $str);
}
$str = str_replace(array("&","<",">","\"", "'", "-"),
array("&", "<", ">", """, "'", "-"),
$str);
// Decode the temp markers back to entities
$str = preg_replace("/$temp(\d+);/","&#\\1;",$str);
if ($protect_all === TRUE)
{
$str = preg_replace("/$temp(\w+);/","&\\1;", $str);
}
return $str;
}
}
// ------------------------------------------------------------------------
/* End of file xml_helper.php */
/* Location: ./system/helpers/xml_helper.php */ | php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/helpers/date_helper.php | system/helpers/date_helper.php | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 5.1.6 or newer
*
* @package CodeIgniter
* @author ExpressionEngine Dev Team
* @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
* @license http://codeigniter.com/user_guide/license.html
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
// ------------------------------------------------------------------------
/**
* CodeIgniter Date Helpers
*
* @package CodeIgniter
* @subpackage Helpers
* @category Helpers
* @author ExpressionEngine Dev Team
* @link http://codeigniter.com/user_guide/helpers/date_helper.html
*/
// ------------------------------------------------------------------------
/**
* Get "now" time
*
* Returns time() or its GMT equivalent based on the config file preference
*
* @access public
* @return integer
*/
if ( ! function_exists('now'))
{
function now()
{
$CI =& get_instance();
if (strtolower($CI->config->item('time_reference')) == 'gmt')
{
$now = time();
$system_time = mktime(gmdate("H", $now), gmdate("i", $now), gmdate("s", $now), gmdate("m", $now), gmdate("d", $now), gmdate("Y", $now));
if (strlen($system_time) < 10)
{
$system_time = time();
log_message('error', 'The Date class could not set a proper GMT timestamp so the local time() value was used.');
}
return $system_time;
}
else
{
return time();
}
}
}
// ------------------------------------------------------------------------
/**
* Convert MySQL Style Datecodes
*
* This function is identical to PHPs date() function,
* except that it allows date codes to be formatted using
* the MySQL style, where each code letter is preceded
* with a percent sign: %Y %m %d etc...
*
* The benefit of doing dates this way is that you don't
* have to worry about escaping your text letters that
* match the date codes.
*
* @access public
* @param string
* @param integer
* @return integer
*/
if ( ! function_exists('mdate'))
{
function mdate($datestr = '', $time = '')
{
if ($datestr == '')
return '';
if ($time == '')
$time = now();
$datestr = str_replace('%\\', '', preg_replace("/([a-z]+?){1}/i", "\\\\\\1", $datestr));
return date($datestr, $time);
}
}
// ------------------------------------------------------------------------
/**
* Standard Date
*
* Returns a date formatted according to the submitted standard.
*
* @access public
* @param string the chosen format
* @param integer Unix timestamp
* @return string
*/
if ( ! function_exists('standard_date'))
{
function standard_date($fmt = 'DATE_RFC822', $time = '')
{
$formats = array(
'DATE_ATOM' => '%Y-%m-%dT%H:%i:%s%Q',
'DATE_COOKIE' => '%l, %d-%M-%y %H:%i:%s UTC',
'DATE_ISO8601' => '%Y-%m-%dT%H:%i:%s%Q',
'DATE_RFC822' => '%D, %d %M %y %H:%i:%s %O',
'DATE_RFC850' => '%l, %d-%M-%y %H:%i:%s UTC',
'DATE_RFC1036' => '%D, %d %M %y %H:%i:%s %O',
'DATE_RFC1123' => '%D, %d %M %Y %H:%i:%s %O',
'DATE_RSS' => '%D, %d %M %Y %H:%i:%s %O',
'DATE_W3C' => '%Y-%m-%dT%H:%i:%s%Q'
);
if ( ! isset($formats[$fmt]))
{
return FALSE;
}
return mdate($formats[$fmt], $time);
}
}
// ------------------------------------------------------------------------
/**
* Timespan
*
* Returns a span of seconds in this format:
* 10 days 14 hours 36 minutes 47 seconds
*
* @access public
* @param integer a number of seconds
* @param integer Unix timestamp
* @return integer
*/
if ( ! function_exists('timespan'))
{
function timespan($seconds = 1, $time = '')
{
$CI =& get_instance();
$CI->lang->load('date');
if ( ! is_numeric($seconds))
{
$seconds = 1;
}
if ( ! is_numeric($time))
{
$time = time();
}
if ($time <= $seconds)
{
$seconds = 1;
}
else
{
$seconds = $time - $seconds;
}
$str = '';
$years = floor($seconds / 31536000);
if ($years > 0)
{
$str .= $years.' '.$CI->lang->line((($years > 1) ? 'date_years' : 'date_year')).', ';
}
$seconds -= $years * 31536000;
$months = floor($seconds / 2628000);
if ($years > 0 OR $months > 0)
{
if ($months > 0)
{
$str .= $months.' '.$CI->lang->line((($months > 1) ? 'date_months' : 'date_month')).', ';
}
$seconds -= $months * 2628000;
}
$weeks = floor($seconds / 604800);
if ($years > 0 OR $months > 0 OR $weeks > 0)
{
if ($weeks > 0)
{
$str .= $weeks.' '.$CI->lang->line((($weeks > 1) ? 'date_weeks' : 'date_week')).', ';
}
$seconds -= $weeks * 604800;
}
$days = floor($seconds / 86400);
if ($months > 0 OR $weeks > 0 OR $days > 0)
{
if ($days > 0)
{
$str .= $days.' '.$CI->lang->line((($days > 1) ? 'date_days' : 'date_day')).', ';
}
$seconds -= $days * 86400;
}
$hours = floor($seconds / 3600);
if ($days > 0 OR $hours > 0)
{
if ($hours > 0)
{
$str .= $hours.' '.$CI->lang->line((($hours > 1) ? 'date_hours' : 'date_hour')).', ';
}
$seconds -= $hours * 3600;
}
$minutes = floor($seconds / 60);
if ($days > 0 OR $hours > 0 OR $minutes > 0)
{
if ($minutes > 0)
{
$str .= $minutes.' '.$CI->lang->line((($minutes > 1) ? 'date_minutes' : 'date_minute')).', ';
}
$seconds -= $minutes * 60;
}
if ($str == '')
{
$str .= $seconds.' '.$CI->lang->line((($seconds > 1) ? 'date_seconds' : 'date_second')).', ';
}
return substr(trim($str), 0, -1);
}
}
// ------------------------------------------------------------------------
/**
* Number of days in a month
*
* Takes a month/year as input and returns the number of days
* for the given month/year. Takes leap years into consideration.
*
* @access public
* @param integer a numeric month
* @param integer a numeric year
* @return integer
*/
if ( ! function_exists('days_in_month'))
{
function days_in_month($month = 0, $year = '')
{
if ($month < 1 OR $month > 12)
{
return 0;
}
if ( ! is_numeric($year) OR strlen($year) != 4)
{
$year = date('Y');
}
if ($month == 2)
{
if ($year % 400 == 0 OR ($year % 4 == 0 AND $year % 100 != 0))
{
return 29;
}
}
$days_in_month = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
return $days_in_month[$month - 1];
}
}
// ------------------------------------------------------------------------
/**
* Converts a local Unix timestamp to GMT
*
* @access public
* @param integer Unix timestamp
* @return integer
*/
if ( ! function_exists('local_to_gmt'))
{
function local_to_gmt($time = '')
{
if ($time == '')
$time = time();
return mktime( gmdate("H", $time), gmdate("i", $time), gmdate("s", $time), gmdate("m", $time), gmdate("d", $time), gmdate("Y", $time));
}
}
// ------------------------------------------------------------------------
/**
* Converts GMT time to a localized value
*
* Takes a Unix timestamp (in GMT) as input, and returns
* at the local value based on the timezone and DST setting
* submitted
*
* @access public
* @param integer Unix timestamp
* @param string timezone
* @param bool whether DST is active
* @return integer
*/
if ( ! function_exists('gmt_to_local'))
{
function gmt_to_local($time = '', $timezone = 'UTC', $dst = FALSE)
{
if ($time == '')
{
return now();
}
$time += timezones($timezone) * 3600;
if ($dst == TRUE)
{
$time += 3600;
}
return $time;
}
}
// ------------------------------------------------------------------------
/**
* Converts a MySQL Timestamp to Unix
*
* @access public
* @param integer Unix timestamp
* @return integer
*/
if ( ! function_exists('mysql_to_unix'))
{
function mysql_to_unix($time = '')
{
// We'll remove certain characters for backward compatibility
// since the formatting changed with MySQL 4.1
// YYYY-MM-DD HH:MM:SS
$time = str_replace('-', '', $time);
$time = str_replace(':', '', $time);
$time = str_replace(' ', '', $time);
// YYYYMMDDHHMMSS
return mktime(
substr($time, 8, 2),
substr($time, 10, 2),
substr($time, 12, 2),
substr($time, 4, 2),
substr($time, 6, 2),
substr($time, 0, 4)
);
}
}
// ------------------------------------------------------------------------
/**
* Unix to "Human"
*
* Formats Unix timestamp to the following prototype: 2006-08-21 11:35 PM
*
* @access public
* @param integer Unix timestamp
* @param bool whether to show seconds
* @param string format: us or euro
* @return string
*/
if ( ! function_exists('unix_to_human'))
{
function unix_to_human($time = '', $seconds = FALSE, $fmt = 'us')
{
$r = date('Y', $time).'-'.date('m', $time).'-'.date('d', $time).' ';
if ($fmt == 'us')
{
$r .= date('h', $time).':'.date('i', $time);
}
else
{
$r .= date('H', $time).':'.date('i', $time);
}
if ($seconds)
{
$r .= ':'.date('s', $time);
}
if ($fmt == 'us')
{
$r .= ' '.date('A', $time);
}
return $r;
}
}
// ------------------------------------------------------------------------
/**
* Convert "human" date to GMT
*
* Reverses the above process
*
* @access public
* @param string format: us or euro
* @return integer
*/
if ( ! function_exists('human_to_unix'))
{
function human_to_unix($datestr = '')
{
if ($datestr == '')
{
return FALSE;
}
$datestr = trim($datestr);
$datestr = preg_replace("/\040+/", ' ', $datestr);
if ( ! preg_match('/^[0-9]{2,4}\-[0-9]{1,2}\-[0-9]{1,2}\s[0-9]{1,2}:[0-9]{1,2}(?::[0-9]{1,2})?(?:\s[AP]M)?$/i', $datestr))
{
return FALSE;
}
$split = explode(' ', $datestr);
$ex = explode("-", $split['0']);
$year = (strlen($ex['0']) == 2) ? '20'.$ex['0'] : $ex['0'];
$month = (strlen($ex['1']) == 1) ? '0'.$ex['1'] : $ex['1'];
$day = (strlen($ex['2']) == 1) ? '0'.$ex['2'] : $ex['2'];
$ex = explode(":", $split['1']);
$hour = (strlen($ex['0']) == 1) ? '0'.$ex['0'] : $ex['0'];
$min = (strlen($ex['1']) == 1) ? '0'.$ex['1'] : $ex['1'];
if (isset($ex['2']) && preg_match('/[0-9]{1,2}/', $ex['2']))
{
$sec = (strlen($ex['2']) == 1) ? '0'.$ex['2'] : $ex['2'];
}
else
{
// Unless specified, seconds get set to zero.
$sec = '00';
}
if (isset($split['2']))
{
$ampm = strtolower($split['2']);
if (substr($ampm, 0, 1) == 'p' AND $hour < 12)
$hour = $hour + 12;
if (substr($ampm, 0, 1) == 'a' AND $hour == 12)
$hour = '00';
if (strlen($hour) == 1)
$hour = '0'.$hour;
}
return mktime($hour, $min, $sec, $month, $day, $year);
}
}
// ------------------------------------------------------------------------
/**
* Timezone Menu
*
* Generates a drop-down menu of timezones.
*
* @access public
* @param string timezone
* @param string classname
* @param string menu name
* @return string
*/
if ( ! function_exists('timezone_menu'))
{
function timezone_menu($default = 'UTC', $class = "", $name = 'timezones')
{
$CI =& get_instance();
$CI->lang->load('date');
if ($default == 'GMT')
$default = 'UTC';
$menu = '<select name="'.$name.'"';
if ($class != '')
{
$menu .= ' class="'.$class.'"';
}
$menu .= ">\n";
foreach (timezones() as $key => $val)
{
$selected = ($default == $key) ? " selected='selected'" : '';
$menu .= "<option value='{$key}'{$selected}>".$CI->lang->line($key)."</option>\n";
}
$menu .= "</select>";
return $menu;
}
}
// ------------------------------------------------------------------------
/**
* Timezones
*
* Returns an array of timezones. This is a helper function
* for various other ones in this library
*
* @access public
* @param string timezone
* @return string
*/
if ( ! function_exists('timezones'))
{
function timezones($tz = '')
{
// Note: Don't change the order of these even though
// some items appear to be in the wrong order
$zones = array(
'UM12' => -12,
'UM11' => -11,
'UM10' => -10,
'UM95' => -9.5,
'UM9' => -9,
'UM8' => -8,
'UM7' => -7,
'UM6' => -6,
'UM5' => -5,
'UM45' => -4.5,
'UM4' => -4,
'UM35' => -3.5,
'UM3' => -3,
'UM2' => -2,
'UM1' => -1,
'UTC' => 0,
'UP1' => +1,
'UP2' => +2,
'UP3' => +3,
'UP35' => +3.5,
'UP4' => +4,
'UP45' => +4.5,
'UP5' => +5,
'UP55' => +5.5,
'UP575' => +5.75,
'UP6' => +6,
'UP65' => +6.5,
'UP7' => +7,
'UP8' => +8,
'UP875' => +8.75,
'UP9' => +9,
'UP95' => +9.5,
'UP10' => +10,
'UP105' => +10.5,
'UP11' => +11,
'UP115' => +11.5,
'UP12' => +12,
'UP1275' => +12.75,
'UP13' => +13,
'UP14' => +14
);
if ($tz == '')
{
return $zones;
}
if ($tz == 'GMT')
$tz = 'UTC';
return ( ! isset($zones[$tz])) ? 0 : $zones[$tz];
}
}
/* End of file date_helper.php */
/* Location: ./system/helpers/date_helper.php */ | php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/helpers/cookie_helper.php | system/helpers/cookie_helper.php | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 5.1.6 or newer
*
* @package CodeIgniter
* @author ExpressionEngine Dev Team
* @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
* @license http://codeigniter.com/user_guide/license.html
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
// ------------------------------------------------------------------------
/**
* CodeIgniter Cookie Helpers
*
* @package CodeIgniter
* @subpackage Helpers
* @category Helpers
* @author ExpressionEngine Dev Team
* @link http://codeigniter.com/user_guide/helpers/cookie_helper.html
*/
// ------------------------------------------------------------------------
/**
* Set cookie
*
* Accepts six parameter, or you can submit an associative
* array in the first parameter containing all the values.
*
* @access public
* @param mixed
* @param string the value of the cookie
* @param string the number of seconds until expiration
* @param string the cookie domain. Usually: .yourdomain.com
* @param string the cookie path
* @param string the cookie prefix
* @return void
*/
if ( ! function_exists('set_cookie'))
{
function set_cookie($name = '', $value = '', $expire = '', $domain = '', $path = '/', $prefix = '', $secure = FALSE)
{
// Set the config file options
$CI =& get_instance();
$CI->input->set_cookie($name, $value, $expire, $domain, $path, $prefix, $secure);
}
}
// --------------------------------------------------------------------
/**
* Fetch an item from the COOKIE array
*
* @access public
* @param string
* @param bool
* @return mixed
*/
if ( ! function_exists('get_cookie'))
{
function get_cookie($index = '', $xss_clean = FALSE)
{
$CI =& get_instance();
$prefix = '';
if ( ! isset($_COOKIE[$index]) && config_item('cookie_prefix') != '')
{
$prefix = config_item('cookie_prefix');
}
return $CI->input->cookie($prefix.$index, $xss_clean);
}
}
// --------------------------------------------------------------------
/**
* Delete a COOKIE
*
* @param mixed
* @param string the cookie domain. Usually: .yourdomain.com
* @param string the cookie path
* @param string the cookie prefix
* @return void
*/
if ( ! function_exists('delete_cookie'))
{
function delete_cookie($name = '', $domain = '', $path = '/', $prefix = '')
{
set_cookie($name, '', '', $domain, $path, $prefix);
}
}
/* End of file cookie_helper.php */
/* Location: ./system/helpers/cookie_helper.php */ | php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/helpers/file_helper.php | system/helpers/file_helper.php | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 5.1.6 or newer
*
* @package CodeIgniter
* @author ExpressionEngine Dev Team
* @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
* @license http://codeigniter.com/user_guide/license.html
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
// ------------------------------------------------------------------------
/**
* CodeIgniter File Helpers
*
* @package CodeIgniter
* @subpackage Helpers
* @category Helpers
* @author ExpressionEngine Dev Team
* @link http://codeigniter.com/user_guide/helpers/file_helpers.html
*/
// ------------------------------------------------------------------------
/**
* Read File
*
* Opens the file specfied in the path and returns it as a string.
*
* @access public
* @param string path to file
* @return string
*/
if ( ! function_exists('read_file'))
{
function read_file($file)
{
if ( ! file_exists($file))
{
return FALSE;
}
if (function_exists('file_get_contents'))
{
return file_get_contents($file);
}
if ( ! $fp = @fopen($file, FOPEN_READ))
{
return FALSE;
}
flock($fp, LOCK_SH);
$data = '';
if (filesize($file) > 0)
{
$data =& fread($fp, filesize($file));
}
flock($fp, LOCK_UN);
fclose($fp);
return $data;
}
}
// ------------------------------------------------------------------------
/**
* Write File
*
* Writes data to the file specified in the path.
* Creates a new file if non-existent.
*
* @access public
* @param string path to file
* @param string file data
* @return bool
*/
if ( ! function_exists('write_file'))
{
function write_file($path, $data, $mode = FOPEN_WRITE_CREATE_DESTRUCTIVE)
{
if ( ! $fp = @fopen($path, $mode))
{
return FALSE;
}
flock($fp, LOCK_EX);
fwrite($fp, $data);
flock($fp, LOCK_UN);
fclose($fp);
return TRUE;
}
}
// ------------------------------------------------------------------------
/**
* Delete Files
*
* Deletes all files contained in the supplied directory path.
* Files must be writable or owned by the system in order to be deleted.
* If the second parameter is set to TRUE, any directories contained
* within the supplied base directory will be nuked as well.
*
* @access public
* @param string path to file
* @param bool whether to delete any directories found in the path
* @return bool
*/
if ( ! function_exists('delete_files'))
{
function delete_files($path, $del_dir = FALSE, $level = 0)
{
// Trim the trailing slash
$path = rtrim($path, DIRECTORY_SEPARATOR);
if ( ! $current_dir = @opendir($path))
{
return FALSE;
}
while (FALSE !== ($filename = @readdir($current_dir)))
{
if ($filename != "." and $filename != "..")
{
if (is_dir($path.DIRECTORY_SEPARATOR.$filename))
{
// Ignore empty folders
if (substr($filename, 0, 1) != '.')
{
delete_files($path.DIRECTORY_SEPARATOR.$filename, $del_dir, $level + 1);
}
}
else
{
unlink($path.DIRECTORY_SEPARATOR.$filename);
}
}
}
@closedir($current_dir);
if ($del_dir == TRUE AND $level > 0)
{
return @rmdir($path);
}
return TRUE;
}
}
// ------------------------------------------------------------------------
/**
* Get Filenames
*
* Reads the specified directory and builds an array containing the filenames.
* Any sub-folders contained within the specified path are read as well.
*
* @access public
* @param string path to source
* @param bool whether to include the path as part of the filename
* @param bool internal variable to determine recursion status - do not use in calls
* @return array
*/
if ( ! function_exists('get_filenames'))
{
function get_filenames($source_dir, $include_path = FALSE, $_recursion = FALSE)
{
static $_filedata = array();
if ($fp = @opendir($source_dir))
{
// reset the array and make sure $source_dir has a trailing slash on the initial call
if ($_recursion === FALSE)
{
$_filedata = array();
$source_dir = rtrim(realpath($source_dir), DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;
}
while (FALSE !== ($file = readdir($fp)))
{
if (@is_dir($source_dir.$file) && strncmp($file, '.', 1) !== 0)
{
get_filenames($source_dir.$file.DIRECTORY_SEPARATOR, $include_path, TRUE);
}
elseif (strncmp($file, '.', 1) !== 0)
{
$_filedata[] = ($include_path == TRUE) ? $source_dir.$file : $file;
}
}
return $_filedata;
}
else
{
return FALSE;
}
}
}
// --------------------------------------------------------------------
/**
* Get Directory File Information
*
* Reads the specified directory and builds an array containing the filenames,
* filesize, dates, and permissions
*
* Any sub-folders contained within the specified path are read as well.
*
* @access public
* @param string path to source
* @param bool Look only at the top level directory specified?
* @param bool internal variable to determine recursion status - do not use in calls
* @return array
*/
if ( ! function_exists('get_dir_file_info'))
{
function get_dir_file_info($source_dir, $top_level_only = TRUE, $_recursion = FALSE)
{
static $_filedata = array();
$relative_path = $source_dir;
if ($fp = @opendir($source_dir))
{
// reset the array and make sure $source_dir has a trailing slash on the initial call
if ($_recursion === FALSE)
{
$_filedata = array();
$source_dir = rtrim(realpath($source_dir), DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;
}
// foreach (scandir($source_dir, 1) as $file) // In addition to being PHP5+, scandir() is simply not as fast
while (FALSE !== ($file = readdir($fp)))
{
if (@is_dir($source_dir.$file) AND strncmp($file, '.', 1) !== 0 AND $top_level_only === FALSE)
{
get_dir_file_info($source_dir.$file.DIRECTORY_SEPARATOR, $top_level_only, TRUE);
}
elseif (strncmp($file, '.', 1) !== 0)
{
$_filedata[$file] = get_file_info($source_dir.$file);
$_filedata[$file]['relative_path'] = $relative_path;
}
}
return $_filedata;
}
else
{
return FALSE;
}
}
}
// --------------------------------------------------------------------
/**
* Get File Info
*
* Given a file and path, returns the name, path, size, date modified
* Second parameter allows you to explicitly declare what information you want returned
* Options are: name, server_path, size, date, readable, writable, executable, fileperms
* Returns FALSE if the file cannot be found.
*
* @access public
* @param string path to file
* @param mixed array or comma separated string of information returned
* @return array
*/
if ( ! function_exists('get_file_info'))
{
function get_file_info($file, $returned_values = array('name', 'server_path', 'size', 'date'))
{
if ( ! file_exists($file))
{
return FALSE;
}
if (is_string($returned_values))
{
$returned_values = explode(',', $returned_values);
}
foreach ($returned_values as $key)
{
switch ($key)
{
case 'name':
$fileinfo['name'] = substr(strrchr($file, DIRECTORY_SEPARATOR), 1);
break;
case 'server_path':
$fileinfo['server_path'] = $file;
break;
case 'size':
$fileinfo['size'] = filesize($file);
break;
case 'date':
$fileinfo['date'] = filemtime($file);
break;
case 'readable':
$fileinfo['readable'] = is_readable($file);
break;
case 'writable':
// There are known problems using is_weritable on IIS. It may not be reliable - consider fileperms()
$fileinfo['writable'] = is_writable($file);
break;
case 'executable':
$fileinfo['executable'] = is_executable($file);
break;
case 'fileperms':
$fileinfo['fileperms'] = fileperms($file);
break;
}
}
return $fileinfo;
}
}
// --------------------------------------------------------------------
/**
* Get Mime by Extension
*
* Translates a file extension into a mime type based on config/mimes.php.
* Returns FALSE if it can't determine the type, or open the mime config file
*
* Note: this is NOT an accurate way of determining file mime types, and is here strictly as a convenience
* It should NOT be trusted, and should certainly NOT be used for security
*
* @access public
* @param string path to file
* @return mixed
*/
if ( ! function_exists('get_mime_by_extension'))
{
function get_mime_by_extension($file)
{
$extension = strtolower(substr(strrchr($file, '.'), 1));
global $mimes;
if ( ! is_array($mimes))
{
if (defined('ENVIRONMENT') AND is_file(APPPATH.'config/'.ENVIRONMENT.'/mimes.php'))
{
include(APPPATH.'config/'.ENVIRONMENT.'/mimes.php');
}
elseif (is_file(APPPATH.'config/mimes.php'))
{
include(APPPATH.'config/mimes.php');
}
if ( ! is_array($mimes))
{
return FALSE;
}
}
if (array_key_exists($extension, $mimes))
{
if (is_array($mimes[$extension]))
{
// Multiple mime types, just give the first one
return current($mimes[$extension]);
}
else
{
return $mimes[$extension];
}
}
else
{
return FALSE;
}
}
}
// --------------------------------------------------------------------
/**
* Symbolic Permissions
*
* Takes a numeric value representing a file's permissions and returns
* standard symbolic notation representing that value
*
* @access public
* @param int
* @return string
*/
if ( ! function_exists('symbolic_permissions'))
{
function symbolic_permissions($perms)
{
if (($perms & 0xC000) == 0xC000)
{
$symbolic = 's'; // Socket
}
elseif (($perms & 0xA000) == 0xA000)
{
$symbolic = 'l'; // Symbolic Link
}
elseif (($perms & 0x8000) == 0x8000)
{
$symbolic = '-'; // Regular
}
elseif (($perms & 0x6000) == 0x6000)
{
$symbolic = 'b'; // Block special
}
elseif (($perms & 0x4000) == 0x4000)
{
$symbolic = 'd'; // Directory
}
elseif (($perms & 0x2000) == 0x2000)
{
$symbolic = 'c'; // Character special
}
elseif (($perms & 0x1000) == 0x1000)
{
$symbolic = 'p'; // FIFO pipe
}
else
{
$symbolic = 'u'; // Unknown
}
// Owner
$symbolic .= (($perms & 0x0100) ? 'r' : '-');
$symbolic .= (($perms & 0x0080) ? 'w' : '-');
$symbolic .= (($perms & 0x0040) ? (($perms & 0x0800) ? 's' : 'x' ) : (($perms & 0x0800) ? 'S' : '-'));
// Group
$symbolic .= (($perms & 0x0020) ? 'r' : '-');
$symbolic .= (($perms & 0x0010) ? 'w' : '-');
$symbolic .= (($perms & 0x0008) ? (($perms & 0x0400) ? 's' : 'x' ) : (($perms & 0x0400) ? 'S' : '-'));
// World
$symbolic .= (($perms & 0x0004) ? 'r' : '-');
$symbolic .= (($perms & 0x0002) ? 'w' : '-');
$symbolic .= (($perms & 0x0001) ? (($perms & 0x0200) ? 't' : 'x' ) : (($perms & 0x0200) ? 'T' : '-'));
return $symbolic;
}
}
// --------------------------------------------------------------------
/**
* Octal Permissions
*
* Takes a numeric value representing a file's permissions and returns
* a three character string representing the file's octal permissions
*
* @access public
* @param int
* @return string
*/
if ( ! function_exists('octal_permissions'))
{
function octal_permissions($perms)
{
return substr(sprintf('%o', $perms), -3);
}
}
/* End of file file_helper.php */
/* Location: ./system/helpers/file_helper.php */ | php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/helpers/number_helper.php | system/helpers/number_helper.php | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 5.1.6 or newer
*
* @package CodeIgniter
* @author ExpressionEngine Dev Team
* @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
* @license http://codeigniter.com/user_guide/license.html
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
// ------------------------------------------------------------------------
/**
* CodeIgniter Number Helpers
*
* @package CodeIgniter
* @subpackage Helpers
* @category Helpers
* @author ExpressionEngine Dev Team
* @link http://codeigniter.com/user_guide/helpers/number_helper.html
*/
// ------------------------------------------------------------------------
/**
* Formats a numbers as bytes, based on size, and adds the appropriate suffix
*
* @access public
* @param mixed // will be cast as int
* @return string
*/
if ( ! function_exists('byte_format'))
{
function byte_format($num, $precision = 1)
{
$CI =& get_instance();
$CI->lang->load('number');
if ($num >= 1000000000000)
{
$num = round($num / 1099511627776, $precision);
$unit = $CI->lang->line('terabyte_abbr');
}
elseif ($num >= 1000000000)
{
$num = round($num / 1073741824, $precision);
$unit = $CI->lang->line('gigabyte_abbr');
}
elseif ($num >= 1000000)
{
$num = round($num / 1048576, $precision);
$unit = $CI->lang->line('megabyte_abbr');
}
elseif ($num >= 1000)
{
$num = round($num / 1024, $precision);
$unit = $CI->lang->line('kilobyte_abbr');
}
else
{
$unit = $CI->lang->line('bytes');
return number_format($num).' '.$unit;
}
return number_format($num, $precision).' '.$unit;
}
}
/* End of file number_helper.php */
/* Location: ./system/helpers/number_helper.php */ | php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/helpers/directory_helper.php | system/helpers/directory_helper.php | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 5.1.6 or newer
*
* @package CodeIgniter
* @author ExpressionEngine Dev Team
* @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
* @license http://codeigniter.com/user_guide/license.html
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
// ------------------------------------------------------------------------
/**
* CodeIgniter Directory Helpers
*
* @package CodeIgniter
* @subpackage Helpers
* @category Helpers
* @author ExpressionEngine Dev Team
* @link http://codeigniter.com/user_guide/helpers/directory_helper.html
*/
// ------------------------------------------------------------------------
/**
* Create a Directory Map
*
* Reads the specified directory and builds an array
* representation of it. Sub-folders contained with the
* directory will be mapped as well.
*
* @access public
* @param string path to source
* @param int depth of directories to traverse (0 = fully recursive, 1 = current dir, etc)
* @return array
*/
if ( ! function_exists('directory_map'))
{
function directory_map($source_dir, $directory_depth = 0, $hidden = FALSE)
{
if ($fp = @opendir($source_dir))
{
$filedata = array();
$new_depth = $directory_depth - 1;
$source_dir = rtrim($source_dir, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;
while (FALSE !== ($file = readdir($fp)))
{
// Remove '.', '..', and hidden files [optional]
if ( ! trim($file, '.') OR ($hidden == FALSE && $file[0] == '.'))
{
continue;
}
if (($directory_depth < 1 OR $new_depth > 0) && @is_dir($source_dir.$file))
{
$filedata[$file] = directory_map($source_dir.$file.DIRECTORY_SEPARATOR, $new_depth, $hidden);
}
else
{
$filedata[] = $file;
}
}
closedir($fp);
return $filedata;
}
return FALSE;
}
}
/* End of file directory_helper.php */
/* Location: ./system/helpers/directory_helper.php */ | php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/libraries/Xmlrpc.php | system/libraries/Xmlrpc.php | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 5.1.6 or newer
*
* @package CodeIgniter
* @author ExpressionEngine Dev Team
* @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
* @license http://codeigniter.com/user_guide/license.html
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
if ( ! function_exists('xml_parser_create'))
{
show_error('Your PHP installation does not support XML');
}
// ------------------------------------------------------------------------
/**
* XML-RPC request handler class
*
* @package CodeIgniter
* @subpackage Libraries
* @category XML-RPC
* @author ExpressionEngine Dev Team
* @link http://codeigniter.com/user_guide/libraries/xmlrpc.html
*/
class CI_Xmlrpc {
var $debug = FALSE; // Debugging on or off
var $xmlrpcI4 = 'i4';
var $xmlrpcInt = 'int';
var $xmlrpcBoolean = 'boolean';
var $xmlrpcDouble = 'double';
var $xmlrpcString = 'string';
var $xmlrpcDateTime = 'dateTime.iso8601';
var $xmlrpcBase64 = 'base64';
var $xmlrpcArray = 'array';
var $xmlrpcStruct = 'struct';
var $xmlrpcTypes = array();
var $valid_parents = array();
var $xmlrpcerr = array(); // Response numbers
var $xmlrpcstr = array(); // Response strings
var $xmlrpc_defencoding = 'UTF-8';
var $xmlrpcName = 'XML-RPC for CodeIgniter';
var $xmlrpcVersion = '1.1';
var $xmlrpcerruser = 800; // Start of user errors
var $xmlrpcerrxml = 100; // Start of XML Parse errors
var $xmlrpc_backslash = ''; // formulate backslashes for escaping regexp
var $client;
var $method;
var $data;
var $message = '';
var $error = ''; // Error string for request
var $result;
var $response = array(); // Response from remote server
var $xss_clean = TRUE;
//-------------------------------------
// VALUES THAT MULTIPLE CLASSES NEED
//-------------------------------------
public function __construct($config = array())
{
$this->xmlrpcName = $this->xmlrpcName;
$this->xmlrpc_backslash = chr(92).chr(92);
// Types for info sent back and forth
$this->xmlrpcTypes = array(
$this->xmlrpcI4 => '1',
$this->xmlrpcInt => '1',
$this->xmlrpcBoolean => '1',
$this->xmlrpcString => '1',
$this->xmlrpcDouble => '1',
$this->xmlrpcDateTime => '1',
$this->xmlrpcBase64 => '1',
$this->xmlrpcArray => '2',
$this->xmlrpcStruct => '3'
);
// Array of Valid Parents for Various XML-RPC elements
$this->valid_parents = array('BOOLEAN' => array('VALUE'),
'I4' => array('VALUE'),
'INT' => array('VALUE'),
'STRING' => array('VALUE'),
'DOUBLE' => array('VALUE'),
'DATETIME.ISO8601' => array('VALUE'),
'BASE64' => array('VALUE'),
'ARRAY' => array('VALUE'),
'STRUCT' => array('VALUE'),
'PARAM' => array('PARAMS'),
'METHODNAME' => array('METHODCALL'),
'PARAMS' => array('METHODCALL', 'METHODRESPONSE'),
'MEMBER' => array('STRUCT'),
'NAME' => array('MEMBER'),
'DATA' => array('ARRAY'),
'FAULT' => array('METHODRESPONSE'),
'VALUE' => array('MEMBER', 'DATA', 'PARAM', 'FAULT')
);
// XML-RPC Responses
$this->xmlrpcerr['unknown_method'] = '1';
$this->xmlrpcstr['unknown_method'] = 'This is not a known method for this XML-RPC Server';
$this->xmlrpcerr['invalid_return'] = '2';
$this->xmlrpcstr['invalid_return'] = 'The XML data received was either invalid or not in the correct form for XML-RPC. Turn on debugging to examine the XML data further.';
$this->xmlrpcerr['incorrect_params'] = '3';
$this->xmlrpcstr['incorrect_params'] = 'Incorrect parameters were passed to method';
$this->xmlrpcerr['introspect_unknown'] = '4';
$this->xmlrpcstr['introspect_unknown'] = "Cannot inspect signature for request: method unknown";
$this->xmlrpcerr['http_error'] = '5';
$this->xmlrpcstr['http_error'] = "Did not receive a '200 OK' response from remote server.";
$this->xmlrpcerr['no_data'] = '6';
$this->xmlrpcstr['no_data'] ='No data received from server.';
$this->initialize($config);
log_message('debug', "XML-RPC Class Initialized");
}
//-------------------------------------
// Initialize Prefs
//-------------------------------------
function initialize($config = array())
{
if (count($config) > 0)
{
foreach ($config as $key => $val)
{
if (isset($this->$key))
{
$this->$key = $val;
}
}
}
}
// END
//-------------------------------------
// Take URL and parse it
//-------------------------------------
function server($url, $port=80)
{
if (substr($url, 0, 4) != "http")
{
$url = "http://".$url;
}
$parts = parse_url($url);
$path = ( ! isset($parts['path'])) ? '/' : $parts['path'];
if (isset($parts['query']) && $parts['query'] != '')
{
$path .= '?'.$parts['query'];
}
$this->client = new XML_RPC_Client($path, $parts['host'], $port);
}
// END
//-------------------------------------
// Set Timeout
//-------------------------------------
function timeout($seconds=5)
{
if ( ! is_null($this->client) && is_int($seconds))
{
$this->client->timeout = $seconds;
}
}
// END
//-------------------------------------
// Set Methods
//-------------------------------------
function method($function)
{
$this->method = $function;
}
// END
//-------------------------------------
// Take Array of Data and Create Objects
//-------------------------------------
function request($incoming)
{
if ( ! is_array($incoming))
{
// Send Error
}
$this->data = array();
foreach ($incoming as $key => $value)
{
$this->data[$key] = $this->values_parsing($value);
}
}
// END
//-------------------------------------
// Set Debug
//-------------------------------------
function set_debug($flag = TRUE)
{
$this->debug = ($flag == TRUE) ? TRUE : FALSE;
}
//-------------------------------------
// Values Parsing
//-------------------------------------
function values_parsing($value, $return = FALSE)
{
if (is_array($value) && array_key_exists(0, $value))
{
if ( ! isset($value['1']) OR ( ! isset($this->xmlrpcTypes[$value['1']])))
{
if (is_array($value[0]))
{
$temp = new XML_RPC_Values($value['0'], 'array');
}
else
{
$temp = new XML_RPC_Values($value['0'], 'string');
}
}
elseif (is_array($value['0']) && ($value['1'] == 'struct' OR $value['1'] == 'array'))
{
while (list($k) = each($value['0']))
{
$value['0'][$k] = $this->values_parsing($value['0'][$k], TRUE);
}
$temp = new XML_RPC_Values($value['0'], $value['1']);
}
else
{
$temp = new XML_RPC_Values($value['0'], $value['1']);
}
}
else
{
$temp = new XML_RPC_Values($value, 'string');
}
return $temp;
}
// END
//-------------------------------------
// Sends XML-RPC Request
//-------------------------------------
function send_request()
{
$this->message = new XML_RPC_Message($this->method,$this->data);
$this->message->debug = $this->debug;
if ( ! $this->result = $this->client->send($this->message))
{
$this->error = $this->result->errstr;
return FALSE;
}
elseif ( ! is_object($this->result->val))
{
$this->error = $this->result->errstr;
return FALSE;
}
$this->response = $this->result->decode();
return TRUE;
}
// END
//-------------------------------------
// Returns Error
//-------------------------------------
function display_error()
{
return $this->error;
}
// END
//-------------------------------------
// Returns Remote Server Response
//-------------------------------------
function display_response()
{
return $this->response;
}
// END
//-------------------------------------
// Sends an Error Message for Server Request
//-------------------------------------
function send_error_message($number, $message)
{
return new XML_RPC_Response('0',$number, $message);
}
// END
//-------------------------------------
// Send Response for Server Request
//-------------------------------------
function send_response($response)
{
// $response should be array of values, which will be parsed
// based on their data and type into a valid group of XML-RPC values
$response = $this->values_parsing($response);
return new XML_RPC_Response($response);
}
// END
} // END XML_RPC Class
/**
* XML-RPC Client class
*
* @category XML-RPC
* @author ExpressionEngine Dev Team
* @link http://codeigniter.com/user_guide/libraries/xmlrpc.html
*/
class XML_RPC_Client extends CI_Xmlrpc
{
var $path = '';
var $server = '';
var $port = 80;
var $errno = '';
var $errstring = '';
var $timeout = 5;
var $no_multicall = FALSE;
public function __construct($path, $server, $port=80)
{
parent::__construct();
$this->port = $port;
$this->server = $server;
$this->path = $path;
}
function send($msg)
{
if (is_array($msg))
{
// Multi-call disabled
$r = new XML_RPC_Response(0, $this->xmlrpcerr['multicall_recursion'],$this->xmlrpcstr['multicall_recursion']);
return $r;
}
return $this->sendPayload($msg);
}
function sendPayload($msg)
{
$fp = @fsockopen($this->server, $this->port,$this->errno, $this->errstr, $this->timeout);
if ( ! is_resource($fp))
{
error_log($this->xmlrpcstr['http_error']);
$r = new XML_RPC_Response(0, $this->xmlrpcerr['http_error'],$this->xmlrpcstr['http_error']);
return $r;
}
if (empty($msg->payload))
{
// $msg = XML_RPC_Messages
$msg->createPayload();
}
$r = "\r\n";
$op = "POST {$this->path} HTTP/1.0$r";
$op .= "Host: {$this->server}$r";
$op .= "Content-Type: text/xml$r";
$op .= "User-Agent: {$this->xmlrpcName}$r";
$op .= "Content-Length: ".strlen($msg->payload). "$r$r";
$op .= $msg->payload;
if ( ! fputs($fp, $op, strlen($op)))
{
error_log($this->xmlrpcstr['http_error']);
$r = new XML_RPC_Response(0, $this->xmlrpcerr['http_error'], $this->xmlrpcstr['http_error']);
return $r;
}
$resp = $msg->parseResponse($fp);
fclose($fp);
return $resp;
}
} // end class XML_RPC_Client
/**
* XML-RPC Response class
*
* @category XML-RPC
* @author ExpressionEngine Dev Team
* @link http://codeigniter.com/user_guide/libraries/xmlrpc.html
*/
class XML_RPC_Response
{
var $val = 0;
var $errno = 0;
var $errstr = '';
var $headers = array();
var $xss_clean = TRUE;
public function __construct($val, $code = 0, $fstr = '')
{
if ($code != 0)
{
// error
$this->errno = $code;
$this->errstr = htmlentities($fstr);
}
else if ( ! is_object($val))
{
// programmer error, not an object
error_log("Invalid type '" . gettype($val) . "' (value: $val) passed to XML_RPC_Response. Defaulting to empty value.");
$this->val = new XML_RPC_Values();
}
else
{
$this->val = $val;
}
}
function faultCode()
{
return $this->errno;
}
function faultString()
{
return $this->errstr;
}
function value()
{
return $this->val;
}
function prepare_response()
{
$result = "<methodResponse>\n";
if ($this->errno)
{
$result .= '<fault>
<value>
<struct>
<member>
<name>faultCode</name>
<value><int>' . $this->errno . '</int></value>
</member>
<member>
<name>faultString</name>
<value><string>' . $this->errstr . '</string></value>
</member>
</struct>
</value>
</fault>';
}
else
{
$result .= "<params>\n<param>\n" .
$this->val->serialize_class() .
"</param>\n</params>";
}
$result .= "\n</methodResponse>";
return $result;
}
function decode($array=FALSE)
{
$CI =& get_instance();
if ($array !== FALSE && is_array($array))
{
while (list($key) = each($array))
{
if (is_array($array[$key]))
{
$array[$key] = $this->decode($array[$key]);
}
else
{
$array[$key] = ($this->xss_clean) ? $CI->security->xss_clean($array[$key]) : $array[$key];
}
}
$result = $array;
}
else
{
$result = $this->xmlrpc_decoder($this->val);
if (is_array($result))
{
$result = $this->decode($result);
}
else
{
$result = ($this->xss_clean) ? $CI->security->xss_clean($result) : $result;
}
}
return $result;
}
//-------------------------------------
// XML-RPC Object to PHP Types
//-------------------------------------
function xmlrpc_decoder($xmlrpc_val)
{
$kind = $xmlrpc_val->kindOf();
if ($kind == 'scalar')
{
return $xmlrpc_val->scalarval();
}
elseif ($kind == 'array')
{
reset($xmlrpc_val->me);
list($a,$b) = each($xmlrpc_val->me);
$size = count($b);
$arr = array();
for ($i = 0; $i < $size; $i++)
{
$arr[] = $this->xmlrpc_decoder($xmlrpc_val->me['array'][$i]);
}
return $arr;
}
elseif ($kind == 'struct')
{
reset($xmlrpc_val->me['struct']);
$arr = array();
while (list($key,$value) = each($xmlrpc_val->me['struct']))
{
$arr[$key] = $this->xmlrpc_decoder($value);
}
return $arr;
}
}
//-------------------------------------
// ISO-8601 time to server or UTC time
//-------------------------------------
function iso8601_decode($time, $utc=0)
{
// return a timet in the localtime, or UTC
$t = 0;
if (preg_match('/([0-9]{4})([0-9]{2})([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})/', $time, $regs))
{
$fnc = ($utc == 1) ? 'gmmktime' : 'mktime';
$t = $fnc($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]);
}
return $t;
}
} // End Response Class
/**
* XML-RPC Message class
*
* @category XML-RPC
* @author ExpressionEngine Dev Team
* @link http://codeigniter.com/user_guide/libraries/xmlrpc.html
*/
class XML_RPC_Message extends CI_Xmlrpc
{
var $payload;
var $method_name;
var $params = array();
var $xh = array();
public function __construct($method, $pars=0)
{
parent::__construct();
$this->method_name = $method;
if (is_array($pars) && count($pars) > 0)
{
for ($i=0; $i<count($pars); $i++)
{
// $pars[$i] = XML_RPC_Values
$this->params[] = $pars[$i];
}
}
}
//-------------------------------------
// Create Payload to Send
//-------------------------------------
function createPayload()
{
$this->payload = "<?xml version=\"1.0\"?".">\r\n<methodCall>\r\n";
$this->payload .= '<methodName>' . $this->method_name . "</methodName>\r\n";
$this->payload .= "<params>\r\n";
for ($i=0; $i<count($this->params); $i++)
{
// $p = XML_RPC_Values
$p = $this->params[$i];
$this->payload .= "<param>\r\n".$p->serialize_class()."</param>\r\n";
}
$this->payload .= "</params>\r\n</methodCall>\r\n";
}
//-------------------------------------
// Parse External XML-RPC Server's Response
//-------------------------------------
function parseResponse($fp)
{
$data = '';
while ($datum = fread($fp, 4096))
{
$data .= $datum;
}
//-------------------------------------
// DISPLAY HTTP CONTENT for DEBUGGING
//-------------------------------------
if ($this->debug === TRUE)
{
echo "<pre>";
echo "---DATA---\n" . htmlspecialchars($data) . "\n---END DATA---\n\n";
echo "</pre>";
}
//-------------------------------------
// Check for data
//-------------------------------------
if ($data == "")
{
error_log($this->xmlrpcstr['no_data']);
$r = new XML_RPC_Response(0, $this->xmlrpcerr['no_data'], $this->xmlrpcstr['no_data']);
return $r;
}
//-------------------------------------
// Check for HTTP 200 Response
//-------------------------------------
if (strncmp($data, 'HTTP', 4) == 0 && ! preg_match('/^HTTP\/[0-9\.]+ 200 /', $data))
{
$errstr= substr($data, 0, strpos($data, "\n")-1);
$r = new XML_RPC_Response(0, $this->xmlrpcerr['http_error'], $this->xmlrpcstr['http_error']. ' (' . $errstr . ')');
return $r;
}
//-------------------------------------
// Create and Set Up XML Parser
//-------------------------------------
$parser = xml_parser_create($this->xmlrpc_defencoding);
$this->xh[$parser] = array();
$this->xh[$parser]['isf'] = 0;
$this->xh[$parser]['ac'] = '';
$this->xh[$parser]['headers'] = array();
$this->xh[$parser]['stack'] = array();
$this->xh[$parser]['valuestack'] = array();
$this->xh[$parser]['isf_reason'] = 0;
xml_set_object($parser, $this);
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true);
xml_set_element_handler($parser, 'open_tag', 'closing_tag');
xml_set_character_data_handler($parser, 'character_data');
//xml_set_default_handler($parser, 'default_handler');
//-------------------------------------
// GET HEADERS
//-------------------------------------
$lines = explode("\r\n", $data);
while (($line = array_shift($lines)))
{
if (strlen($line) < 1)
{
break;
}
$this->xh[$parser]['headers'][] = $line;
}
$data = implode("\r\n", $lines);
//-------------------------------------
// PARSE XML DATA
//-------------------------------------
if ( ! xml_parse($parser, $data, count($data)))
{
$errstr = sprintf('XML error: %s at line %d',
xml_error_string(xml_get_error_code($parser)),
xml_get_current_line_number($parser));
//error_log($errstr);
$r = new XML_RPC_Response(0, $this->xmlrpcerr['invalid_return'], $this->xmlrpcstr['invalid_return']);
xml_parser_free($parser);
return $r;
}
xml_parser_free($parser);
// ---------------------------------------
// Got Ourselves Some Badness, It Seems
// ---------------------------------------
if ($this->xh[$parser]['isf'] > 1)
{
if ($this->debug === TRUE)
{
echo "---Invalid Return---\n";
echo $this->xh[$parser]['isf_reason'];
echo "---Invalid Return---\n\n";
}
$r = new XML_RPC_Response(0, $this->xmlrpcerr['invalid_return'],$this->xmlrpcstr['invalid_return'].' '.$this->xh[$parser]['isf_reason']);
return $r;
}
elseif ( ! is_object($this->xh[$parser]['value']))
{
$r = new XML_RPC_Response(0, $this->xmlrpcerr['invalid_return'],$this->xmlrpcstr['invalid_return'].' '.$this->xh[$parser]['isf_reason']);
return $r;
}
//-------------------------------------
// DISPLAY XML CONTENT for DEBUGGING
//-------------------------------------
if ($this->debug === TRUE)
{
echo "<pre>";
if (count($this->xh[$parser]['headers'] > 0))
{
echo "---HEADERS---\n";
foreach ($this->xh[$parser]['headers'] as $header)
{
echo "$header\n";
}
echo "---END HEADERS---\n\n";
}
echo "---DATA---\n" . htmlspecialchars($data) . "\n---END DATA---\n\n";
echo "---PARSED---\n" ;
var_dump($this->xh[$parser]['value']);
echo "\n---END PARSED---</pre>";
}
//-------------------------------------
// SEND RESPONSE
//-------------------------------------
$v = $this->xh[$parser]['value'];
if ($this->xh[$parser]['isf'])
{
$errno_v = $v->me['struct']['faultCode'];
$errstr_v = $v->me['struct']['faultString'];
$errno = $errno_v->scalarval();
if ($errno == 0)
{
// FAULT returned, errno needs to reflect that
$errno = -1;
}
$r = new XML_RPC_Response($v, $errno, $errstr_v->scalarval());
}
else
{
$r = new XML_RPC_Response($v);
}
$r->headers = $this->xh[$parser]['headers'];
return $r;
}
// ------------------------------------
// Begin Return Message Parsing section
// ------------------------------------
// quick explanation of components:
// ac - used to accumulate values
// isf - used to indicate a fault
// lv - used to indicate "looking for a value": implements
// the logic to allow values with no types to be strings
// params - used to store parameters in method calls
// method - used to store method name
// stack - array with parent tree of the xml element,
// used to validate the nesting of elements
//-------------------------------------
// Start Element Handler
//-------------------------------------
function open_tag($the_parser, $name, $attrs)
{
// If invalid nesting, then return
if ($this->xh[$the_parser]['isf'] > 1) return;
// Evaluate and check for correct nesting of XML elements
if (count($this->xh[$the_parser]['stack']) == 0)
{
if ($name != 'METHODRESPONSE' && $name != 'METHODCALL')
{
$this->xh[$the_parser]['isf'] = 2;
$this->xh[$the_parser]['isf_reason'] = 'Top level XML-RPC element is missing';
return;
}
}
else
{
// not top level element: see if parent is OK
if ( ! in_array($this->xh[$the_parser]['stack'][0], $this->valid_parents[$name], TRUE))
{
$this->xh[$the_parser]['isf'] = 2;
$this->xh[$the_parser]['isf_reason'] = "XML-RPC element $name cannot be child of ".$this->xh[$the_parser]['stack'][0];
return;
}
}
switch($name)
{
case 'STRUCT':
case 'ARRAY':
// Creates array for child elements
$cur_val = array('value' => array(),
'type' => $name);
array_unshift($this->xh[$the_parser]['valuestack'], $cur_val);
break;
case 'METHODNAME':
case 'NAME':
$this->xh[$the_parser]['ac'] = '';
break;
case 'FAULT':
$this->xh[$the_parser]['isf'] = 1;
break;
case 'PARAM':
$this->xh[$the_parser]['value'] = NULL;
break;
case 'VALUE':
$this->xh[$the_parser]['vt'] = 'value';
$this->xh[$the_parser]['ac'] = '';
$this->xh[$the_parser]['lv'] = 1;
break;
case 'I4':
case 'INT':
case 'STRING':
case 'BOOLEAN':
case 'DOUBLE':
case 'DATETIME.ISO8601':
case 'BASE64':
if ($this->xh[$the_parser]['vt'] != 'value')
{
//two data elements inside a value: an error occurred!
$this->xh[$the_parser]['isf'] = 2;
$this->xh[$the_parser]['isf_reason'] = "'Twas a $name element following a ".$this->xh[$the_parser]['vt']." element inside a single value";
return;
}
$this->xh[$the_parser]['ac'] = '';
break;
case 'MEMBER':
// Set name of <member> to nothing to prevent errors later if no <name> is found
$this->xh[$the_parser]['valuestack'][0]['name'] = '';
// Set NULL value to check to see if value passed for this param/member
$this->xh[$the_parser]['value'] = NULL;
break;
case 'DATA':
case 'METHODCALL':
case 'METHODRESPONSE':
case 'PARAMS':
// valid elements that add little to processing
break;
default:
/// An Invalid Element is Found, so we have trouble
$this->xh[$the_parser]['isf'] = 2;
$this->xh[$the_parser]['isf_reason'] = "Invalid XML-RPC element found: $name";
break;
}
// Add current element name to stack, to allow validation of nesting
array_unshift($this->xh[$the_parser]['stack'], $name);
if ($name != 'VALUE') $this->xh[$the_parser]['lv'] = 0;
}
// END
//-------------------------------------
// End Element Handler
//-------------------------------------
function closing_tag($the_parser, $name)
{
if ($this->xh[$the_parser]['isf'] > 1) return;
// Remove current element from stack and set variable
// NOTE: If the XML validates, then we do not have to worry about
// the opening and closing of elements. Nesting is checked on the opening
// tag so we be safe there as well.
$curr_elem = array_shift($this->xh[$the_parser]['stack']);
switch($name)
{
case 'STRUCT':
case 'ARRAY':
$cur_val = array_shift($this->xh[$the_parser]['valuestack']);
$this->xh[$the_parser]['value'] = ( ! isset($cur_val['values'])) ? array() : $cur_val['values'];
$this->xh[$the_parser]['vt'] = strtolower($name);
break;
case 'NAME':
$this->xh[$the_parser]['valuestack'][0]['name'] = $this->xh[$the_parser]['ac'];
break;
case 'BOOLEAN':
case 'I4':
case 'INT':
case 'STRING':
case 'DOUBLE':
case 'DATETIME.ISO8601':
case 'BASE64':
$this->xh[$the_parser]['vt'] = strtolower($name);
if ($name == 'STRING')
{
$this->xh[$the_parser]['value'] = $this->xh[$the_parser]['ac'];
}
elseif ($name=='DATETIME.ISO8601')
{
$this->xh[$the_parser]['vt'] = $this->xmlrpcDateTime;
$this->xh[$the_parser]['value'] = $this->xh[$the_parser]['ac'];
}
elseif ($name=='BASE64')
{
$this->xh[$the_parser]['value'] = base64_decode($this->xh[$the_parser]['ac']);
}
elseif ($name=='BOOLEAN')
{
// Translated BOOLEAN values to TRUE AND FALSE
if ($this->xh[$the_parser]['ac'] == '1')
{
$this->xh[$the_parser]['value'] = TRUE;
}
else
{
$this->xh[$the_parser]['value'] = FALSE;
}
}
elseif ($name=='DOUBLE')
{
// we have a DOUBLE
// we must check that only 0123456789-.<space> are characters here
if ( ! preg_match('/^[+-]?[eE0-9\t \.]+$/', $this->xh[$the_parser]['ac']))
{
$this->xh[$the_parser]['value'] = 'ERROR_NON_NUMERIC_FOUND';
}
else
{
$this->xh[$the_parser]['value'] = (double)$this->xh[$the_parser]['ac'];
}
}
else
{
// we have an I4/INT
// we must check that only 0123456789-<space> are characters here
if ( ! preg_match('/^[+-]?[0-9\t ]+$/', $this->xh[$the_parser]['ac']))
{
$this->xh[$the_parser]['value'] = 'ERROR_NON_NUMERIC_FOUND';
}
else
{
$this->xh[$the_parser]['value'] = (int)$this->xh[$the_parser]['ac'];
}
}
$this->xh[$the_parser]['ac'] = '';
$this->xh[$the_parser]['lv'] = 3; // indicate we've found a value
break;
case 'VALUE':
// This if() detects if no scalar was inside <VALUE></VALUE>
if ($this->xh[$the_parser]['vt']=='value')
{
$this->xh[$the_parser]['value'] = $this->xh[$the_parser]['ac'];
$this->xh[$the_parser]['vt'] = $this->xmlrpcString;
}
// build the XML-RPC value out of the data received, and substitute it
$temp = new XML_RPC_Values($this->xh[$the_parser]['value'], $this->xh[$the_parser]['vt']);
if (count($this->xh[$the_parser]['valuestack']) && $this->xh[$the_parser]['valuestack'][0]['type'] == 'ARRAY')
{
// Array
$this->xh[$the_parser]['valuestack'][0]['values'][] = $temp;
}
else
{
// Struct
$this->xh[$the_parser]['value'] = $temp;
}
break;
case 'MEMBER':
$this->xh[$the_parser]['ac']='';
// If value add to array in the stack for the last element built
if ($this->xh[$the_parser]['value'])
{
$this->xh[$the_parser]['valuestack'][0]['values'][$this->xh[$the_parser]['valuestack'][0]['name']] = $this->xh[$the_parser]['value'];
}
break;
case 'DATA':
$this->xh[$the_parser]['ac']='';
break;
case 'PARAM':
if ($this->xh[$the_parser]['value'])
{
$this->xh[$the_parser]['params'][] = $this->xh[$the_parser]['value'];
}
break;
case 'METHODNAME':
$this->xh[$the_parser]['method'] = ltrim($this->xh[$the_parser]['ac']);
break;
case 'PARAMS':
case 'FAULT':
case 'METHODCALL':
case 'METHORESPONSE':
// We're all good kids with nuthin' to do
break;
default:
// End of an Invalid Element. Taken care of during the opening tag though
break;
}
}
//-------------------------------------
// Parses Character Data
//-------------------------------------
function character_data($the_parser, $data)
{
if ($this->xh[$the_parser]['isf'] > 1) return; // XML Fault found already
// If a value has not been found
if ($this->xh[$the_parser]['lv'] != 3)
{
if ($this->xh[$the_parser]['lv'] == 1)
{
$this->xh[$the_parser]['lv'] = 2; // Found a value
}
if ( ! @isset($this->xh[$the_parser]['ac']))
{
$this->xh[$the_parser]['ac'] = '';
}
$this->xh[$the_parser]['ac'] .= $data;
}
}
function addParam($par) { $this->params[]=$par; }
function output_parameters($array=FALSE)
{
$CI =& get_instance();
if ($array !== FALSE && is_array($array))
{
while (list($key) = each($array))
{
if (is_array($array[$key]))
{
$array[$key] = $this->output_parameters($array[$key]);
}
else
{
// 'bits' is for the MetaWeblog API image bits
// @todo - this needs to be made more general purpose
$array[$key] = ($key == 'bits' OR $this->xss_clean == FALSE) ? $array[$key] : $CI->security->xss_clean($array[$key]);
}
}
$parameters = $array;
}
else
{
$parameters = array();
for ($i = 0; $i < count($this->params); $i++)
{
$a_param = $this->decode_message($this->params[$i]);
if (is_array($a_param))
{
$parameters[] = $this->output_parameters($a_param);
}
else
{
$parameters[] = ($this->xss_clean) ? $CI->security->xss_clean($a_param) : $a_param;
}
}
}
return $parameters;
}
function decode_message($param)
{
$kind = $param->kindOf();
if ($kind == 'scalar')
{
return $param->scalarval();
}
elseif ($kind == 'array')
{
reset($param->me);
list($a,$b) = each($param->me);
$arr = array();
for($i = 0; $i < count($b); $i++)
{
$arr[] = $this->decode_message($param->me['array'][$i]);
}
return $arr;
}
elseif ($kind == 'struct')
{
reset($param->me['struct']);
$arr = array();
while (list($key,$value) = each($param->me['struct']))
{
$arr[$key] = $this->decode_message($value);
}
return $arr;
}
}
} // End XML_RPC_Messages class
/**
* XML-RPC Values class
*
* @category XML-RPC
* @author ExpressionEngine Dev Team
* @link http://codeigniter.com/user_guide/libraries/xmlrpc.html
*/
class XML_RPC_Values extends CI_Xmlrpc
{
var $me = array();
var $mytype = 0;
public function __construct($val=-1, $type='')
{
parent::__construct();
if ($val != -1 OR $type != '')
{
$type = $type == '' ? 'string' : $type;
if ($this->xmlrpcTypes[$type] == 1)
{
$this->addScalar($val,$type);
}
elseif ($this->xmlrpcTypes[$type] == 2)
{
$this->addArray($val);
}
elseif ($this->xmlrpcTypes[$type] == 3)
{
$this->addStruct($val);
}
}
}
function addScalar($val, $type='string')
{
$typeof = $this->xmlrpcTypes[$type];
if ($this->mytype==1)
{
echo '<strong>XML_RPC_Values</strong>: scalar can have only one value<br />';
return 0;
}
if ($typeof != 1)
{
echo '<strong>XML_RPC_Values</strong>: not a scalar type (${typeof})<br />';
return 0;
}
if ($type == $this->xmlrpcBoolean)
{
if (strcasecmp($val,'true')==0 OR $val==1 OR ($val==true && strcasecmp($val,'false')))
{
$val = 1;
}
else
{
$val=0;
}
}
if ($this->mytype == 2)
{
// adding to an array here
$ar = $this->me['array'];
$ar[] = new XML_RPC_Values($val, $type);
$this->me['array'] = $ar;
}
else
{
// a scalar, so set the value and remember we're scalar
$this->me[$type] = $val;
$this->mytype = $typeof;
}
return 1;
}
function addArray($vals)
{
if ($this->mytype != 0)
{
echo '<strong>XML_RPC_Values</strong>: already initialized as a [' . $this->kindOf() . ']<br />';
return 0;
}
$this->mytype = $this->xmlrpcTypes['array'];
$this->me['array'] = $vals;
return 1;
}
function addStruct($vals)
{
if ($this->mytype != 0)
{
echo '<strong>XML_RPC_Values</strong>: already initialized as a [' . $this->kindOf() . ']<br />';
return 0;
}
$this->mytype = $this->xmlrpcTypes['struct'];
$this->me['struct'] = $vals;
return 1;
}
function kindOf()
{
switch($this->mytype)
{
case 3:
return 'struct';
break;
case 2:
return 'array';
break;
case 1:
return 'scalar';
break;
default:
return 'undef';
}
}
function serializedata($typ, $val)
{
$rs = '';
switch($this->xmlrpcTypes[$typ])
{
case 3:
// struct
$rs .= "<struct>\n";
reset($val);
while (list($key2, $val2) = each($val))
{
$rs .= "<member>\n<name>{$key2}</name>\n";
$rs .= $this->serializeval($val2);
$rs .= "</member>\n";
}
$rs .= '</struct>';
break;
case 2:
// array
$rs .= "<array>\n<data>\n";
for($i=0; $i < count($val); $i++)
{
$rs .= $this->serializeval($val[$i]);
}
$rs.="</data>\n</array>\n";
break;
case 1:
// others
switch ($typ)
{
case $this->xmlrpcBase64:
$rs .= "<{$typ}>" . base64_encode((string)$val) . "</{$typ}>\n";
break;
case $this->xmlrpcBoolean:
$rs .= "<{$typ}>" . ((bool)$val ? '1' : '0') . "</{$typ}>\n";
break;
case $this->xmlrpcString:
$rs .= "<{$typ}>" . htmlspecialchars((string)$val). "</{$typ}>\n";
break;
default:
$rs .= "<{$typ}>{$val}</{$typ}>\n";
break;
}
default:
break;
}
return $rs;
}
function serialize_class()
{
return $this->serializeval($this);
}
function serializeval($o)
{
| php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | true |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/libraries/Form_validation.php | system/libraries/Form_validation.php | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 5.1.6 or newer
*
* @package CodeIgniter
* @author ExpressionEngine Dev Team
* @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
* @license http://codeigniter.com/user_guide/license.html
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
// ------------------------------------------------------------------------
/**
* Form Validation Class
*
* @package CodeIgniter
* @subpackage Libraries
* @category Validation
* @author ExpressionEngine Dev Team
* @link http://codeigniter.com/user_guide/libraries/form_validation.html
*/
class CI_Form_validation {
protected $CI;
protected $_field_data = array();
protected $_config_rules = array();
protected $_error_array = array();
protected $_error_messages = array();
protected $_error_prefix = '<p>';
protected $_error_suffix = '</p>';
protected $error_string = '';
protected $_safe_form_data = FALSE;
/**
* Constructor
*/
public function __construct($rules = array())
{
$this->CI =& get_instance();
// Validation rules can be stored in a config file.
$this->_config_rules = $rules;
// Automatically load the form helper
$this->CI->load->helper('form');
// Set the character encoding in MB.
if (function_exists('mb_internal_encoding'))
{
mb_internal_encoding($this->CI->config->item('charset'));
}
log_message('debug', "Form Validation Class Initialized");
}
// --------------------------------------------------------------------
/**
* Set Rules
*
* This function takes an array of field names and validation
* rules as input, validates the info, and stores it
*
* @access public
* @param mixed
* @param string
* @return void
*/
public function set_rules($field, $label = '', $rules = '')
{
// No reason to set rules if we have no POST data
if (count($_POST) == 0)
{
return $this;
}
// If an array was passed via the first parameter instead of indidual string
// values we cycle through it and recursively call this function.
if (is_array($field))
{
foreach ($field as $row)
{
// Houston, we have a problem...
if ( ! isset($row['field']) OR ! isset($row['rules']))
{
continue;
}
// If the field label wasn't passed we use the field name
$label = ( ! isset($row['label'])) ? $row['field'] : $row['label'];
// Here we go!
$this->set_rules($row['field'], $label, $row['rules']);
}
return $this;
}
// No fields? Nothing to do...
if ( ! is_string($field) OR ! is_string($rules) OR $field == '')
{
return $this;
}
// If the field label wasn't passed we use the field name
$label = ($label == '') ? $field : $label;
// Is the field name an array? We test for the existence of a bracket "[" in
// the field name to determine this. If it is an array, we break it apart
// into its components so that we can fetch the corresponding POST data later
if (strpos($field, '[') !== FALSE AND preg_match_all('/\[(.*?)\]/', $field, $matches))
{
// Note: Due to a bug in current() that affects some versions
// of PHP we can not pass function call directly into it
$x = explode('[', $field);
$indexes[] = current($x);
for ($i = 0; $i < count($matches['0']); $i++)
{
if ($matches['1'][$i] != '')
{
$indexes[] = $matches['1'][$i];
}
}
$is_array = TRUE;
}
else
{
$indexes = array();
$is_array = FALSE;
}
// Build our master array
$this->_field_data[$field] = array(
'field' => $field,
'label' => $label,
'rules' => $rules,
'is_array' => $is_array,
'keys' => $indexes,
'postdata' => NULL,
'error' => ''
);
return $this;
}
// --------------------------------------------------------------------
/**
* Set Error Message
*
* Lets users set their own error messages on the fly. Note: The key
* name has to match the function name that it corresponds to.
*
* @access public
* @param string
* @param string
* @return string
*/
public function set_message($lang, $val = '')
{
if ( ! is_array($lang))
{
$lang = array($lang => $val);
}
$this->_error_messages = array_merge($this->_error_messages, $lang);
return $this;
}
// --------------------------------------------------------------------
/**
* Set The Error Delimiter
*
* Permits a prefix/suffix to be added to each error message
*
* @access public
* @param string
* @param string
* @return void
*/
public function set_error_delimiters($prefix = '<p>', $suffix = '</p>')
{
$this->_error_prefix = $prefix;
$this->_error_suffix = $suffix;
return $this;
}
// --------------------------------------------------------------------
/**
* Get Error Message
*
* Gets the error message associated with a particular field
*
* @access public
* @param string the field name
* @return void
*/
public function error($field = '', $prefix = '', $suffix = '')
{
if ( ! isset($this->_field_data[$field]['error']) OR $this->_field_data[$field]['error'] == '')
{
return '';
}
if ($prefix == '')
{
$prefix = $this->_error_prefix;
}
if ($suffix == '')
{
$suffix = $this->_error_suffix;
}
return $prefix.$this->_field_data[$field]['error'].$suffix;
}
// --------------------------------------------------------------------
/**
* Error String
*
* Returns the error messages as a string, wrapped in the error delimiters
*
* @access public
* @param string
* @param string
* @return str
*/
public function error_string($prefix = '', $suffix = '')
{
// No errrors, validation passes!
if (count($this->_error_array) === 0)
{
return '';
}
if ($prefix == '')
{
$prefix = $this->_error_prefix;
}
if ($suffix == '')
{
$suffix = $this->_error_suffix;
}
// Generate the error string
$str = '';
foreach ($this->_error_array as $val)
{
if ($val != '')
{
$str .= $prefix.$val.$suffix."\n";
}
}
return $str;
}
// --------------------------------------------------------------------
/**
* Run the Validator
*
* This function does all the work.
*
* @access public
* @return bool
*/
public function run($group = '')
{
// Do we even have any data to process? Mm?
if (count($_POST) == 0)
{
return FALSE;
}
// Does the _field_data array containing the validation rules exist?
// If not, we look to see if they were assigned via a config file
if (count($this->_field_data) == 0)
{
// No validation rules? We're done...
if (count($this->_config_rules) == 0)
{
return FALSE;
}
// Is there a validation rule for the particular URI being accessed?
$uri = ($group == '') ? trim($this->CI->uri->ruri_string(), '/') : $group;
if ($uri != '' AND isset($this->_config_rules[$uri]))
{
$this->set_rules($this->_config_rules[$uri]);
}
else
{
$this->set_rules($this->_config_rules);
}
// We're we able to set the rules correctly?
if (count($this->_field_data) == 0)
{
log_message('debug', "Unable to find validation rules");
return FALSE;
}
}
// Load the language file containing error messages
$this->CI->lang->load('form_validation');
// Cycle through the rules for each field, match the
// corresponding $_POST item and test for errors
foreach ($this->_field_data as $field => $row)
{
// Fetch the data from the corresponding $_POST array and cache it in the _field_data array.
// Depending on whether the field name is an array or a string will determine where we get it from.
if ($row['is_array'] == TRUE)
{
$this->_field_data[$field]['postdata'] = $this->_reduce_array($_POST, $row['keys']);
}
else
{
if (isset($_POST[$field]) AND $_POST[$field] != "")
{
$this->_field_data[$field]['postdata'] = $_POST[$field];
}
}
$this->_execute($row, explode('|', $row['rules']), $this->_field_data[$field]['postdata']);
}
// Did we end up with any errors?
$total_errors = count($this->_error_array);
if ($total_errors > 0)
{
$this->_safe_form_data = TRUE;
}
// Now we need to re-set the POST data with the new, processed data
$this->_reset_post_array();
// No errors, validation passes!
if ($total_errors == 0)
{
return TRUE;
}
// Validation fails
return FALSE;
}
// --------------------------------------------------------------------
/**
* Traverse a multidimensional $_POST array index until the data is found
*
* @access private
* @param array
* @param array
* @param integer
* @return mixed
*/
protected function _reduce_array($array, $keys, $i = 0)
{
if (is_array($array))
{
if (isset($keys[$i]))
{
if (isset($array[$keys[$i]]))
{
$array = $this->_reduce_array($array[$keys[$i]], $keys, ($i+1));
}
else
{
return NULL;
}
}
else
{
return $array;
}
}
return $array;
}
// --------------------------------------------------------------------
/**
* Re-populate the _POST array with our finalized and processed data
*
* @access private
* @return null
*/
protected function _reset_post_array()
{
foreach ($this->_field_data as $field => $row)
{
if ( ! is_null($row['postdata']))
{
if ($row['is_array'] == FALSE)
{
if (isset($_POST[$row['field']]))
{
$_POST[$row['field']] = $this->prep_for_form($row['postdata']);
}
}
else
{
// start with a reference
$post_ref =& $_POST;
// before we assign values, make a reference to the right POST key
if (count($row['keys']) == 1)
{
$post_ref =& $post_ref[current($row['keys'])];
}
else
{
foreach ($row['keys'] as $val)
{
$post_ref =& $post_ref[$val];
}
}
if (is_array($row['postdata']))
{
$array = array();
foreach ($row['postdata'] as $k => $v)
{
$array[$k] = $this->prep_for_form($v);
}
$post_ref = $array;
}
else
{
$post_ref = $this->prep_for_form($row['postdata']);
}
}
}
}
}
// --------------------------------------------------------------------
/**
* Executes the Validation routines
*
* @access private
* @param array
* @param array
* @param mixed
* @param integer
* @return mixed
*/
protected function _execute($row, $rules, $postdata = NULL, $cycles = 0)
{
// If the $_POST data is an array we will run a recursive call
if (is_array($postdata))
{
foreach ($postdata as $key => $val)
{
$this->_execute($row, $rules, $val, $cycles);
$cycles++;
}
return;
}
// --------------------------------------------------------------------
// If the field is blank, but NOT required, no further tests are necessary
$callback = FALSE;
if ( ! in_array('required', $rules) AND is_null($postdata))
{
// Before we bail out, does the rule contain a callback?
if (preg_match("/(callback_\w+(\[.*?\])?)/", implode(' ', $rules), $match))
{
$callback = TRUE;
$rules = (array('1' => $match[1]));
}
else
{
return;
}
}
// --------------------------------------------------------------------
// Isset Test. Typically this rule will only apply to checkboxes.
if (is_null($postdata) AND $callback == FALSE)
{
if (in_array('isset', $rules, TRUE) OR in_array('required', $rules))
{
// Set the message type
$type = (in_array('required', $rules)) ? 'required' : 'isset';
if ( ! isset($this->_error_messages[$type]))
{
if (FALSE === ($line = $this->CI->lang->line($type)))
{
$line = 'The field was not set';
}
}
else
{
$line = $this->_error_messages[$type];
}
// Build the error message
$message = sprintf($line, $this->_translate_fieldname($row['label']));
// Save the error message
$this->_field_data[$row['field']]['error'] = $message;
if ( ! isset($this->_error_array[$row['field']]))
{
$this->_error_array[$row['field']] = $message;
}
}
return;
}
// --------------------------------------------------------------------
// Cycle through each rule and run it
foreach ($rules As $rule)
{
$_in_array = FALSE;
// We set the $postdata variable with the current data in our master array so that
// each cycle of the loop is dealing with the processed data from the last cycle
if ($row['is_array'] == TRUE AND is_array($this->_field_data[$row['field']]['postdata']))
{
// We shouldn't need this safety, but just in case there isn't an array index
// associated with this cycle we'll bail out
if ( ! isset($this->_field_data[$row['field']]['postdata'][$cycles]))
{
continue;
}
$postdata = $this->_field_data[$row['field']]['postdata'][$cycles];
$_in_array = TRUE;
}
else
{
$postdata = $this->_field_data[$row['field']]['postdata'];
}
// --------------------------------------------------------------------
// Is the rule a callback?
$callback = FALSE;
if (substr($rule, 0, 9) == 'callback_')
{
$rule = substr($rule, 9);
$callback = TRUE;
}
// Strip the parameter (if exists) from the rule
// Rules can contain a parameter: max_length[5]
$param = FALSE;
if (preg_match("/(.*?)\[(.*)\]/", $rule, $match))
{
$rule = $match[1];
$param = $match[2];
}
// Call the function that corresponds to the rule
if ($callback === TRUE)
{
if ( ! method_exists($this->CI, $rule))
{
continue;
}
// Run the function and grab the result
$result = $this->CI->$rule($postdata, $param);
// Re-assign the result to the master data array
if ($_in_array == TRUE)
{
$this->_field_data[$row['field']]['postdata'][$cycles] = (is_bool($result)) ? $postdata : $result;
}
else
{
$this->_field_data[$row['field']]['postdata'] = (is_bool($result)) ? $postdata : $result;
}
// If the field isn't required and we just processed a callback we'll move on...
if ( ! in_array('required', $rules, TRUE) AND $result !== FALSE)
{
continue;
}
}
else
{
if ( ! method_exists($this, $rule))
{
// If our own wrapper function doesn't exist we see if a native PHP function does.
// Users can use any native PHP function call that has one param.
if (function_exists($rule))
{
$result = $rule($postdata);
if ($_in_array == TRUE)
{
$this->_field_data[$row['field']]['postdata'][$cycles] = (is_bool($result)) ? $postdata : $result;
}
else
{
$this->_field_data[$row['field']]['postdata'] = (is_bool($result)) ? $postdata : $result;
}
}
else
{
log_message('debug', "Unable to find validation rule: ".$rule);
}
continue;
}
$result = $this->$rule($postdata, $param);
if ($_in_array == TRUE)
{
$this->_field_data[$row['field']]['postdata'][$cycles] = (is_bool($result)) ? $postdata : $result;
}
else
{
$this->_field_data[$row['field']]['postdata'] = (is_bool($result)) ? $postdata : $result;
}
}
// Did the rule test negatively? If so, grab the error.
if ($result === FALSE)
{
if ( ! isset($this->_error_messages[$rule]))
{
if (FALSE === ($line = $this->CI->lang->line($rule)))
{
$line = 'Unable to access an error message corresponding to your field name.';
}
}
else
{
$line = $this->_error_messages[$rule];
}
// Is the parameter we are inserting into the error message the name
// of another field? If so we need to grab its "field label"
if (isset($this->_field_data[$param]) AND isset($this->_field_data[$param]['label']))
{
$param = $this->_translate_fieldname($this->_field_data[$param]['label']);
}
// Build the error message
$message = sprintf($line, $this->_translate_fieldname($row['label']), $param);
// Save the error message
$this->_field_data[$row['field']]['error'] = $message;
if ( ! isset($this->_error_array[$row['field']]))
{
$this->_error_array[$row['field']] = $message;
}
return;
}
}
}
// --------------------------------------------------------------------
/**
* Translate a field name
*
* @access private
* @param string the field name
* @return string
*/
protected function _translate_fieldname($fieldname)
{
// Do we need to translate the field name?
// We look for the prefix lang: to determine this
if (substr($fieldname, 0, 5) == 'lang:')
{
// Grab the variable
$line = substr($fieldname, 5);
// Were we able to translate the field name? If not we use $line
if (FALSE === ($fieldname = $this->CI->lang->line($line)))
{
return $line;
}
}
return $fieldname;
}
// --------------------------------------------------------------------
/**
* Get the value from a form
*
* Permits you to repopulate a form field with the value it was submitted
* with, or, if that value doesn't exist, with the default
*
* @access public
* @param string the field name
* @param string
* @return void
*/
public function set_value($field = '', $default = '')
{
if ( ! isset($this->_field_data[$field]))
{
return $default;
}
// If the data is an array output them one at a time.
// E.g: form_input('name[]', set_value('name[]');
if (is_array($this->_field_data[$field]['postdata']))
{
return array_shift($this->_field_data[$field]['postdata']);
}
return $this->_field_data[$field]['postdata'];
}
// --------------------------------------------------------------------
/**
* Set Select
*
* Enables pull-down lists to be set to the value the user
* selected in the event of an error
*
* @access public
* @param string
* @param string
* @return string
*/
public function set_select($field = '', $value = '', $default = FALSE)
{
if ( ! isset($this->_field_data[$field]) OR ! isset($this->_field_data[$field]['postdata']))
{
if ($default === TRUE AND count($this->_field_data) === 0)
{
return ' selected="selected"';
}
return '';
}
$field = $this->_field_data[$field]['postdata'];
if (is_array($field))
{
if ( ! in_array($value, $field))
{
return '';
}
}
else
{
if (($field == '' OR $value == '') OR ($field != $value))
{
return '';
}
}
return ' selected="selected"';
}
// --------------------------------------------------------------------
/**
* Set Radio
*
* Enables radio buttons to be set to the value the user
* selected in the event of an error
*
* @access public
* @param string
* @param string
* @return string
*/
public function set_radio($field = '', $value = '', $default = FALSE)
{
if ( ! isset($this->_field_data[$field]) OR ! isset($this->_field_data[$field]['postdata']))
{
if ($default === TRUE AND count($this->_field_data) === 0)
{
return ' checked="checked"';
}
return '';
}
$field = $this->_field_data[$field]['postdata'];
if (is_array($field))
{
if ( ! in_array($value, $field))
{
return '';
}
}
else
{
if (($field == '' OR $value == '') OR ($field != $value))
{
return '';
}
}
return ' checked="checked"';
}
// --------------------------------------------------------------------
/**
* Set Checkbox
*
* Enables checkboxes to be set to the value the user
* selected in the event of an error
*
* @access public
* @param string
* @param string
* @return string
*/
public function set_checkbox($field = '', $value = '', $default = FALSE)
{
if ( ! isset($this->_field_data[$field]) OR ! isset($this->_field_data[$field]['postdata']))
{
if ($default === TRUE AND count($this->_field_data) === 0)
{
return ' checked="checked"';
}
return '';
}
$field = $this->_field_data[$field]['postdata'];
if (is_array($field))
{
if ( ! in_array($value, $field))
{
return '';
}
}
else
{
if (($field == '' OR $value == '') OR ($field != $value))
{
return '';
}
}
return ' checked="checked"';
}
// --------------------------------------------------------------------
/**
* Required
*
* @access public
* @param string
* @return bool
*/
public function required($str)
{
if ( ! is_array($str))
{
return (trim($str) == '') ? FALSE : TRUE;
}
else
{
return ( ! empty($str));
}
}
// --------------------------------------------------------------------
/**
* Performs a Regular Expression match test.
*
* @access public
* @param string
* @param regex
* @return bool
*/
public function regex_match($str, $regex)
{
if ( ! preg_match($regex, $str))
{
return FALSE;
}
return TRUE;
}
// --------------------------------------------------------------------
/**
* Match one field to another
*
* @access public
* @param string
* @param field
* @return bool
*/
public function matches($str, $field)
{
if ( ! isset($_POST[$field]))
{
return FALSE;
}
$field = $_POST[$field];
return ($str !== $field) ? FALSE : TRUE;
}
// --------------------------------------------------------------------
/**
* Match one field to another
*
* @access public
* @param string
* @param field
* @return bool
*/
public function is_unique($str, $field)
{
list($table, $field)=explode('.', $field);
$query = $this->CI->db->limit(1)->get_where($table, array($field => $str));
return $query->num_rows() === 0;
}
// --------------------------------------------------------------------
/**
* Minimum Length
*
* @access public
* @param string
* @param value
* @return bool
*/
public function min_length($str, $val)
{
if (preg_match("/[^0-9]/", $val))
{
return FALSE;
}
if (function_exists('mb_strlen'))
{
return (mb_strlen($str) < $val) ? FALSE : TRUE;
}
return (strlen($str) < $val) ? FALSE : TRUE;
}
// --------------------------------------------------------------------
/**
* Max Length
*
* @access public
* @param string
* @param value
* @return bool
*/
public function max_length($str, $val)
{
if (preg_match("/[^0-9]/", $val))
{
return FALSE;
}
if (function_exists('mb_strlen'))
{
return (mb_strlen($str) > $val) ? FALSE : TRUE;
}
return (strlen($str) > $val) ? FALSE : TRUE;
}
// --------------------------------------------------------------------
/**
* Exact Length
*
* @access public
* @param string
* @param value
* @return bool
*/
public function exact_length($str, $val)
{
if (preg_match("/[^0-9]/", $val))
{
return FALSE;
}
if (function_exists('mb_strlen'))
{
return (mb_strlen($str) != $val) ? FALSE : TRUE;
}
return (strlen($str) != $val) ? FALSE : TRUE;
}
// --------------------------------------------------------------------
/**
* Valid Email
*
* @access public
* @param string
* @return bool
*/
public function valid_email($str)
{
return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;
}
// --------------------------------------------------------------------
/**
* Valid Emails
*
* @access public
* @param string
* @return bool
*/
public function valid_emails($str)
{
if (strpos($str, ',') === FALSE)
{
return $this->valid_email(trim($str));
}
foreach (explode(',', $str) as $email)
{
if (trim($email) != '' && $this->valid_email(trim($email)) === FALSE)
{
return FALSE;
}
}
return TRUE;
}
// --------------------------------------------------------------------
/**
* Validate IP Address
*
* @access public
* @param string
* @param string "ipv4" or "ipv6" to validate a specific ip format
* @return string
*/
public function valid_ip($ip, $which = '')
{
return $this->CI->input->valid_ip($ip, $which);
}
// --------------------------------------------------------------------
/**
* Alpha
*
* @access public
* @param string
* @return bool
*/
public function alpha($str)
{
return ( ! preg_match("/^([a-z])+$/i", $str)) ? FALSE : TRUE;
}
// --------------------------------------------------------------------
/**
* Alpha-numeric
*
* @access public
* @param string
* @return bool
*/
public function alpha_numeric($str)
{
return ( ! preg_match("/^([a-z0-9])+$/i", $str)) ? FALSE : TRUE;
}
// --------------------------------------------------------------------
/**
* Alpha-numeric with underscores and dashes
*
* @access public
* @param string
* @return bool
*/
public function alpha_dash($str)
{
return ( ! preg_match("/^([-a-z0-9_-])+$/i", $str)) ? FALSE : TRUE;
}
// --------------------------------------------------------------------
/**
* Numeric
*
* @access public
* @param string
* @return bool
*/
public function numeric($str)
{
return (bool)preg_match( '/^[\-+]?[0-9]*\.?[0-9]+$/', $str);
}
// --------------------------------------------------------------------
/**
* Is Numeric
*
* @access public
* @param string
* @return bool
*/
public function is_numeric($str)
{
return ( ! is_numeric($str)) ? FALSE : TRUE;
}
// --------------------------------------------------------------------
/**
* Integer
*
* @access public
* @param string
* @return bool
*/
public function integer($str)
{
return (bool) preg_match('/^[\-+]?[0-9]+$/', $str);
}
// --------------------------------------------------------------------
/**
* Decimal number
*
* @access public
* @param string
* @return bool
*/
public function decimal($str)
{
return (bool) preg_match('/^[\-+]?[0-9]+\.[0-9]+$/', $str);
}
// --------------------------------------------------------------------
/**
* Greather than
*
* @access public
* @param string
* @return bool
*/
public function greater_than($str, $min)
{
if ( ! is_numeric($str))
{
return FALSE;
}
return $str > $min;
}
// --------------------------------------------------------------------
/**
* Less than
*
* @access public
* @param string
* @return bool
*/
public function less_than($str, $max)
{
if ( ! is_numeric($str))
{
return FALSE;
}
return $str < $max;
}
// --------------------------------------------------------------------
/**
* Is a Natural number (0,1,2,3, etc.)
*
* @access public
* @param string
* @return bool
*/
public function is_natural($str)
{
return (bool) preg_match( '/^[0-9]+$/', $str);
}
// --------------------------------------------------------------------
/**
* Is a Natural number, but not a zero (1,2,3, etc.)
*
* @access public
* @param string
* @return bool
*/
public function is_natural_no_zero($str)
{
if ( ! preg_match( '/^[0-9]+$/', $str))
{
return FALSE;
}
if ($str == 0)
{
return FALSE;
}
return TRUE;
}
// --------------------------------------------------------------------
/**
* Valid Base64
*
* Tests a string for characters outside of the Base64 alphabet
* as defined by RFC 2045 http://www.faqs.org/rfcs/rfc2045
*
* @access public
* @param string
* @return bool
*/
public function valid_base64($str)
{
return (bool) ! preg_match('/[^a-zA-Z0-9\/\+=]/', $str);
}
// --------------------------------------------------------------------
/**
* Prep data for form
*
* This function allows HTML to be safely shown in a form.
* Special characters are converted.
*
* @access public
* @param string
* @return string
*/
public function prep_for_form($data = '')
{
if (is_array($data))
{
foreach ($data as $key => $val)
{
$data[$key] = $this->prep_for_form($val);
}
return $data;
}
if ($this->_safe_form_data == FALSE OR $data === '')
{
return $data;
}
return str_replace(array("'", '"', '<', '>'), array("'", """, '<', '>'), stripslashes($data));
}
// --------------------------------------------------------------------
/**
* Prep URL
*
* @access public
* @param string
* @return string
*/
public function prep_url($str = '')
{
if ($str == 'http://' OR $str == '')
{
return '';
}
if (substr($str, 0, 7) != 'http://' && substr($str, 0, 8) != 'https://')
{
$str = 'http://'.$str;
}
return $str;
}
// --------------------------------------------------------------------
/**
* Strip Image Tags
*
* @access public
* @param string
* @return string
*/
public function strip_image_tags($str)
{
return $this->CI->input->strip_image_tags($str);
}
// --------------------------------------------------------------------
/**
* XSS Clean
*
* @access public
* @param string
* @return string
*/
public function xss_clean($str)
{
return $this->CI->security->xss_clean($str);
}
// --------------------------------------------------------------------
/**
* Convert PHP tags to entities
*
* @access public
* @param string
* @return string
*/
public function encode_php_tags($str)
{
return str_replace(array('<?php', '<?PHP', '<?', '?>'), array('<?php', '<?PHP', '<?', '?>'), $str);
}
}
// END Form Validation Class
/* End of file Form_validation.php */
/* Location: ./system/libraries/Form_validation.php */
| php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/libraries/Encrypt.php | system/libraries/Encrypt.php | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 5.1.6 or newer
*
* @package CodeIgniter
* @author ExpressionEngine Dev Team
* @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
* @license http://codeigniter.com/user_guide/license.html
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
// ------------------------------------------------------------------------
/**
* CodeIgniter Encryption Class
*
* Provides two-way keyed encoding using XOR Hashing and Mcrypt
*
* @package CodeIgniter
* @subpackage Libraries
* @category Libraries
* @author ExpressionEngine Dev Team
* @link http://codeigniter.com/user_guide/libraries/encryption.html
*/
class CI_Encrypt {
var $CI;
var $encryption_key = '';
var $_hash_type = 'sha1';
var $_mcrypt_exists = FALSE;
var $_mcrypt_cipher;
var $_mcrypt_mode;
/**
* Constructor
*
* Simply determines whether the mcrypt library exists.
*
*/
public function __construct()
{
$this->CI =& get_instance();
$this->_mcrypt_exists = ( ! function_exists('mcrypt_encrypt')) ? FALSE : TRUE;
log_message('debug', "Encrypt Class Initialized");
}
// --------------------------------------------------------------------
/**
* Fetch the encryption key
*
* Returns it as MD5 in order to have an exact-length 128 bit key.
* Mcrypt is sensitive to keys that are not the correct length
*
* @access public
* @param string
* @return string
*/
function get_key($key = '')
{
if ($key == '')
{
if ($this->encryption_key != '')
{
return $this->encryption_key;
}
$CI =& get_instance();
$key = $CI->config->item('encryption_key');
if ($key == FALSE)
{
show_error('In order to use the encryption class requires that you set an encryption key in your config file.');
}
}
return md5($key);
}
// --------------------------------------------------------------------
/**
* Set the encryption key
*
* @access public
* @param string
* @return void
*/
function set_key($key = '')
{
$this->encryption_key = $key;
}
// --------------------------------------------------------------------
/**
* Encode
*
* Encodes the message string using bitwise XOR encoding.
* The key is combined with a random hash, and then it
* too gets converted using XOR. The whole thing is then run
* through mcrypt (if supported) using the randomized key.
* The end result is a double-encrypted message string
* that is randomized with each call to this function,
* even if the supplied message and key are the same.
*
* @access public
* @param string the string to encode
* @param string the key
* @return string
*/
function encode($string, $key = '')
{
$key = $this->get_key($key);
if ($this->_mcrypt_exists === TRUE)
{
$enc = $this->mcrypt_encode($string, $key);
}
else
{
$enc = $this->_xor_encode($string, $key);
}
return base64_encode($enc);
}
// --------------------------------------------------------------------
/**
* Decode
*
* Reverses the above process
*
* @access public
* @param string
* @param string
* @return string
*/
function decode($string, $key = '')
{
$key = $this->get_key($key);
if (preg_match('/[^a-zA-Z0-9\/\+=]/', $string))
{
return FALSE;
}
$dec = base64_decode($string);
if ($this->_mcrypt_exists === TRUE)
{
if (($dec = $this->mcrypt_decode($dec, $key)) === FALSE)
{
return FALSE;
}
}
else
{
$dec = $this->_xor_decode($dec, $key);
}
return $dec;
}
// --------------------------------------------------------------------
/**
* Encode from Legacy
*
* Takes an encoded string from the original Encryption class algorithms and
* returns a newly encoded string using the improved method added in 2.0.0
* This allows for backwards compatibility and a method to transition to the
* new encryption algorithms.
*
* For more details, see http://codeigniter.com/user_guide/installation/upgrade_200.html#encryption
*
* @access public
* @param string
* @param int (mcrypt mode constant)
* @param string
* @return string
*/
function encode_from_legacy($string, $legacy_mode = MCRYPT_MODE_ECB, $key = '')
{
if ($this->_mcrypt_exists === FALSE)
{
log_message('error', 'Encoding from legacy is available only when Mcrypt is in use.');
return FALSE;
}
// decode it first
// set mode temporarily to what it was when string was encoded with the legacy
// algorithm - typically MCRYPT_MODE_ECB
$current_mode = $this->_get_mode();
$this->set_mode($legacy_mode);
$key = $this->get_key($key);
if (preg_match('/[^a-zA-Z0-9\/\+=]/', $string))
{
return FALSE;
}
$dec = base64_decode($string);
if (($dec = $this->mcrypt_decode($dec, $key)) === FALSE)
{
return FALSE;
}
$dec = $this->_xor_decode($dec, $key);
// set the mcrypt mode back to what it should be, typically MCRYPT_MODE_CBC
$this->set_mode($current_mode);
// and re-encode
return base64_encode($this->mcrypt_encode($dec, $key));
}
// --------------------------------------------------------------------
/**
* XOR Encode
*
* Takes a plain-text string and key as input and generates an
* encoded bit-string using XOR
*
* @access private
* @param string
* @param string
* @return string
*/
function _xor_encode($string, $key)
{
$rand = '';
while (strlen($rand) < 32)
{
$rand .= mt_rand(0, mt_getrandmax());
}
$rand = $this->hash($rand);
$enc = '';
for ($i = 0; $i < strlen($string); $i++)
{
$enc .= substr($rand, ($i % strlen($rand)), 1).(substr($rand, ($i % strlen($rand)), 1) ^ substr($string, $i, 1));
}
return $this->_xor_merge($enc, $key);
}
// --------------------------------------------------------------------
/**
* XOR Decode
*
* Takes an encoded string and key as input and generates the
* plain-text original message
*
* @access private
* @param string
* @param string
* @return string
*/
function _xor_decode($string, $key)
{
$string = $this->_xor_merge($string, $key);
$dec = '';
for ($i = 0; $i < strlen($string); $i++)
{
$dec .= (substr($string, $i++, 1) ^ substr($string, $i, 1));
}
return $dec;
}
// --------------------------------------------------------------------
/**
* XOR key + string Combiner
*
* Takes a string and key as input and computes the difference using XOR
*
* @access private
* @param string
* @param string
* @return string
*/
function _xor_merge($string, $key)
{
$hash = $this->hash($key);
$str = '';
for ($i = 0; $i < strlen($string); $i++)
{
$str .= substr($string, $i, 1) ^ substr($hash, ($i % strlen($hash)), 1);
}
return $str;
}
// --------------------------------------------------------------------
/**
* Encrypt using Mcrypt
*
* @access public
* @param string
* @param string
* @return string
*/
function mcrypt_encode($data, $key)
{
$init_size = mcrypt_get_iv_size($this->_get_cipher(), $this->_get_mode());
$init_vect = mcrypt_create_iv($init_size, MCRYPT_RAND);
return $this->_add_cipher_noise($init_vect.mcrypt_encrypt($this->_get_cipher(), $key, $data, $this->_get_mode(), $init_vect), $key);
}
// --------------------------------------------------------------------
/**
* Decrypt using Mcrypt
*
* @access public
* @param string
* @param string
* @return string
*/
function mcrypt_decode($data, $key)
{
$data = $this->_remove_cipher_noise($data, $key);
$init_size = mcrypt_get_iv_size($this->_get_cipher(), $this->_get_mode());
if ($init_size > strlen($data))
{
return FALSE;
}
$init_vect = substr($data, 0, $init_size);
$data = substr($data, $init_size);
return rtrim(mcrypt_decrypt($this->_get_cipher(), $key, $data, $this->_get_mode(), $init_vect), "\0");
}
// --------------------------------------------------------------------
/**
* Adds permuted noise to the IV + encrypted data to protect
* against Man-in-the-middle attacks on CBC mode ciphers
* http://www.ciphersbyritter.com/GLOSSARY.HTM#IV
*
* Function description
*
* @access private
* @param string
* @param string
* @return string
*/
function _add_cipher_noise($data, $key)
{
$keyhash = $this->hash($key);
$keylen = strlen($keyhash);
$str = '';
for ($i = 0, $j = 0, $len = strlen($data); $i < $len; ++$i, ++$j)
{
if ($j >= $keylen)
{
$j = 0;
}
$str .= chr((ord($data[$i]) + ord($keyhash[$j])) % 256);
}
return $str;
}
// --------------------------------------------------------------------
/**
* Removes permuted noise from the IV + encrypted data, reversing
* _add_cipher_noise()
*
* Function description
*
* @access public
* @param type
* @return type
*/
function _remove_cipher_noise($data, $key)
{
$keyhash = $this->hash($key);
$keylen = strlen($keyhash);
$str = '';
for ($i = 0, $j = 0, $len = strlen($data); $i < $len; ++$i, ++$j)
{
if ($j >= $keylen)
{
$j = 0;
}
$temp = ord($data[$i]) - ord($keyhash[$j]);
if ($temp < 0)
{
$temp = $temp + 256;
}
$str .= chr($temp);
}
return $str;
}
// --------------------------------------------------------------------
/**
* Set the Mcrypt Cipher
*
* @access public
* @param constant
* @return string
*/
function set_cipher($cipher)
{
$this->_mcrypt_cipher = $cipher;
}
// --------------------------------------------------------------------
/**
* Set the Mcrypt Mode
*
* @access public
* @param constant
* @return string
*/
function set_mode($mode)
{
$this->_mcrypt_mode = $mode;
}
// --------------------------------------------------------------------
/**
* Get Mcrypt cipher Value
*
* @access private
* @return string
*/
function _get_cipher()
{
if ($this->_mcrypt_cipher == '')
{
$this->_mcrypt_cipher = MCRYPT_RIJNDAEL_256;
}
return $this->_mcrypt_cipher;
}
// --------------------------------------------------------------------
/**
* Get Mcrypt Mode Value
*
* @access private
* @return string
*/
function _get_mode()
{
if ($this->_mcrypt_mode == '')
{
$this->_mcrypt_mode = MCRYPT_MODE_CBC;
}
return $this->_mcrypt_mode;
}
// --------------------------------------------------------------------
/**
* Set the Hash type
*
* @access public
* @param string
* @return string
*/
function set_hash($type = 'sha1')
{
$this->_hash_type = ($type != 'sha1' AND $type != 'md5') ? 'sha1' : $type;
}
// --------------------------------------------------------------------
/**
* Hash encode a string
*
* @access public
* @param string
* @return string
*/
function hash($str)
{
return ($this->_hash_type == 'sha1') ? $this->sha1($str) : md5($str);
}
// --------------------------------------------------------------------
/**
* Generate an SHA1 Hash
*
* @access public
* @param string
* @return string
*/
function sha1($str)
{
if ( ! function_exists('sha1'))
{
if ( ! function_exists('mhash'))
{
require_once(BASEPATH.'libraries/Sha1.php');
$SH = new CI_SHA;
return $SH->generate($str);
}
else
{
return bin2hex(mhash(MHASH_SHA1, $str));
}
}
else
{
return sha1($str);
}
}
}
// END CI_Encrypt class
/* End of file Encrypt.php */
/* Location: ./system/libraries/Encrypt.php */ | php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/libraries/Pagination.php | system/libraries/Pagination.php | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 5.1.6 or newer
*
* @package CodeIgniter
* @author ExpressionEngine Dev Team
* @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
* @license http://codeigniter.com/user_guide/license.html
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
// ------------------------------------------------------------------------
/**
* Pagination Class
*
* @package CodeIgniter
* @subpackage Libraries
* @category Pagination
* @author ExpressionEngine Dev Team
* @link http://codeigniter.com/user_guide/libraries/pagination.html
*/
class CI_Pagination {
var $base_url = ''; // The page we are linking to
var $prefix = ''; // A custom prefix added to the path.
var $suffix = ''; // A custom suffix added to the path.
var $total_rows = 0; // Total number of items (database results)
var $per_page = 10; // Max number of items you want shown per page
var $num_links = 2; // Number of "digit" links to show before/after the currently viewed page
var $cur_page = 0; // The current page being viewed
var $use_page_numbers = FALSE; // Use page number for segment instead of offset
var $first_link = '‹ First';
var $next_link = '>';
var $prev_link = '<';
var $last_link = 'Last ›';
var $uri_segment = 3;
var $full_tag_open = '';
var $full_tag_close = '';
var $first_tag_open = '';
var $first_tag_close = ' ';
var $last_tag_open = ' ';
var $last_tag_close = '';
var $first_url = ''; // Alternative URL for the First Page.
var $cur_tag_open = ' <strong>';
var $cur_tag_close = '</strong>';
var $next_tag_open = ' ';
var $next_tag_close = ' ';
var $prev_tag_open = ' ';
var $prev_tag_close = '';
var $num_tag_open = ' ';
var $num_tag_close = '';
var $page_query_string = FALSE;
var $query_string_segment = 'per_page';
var $display_pages = TRUE;
var $anchor_class = '';
/**
* Constructor
*
* @access public
* @param array initialization parameters
*/
public function __construct($params = array())
{
if (count($params) > 0)
{
$this->initialize($params);
}
if ($this->anchor_class != '')
{
$this->anchor_class = 'class="'.$this->anchor_class.'" ';
}
log_message('debug', "Pagination Class Initialized");
}
// --------------------------------------------------------------------
/**
* Initialize Preferences
*
* @access public
* @param array initialization parameters
* @return void
*/
function initialize($params = array())
{
if (count($params) > 0)
{
foreach ($params as $key => $val)
{
if (isset($this->$key))
{
$this->$key = $val;
}
}
}
}
// --------------------------------------------------------------------
/**
* Generate the pagination links
*
* @access public
* @return string
*/
function create_links()
{
// If our item count or per-page total is zero there is no need to continue.
if ($this->total_rows == 0 OR $this->per_page == 0)
{
return '';
}
// Calculate the total number of pages
$num_pages = ceil($this->total_rows / $this->per_page);
// Is there only one page? Hm... nothing more to do here then.
if ($num_pages == 1)
{
return '';
}
// Set the base page index for starting page number
if ($this->use_page_numbers)
{
$base_page = 1;
}
else
{
$base_page = 0;
}
// Determine the current page number.
$CI =& get_instance();
if ($CI->config->item('enable_query_strings') === TRUE OR $this->page_query_string === TRUE)
{
if ($CI->input->get($this->query_string_segment) != $base_page)
{
$this->cur_page = $CI->input->get($this->query_string_segment);
// Prep the current page - no funny business!
$this->cur_page = (int) $this->cur_page;
}
}
else
{
if ($CI->uri->segment($this->uri_segment) != $base_page)
{
$this->cur_page = $CI->uri->segment($this->uri_segment);
// Prep the current page - no funny business!
$this->cur_page = (int) $this->cur_page;
}
}
// Set current page to 1 if using page numbers instead of offset
if ($this->use_page_numbers AND $this->cur_page == 0)
{
$this->cur_page = $base_page;
}
$this->num_links = (int)$this->num_links;
if ($this->num_links < 1)
{
show_error('Your number of links must be a positive number.');
}
if ( ! is_numeric($this->cur_page))
{
$this->cur_page = $base_page;
}
// Is the page number beyond the result range?
// If so we show the last page
if ($this->use_page_numbers)
{
if ($this->cur_page > $num_pages)
{
$this->cur_page = $num_pages;
}
}
else
{
if ($this->cur_page > $this->total_rows)
{
$this->cur_page = ($num_pages - 1) * $this->per_page;
}
}
$uri_page_number = $this->cur_page;
if ( ! $this->use_page_numbers)
{
$this->cur_page = floor(($this->cur_page/$this->per_page) + 1);
}
// Calculate the start and end numbers. These determine
// which number to start and end the digit links with
$start = (($this->cur_page - $this->num_links) > 0) ? $this->cur_page - ($this->num_links - 1) : 1;
$end = (($this->cur_page + $this->num_links) < $num_pages) ? $this->cur_page + $this->num_links : $num_pages;
// Is pagination being used over GET or POST? If get, add a per_page query
// string. If post, add a trailing slash to the base URL if needed
if ($CI->config->item('enable_query_strings') === TRUE OR $this->page_query_string === TRUE)
{
$this->base_url = rtrim($this->base_url).'&'.$this->query_string_segment.'=';
}
else
{
$this->base_url = rtrim($this->base_url, '/') .'/';
}
// And here we go...
$output = '';
// Render the "First" link
if ($this->first_link !== FALSE AND $this->cur_page > ($this->num_links + 1))
{
$first_url = ($this->first_url == '') ? $this->base_url : $this->first_url;
$output .= $this->first_tag_open.'<a '.$this->anchor_class.'href="'.$first_url.'">'.$this->first_link.'</a>'.$this->first_tag_close;
}
// Render the "previous" link
if ($this->prev_link !== FALSE AND $this->cur_page != 1)
{
if ($this->use_page_numbers)
{
$i = $uri_page_number - 1;
}
else
{
$i = $uri_page_number - $this->per_page;
}
if ($i == 0 && $this->first_url != '')
{
$output .= $this->prev_tag_open.'<a '.$this->anchor_class.'href="'.$this->first_url.'">'.$this->prev_link.'</a>'.$this->prev_tag_close;
}
else
{
$i = ($i == 0) ? '' : $this->prefix.$i.$this->suffix;
$output .= $this->prev_tag_open.'<a '.$this->anchor_class.'href="'.$this->base_url.$i.'">'.$this->prev_link.'</a>'.$this->prev_tag_close;
}
}
// Render the pages
if ($this->display_pages !== FALSE)
{
// Write the digit links
for ($loop = $start -1; $loop <= $end; $loop++)
{
if ($this->use_page_numbers)
{
$i = $loop;
}
else
{
$i = ($loop * $this->per_page) - $this->per_page;
}
if ($i >= $base_page)
{
if ($this->cur_page == $loop)
{
$output .= $this->cur_tag_open.$loop.$this->cur_tag_close; // Current page
}
else
{
$n = ($i == $base_page) ? '' : $i;
if ($n == '' && $this->first_url != '')
{
$output .= $this->num_tag_open.'<a '.$this->anchor_class.'href="'.$this->first_url.'">'.$loop.'</a>'.$this->num_tag_close;
}
else
{
$n = ($n == '') ? '' : $this->prefix.$n.$this->suffix;
$output .= $this->num_tag_open.'<a '.$this->anchor_class.'href="'.$this->base_url.$n.'">'.$loop.'</a>'.$this->num_tag_close;
}
}
}
}
}
// Render the "next" link
if ($this->next_link !== FALSE AND $this->cur_page < $num_pages)
{
if ($this->use_page_numbers)
{
$i = $this->cur_page + 1;
}
else
{
$i = ($this->cur_page * $this->per_page);
}
$output .= $this->next_tag_open.'<a '.$this->anchor_class.'href="'.$this->base_url.$this->prefix.$i.$this->suffix.'">'.$this->next_link.'</a>'.$this->next_tag_close;
}
// Render the "Last" link
if ($this->last_link !== FALSE AND ($this->cur_page + $this->num_links) < $num_pages)
{
if ($this->use_page_numbers)
{
$i = $num_pages;
}
else
{
$i = (($num_pages * $this->per_page) - $this->per_page);
}
$output .= $this->last_tag_open.'<a '.$this->anchor_class.'href="'.$this->base_url.$this->prefix.$i.$this->suffix.'">'.$this->last_link.'</a>'.$this->last_tag_close;
}
// Kill double slashes. Note: Sometimes we can end up with a double slash
// in the penultimate link so we'll kill all double slashes.
$output = preg_replace("#([^:])//+#", "\\1/", $output);
// Add the wrapper HTML if exists
$output = $this->full_tag_open.$output.$this->full_tag_close;
return $output;
}
}
// END Pagination Class
/* End of file Pagination.php */
/* Location: ./system/libraries/Pagination.php */ | php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/libraries/Ftp.php | system/libraries/Ftp.php | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 5.1.6 or newer
*
* @package CodeIgniter
* @author ExpressionEngine Dev Team
* @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
* @license http://codeigniter.com/user_guide/license.html
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
// ------------------------------------------------------------------------
/**
* FTP Class
*
* @package CodeIgniter
* @subpackage Libraries
* @category Libraries
* @author ExpressionEngine Dev Team
* @link http://codeigniter.com/user_guide/libraries/ftp.html
*/
class CI_FTP {
var $hostname = '';
var $username = '';
var $password = '';
var $port = 21;
var $passive = TRUE;
var $debug = FALSE;
var $conn_id = FALSE;
/**
* Constructor - Sets Preferences
*
* The constructor can be passed an array of config values
*/
public function __construct($config = array())
{
if (count($config) > 0)
{
$this->initialize($config);
}
log_message('debug', "FTP Class Initialized");
}
// --------------------------------------------------------------------
/**
* Initialize preferences
*
* @access public
* @param array
* @return void
*/
function initialize($config = array())
{
foreach ($config as $key => $val)
{
if (isset($this->$key))
{
$this->$key = $val;
}
}
// Prep the hostname
$this->hostname = preg_replace('|.+?://|', '', $this->hostname);
}
// --------------------------------------------------------------------
/**
* FTP Connect
*
* @access public
* @param array the connection values
* @return bool
*/
function connect($config = array())
{
if (count($config) > 0)
{
$this->initialize($config);
}
if (FALSE === ($this->conn_id = @ftp_connect($this->hostname, $this->port)))
{
if ($this->debug == TRUE)
{
$this->_error('ftp_unable_to_connect');
}
return FALSE;
}
if ( ! $this->_login())
{
if ($this->debug == TRUE)
{
$this->_error('ftp_unable_to_login');
}
return FALSE;
}
// Set passive mode if needed
if ($this->passive == TRUE)
{
ftp_pasv($this->conn_id, TRUE);
}
return TRUE;
}
// --------------------------------------------------------------------
/**
* FTP Login
*
* @access private
* @return bool
*/
function _login()
{
return @ftp_login($this->conn_id, $this->username, $this->password);
}
// --------------------------------------------------------------------
/**
* Validates the connection ID
*
* @access private
* @return bool
*/
function _is_conn()
{
if ( ! is_resource($this->conn_id))
{
if ($this->debug == TRUE)
{
$this->_error('ftp_no_connection');
}
return FALSE;
}
return TRUE;
}
// --------------------------------------------------------------------
/**
* Change directory
*
* The second parameter lets us momentarily turn off debugging so that
* this function can be used to test for the existence of a folder
* without throwing an error. There's no FTP equivalent to is_dir()
* so we do it by trying to change to a particular directory.
* Internally, this parameter is only used by the "mirror" function below.
*
* @access public
* @param string
* @param bool
* @return bool
*/
function changedir($path = '', $supress_debug = FALSE)
{
if ($path == '' OR ! $this->_is_conn())
{
return FALSE;
}
$result = @ftp_chdir($this->conn_id, $path);
if ($result === FALSE)
{
if ($this->debug == TRUE AND $supress_debug == FALSE)
{
$this->_error('ftp_unable_to_changedir');
}
return FALSE;
}
return TRUE;
}
// --------------------------------------------------------------------
/**
* Create a directory
*
* @access public
* @param string
* @return bool
*/
function mkdir($path = '', $permissions = NULL)
{
if ($path == '' OR ! $this->_is_conn())
{
return FALSE;
}
$result = @ftp_mkdir($this->conn_id, $path);
if ($result === FALSE)
{
if ($this->debug == TRUE)
{
$this->_error('ftp_unable_to_makdir');
}
return FALSE;
}
// Set file permissions if needed
if ( ! is_null($permissions))
{
$this->chmod($path, (int)$permissions);
}
return TRUE;
}
// --------------------------------------------------------------------
/**
* Upload a file to the server
*
* @access public
* @param string
* @param string
* @param string
* @return bool
*/
function upload($locpath, $rempath, $mode = 'auto', $permissions = NULL)
{
if ( ! $this->_is_conn())
{
return FALSE;
}
if ( ! file_exists($locpath))
{
$this->_error('ftp_no_source_file');
return FALSE;
}
// Set the mode if not specified
if ($mode == 'auto')
{
// Get the file extension so we can set the upload type
$ext = $this->_getext($locpath);
$mode = $this->_settype($ext);
}
$mode = ($mode == 'ascii') ? FTP_ASCII : FTP_BINARY;
$result = @ftp_put($this->conn_id, $rempath, $locpath, $mode);
if ($result === FALSE)
{
if ($this->debug == TRUE)
{
$this->_error('ftp_unable_to_upload');
}
return FALSE;
}
// Set file permissions if needed
if ( ! is_null($permissions))
{
$this->chmod($rempath, (int)$permissions);
}
return TRUE;
}
// --------------------------------------------------------------------
/**
* Download a file from a remote server to the local server
*
* @access public
* @param string
* @param string
* @param string
* @return bool
*/
function download($rempath, $locpath, $mode = 'auto')
{
if ( ! $this->_is_conn())
{
return FALSE;
}
// Set the mode if not specified
if ($mode == 'auto')
{
// Get the file extension so we can set the upload type
$ext = $this->_getext($rempath);
$mode = $this->_settype($ext);
}
$mode = ($mode == 'ascii') ? FTP_ASCII : FTP_BINARY;
$result = @ftp_get($this->conn_id, $locpath, $rempath, $mode);
if ($result === FALSE)
{
if ($this->debug == TRUE)
{
$this->_error('ftp_unable_to_download');
}
return FALSE;
}
return TRUE;
}
// --------------------------------------------------------------------
/**
* Rename (or move) a file
*
* @access public
* @param string
* @param string
* @param bool
* @return bool
*/
function rename($old_file, $new_file, $move = FALSE)
{
if ( ! $this->_is_conn())
{
return FALSE;
}
$result = @ftp_rename($this->conn_id, $old_file, $new_file);
if ($result === FALSE)
{
if ($this->debug == TRUE)
{
$msg = ($move == FALSE) ? 'ftp_unable_to_rename' : 'ftp_unable_to_move';
$this->_error($msg);
}
return FALSE;
}
return TRUE;
}
// --------------------------------------------------------------------
/**
* Move a file
*
* @access public
* @param string
* @param string
* @return bool
*/
function move($old_file, $new_file)
{
return $this->rename($old_file, $new_file, TRUE);
}
// --------------------------------------------------------------------
/**
* Rename (or move) a file
*
* @access public
* @param string
* @return bool
*/
function delete_file($filepath)
{
if ( ! $this->_is_conn())
{
return FALSE;
}
$result = @ftp_delete($this->conn_id, $filepath);
if ($result === FALSE)
{
if ($this->debug == TRUE)
{
$this->_error('ftp_unable_to_delete');
}
return FALSE;
}
return TRUE;
}
// --------------------------------------------------------------------
/**
* Delete a folder and recursively delete everything (including sub-folders)
* containted within it.
*
* @access public
* @param string
* @return bool
*/
function delete_dir($filepath)
{
if ( ! $this->_is_conn())
{
return FALSE;
}
// Add a trailing slash to the file path if needed
$filepath = preg_replace("/(.+?)\/*$/", "\\1/", $filepath);
$list = $this->list_files($filepath);
if ($list !== FALSE AND count($list) > 0)
{
foreach ($list as $item)
{
// If we can't delete the item it's probaly a folder so
// we'll recursively call delete_dir()
if ( ! @ftp_delete($this->conn_id, $item))
{
$this->delete_dir($item);
}
}
}
$result = @ftp_rmdir($this->conn_id, $filepath);
if ($result === FALSE)
{
if ($this->debug == TRUE)
{
$this->_error('ftp_unable_to_delete');
}
return FALSE;
}
return TRUE;
}
// --------------------------------------------------------------------
/**
* Set file permissions
*
* @access public
* @param string the file path
* @param string the permissions
* @return bool
*/
function chmod($path, $perm)
{
if ( ! $this->_is_conn())
{
return FALSE;
}
// Permissions can only be set when running PHP 5
if ( ! function_exists('ftp_chmod'))
{
if ($this->debug == TRUE)
{
$this->_error('ftp_unable_to_chmod');
}
return FALSE;
}
$result = @ftp_chmod($this->conn_id, $perm, $path);
if ($result === FALSE)
{
if ($this->debug == TRUE)
{
$this->_error('ftp_unable_to_chmod');
}
return FALSE;
}
return TRUE;
}
// --------------------------------------------------------------------
/**
* FTP List files in the specified directory
*
* @access public
* @return array
*/
function list_files($path = '.')
{
if ( ! $this->_is_conn())
{
return FALSE;
}
return ftp_nlist($this->conn_id, $path);
}
// ------------------------------------------------------------------------
/**
* Read a directory and recreate it remotely
*
* This function recursively reads a folder and everything it contains (including
* sub-folders) and creates a mirror via FTP based on it. Whatever the directory structure
* of the original file path will be recreated on the server.
*
* @access public
* @param string path to source with trailing slash
* @param string path to destination - include the base folder with trailing slash
* @return bool
*/
function mirror($locpath, $rempath)
{
if ( ! $this->_is_conn())
{
return FALSE;
}
// Open the local file path
if ($fp = @opendir($locpath))
{
// Attempt to open the remote file path.
if ( ! $this->changedir($rempath, TRUE))
{
// If it doesn't exist we'll attempt to create the direcotory
if ( ! $this->mkdir($rempath) OR ! $this->changedir($rempath))
{
return FALSE;
}
}
// Recursively read the local directory
while (FALSE !== ($file = readdir($fp)))
{
if (@is_dir($locpath.$file) && substr($file, 0, 1) != '.')
{
$this->mirror($locpath.$file."/", $rempath.$file."/");
}
elseif (substr($file, 0, 1) != ".")
{
// Get the file extension so we can se the upload type
$ext = $this->_getext($file);
$mode = $this->_settype($ext);
$this->upload($locpath.$file, $rempath.$file, $mode);
}
}
return TRUE;
}
return FALSE;
}
// --------------------------------------------------------------------
/**
* Extract the file extension
*
* @access private
* @param string
* @return string
*/
function _getext($filename)
{
if (FALSE === strpos($filename, '.'))
{
return 'txt';
}
$x = explode('.', $filename);
return end($x);
}
// --------------------------------------------------------------------
/**
* Set the upload type
*
* @access private
* @param string
* @return string
*/
function _settype($ext)
{
$text_types = array(
'txt',
'text',
'php',
'phps',
'php4',
'js',
'css',
'htm',
'html',
'phtml',
'shtml',
'log',
'xml'
);
return (in_array($ext, $text_types)) ? 'ascii' : 'binary';
}
// ------------------------------------------------------------------------
/**
* Close the connection
*
* @access public
* @param string path to source
* @param string path to destination
* @return bool
*/
function close()
{
if ( ! $this->_is_conn())
{
return FALSE;
}
@ftp_close($this->conn_id);
}
// ------------------------------------------------------------------------
/**
* Display error message
*
* @access private
* @param string
* @return bool
*/
function _error($line)
{
$CI =& get_instance();
$CI->lang->load('ftp');
show_error($CI->lang->line($line));
}
}
// END FTP Class
/* End of file Ftp.php */
/* Location: ./system/libraries/Ftp.php */ | php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/libraries/Migration.php | system/libraries/Migration.php | <?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 5.1.6 or newer
*
* @package CodeIgniter
* @author EllisLab Dev Team
* @copyright Copyright (c) 2006 - 2012, EllisLab, Inc.
* @license http://codeigniter.com/user_guide/license.html
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
// ------------------------------------------------------------------------
/**
* Migration Class
*
* All migrations should implement this, forces up() and down() and gives
* access to the CI super-global.
*
* @package CodeIgniter
* @subpackage Libraries
* @category Libraries
* @author Reactor Engineers
* @link
*/
class CI_Migration {
protected $_migration_enabled = FALSE;
protected $_migration_path = NULL;
protected $_migration_version = 0;
protected $_error_string = '';
public function __construct($config = array())
{
# Only run this constructor on main library load
if (get_parent_class($this) !== FALSE)
{
return;
}
foreach ($config as $key => $val)
{
$this->{'_' . $key} = $val;
}
log_message('debug', 'Migrations class initialized');
// Are they trying to use migrations while it is disabled?
if ($this->_migration_enabled !== TRUE)
{
show_error('Migrations has been loaded but is disabled or set up incorrectly.');
}
// If not set, set it
$this->_migration_path == '' AND $this->_migration_path = APPPATH . 'migrations/';
// Add trailing slash if not set
$this->_migration_path = rtrim($this->_migration_path, '/').'/';
// Load migration language
$this->lang->load('migration');
// They'll probably be using dbforge
$this->load->dbforge();
// If the migrations table is missing, make it
if ( ! $this->db->table_exists('migrations'))
{
$this->dbforge->add_field(array(
'version' => array('type' => 'INT', 'constraint' => 3),
));
$this->dbforge->create_table('migrations', TRUE);
$this->db->insert('migrations', array('version' => 0));
}
}
// --------------------------------------------------------------------
/**
* Migrate to a schema version
*
* Calls each migration step required to get to the schema version of
* choice
*
* @param int Target schema version
* @return mixed TRUE if already latest, FALSE if failed, int if upgraded
*/
public function version($target_version)
{
$start = $current_version = $this->_get_version();
$stop = $target_version;
if ($target_version > $current_version)
{
// Moving Up
++$start;
++$stop;
$step = 1;
}
else
{
// Moving Down
$step = -1;
}
$method = ($step === 1) ? 'up' : 'down';
$migrations = array();
// We now prepare to actually DO the migrations
// But first let's make sure that everything is the way it should be
for ($i = $start; $i != $stop; $i += $step)
{
$f = glob(sprintf($this->_migration_path . '%03d_*.php', $i));
// Only one migration per step is permitted
if (count($f) > 1)
{
$this->_error_string = sprintf($this->lang->line('migration_multiple_version'), $i);
return FALSE;
}
// Migration step not found
if (count($f) == 0)
{
// If trying to migrate up to a version greater than the last
// existing one, migrate to the last one.
if ($step == 1)
{
break;
}
// If trying to migrate down but we're missing a step,
// something must definitely be wrong.
$this->_error_string = sprintf($this->lang->line('migration_not_found'), $i);
return FALSE;
}
$file = basename($f[0]);
$name = basename($f[0], '.php');
// Filename validations
if (preg_match('/^\d{3}_(\w+)$/', $name, $match))
{
$match[1] = strtolower($match[1]);
// Cannot repeat a migration at different steps
if (in_array($match[1], $migrations))
{
$this->_error_string = sprintf($this->lang->line('migration_multiple_version'), $match[1]);
return FALSE;
}
include $f[0];
$class = 'Migration_' . ucfirst($match[1]);
if ( ! class_exists($class))
{
$this->_error_string = sprintf($this->lang->line('migration_class_doesnt_exist'), $class);
return FALSE;
}
if ( ! is_callable(array($class, $method)))
{
$this->_error_string = sprintf($this->lang->line('migration_missing_'.$method.'_method'), $class);
return FALSE;
}
$migrations[] = $match[1];
}
else
{
$this->_error_string = sprintf($this->lang->line('migration_invalid_filename'), $file);
return FALSE;
}
}
log_message('debug', 'Current migration: ' . $current_version);
$version = $i + ($step == 1 ? -1 : 0);
// If there is nothing to do so quit
if ($migrations === array())
{
return TRUE;
}
log_message('debug', 'Migrating from ' . $method . ' to version ' . $version);
// Loop through the migrations
foreach ($migrations AS $migration)
{
// Run the migration class
$class = 'Migration_' . ucfirst(strtolower($migration));
call_user_func(array(new $class, $method));
$current_version += $step;
$this->_update_version($current_version);
}
log_message('debug', 'Finished migrating to '.$current_version);
return $current_version;
}
// --------------------------------------------------------------------
/**
* Set's the schema to the latest migration
*
* @return mixed true if already latest, false if failed, int if upgraded
*/
public function latest()
{
if ( ! $migrations = $this->find_migrations())
{
$this->_error_string = $this->line->lang('migration_none_found');
return false;
}
$last_migration = basename(end($migrations));
// Calculate the last migration step from existing migration
// filenames and procceed to the standard version migration
return $this->version((int) substr($last_migration, 0, 3));
}
// --------------------------------------------------------------------
/**
* Set's the schema to the migration version set in config
*
* @return mixed true if already current, false if failed, int if upgraded
*/
public function current()
{
return $this->version($this->_migration_version);
}
// --------------------------------------------------------------------
/**
* Error string
*
* @return string Error message returned as a string
*/
public function error_string()
{
return $this->_error_string;
}
// --------------------------------------------------------------------
/**
* Set's the schema to the latest migration
*
* @return mixed true if already latest, false if failed, int if upgraded
*/
protected function find_migrations()
{
// Load all *_*.php files in the migrations path
$files = glob($this->_migration_path . '*_*.php');
$file_count = count($files);
for ($i = 0; $i < $file_count; $i++)
{
// Mark wrongly formatted files as false for later filtering
$name = basename($files[$i], '.php');
if ( ! preg_match('/^\d{3}_(\w+)$/', $name))
{
$files[$i] = FALSE;
}
}
sort($files);
return $files;
}
// --------------------------------------------------------------------
/**
* Retrieves current schema version
*
* @return int Current Migration
*/
protected function _get_version()
{
$row = $this->db->get('migrations')->row();
return $row ? $row->version : 0;
}
// --------------------------------------------------------------------
/**
* Stores the current schema version
*
* @param int Migration reached
* @return bool
*/
protected function _update_version($migrations)
{
return $this->db->update('migrations', array(
'version' => $migrations
));
}
// --------------------------------------------------------------------
/**
* Enable the use of CI super-global
*
* @param mixed $var
* @return mixed
*/
public function __get($var)
{
return get_instance()->$var;
}
}
/* End of file Migration.php */
/* Location: ./system/libraries/Migration.php */ | php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/system/libraries/Table.php | system/libraries/Table.php | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 5.1.6 or newer
*
* @package CodeIgniter
* @author ExpressionEngine Dev Team
* @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
* @license http://codeigniter.com/user_guide/license.html
* @link http://codeigniter.com
* @since Version 1.3.1
* @filesource
*/
// ------------------------------------------------------------------------
/**
* HTML Table Generating Class
*
* Lets you create tables manually or from database result objects, or arrays.
*
* @package CodeIgniter
* @subpackage Libraries
* @category HTML Tables
* @author ExpressionEngine Dev Team
* @link http://codeigniter.com/user_guide/libraries/uri.html
*/
class CI_Table {
var $rows = array();
var $heading = array();
var $auto_heading = TRUE;
var $caption = NULL;
var $template = NULL;
var $newline = "\n";
var $empty_cells = "";
var $function = FALSE;
public function __construct()
{
log_message('debug', "Table Class Initialized");
}
// --------------------------------------------------------------------
/**
* Set the template
*
* @access public
* @param array
* @return void
*/
function set_template($template)
{
if ( ! is_array($template))
{
return FALSE;
}
$this->template = $template;
}
// --------------------------------------------------------------------
/**
* Set the table heading
*
* Can be passed as an array or discreet params
*
* @access public
* @param mixed
* @return void
*/
function set_heading()
{
$args = func_get_args();
$this->heading = $this->_prep_args($args);
}
// --------------------------------------------------------------------
/**
* Set columns. Takes a one-dimensional array as input and creates
* a multi-dimensional array with a depth equal to the number of
* columns. This allows a single array with many elements to be
* displayed in a table that has a fixed column count.
*
* @access public
* @param array
* @param int
* @return void
*/
function make_columns($array = array(), $col_limit = 0)
{
if ( ! is_array($array) OR count($array) == 0)
{
return FALSE;
}
// Turn off the auto-heading feature since it's doubtful we
// will want headings from a one-dimensional array
$this->auto_heading = FALSE;
if ($col_limit == 0)
{
return $array;
}
$new = array();
while (count($array) > 0)
{
$temp = array_splice($array, 0, $col_limit);
if (count($temp) < $col_limit)
{
for ($i = count($temp); $i < $col_limit; $i++)
{
$temp[] = ' ';
}
}
$new[] = $temp;
}
return $new;
}
// --------------------------------------------------------------------
/**
* Set "empty" cells
*
* Can be passed as an array or discreet params
*
* @access public
* @param mixed
* @return void
*/
function set_empty($value)
{
$this->empty_cells = $value;
}
// --------------------------------------------------------------------
/**
* Add a table row
*
* Can be passed as an array or discreet params
*
* @access public
* @param mixed
* @return void
*/
function add_row()
{
$args = func_get_args();
$this->rows[] = $this->_prep_args($args);
}
// --------------------------------------------------------------------
/**
* Prep Args
*
* Ensures a standard associative array format for all cell data
*
* @access public
* @param type
* @return type
*/
function _prep_args($args)
{
// If there is no $args[0], skip this and treat as an associative array
// This can happen if there is only a single key, for example this is passed to table->generate
// array(array('foo'=>'bar'))
if (isset($args[0]) AND (count($args) == 1 && is_array($args[0])))
{
// args sent as indexed array
if ( ! isset($args[0]['data']))
{
foreach ($args[0] as $key => $val)
{
if (is_array($val) && isset($val['data']))
{
$args[$key] = $val;
}
else
{
$args[$key] = array('data' => $val);
}
}
}
}
else
{
foreach ($args as $key => $val)
{
if ( ! is_array($val))
{
$args[$key] = array('data' => $val);
}
}
}
return $args;
}
// --------------------------------------------------------------------
/**
* Add a table caption
*
* @access public
* @param string
* @return void
*/
function set_caption($caption)
{
$this->caption = $caption;
}
// --------------------------------------------------------------------
/**
* Generate the table
*
* @access public
* @param mixed
* @return string
*/
function generate($table_data = NULL)
{
// The table data can optionally be passed to this function
// either as a database result object or an array
if ( ! is_null($table_data))
{
if (is_object($table_data))
{
$this->_set_from_object($table_data);
}
elseif (is_array($table_data))
{
$set_heading = (count($this->heading) == 0 AND $this->auto_heading == FALSE) ? FALSE : TRUE;
$this->_set_from_array($table_data, $set_heading);
}
}
// Is there anything to display? No? Smite them!
if (count($this->heading) == 0 AND count($this->rows) == 0)
{
return 'Undefined table data';
}
// Compile and validate the template date
$this->_compile_template();
// set a custom cell manipulation function to a locally scoped variable so its callable
$function = $this->function;
// Build the table!
$out = $this->template['table_open'];
$out .= $this->newline;
// Add any caption here
if ($this->caption)
{
$out .= $this->newline;
$out .= '<caption>' . $this->caption . '</caption>';
$out .= $this->newline;
}
// Is there a table heading to display?
if (count($this->heading) > 0)
{
$out .= $this->template['thead_open'];
$out .= $this->newline;
$out .= $this->template['heading_row_start'];
$out .= $this->newline;
foreach ($this->heading as $heading)
{
$temp = $this->template['heading_cell_start'];
foreach ($heading as $key => $val)
{
if ($key != 'data')
{
$temp = str_replace('<th', "<th $key='$val'", $temp);
}
}
$out .= $temp;
$out .= isset($heading['data']) ? $heading['data'] : '';
$out .= $this->template['heading_cell_end'];
}
$out .= $this->template['heading_row_end'];
$out .= $this->newline;
$out .= $this->template['thead_close'];
$out .= $this->newline;
}
// Build the table rows
if (count($this->rows) > 0)
{
$out .= $this->template['tbody_open'];
$out .= $this->newline;
$i = 1;
foreach ($this->rows as $row)
{
if ( ! is_array($row))
{
break;
}
// We use modulus to alternate the row colors
$name = (fmod($i++, 2)) ? '' : 'alt_';
$out .= $this->template['row_'.$name.'start'];
$out .= $this->newline;
foreach ($row as $cell)
{
$temp = $this->template['cell_'.$name.'start'];
foreach ($cell as $key => $val)
{
if ($key != 'data')
{
$temp = str_replace('<td', "<td $key='$val'", $temp);
}
}
$cell = isset($cell['data']) ? $cell['data'] : '';
$out .= $temp;
if ($cell === "" OR $cell === NULL)
{
$out .= $this->empty_cells;
}
else
{
if ($function !== FALSE && is_callable($function))
{
$out .= call_user_func($function, $cell);
}
else
{
$out .= $cell;
}
}
$out .= $this->template['cell_'.$name.'end'];
}
$out .= $this->template['row_'.$name.'end'];
$out .= $this->newline;
}
$out .= $this->template['tbody_close'];
$out .= $this->newline;
}
$out .= $this->template['table_close'];
// Clear table class properties before generating the table
$this->clear();
return $out;
}
// --------------------------------------------------------------------
/**
* Clears the table arrays. Useful if multiple tables are being generated
*
* @access public
* @return void
*/
function clear()
{
$this->rows = array();
$this->heading = array();
$this->auto_heading = TRUE;
}
// --------------------------------------------------------------------
/**
* Set table data from a database result object
*
* @access public
* @param object
* @return void
*/
function _set_from_object($query)
{
if ( ! is_object($query))
{
return FALSE;
}
// First generate the headings from the table column names
if (count($this->heading) == 0)
{
if ( ! method_exists($query, 'list_fields'))
{
return FALSE;
}
$this->heading = $this->_prep_args($query->list_fields());
}
// Next blast through the result array and build out the rows
if ($query->num_rows() > 0)
{
foreach ($query->result_array() as $row)
{
$this->rows[] = $this->_prep_args($row);
}
}
}
// --------------------------------------------------------------------
/**
* Set table data from an array
*
* @access public
* @param array
* @return void
*/
function _set_from_array($data, $set_heading = TRUE)
{
if ( ! is_array($data) OR count($data) == 0)
{
return FALSE;
}
$i = 0;
foreach ($data as $row)
{
// If a heading hasn't already been set we'll use the first row of the array as the heading
if ($i == 0 AND count($data) > 1 AND count($this->heading) == 0 AND $set_heading == TRUE)
{
$this->heading = $this->_prep_args($row);
}
else
{
$this->rows[] = $this->_prep_args($row);
}
$i++;
}
}
// --------------------------------------------------------------------
/**
* Compile Template
*
* @access private
* @return void
*/
function _compile_template()
{
if ($this->template == NULL)
{
$this->template = $this->_default_template();
return;
}
$this->temp = $this->_default_template();
foreach (array('table_open', 'thead_open', 'thead_close', 'heading_row_start', 'heading_row_end', 'heading_cell_start', 'heading_cell_end', 'tbody_open', 'tbody_close', 'row_start', 'row_end', 'cell_start', 'cell_end', 'row_alt_start', 'row_alt_end', 'cell_alt_start', 'cell_alt_end', 'table_close') as $val)
{
if ( ! isset($this->template[$val]))
{
$this->template[$val] = $this->temp[$val];
}
}
}
// --------------------------------------------------------------------
/**
* Default Template
*
* @access private
* @return void
*/
function _default_template()
{
return array (
'table_open' => '<table border="0" cellpadding="4" cellspacing="0">',
'thead_open' => '<thead>',
'thead_close' => '</thead>',
'heading_row_start' => '<tr>',
'heading_row_end' => '</tr>',
'heading_cell_start' => '<th>',
'heading_cell_end' => '</th>',
'tbody_open' => '<tbody>',
'tbody_close' => '</tbody>',
'row_start' => '<tr>',
'row_end' => '</tr>',
'cell_start' => '<td>',
'cell_end' => '</td>',
'row_alt_start' => '<tr>',
'row_alt_end' => '</tr>',
'cell_alt_start' => '<td>',
'cell_alt_end' => '</td>',
'table_close' => '</table>'
);
}
}
/* End of file Table.php */
/* Location: ./system/libraries/Table.php */ | php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.