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 |
|---|---|---|---|---|---|---|---|---|
ytake/Laravel-Aspect | https://github.com/ytake/Laravel-Aspect/blob/c00a321e6c5fd816f7ec86874acea0089c1a3a64/tests/src/AspectRetryOnFailure.php | tests/src/AspectRetryOnFailure.php | <?php
namespace __Test;
use Ytake\LaravelAspect\Annotation\RetryOnFailure;
/**
* Class AspectRetryOnFailure
*/
class AspectRetryOnFailure
{
/** @var int */
public $counter = 0;
/**
* @RetryOnFailure(
* types={
* \LogicException::class
* },
* attempts=3
* )
*/
public function call()
{
$this->counter += 1;
throw new \LogicException;
}
/**
* @RetryOnFailure(
* types={
* LogicException::class,
* },
* attempts=3,
* ignore=Exception::class
* )
*/
public function ignoreException()
{
$this->counter += 1;
throw new \Exception;
}
}
| php | MIT | c00a321e6c5fd816f7ec86874acea0089c1a3a64 | 2026-01-05T04:51:02.354274Z | false |
ytake/Laravel-Aspect | https://github.com/ytake/Laravel-Aspect/blob/c00a321e6c5fd816f7ec86874acea0089c1a3a64/tests/src/MessageDrivenModule.php | tests/src/MessageDrivenModule.php | <?php
namespace __Test;
/**
* Class MessageDrivenModule
*/
class MessageDrivenModule extends \Ytake\LaravelAspect\Modules\MessageDrivenModule
{
/** @var array */
protected $classes = [
AspectMessageDriven::class,
];
}
| php | MIT | c00a321e6c5fd816f7ec86874acea0089c1a3a64 | 2026-01-05T04:51:02.354274Z | false |
ytake/Laravel-Aspect | https://github.com/ytake/Laravel-Aspect/blob/c00a321e6c5fd816f7ec86874acea0089c1a3a64/tests/src/AspectLoggable.php | tests/src/AspectLoggable.php | <?php
/**
* for test
*/
namespace __Test;
use Ytake\LaravelAspect\Annotation\Loggable;
class AspectLoggable
{
/**
* @Loggable
* @param null $id
* @return null
*/
public function normalLog($id = null)
{
return $id;
}
/**
* @Loggable(skipResult=true)
* @param null $id
* @return null
*/
public function skipResultLog($id = null)
{
return $id;
}
}
| php | MIT | c00a321e6c5fd816f7ec86874acea0089c1a3a64 | 2026-01-05T04:51:02.354274Z | false |
ytake/Laravel-Aspect | https://github.com/ytake/Laravel-Aspect/blob/c00a321e6c5fd816f7ec86874acea0089c1a3a64/tests/src/LogExceptionsModule.php | tests/src/LogExceptionsModule.php | <?php
namespace __Test;
use Ytake\LaravelAspect\Modules\LogExceptionsModule as Loggable;
class LogExceptionsModule extends Loggable
{
/**
* @var array
*/
protected $classes = [
\__Test\AspectLogExceptions::class,
\__Test\AnnotationStub::class
];
}
| php | MIT | c00a321e6c5fd816f7ec86874acea0089c1a3a64 | 2026-01-05T04:51:02.354274Z | false |
ytake/Laravel-Aspect | https://github.com/ytake/Laravel-Aspect/blob/c00a321e6c5fd816f7ec86874acea0089c1a3a64/tests/src/AnnotationStub.php | tests/src/AnnotationStub.php | <?php
namespace __Test;
use Ytake\LaravelAspect\Annotation\LogExceptions;
/**
* Class AnnotationStub
* for tests
* @Resource
*/
class AnnotationStub
{
/**
* @LogExceptions
* @Get
* @param null $id
* @return null
*/
public function testing($id = null)
{
return $id;
}
}
| php | MIT | c00a321e6c5fd816f7ec86874acea0089c1a3a64 | 2026-01-05T04:51:02.354274Z | false |
ytake/Laravel-Aspect | https://github.com/ytake/Laravel-Aspect/blob/c00a321e6c5fd816f7ec86874acea0089c1a3a64/tests/src/TransactionalModule.php | tests/src/TransactionalModule.php | <?php
namespace __Test;
use Ytake\LaravelAspect\Modules\TransactionalModule as Transactional;
class TransactionalModule extends Transactional
{
/**
* @var array
*/
protected $classes = [
AspectTransactionalDatabase::class,
AspectTransactionalString::class,
AspectQueryLog::class
];
}
| php | MIT | c00a321e6c5fd816f7ec86874acea0089c1a3a64 | 2026-01-05T04:51:02.354274Z | false |
ytake/Laravel-Aspect | https://github.com/ytake/Laravel-Aspect/blob/c00a321e6c5fd816f7ec86874acea0089c1a3a64/tests/src/RetryOnFailureModule.php | tests/src/RetryOnFailureModule.php | <?php
namespace __Test;
/**
* Class RetryOnFailureModule
*/
class RetryOnFailureModule extends \Ytake\LaravelAspect\Modules\RetryOnFailureModule
{
/** @var array */
protected $classes = [
AspectRetryOnFailure::class,
];
}
| php | MIT | c00a321e6c5fd816f7ec86874acea0089c1a3a64 | 2026-01-05T04:51:02.354274Z | false |
ytake/Laravel-Aspect | https://github.com/ytake/Laravel-Aspect/blob/c00a321e6c5fd816f7ec86874acea0089c1a3a64/tests/src/QueryLogModule.php | tests/src/QueryLogModule.php | <?php
namespace __Test;
use Ytake\LaravelAspect\Modules\QueryLogModule as QueryLog;
class QueryLogModule extends QueryLog
{
/**
* @var array
*/
protected $classes = [
AspectQueryLog::class
];
}
| php | MIT | c00a321e6c5fd816f7ec86874acea0089c1a3a64 | 2026-01-05T04:51:02.354274Z | false |
ytake/Laravel-Aspect | https://github.com/ytake/Laravel-Aspect/blob/c00a321e6c5fd816f7ec86874acea0089c1a3a64/tests/src/CacheableModule.php | tests/src/CacheableModule.php | <?php
namespace __Test;
class CacheableModule extends \Ytake\LaravelAspect\Modules\CacheableModule
{
/**
* @var array
*/
protected $classes = [
\__Test\AspectCacheable::class,
\__Test\AspectCacheEvict::class,
\__Test\AspectMerge::class,
\ResolveMockClass::class,
];
}
| php | MIT | c00a321e6c5fd816f7ec86874acea0089c1a3a64 | 2026-01-05T04:51:02.354274Z | false |
ytake/Laravel-Aspect | https://github.com/ytake/Laravel-Aspect/blob/c00a321e6c5fd816f7ec86874acea0089c1a3a64/tests/src/AspectTransactionalDatabase.php | tests/src/AspectTransactionalDatabase.php | <?php
/**
* for test
*/
namespace __Test;
use Illuminate\Database\QueryException;
use Ytake\LaravelAspect\Annotation\Transactional;
use Illuminate\Database\ConnectionResolverInterface;
/**
* Class AspectTransactionalDatabase
*
* @package __Test
*/
class AspectTransactionalDatabase
{
/** @var ConnectionResolverInterface */
protected $db;
/**
* @param ConnectionResolverInterface $db
*/
public function __construct(ConnectionResolverInterface $db)
{
$this->db = $db;
}
/**
* @Transactional(value="testing")
*
* @return string
*/
public function start()
{
return $this->db->connection()->select("SELECT date('now')");
}
/**
* @Transactional(value="testing")
*/
public function error()
{
$this->db->connection()->statement('CREATE TABLE tests (test varchar(255) NOT NULL)');
$this->db->connection()->table("tests")->insert(['test' => 'testing']);
throw new QueryException("tests", "SELECT date('now')", [], new \Exception);
}
/**
* @Transactional(value="testing",expect=\LogicException::class)
*/
public function errorException()
{
$this->db->connection()->statement('CREATE TABLE tests (test varchar(255) NOT NULL)');
$this->db->connection()->table("tests")->insert(['test' => 'testing']);
throw new \LogicException;
}
/**
* @Transactional(value="testing")
* @param array $record
*
* @return bool
*/
public function appendRecord(array $record)
{
$this->db->connection()->statement('CREATE TABLE tests (test varchar(255) NOT NULL)');
return $this->db->connection()->table("tests")->insert($record);
}
/**
* @Transactional({"testing", "testing_second"})
*/
public function multipleDatabaseAppendRecordException()
{
$this->db->connection()->statement('CREATE TABLE tests (test varchar(255) NOT NULL)');
$this->db->connection('testing_second')->statement('CREATE TABLE tests (test varchar(255) NOT NULL)');
$this->db->connection()->table("tests")->insert(['test' => 'testing']);
$this->db->connection('testing_second')->table("tests")->insert(['test' => 'testing second']);
throw new QueryException("test", "SELECT date('now')", [], new \Exception);
}
/**
* @Transactional({"testing", "testing_second"})
*/
public function multipleDatabaseAppendRecord()
{
$this->db->connection()->statement('CREATE TABLE tests (test varchar(255) NOT NULL)');
$this->db->connection('testing_second')->statement('CREATE TABLE tests (test varchar(255) NOT NULL)');
$this->db->connection()->table("tests")->insert(['test' => 'testing']);
$this->db->connection('testing_second')->table("tests")->insert(['test' => 'testing second']);
return 'transaction test';
}
}
| php | MIT | c00a321e6c5fd816f7ec86874acea0089c1a3a64 | 2026-01-05T04:51:02.354274Z | false |
ytake/Laravel-Aspect | https://github.com/ytake/Laravel-Aspect/blob/c00a321e6c5fd816f7ec86874acea0089c1a3a64/tests/src/AspectTransactionalString.php | tests/src/AspectTransactionalString.php | <?php
/**
* for test
*/
namespace __Test;
use Ytake\LaravelAspect\Annotation\Transactional;
/**
* Class AspectTransactional
* @package Test
*/
class AspectTransactionalString
{
/**
* @Transactional(value="testing")
*
* @return string
*/
public function start()
{
return 'testing';
}
}
| php | MIT | c00a321e6c5fd816f7ec86874acea0089c1a3a64 | 2026-01-05T04:51:02.354274Z | false |
ytake/Laravel-Aspect | https://github.com/ytake/Laravel-Aspect/blob/c00a321e6c5fd816f7ec86874acea0089c1a3a64/tests/src/AspectMerge.php | tests/src/AspectMerge.php | <?php
/**
* for test
*/
namespace __Test;
use Ytake\LaravelAspect\Annotation\Cacheable;
use Ytake\LaravelAspect\Annotation\CacheEvict;
/**
* Class AspectMerge
*/
class AspectMerge implements AspectMergeInterface
{
/**
*
* @CacheEvict(tags={"testing1","testing2"},key={"#id"})
* @Cacheable(tags={"testing1","testing2"},key={"#id"})
* @param $id
* @return mixed
*/
public function caching($id)
{
return $id;
}
}
| php | MIT | c00a321e6c5fd816f7ec86874acea0089c1a3a64 | 2026-01-05T04:51:02.354274Z | false |
ytake/Laravel-Aspect | https://github.com/ytake/Laravel-Aspect/blob/c00a321e6c5fd816f7ec86874acea0089c1a3a64/tests/src/AspectLogExceptions.php | tests/src/AspectLogExceptions.php | <?php
/**
* for test
*/
namespace __Test;
use Ytake\LaravelAspect\Annotation\LogExceptions;
use Ytake\LaravelAspect\Exception\FileNotFoundException;
class AspectLogExceptions
{
/**
* @LogExceptions(driver="custom")
* @param null $id
* @return null
* @throws \Exception
*/
public function normalLog($id = null)
{
throw new \Exception;
return $id;
}
/**
* @LogExceptions(expect="\LogicException",driver="custom")
*/
public function expectException()
{
throw new \LogicException;
}
/**
* @LogExceptions(expect="\LogicException")
*/
public function expectNoException()
{
throw new FileNotFoundException(__DIR__);
}
/**
* @return int
*/
public function noException()
{
return 1;
}
}
| php | MIT | c00a321e6c5fd816f7ec86874acea0089c1a3a64 | 2026-01-05T04:51:02.354274Z | false |
ytake/Laravel-Aspect | https://github.com/ytake/Laravel-Aspect/blob/c00a321e6c5fd816f7ec86874acea0089c1a3a64/tests/src/AspectContextualBinding.php | tests/src/AspectContextualBinding.php | <?php
namespace __Test;
use Ytake\LaravelAspect\Annotation\Loggable;
/**
* Class AspectContextualBinding
*
* for testing
*/
class AspectContextualBinding
{
/** @var \ResolveMockInterface */
protected $resolveMock;
/**
* AspectContextualBinding constructor.
*
* @param \ResolveMockInterface $resolveMock
*/
public function __construct(\ResolveMockInterface $resolveMock)
{
$this->resolveMock = $resolveMock;
}
/**
* @Loggable
* @return mixed
*/
public function testing()
{
return $this->resolveMock->get();
}
} | php | MIT | c00a321e6c5fd816f7ec86874acea0089c1a3a64 | 2026-01-05T04:51:02.354274Z | false |
ytake/Laravel-Aspect | https://github.com/ytake/Laravel-Aspect/blob/c00a321e6c5fd816f7ec86874acea0089c1a3a64/tests/src/AspectMergeInterface.php | tests/src/AspectMergeInterface.php | <?php
namespace __Test;
/**
* Class AspectMergeInterface
* @package __Test
*/
interface AspectMergeInterface
{
}
| php | MIT | c00a321e6c5fd816f7ec86874acea0089c1a3a64 | 2026-01-05T04:51:02.354274Z | false |
ytake/Laravel-Aspect | https://github.com/ytake/Laravel-Aspect/blob/c00a321e6c5fd816f7ec86874acea0089c1a3a64/tests/src/AspectCacheable.php | tests/src/AspectCacheable.php | <?php
/**
* for test
*/
namespace __Test;
use Ytake\LaravelAspect\Annotation\Cacheable;
/**
* Class AspectCacheable
*
* @package __Test
*/
class AspectCacheable
{
/**
* @Cacheable(key="#id",driver="null")
* @param null $id
*
* @return null
*/
public function singleKey($id = null)
{
return $id;
}
/**
* @Cacheable(key={"#id","#value"},driver="array")
* @param $id
* @param $value
*
* @return mixed
*/
public function multipleKey($id, $value)
{
return $id;
}
/**
* @Cacheable(cacheName="testing1",key={"#id","#value"})
* @param $id
* @param $value
*
* @return mixed
*/
public function namedMultipleKey($id, $value)
{
return $id;
}
/**
* @Cacheable(tags={"testing1","testing2"},key={"#id","#value"})
* @param $id
* @param $value
*
* @return mixed
*/
public function namedMultipleNameAndKey($id, $value)
{
return $id;
}
/**
* @Cacheable(tags={"testing1","testing2"},key={"#id","#class"})
* @param $id
* @param \stdClass $class
*
* @return mixed
*/
public function cachingKeyObject($id, \stdClass $class)
{
return $id;
}
/**
* @Cacheable(negative=true,cacheName="negative")
* @return null
*/
public function negativeCache()
{
return null;
}
}
| php | MIT | c00a321e6c5fd816f7ec86874acea0089c1a3a64 | 2026-01-05T04:51:02.354274Z | false |
ytake/Laravel-Aspect | https://github.com/ytake/Laravel-Aspect/blob/c00a321e6c5fd816f7ec86874acea0089c1a3a64/tests/src/AspectQueryLog.php | tests/src/AspectQueryLog.php | <?php
/**
* for test
*/
namespace __Test;
use Ytake\LaravelAspect\Annotation\QueryLog;
use Ytake\LaravelAspect\Annotation\Transactional;
use Illuminate\Database\ConnectionResolverInterface;
/**
* Class AspectQueryLog
*/
class AspectQueryLog
{
/** @var ConnectionResolverInterface */
protected $db;
/**
* @param ConnectionResolverInterface $db
*/
public function __construct(ConnectionResolverInterface $db)
{
$this->db = $db;
}
/**
* @QueryLog(driver="stack")
* @Transactional(value="testing")
*
* @return string
*/
public function start()
{
return $this->db->connection()->select("SELECT date('now')");
}
/**
* @QueryLog(driver="stack")
* @Transactional(value="testing")
* @param array $record
*
* @return bool
*/
public function appendRecord(array $record)
{
$this->db->connection()->statement('CREATE TABLE tests (test varchar(255) NOT NULL)');
$this->db->connection()->table("tests")->insert($record);
throw new \Exception;
}
/**
* @Transactional({"testing", "testing_second"})
* @QueryLog(driver="stack")
*/
public function multipleDatabaseAppendRecord()
{
$this->db->connection()->statement('CREATE TABLE tests (test varchar(255) NOT NULL)');
$this->db->connection('testing_second')->statement('CREATE TABLE tests (test varchar(255) NOT NULL)');
$this->db->connection()->table("tests")->insert(['test' => 'testing']);
$this->db->connection('testing_second')->table("tests")->insert(['test' => 'testing second']);
return 'transaction test';
}
}
| php | MIT | c00a321e6c5fd816f7ec86874acea0089c1a3a64 | 2026-01-05T04:51:02.354274Z | false |
ytake/Laravel-Aspect | https://github.com/ytake/Laravel-Aspect/blob/c00a321e6c5fd816f7ec86874acea0089c1a3a64/tests/src/TestableLogger.php | tests/src/TestableLogger.php | <?php
declare(strict_types=1);
namespace __Test;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Psr\Log\LoggerInterface;
class TestableLogger
{
/**
* @param array $config
*
* @return LoggerInterface
* @throws \Exception
*/
public function __invoke(array $config): LoggerInterface
{
return new Logger('testing', [
new StreamHandler($config['path'])
]);
}
}
| php | MIT | c00a321e6c5fd816f7ec86874acea0089c1a3a64 | 2026-01-05T04:51:02.354274Z | false |
ytake/Laravel-Aspect | https://github.com/ytake/Laravel-Aspect/blob/c00a321e6c5fd816f7ec86874acea0089c1a3a64/tests/src/AspectCacheEvict.php | tests/src/AspectCacheEvict.php | <?php
/**
* for test
*/
namespace __Test;
use Ytake\LaravelAspect\Annotation\Cacheable;
use Ytake\LaravelAspect\Annotation\CacheEvict;
/**
* Class AspectCacheEvict
*
* @package __Test
*/
class AspectCacheEvict
{
/**
* @CacheEvict(cacheName="singleCacheDelete")
* @return string
*/
public function singleCacheDelete()
{
return 'testing';
}
/**
* @Cacheable(cacheName="testing",tags={"testing1"},key={"#id","#value"})
* @param $id
* @param $value
* @return mixed
*/
public function cached($id, $value)
{
return $id;
}
/**
* @CacheEvict(cacheName="testing",tags={"testing1"},allEntries=true)
* @return null
*/
public function removeCache()
{
return null;
}
}
| php | MIT | c00a321e6c5fd816f7ec86874acea0089c1a3a64 | 2026-01-05T04:51:02.354274Z | false |
ytake/Laravel-Aspect | https://github.com/ytake/Laravel-Aspect/blob/c00a321e6c5fd816f7ec86874acea0089c1a3a64/tests/src/LoggableModule.php | tests/src/LoggableModule.php | <?php
namespace __Test;
use Ytake\LaravelAspect\Modules\LoggableModule as Loggable;
class LoggableModule extends Loggable
{
/**
* @var array
*/
protected $classes = [
AspectLoggable::class,
AspectContextualBinding::class,
AspectMessageDriven::class,
];
}
| php | MIT | c00a321e6c5fd816f7ec86874acea0089c1a3a64 | 2026-01-05T04:51:02.354274Z | false |
ytake/Laravel-Aspect | https://github.com/ytake/Laravel-Aspect/blob/c00a321e6c5fd816f7ec86874acea0089c1a3a64/tests/src/CachePutModule.php | tests/src/CachePutModule.php | <?php
namespace __Test;
class CachePutModule extends \Ytake\LaravelAspect\Modules\CachePutModule
{
/**
* @var array
*/
protected $classes = [
\__Test\AspectCachePut::class,
];
}
| php | MIT | c00a321e6c5fd816f7ec86874acea0089c1a3a64 | 2026-01-05T04:51:02.354274Z | false |
ytake/Laravel-Aspect | https://github.com/ytake/Laravel-Aspect/blob/c00a321e6c5fd816f7ec86874acea0089c1a3a64/tests/src/CacheEvictModule.php | tests/src/CacheEvictModule.php | <?php
namespace __Test;
class CacheEvictModule extends \Ytake\LaravelAspect\Modules\CacheEvictModule
{
/**
* @var array
*/
protected $classes = [
\__Test\AspectCacheEvict::class,
\__Test\AspectMerge::class
];
}
| php | MIT | c00a321e6c5fd816f7ec86874acea0089c1a3a64 | 2026-01-05T04:51:02.354274Z | false |
ytake/Laravel-Aspect | https://github.com/ytake/Laravel-Aspect/blob/c00a321e6c5fd816f7ec86874acea0089c1a3a64/tests/Interceptor/MessageDrivenInterceptorTest.php | tests/Interceptor/MessageDrivenInterceptorTest.php | <?php
declare(strict_types=1);
use Illuminate\Container\Container;
use Illuminate\Contracts\Bus\Dispatcher;
use Ytake\LaravelAspect\Annotation\MessageDriven;
use Ytake\LaravelAspect\Interceptor\MessageDrivenInterceptor;
final class MessageDrivenInterceptorTest extends \AspectTestCase
{
/** @var \Ytake\LaravelAspect\AspectManager $manager */
protected $manager;
/** @var MessageDrivenInterceptor */
private $interceptor;
protected function setUp(): void
{
parent::setUp();
$this->manager = new \Ytake\LaravelAspect\AspectManager($this->app);
$this->resolveManager();
$this->interceptor = new MessageDrivenInterceptor;
}
public function testShouldDispatchMethod(): void
{
$this->expectOutputString('this');
$this->interceptor->setBusDispatcher(
$this->app->make(Dispatcher::class)
);
$this->interceptor->setAnnotation(MessageDriven::class);
$this->interceptor->invoke(
new StubMessageDrivenInvocation()
);
}
/**
*
*/
protected function resolveManager()
{
$aspect = $this->manager->driver('ray');
$aspect->register(\__Test\MessageDrivenModule::class);
$aspect->weave();
}
}
class StubMessageDrivenInvocation implements \Ray\Aop\MethodInvocation
{
/** @var ReflectionMethod */
protected $reflectionMethod;
public function getNamedArguments(): \ArrayObject
{
return new \ArrayObject([]);
}
public function getArguments(): \ArrayObject
{
return new \ArrayObject(['argument' => 'this']);
}
public function proceed()
{
return $this->intercept()->exec('this');
}
public function getThis()
{
return new \__Test\AspectMessageDriven();
}
/**
* @return \Ray\Aop\ReflectionMethod
* @throws ReflectionException
* @throws \Illuminate\Contracts\Container\BindingResolutionException
*/
public function getMethod(): \Ray\Aop\ReflectionMethod
{
$reflectionClass = new \ReflectionClass(\__Test\AspectMessageDriven::class);
$reflectionMethod = new \Ray\Aop\ReflectionMethod(\__Test\AspectMessageDriven::class, 'exec');
$reflectionMethod->setObject(
Container::getInstance()->make(\__Test\AspectMessageDriven::class, []),
$reflectionClass->getMethod('exec')
);
return $reflectionMethod;
}
public function getName()
{
return $this->reflectionMethod->getName();
}
public function getAnnotation($name)
{
$reader = new \Doctrine\Common\Annotations\AnnotationReader();
return $reader->getMethodAnnotation($this->reflectionMethod, $name);
}
protected function intercept()
{
return new \__Test\AspectMessageDriven;
}
}
| php | MIT | c00a321e6c5fd816f7ec86874acea0089c1a3a64 | 2026-01-05T04:51:02.354274Z | false |
ytake/Laravel-Aspect | https://github.com/ytake/Laravel-Aspect/blob/c00a321e6c5fd816f7ec86874acea0089c1a3a64/tests/Commands/AspectClearCacheCommandTest.php | tests/Commands/AspectClearCacheCommandTest.php | <?php
/**
* Class AspectClearCacheCommandTest
*/
class AspectClearCacheCommandTest extends \AspectTestCase
{
/** @var \Ytake\LaravelAspect\AspectManager $manager */
protected $manager;
/** @var \Ytake\LaravelAspect\Console\ClearCacheCommand */
protected $command;
protected function setUp(): void
{
parent::setUp();
$this->manager = new \Ytake\LaravelAspect\AspectManager($this->app);
$this->resolveManager();
$this->command = new \Ytake\LaravelAspect\Console\ClearCacheCommand(
$this->app['config'],
$this->app['files']
);
$this->command->setLaravel(new MockApplication());
}
public function testCacheClearFile()
{
$cache = $this->app->make(\__Test\AspectCacheable::class);
$cache->namedMultipleNameAndKey(1000, 'testing');
$output = new \Symfony\Component\Console\Output\BufferedOutput();
$this->command->run(
new \Symfony\Component\Console\Input\ArrayInput([]),
$output
);
$this->assertSame('aspect code cache clear!', trim($output->fetch()));
$configure = $this->app['config']->get('ytake-laravel-aop');
$driverConfig = $configure['aspect']['drivers'][$configure['aspect']['default']];
if (isset($driverConfig['cache_dir'])) {
$files = $this->app['files']->files($driverConfig['cache_dir']);
$this->assertCount(0, $files);
}
}
/**
*
*/
protected function resolveManager()
{
$aspect = $this->manager->driver('ray');
$aspect->register(\__Test\CacheableModule::class);
}
}
| php | MIT | c00a321e6c5fd816f7ec86874acea0089c1a3a64 | 2026-01-05T04:51:02.354274Z | false |
ytake/Laravel-Aspect | https://github.com/ytake/Laravel-Aspect/blob/c00a321e6c5fd816f7ec86874acea0089c1a3a64/tests/config/logging.php | tests/config/logging.php | <?php
use Monolog\Handler\StreamHandler;
return [
/*
|--------------------------------------------------------------------------
| Default Log Channel
|--------------------------------------------------------------------------
|
| This option defines the default log channel that gets used when writing
| messages to the logs. The name specified in this option should match
| one of the channels defined in the "channels" configuration array.
|
*/
'default' => env('LOG_CHANNEL', 'stack'),
/*
|--------------------------------------------------------------------------
| Log Channels
|--------------------------------------------------------------------------
|
| Here you may configure the log channels for your application. Out of
| the box, Laravel uses the Monolog PHP logging library. This gives
| you a variety of powerful log handlers / formatters to utilize.
|
| Available Drivers: "single", "daily", "slack", "syslog",
| "errorlog", "monolog",
| "custom", "stack"
|
*/
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => ['single'],
],
'single' => [
'driver' => 'single',
'path' => __DIR__ . '/../storage/log/.testing.log',
'level' => 'debug',
],
'custom' => [
'driver' => 'custom',
'via' => __Test\TestableLogger::class,
'path' => __DIR__ . '/../storage/log/.testing.exceptions.log',
'level' => 'debug',
],
'daily' => [
'driver' => 'daily',
'path' => __DIR__ . '/../storage/log/.testing.log',
'level' => 'debug',
'days' => 7,
],
'stderr' => [
'driver' => 'monolog',
'handler' => StreamHandler::class,
'with' => [
'stream' => 'php://stderr',
],
],
'syslog' => [
'driver' => 'syslog',
'level' => 'debug',
],
'errorlog' => [
'driver' => 'errorlog',
'level' => 'debug',
],
],
]; | php | MIT | c00a321e6c5fd816f7ec86874acea0089c1a3a64 | 2026-01-05T04:51:02.354274Z | false |
ytake/Laravel-Aspect | https://github.com/ytake/Laravel-Aspect/blob/c00a321e6c5fd816f7ec86874acea0089c1a3a64/tests/config/queue.php | tests/config/queue.php | <?php
return [
'default' => 'sync',
'connections' => [
'sync' => [
'driver' => 'sync',
],
'database' => [
'driver' => 'database',
'table' => 'jobs',
'queue' => 'default',
'retry_after' => 90,
],
'redis' => [
'driver' => 'redis',
'connection' => 'default',
'queue' => 'default',
'retry_after' => 90,
],
],
'failed' => [
'database' => 'mysql',
'table' => 'failed_jobs',
],
];
| php | MIT | c00a321e6c5fd816f7ec86874acea0089c1a3a64 | 2026-01-05T04:51:02.354274Z | false |
ytake/Laravel-Aspect | https://github.com/ytake/Laravel-Aspect/blob/c00a321e6c5fd816f7ec86874acea0089c1a3a64/tests/config/ytake-laravel-aop.php | tests/config/ytake-laravel-aop.php | <?php
return [
'aspect' => [
/**
* choose aop library
* "ray"(Ray.Aop), "none"(for testing)
*/
'default' => 'ray',
/**
*
*/
'drivers' => [
'ray' => [
'force_compile' => false,
// string Path to the cache directory where compiled classes will be stored
'compile_dir' => __DIR__ . '/../storage/aop/compile',
'cache' => false,
'cache_dir' => __DIR__ . '/../storage/aop/cache',
],
'none' => [
// for testing driver
// no use aspect
]
],
],
'annotation' => [
'ignores' => [
// global Ignored Annotations
'Get',
'Resource'
],
'custom' => [
// added your annotation class
],
],
];
| php | MIT | c00a321e6c5fd816f7ec86874acea0089c1a3a64 | 2026-01-05T04:51:02.354274Z | false |
ytake/Laravel-Aspect | https://github.com/ytake/Laravel-Aspect/blob/c00a321e6c5fd816f7ec86874acea0089c1a3a64/tests/config/cache.php | tests/config/cache.php | <?php
return [
'default' => 'array',
'stores' => [
'array' => [
'driver' => 'array',
],
'null' => [
'driver' => 'null',
],
],
'prefix' => 'laravel-aop-package',
];
| php | MIT | c00a321e6c5fd816f7ec86874acea0089c1a3a64 | 2026-01-05T04:51:02.354274Z | false |
ytake/Laravel-Aspect | https://github.com/ytake/Laravel-Aspect/blob/c00a321e6c5fd816f7ec86874acea0089c1a3a64/tests/config/database.php | tests/config/database.php | <?php
return [
'fetch' => PDO::FETCH_CLASS,
'default' => 'testing',
'connections' => [
'testing' => [
'driver' => 'sqlite',
'database' => ':memory:',
'prefix' => '',
],
'testing_second' => [
'driver' => 'sqlite',
'database' => ':memory:',
'prefix' => '',
],
],
'migrations' => 'migrations',
'redis' => [
'cluster' => false,
'default' => [
'host' => '127.0.0.1',
'port' => 6379,
'database' => 0,
],
],
];
| php | MIT | c00a321e6c5fd816f7ec86874acea0089c1a3a64 | 2026-01-05T04:51:02.354274Z | false |
alexdebril/rss-atom-bundle | https://github.com/alexdebril/rss-atom-bundle/blob/29e624c428d4284726e5da5e0d245cbc93d1f17a/src/DebrilRssAtomBundle.php | src/DebrilRssAtomBundle.php | <?php
namespace Debril\RssAtomBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class DebrilRssAtomBundle extends Bundle
{
}
| php | MIT | 29e624c428d4284726e5da5e0d245cbc93d1f17a | 2026-01-05T04:51:13.799383Z | false |
alexdebril/rss-atom-bundle | https://github.com/alexdebril/rss-atom-bundle/blob/29e624c428d4284726e5da5e0d245cbc93d1f17a/src/Controller/StreamController.php | src/Controller/StreamController.php | <?php declare(strict_types=1);
namespace Debril\RssAtomBundle\Controller;
use Debril\RssAtomBundle\Provider\FeedProviderInterface;
use Debril\RssAtomBundle\Exception\FeedException\FeedNotFoundException;
use Debril\RssAtomBundle\Response\FeedBuilder;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class StreamController
{
/**
* @param Request $request
* @param FeedBuilder $feedBuilder
* @param FeedProviderInterface $provider
* @return Response
*/
public function indexAction(Request $request, FeedBuilder $feedBuilder, FeedProviderInterface $provider) : Response
{
try {
return $feedBuilder->getResponse(
$request->get('format', 'rss'),
$provider->getFeed($request)
);
} catch (FeedNotFoundException $e) {
throw new NotFoundHttpException('feed not found');
}
}
}
| php | MIT | 29e624c428d4284726e5da5e0d245cbc93d1f17a | 2026-01-05T04:51:13.799383Z | false |
alexdebril/rss-atom-bundle | https://github.com/alexdebril/rss-atom-bundle/blob/29e624c428d4284726e5da5e0d245cbc93d1f17a/src/Request/ModifiedSince.php | src/Request/ModifiedSince.php | <?php declare(strict_types=1);
namespace Debril\RssAtomBundle\Request;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
class ModifiedSince
{
const HTTP_HEADER_NAME = 'If-Modified-Since';
private $logger;
private $requestStack;
public function __construct(RequestStack $requestStack, LoggerInterface $logger)
{
$this->logger = $logger;
$this->requestStack = $requestStack;
}
/**
* @return \DateTime
*/
public function getValue(): \DateTime
{
return $this->getModifiedSince($this->requestStack->getCurrentRequest());
}
private function getModifiedSince(Request $request):\DateTime
{
if ($request->headers->has(self::HTTP_HEADER_NAME)) {
try {
$string = $request->headers->get(self::HTTP_HEADER_NAME);
return new \DateTime($string);
} catch (\TypeError|\Exception $e) {
$this->logger->notice(sprintf('If-Modified-Since Header has a unexpected value, exception was %s', $e->getMessage()));
}
}
return new \DateTime('@1');
}
}
| php | MIT | 29e624c428d4284726e5da5e0d245cbc93d1f17a | 2026-01-05T04:51:13.799383Z | false |
alexdebril/rss-atom-bundle | https://github.com/alexdebril/rss-atom-bundle/blob/29e624c428d4284726e5da5e0d245cbc93d1f17a/src/DependencyInjection/Configuration.php | src/DependencyInjection/Configuration.php | <?php declare(strict_types=1);
namespace Debril\RssAtomBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* This is the class that validates and merges configuration from your app/config files.
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritDoc}
*/
public function getConfigTreeBuilder() : TreeBuilder
{
$treeBuilder = new TreeBuilder('debril_rss_atom');
// For BC with symfony/config < 4.2
if (method_exists($treeBuilder, 'getRootNode')) {
/** @var ArrayNodeDefinition $rootNode */
$rootNode = $treeBuilder->getRootNode();
} else {
$rootNode = $treeBuilder->root('debril_rss_atom');
}
$rootNode
->children()
->booleanNode('private')
->info('Change cache headers so the RSS feed is not cached by public caches (like reverse-proxies...).')
->defaultValue(false)
->end()
->booleanNode('force_refresh')
->info('Do not send 304 status if the feed has not been modified since last hit')
->defaultValue(false)
->end()
->scalarNode('content_type_json')
->info('Content-Type header value to use for json feed generation.')
->defaultValue('application/json')
->end()
->scalarNode('content_type_xml')
->info('Content-Type header value to use for xml feed generation (atom and rss).')
->defaultValue('application/xhtml+xml')
->end()
->arrayNode('date_formats')
->prototype('scalar')->end()
->end()
->end()
;
// Here you should define the parameters that are allowed to
// configure your bundle. See the documentation linked above for
// more information on that topic.
return $treeBuilder;
}
}
| php | MIT | 29e624c428d4284726e5da5e0d245cbc93d1f17a | 2026-01-05T04:51:13.799383Z | false |
alexdebril/rss-atom-bundle | https://github.com/alexdebril/rss-atom-bundle/blob/29e624c428d4284726e5da5e0d245cbc93d1f17a/src/DependencyInjection/DebrilRssAtomExtension.php | src/DependencyInjection/DebrilRssAtomExtension.php | <?php declare(strict_types=1);
namespace Debril\RssAtomBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;
/**
* This is the class that loads and manages your bundle configuration.
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
*/
class DebrilRssAtomExtension extends Extension implements CompilerPassInterface
{
/**
* @var array
*/
protected $defaultDateFormats = [
\DateTime::RFC3339,
\DateTime::RSS,
\DateTime::W3C,
'Y-m-d\TH:i:s.uP',
'Y-m-d',
'd/m/Y',
'd M Y H:i:s P',
'D, d M Y H:i O',
'D, d M Y H:i:s O',
'D M d Y H:i:s e',
];
/**
* {@inheritDoc}
*/
public function load(array $configs, ContainerBuilder $container) : void
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
$loader->load('services.yml');
$this->setDateFormats($container, $config);
$container->setParameter('debril_rss_atom.public_feeds', !$config['private']);
$container->setParameter('debril_rss_atom.force_refresh', $config['force_refresh']);
$container->setParameter('debril_rss_atom.content_type_json', $config['content_type_json']);
$container->setParameter('debril_rss_atom.content_type_xml', $config['content_type_xml']);
}
/**
* @param ContainerBuilder $container
* @param array $config
* @return $this
*/
protected function setDateFormats(ContainerBuilder $container, array $config) : self
{
$dateFormats = isset($config['date_formats']) ?
array_merge($this->defaultDateFormats, $config['date_formats']):
$this->defaultDateFormats;
$container->setParameter(
'debril_rss_atom.date_formats',
$dateFormats
);
return $this;
}
/**
* @param ContainerBuilder $container
*/
public function process(ContainerBuilder $container) : void
{
$this->setDefinition($container, 'logger', 'Psr\Log\NullLogger');
}
/**
* @param ContainerBuilder $container
* @param string $serviceName
* @param string $className
* @return DebrilRssAtomExtension
*/
protected function setDefinition(ContainerBuilder $container, string $serviceName, string $className) : self
{
if ( ! $container->has($serviceName) ) {
$container->setDefinition($serviceName, new Definition($className));
}
return $this;
}
}
| php | MIT | 29e624c428d4284726e5da5e0d245cbc93d1f17a | 2026-01-05T04:51:13.799383Z | false |
alexdebril/rss-atom-bundle | https://github.com/alexdebril/rss-atom-bundle/blob/29e624c428d4284726e5da5e0d245cbc93d1f17a/src/Response/HeadersBuilder.php | src/Response/HeadersBuilder.php | <?php declare(strict_types=1);
namespace Debril\RssAtomBundle\Response;
use Symfony\Component\HttpFoundation\Response;
class HeadersBuilder
{
const DEFAULT_MAX_AGE = 3600;
const FORMAT_XML = 'xml';
const DEFAULT_XML_CONTENT_TYPE = 'application/xhtml+xml';
/**
* supported content-types
* @var array
*/
private $contentTypes = [
self::FORMAT_XML => self::DEFAULT_XML_CONTENT_TYPE
];
/**
* if true, the response is marked s public
* @var bool
*/
private $public;
/**
* maximum amount of time before the cache gets invalidated (in seconds)
* @var int
*/
private $maxAge;
/**
* HeadersBuilder constructor.
* @param $public
* @param $maxAge
*/
public function __construct(bool $public = true, int $maxAge = self::DEFAULT_MAX_AGE)
{
$this->public = $public;
$this->maxAge = $maxAge;
}
public function setContentType(string $format, $value): void
{
$this->contentTypes[$format] = $value;
}
public function setResponseHeaders(Response $response, string $format, \DateTime $lastModified): void
{
$response->headers->set('Content-Type', $this->getContentType($format));
$this->public ? $response->setPublic() : $response->setPrivate();
$response->setMaxAge($this->maxAge);
$response->setLastModified($lastModified);
}
private function getContentType(string $format): string
{
return $this->contentTypes[$format] ?? $this->contentTypes[self::FORMAT_XML];
}
}
| php | MIT | 29e624c428d4284726e5da5e0d245cbc93d1f17a | 2026-01-05T04:51:13.799383Z | false |
alexdebril/rss-atom-bundle | https://github.com/alexdebril/rss-atom-bundle/blob/29e624c428d4284726e5da5e0d245cbc93d1f17a/src/Response/FeedBuilder.php | src/Response/FeedBuilder.php | <?php declare(strict_types=1);
namespace Debril\RssAtomBundle\Response;
use Debril\RssAtomBundle\Request\ModifiedSince;
use FeedIo\FeedInterface;
use FeedIo\FeedIo;
use Symfony\Component\HttpFoundation\Response;
class FeedBuilder
{
/**
* @var FeedIo
*/
private $feedIo;
/**
* @var ModifiedSince
*/
private $modifiedSince;
/**
* @var HeadersBuilder
*/
private $headersBuilder;
/**
* @var bool
*/
private $forceRefresh;
/**
* @param FeedIo $feedIo
* @param HeadersBuilder $headersBuilder
* @param ModifiedSince $modifiedSince
* @param bool $forceRefresh
*/
public function __construct(FeedIo $feedIo, HeadersBuilder $headersBuilder, ModifiedSince $modifiedSince, bool $forceRefresh = false)
{
$this->feedIo = $feedIo;
$this->headersBuilder = $headersBuilder;
$this->modifiedSince = $modifiedSince;
$this->forceRefresh = $forceRefresh;
}
/**
* Creates the HttpFoundation\Response instance corresponding to given feed
*
* @param string $format
* @param FeedInterface $feed
* @return Response
*/
public function getResponse(string $format, FeedInterface $feed): Response
{
if ($this->forceRefresh || $feed->getLastModified() > $this->modifiedSince->getValue()) {
$response = new Response($this->feedIo->format($feed, $format));
$this->headersBuilder->setResponseHeaders($response, $format, $feed->getLastModified());
} else {
$response = new Response();
$response->setNotModified();
}
return $response;
}
}
| php | MIT | 29e624c428d4284726e5da5e0d245cbc93d1f17a | 2026-01-05T04:51:13.799383Z | false |
alexdebril/rss-atom-bundle | https://github.com/alexdebril/rss-atom-bundle/blob/29e624c428d4284726e5da5e0d245cbc93d1f17a/src/Exception/FeedException.php | src/Exception/FeedException.php | <?php
/**
* Rss/Atom Bundle for Symfony.
*
*
* @license http://opensource.org/licenses/lgpl-3.0.html LGPL
* @copyright (c) 2013, Alexandre Debril
*/
namespace Debril\RssAtomBundle\Exception;
/**
* Class FeedException.
*
* @author Sullivan Senechal <soullivaneuh@gmail.com>
*/
class FeedException extends RssAtomException
{
}
| php | MIT | 29e624c428d4284726e5da5e0d245cbc93d1f17a | 2026-01-05T04:51:13.799383Z | false |
alexdebril/rss-atom-bundle | https://github.com/alexdebril/rss-atom-bundle/blob/29e624c428d4284726e5da5e0d245cbc93d1f17a/src/Exception/RssAtomException.php | src/Exception/RssAtomException.php | <?php
/**
* Rss/Atom Bundle for Symfony.
*
*
* @license http://opensource.org/licenses/lgpl-3.0.html LGPL
* @copyright (c) 2013, Alexandre Debril
*/
namespace Debril\RssAtomBundle\Exception;
/**
* Class RssAtomException.
*
* @author Sullivan Senechal <soullivaneuh@gmail.com>
*/
class RssAtomException extends \RuntimeException
{
}
| php | MIT | 29e624c428d4284726e5da5e0d245cbc93d1f17a | 2026-01-05T04:51:13.799383Z | false |
alexdebril/rss-atom-bundle | https://github.com/alexdebril/rss-atom-bundle/blob/29e624c428d4284726e5da5e0d245cbc93d1f17a/src/Exception/ParserException.php | src/Exception/ParserException.php | <?php
/**
* Rss/Atom Bundle for Symfony.
*
*
* @license http://opensource.org/licenses/lgpl-3.0.html LGPL
* @copyright (c) 2013, Alexandre Debril
*/
namespace Debril\RssAtomBundle\Exception;
/**
* Class ParserException.
* @deprecated removed in version 3.0
*/
class ParserException extends RssAtomException
{
}
| php | MIT | 29e624c428d4284726e5da5e0d245cbc93d1f17a | 2026-01-05T04:51:13.799383Z | false |
alexdebril/rss-atom-bundle | https://github.com/alexdebril/rss-atom-bundle/blob/29e624c428d4284726e5da5e0d245cbc93d1f17a/src/Exception/DriverUnreachableResourceException.php | src/Exception/DriverUnreachableResourceException.php | <?php
/**
* Rss/Atom Bundle for Symfony.
*
*
* @license http://opensource.org/licenses/lgpl-3.0.html LGPL
* @copyright (c) 2013, Alexandre Debril
*/
namespace Debril\RssAtomBundle\Exception;
/**
* Class DriverUnreachableResourceException.
* @deprecated removed in version 3.0
*/
class DriverUnreachableResourceException extends RssAtomException
{
}
| php | MIT | 29e624c428d4284726e5da5e0d245cbc93d1f17a | 2026-01-05T04:51:13.799383Z | false |
alexdebril/rss-atom-bundle | https://github.com/alexdebril/rss-atom-bundle/blob/29e624c428d4284726e5da5e0d245cbc93d1f17a/src/Exception/FeedException/FeedServerErrorException.php | src/Exception/FeedException/FeedServerErrorException.php | <?php
/**
* Rss/Atom Bundle for Symfony.
*
*
* @license http://opensource.org/licenses/lgpl-3.0.html LGPL
* @copyright (c) 2013, Alexandre Debril
*/
namespace Debril\RssAtomBundle\Exception\FeedException;
use Debril\RssAtomBundle\Exception\FeedException;
/**
* Class FeedServerErrorException.
*/
class FeedServerErrorException extends FeedException
{
}
| php | MIT | 29e624c428d4284726e5da5e0d245cbc93d1f17a | 2026-01-05T04:51:13.799383Z | false |
alexdebril/rss-atom-bundle | https://github.com/alexdebril/rss-atom-bundle/blob/29e624c428d4284726e5da5e0d245cbc93d1f17a/src/Exception/FeedException/FeedCannotBeReadException.php | src/Exception/FeedException/FeedCannotBeReadException.php | <?php
/**
* Rss/Atom Bundle for Symfony.
*
*
* @license http://opensource.org/licenses/lgpl-3.0.html LGPL
* @copyright (c) 2013, Alexandre Debril
*/
namespace Debril\RssAtomBundle\Exception\FeedException;
use Debril\RssAtomBundle\Exception\FeedException;
/**
* Class FeedCannotBeReadException.
*/
class FeedCannotBeReadException extends FeedException
{
}
| php | MIT | 29e624c428d4284726e5da5e0d245cbc93d1f17a | 2026-01-05T04:51:13.799383Z | false |
alexdebril/rss-atom-bundle | https://github.com/alexdebril/rss-atom-bundle/blob/29e624c428d4284726e5da5e0d245cbc93d1f17a/src/Exception/FeedException/FeedNotFoundException.php | src/Exception/FeedException/FeedNotFoundException.php | <?php
/**
* Rss/Atom Bundle for Symfony.
*
*
* @license http://opensource.org/licenses/lgpl-3.0.html LGPL
* @copyright (c) 2013, Alexandre Debril
*/
namespace Debril\RssAtomBundle\Exception\FeedException;
use Debril\RssAtomBundle\Exception\FeedException;
/**
* Class FeedNotFoundException.
*/
class FeedNotFoundException extends FeedException
{
}
| php | MIT | 29e624c428d4284726e5da5e0d245cbc93d1f17a | 2026-01-05T04:51:13.799383Z | false |
alexdebril/rss-atom-bundle | https://github.com/alexdebril/rss-atom-bundle/blob/29e624c428d4284726e5da5e0d245cbc93d1f17a/src/Exception/FeedException/FeedForbiddenException.php | src/Exception/FeedException/FeedForbiddenException.php | <?php
/**
* Rss/Atom Bundle for Symfony.
*
*
* @license http://opensource.org/licenses/lgpl-3.0.html LGPL
* @copyright (c) 2013, Alexandre Debril
*/
namespace Debril\RssAtomBundle\Exception\FeedException;
use Debril\RssAtomBundle\Exception\FeedException;
/**
* Class FeedForbiddenException.
*/
class FeedForbiddenException extends FeedException
{
}
| php | MIT | 29e624c428d4284726e5da5e0d245cbc93d1f17a | 2026-01-05T04:51:13.799383Z | false |
alexdebril/rss-atom-bundle | https://github.com/alexdebril/rss-atom-bundle/blob/29e624c428d4284726e5da5e0d245cbc93d1f17a/src/Exception/FeedException/FeedNotModifiedException.php | src/Exception/FeedException/FeedNotModifiedException.php | <?php
/**
* Rss/Atom Bundle for Symfony.
*
*
* @license http://opensource.org/licenses/lgpl-3.0.html LGPL
* @copyright (c) 2013, Alexandre Debril
*/
namespace Debril\RssAtomBundle\Exception\FeedException;
use Debril\RssAtomBundle\Exception\FeedException;
/**
* Class FeedNotModifiedException.
*/
class FeedNotModifiedException extends FeedException
{
}
| php | MIT | 29e624c428d4284726e5da5e0d245cbc93d1f17a | 2026-01-05T04:51:13.799383Z | false |
alexdebril/rss-atom-bundle | https://github.com/alexdebril/rss-atom-bundle/blob/29e624c428d4284726e5da5e0d245cbc93d1f17a/src/Resources/sample/Provider.php | src/Resources/sample/Provider.php | <?php
# src/Feed/provider.php
namespace App\Feed;
// this part assumes that you published "Post" entities
use App\Entity\Post;
use App\Repository\PostRepository;
// All you really need to create a feed
use Debril\RssAtomBundle\Provider\FeedProviderInterface;
use Doctrine\Bundle\DoctrineBundle\Registry;
use FeedIo\Feed;
use FeedIo\Feed\Node\Category;
use FeedIo\FeedInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Router;
class Provider implements FeedProviderInterface
{
protected $logger;
protected $registry;
protected $router;
/**
* Provider constructor.
* @param LoggerInterface $logger
* @param Registry $registry
* @param Router $router
*/
public function __construct(LoggerInterface $logger, Registry $registry, Router $router)
{
$this->logger = $logger;
$this->registry = $registry;
$this->router = $router;
}
/**
* @param array $options
* @return FeedInterface
*/
public function getFeed(Request $request) : FeedInterface
{
$feed = new Feed();
$feed->setTitle('Feed Title')
->setLink('Feed URL')
->setDescription('Feed description')
->setPublicId('Feed ID');
$lastPostPublicationDate = null;
$posts = $this->getPosts();
/**
* @var \App\Entity\Post $post
*/
foreach ($posts as $post) {
$lastPostPublicationDate = is_null($lastPostPublicationDate) ? $post->getPublicationDate():$lastPostPublicationDate;
$item = new Feed\Item();
$item->setTitle($post->getTitle());
$category = new Category();
$category->setLabel($post->getCategory());
$item->addCategory($category);
$item->setLastModified($post->getPublicationDate());
// ... and all the stuff about content, public id, etc ...
$feed->add($item);
}
// if the publication date is still empty, set it the current Date
$lastPostPublicationDate = is_null($lastPostPublicationDate) ? new \DateTime():$lastPostPublicationDate;
$feed->setLastModified($lastPostPublicationDate);
return $feed;
}
/**
* You'll need to code this
* @return array
*/
protected function getPosts()
{
return [];
}
}
| php | MIT | 29e624c428d4284726e5da5e0d245cbc93d1f17a | 2026-01-05T04:51:13.799383Z | false |
alexdebril/rss-atom-bundle | https://github.com/alexdebril/rss-atom-bundle/blob/29e624c428d4284726e5da5e0d245cbc93d1f17a/src/Provider/FeedProviderInterface.php | src/Provider/FeedProviderInterface.php | <?php declare(strict_types=1);
namespace Debril\RssAtomBundle\Provider;
use Debril\RssAtomBundle\Exception\FeedException\FeedNotFoundException;
use FeedIo\FeedInterface;
use Symfony\Component\HttpFoundation\Request;
interface FeedProviderInterface
{
/**
* @param Request $request
* @return FeedInterface
* @throws FeedNotFoundException
*/
public function getFeed(Request $request): FeedInterface;
}
| php | MIT | 29e624c428d4284726e5da5e0d245cbc93d1f17a | 2026-01-05T04:51:13.799383Z | false |
alexdebril/rss-atom-bundle | https://github.com/alexdebril/rss-atom-bundle/blob/29e624c428d4284726e5da5e0d245cbc93d1f17a/src/Provider/MockProvider.php | src/Provider/MockProvider.php | <?php declare(strict_types=1);
/**
* RssAtomBundle.
*
*
* @license http://opensource.org/licenses/lgpl-3.0.html LGPL
* @copyright (c) 2013, Alexandre Debril
*
* creation date : 31 mars 2013
*/
namespace Debril\RssAtomBundle\Provider;
use FeedIo\Feed;
use FeedIo\Feed\Item;
use Debril\RssAtomBundle\Exception\FeedException\FeedNotFoundException;
use FeedIo\FeedInterface;
use Symfony\Component\HttpFoundation\Request;
class MockProvider implements FeedProviderInterface
{
/**
* @param Request $request
* @return FeedInterface
* @throws FeedNotFoundException
*/
public function getFeed(Request $request): FeedInterface
{
$id = $request->get('id');
return $this->buildFeed($id);
}
/**
* @param string $id
* @return FeedInterface
* @throws FeedNotFoundException
*/
protected function buildFeed(string $id): FeedInterface
{
if ($id === 'not-found') {
throw new FeedNotFoundException();
}
$feed = new Feed();
$feed->setPublicId($id);
$feed->setTitle('thank you for using RssAtomBundle');
$feed->setDescription('this is the mock FeedContent');
$feed->setLink('https://raw.github.com/alexdebril/rss-atom-bundle/');
$feed->setLastModified(new \DateTime());
return $this->addItem($feed);
}
/**
* @param Feed $feed
* @return FeedInterface
* @throws \Exception
*/
protected function addItem(Feed $feed) : FeedInterface
{
$item = new Item();
$item->setPublicId('1');
$item->setLink('https://raw.github.com/alexdebril/rss-atom-bundle/somelink');
$item->setTitle('This is an item');
$item->setDescription('this stream was generated using the MockProvider class');
$item->setLastModified(new \DateTime());
$feed->add($item);
return $feed;
}
}
| php | MIT | 29e624c428d4284726e5da5e0d245cbc93d1f17a | 2026-01-05T04:51:13.799383Z | false |
alexdebril/rss-atom-bundle | https://github.com/alexdebril/rss-atom-bundle/blob/29e624c428d4284726e5da5e0d245cbc93d1f17a/tests/bootstrap.php | tests/bootstrap.php | <?php
/**
* Rss/Atom Bundle for Symfony.
*
*
* @license http://opensource.org/licenses/lgpl-3.0.html LGPL
* @copyright (c) 2013, Alexandre Debril
*/
$file = __DIR__.'/../../../../../../vendor/autoload.php';
if (!file_exists($file)) {
$file = __DIR__.'/../vendor/autoload.php';
}
if (!file_exists($file)) {
throw new RuntimeException('Install dependencies to run test suite.');
}
$autoload = require $file;
\Doctrine\Common\Annotations\AnnotationRegistry::registerLoader(array($autoload, 'loadClass'));
spl_autoload_register(function ($class) {
if (0 === strpos($class, 'Debril\\RssAtomBundle\\')) {
$path = __DIR__.'/../'.implode('/', array_slice(explode('\\', $class), 2)).'.php';
if (!stream_resolve_include_path($path)) {
return false;
}
require_once $path;
return true;
}
});
| php | MIT | 29e624c428d4284726e5da5e0d245cbc93d1f17a | 2026-01-05T04:51:13.799383Z | false |
alexdebril/rss-atom-bundle | https://github.com/alexdebril/rss-atom-bundle/blob/29e624c428d4284726e5da5e0d245cbc93d1f17a/tests/Controller/StreamControllerTest.php | tests/Controller/StreamControllerTest.php | <?php
namespace Debril\RssAtomBundle\Tests\Controller;
use FeedIo\Reader\Document;
use FeedIo\Rule\DateTimeBuilder;
use FeedIo\Standard\Atom;
use FeedIo\Standard\Json;
use FeedIo\Standard\Rss;
use Psr\Log\NullLogger;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
/**
* Class StreamControllerTest.
*/
class StreamControllerTest extends WebTestCase
{
public function testIndex()
{
$client = static::createClient();
$client->request('GET', '/mock/rss/id');
$response = $client->getResponse();
$this->assertEquals('200', $response->getStatusCode());
$lastModified = $response->getLastModified();
$lastModified->setTimezone(
new \DateTimeZone(date_default_timezone_get())
);
$lastModified->add(new \DateInterval('PT10S'));
$this->assertInstanceOf('\DateTime', $lastModified);
$this->assertGreaterThan(0, $response->getMaxAge());
$this->assertGreaterThan(0, strlen($response->getContent()));
$this->assertTrue($response->isCacheable());
$client->request('GET', '/mock/rss/id', array(), array(), array('HTTP_If-Modified-Since' => $lastModified->format(\DateTime::RSS)));
$response2 = $client->getResponse();
$this->assertEquals('304', $response2->getStatusCode());
$this->assertEquals(0, strlen($response2->getContent()));
}
public function testGetAtom()
{
$client = static::createClient();
$client->request('GET', '/atom/1');
$response = $client->getResponse();
$this->assertEquals('200', $response->getStatusCode());
$this->assertEquals('application/xhtml+xml', $response->headers->get('content-type'));
$atom = new Document($response->getContent());
$standard = new Atom(new DateTimeBuilder(new NullLogger()));
$this->assertTrue($standard->canHandle($atom));
}
public function testGetRss()
{
$client = static::createClient();
$client->request('GET', '/rss/1');
$response = $client->getResponse();
$this->assertEquals('200', $response->getStatusCode());
$this->assertEquals('application/xhtml+xml', $response->headers->get('content-type'));
$rss = new Document($response->getContent());
$standard = new Rss(new DateTimeBuilder(new NullLogger()));
$this->assertTrue($standard->canHandle($rss));
}
public function testGetJson()
{
$client = static::createClient();
$client->request('GET', '/json/1');
$response = $client->getResponse();
$this->assertEquals('200', $response->getStatusCode());
$this->assertEquals('application/json', $response->headers->get('content-type'));
$json = new Document($response->getContent());
$standard = new Json(new DateTimeBuilder(new NullLogger()));
$this->assertTrue($standard->canHandle($json));
}
/**
* @expectedException \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
*/
public function testNotFound()
{
$client = static::createClient();
$client->request('GET', '/mock/rss/not-found');
}
/**
* @expectedException \Exception
*/
public function testBadProvider()
{
$client = static::createClient();
$client->request('GET', '/bad/provider');
}
}
| php | MIT | 29e624c428d4284726e5da5e0d245cbc93d1f17a | 2026-01-05T04:51:13.799383Z | false |
alexdebril/rss-atom-bundle | https://github.com/alexdebril/rss-atom-bundle/blob/29e624c428d4284726e5da5e0d245cbc93d1f17a/tests/Controller/App/AppKernel.php | tests/Controller/App/AppKernel.php | <?php
// Tests/Controller/App/AppKernel.php
namespace Debril\RssAtomBundle\Tests\Controller\App;
use \Symfony\Component\HttpKernel\Bundle\Bundle;
use \Symfony\Component\HttpKernel\Kernel;
use \Symfony\Component\Config\Loader\LoaderInterface;
/**
* Class AppKernel.
*/
class AppKernel extends Kernel
{
/**
* @return Bundle[]
*/
public function registerBundles()
{
$bundles = array(
// Dependencies
new \Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
// My Bundle to test
new \Debril\RssAtomBundle\DebrilRssAtomBundle(),
);
return $bundles;
}
/**
* @param LoaderInterface $loader
*/
public function registerContainerConfiguration(LoaderInterface $loader)
{
// We don't need that Environment stuff, just one config
$loader->load(__DIR__.'/config.yml');
}
}
| php | MIT | 29e624c428d4284726e5da5e0d245cbc93d1f17a | 2026-01-05T04:51:13.799383Z | false |
alexdebril/rss-atom-bundle | https://github.com/alexdebril/rss-atom-bundle/blob/29e624c428d4284726e5da5e0d245cbc93d1f17a/tests/Request/ModifiedSinceTest.php | tests/Request/ModifiedSinceTest.php | <?php
namespace Debril\RssAtomBundle\Tests\Request;
use Debril\RssAtomBundle\Request\ModifiedSince;
use PHPUnit\Framework\TestCase;
use Psr\Log\NullLogger;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
class ModifiedSinceTest extends TestCase
{
public function testGetValue()
{
$stack = new RequestStack();
$request = new Request();
$date = new \DateTime('2018-06-01');
$request->headers->set('If-Modified-Since', $date->format(\DATE_RSS));
$stack->push($request);
$modifiedSince = new ModifiedSince($stack, new NullLogger());
$this->assertEquals($date, $modifiedSince->getValue());
}
public function testGetBadValue()
{
$stack = new RequestStack();
$request = new Request();
$request->headers->set('If-Modified-Since', 'something that is not a date');
$stack->push($request);
$modifiedSince = new ModifiedSince($stack, new NullLogger());
$this->assertInstanceOf('\DateTime', $modifiedSince->getValue());
}
public function testGetEmptyArrayValue()
{
$stack = new RequestStack();
$request = new Request();
$request->headers->set('If-Modified-Since', array());
$stack->push($request);
$modifiedSince = new ModifiedSince($stack, new NullLogger());
$this->assertInstanceOf('\DateTime', $modifiedSince->getValue());
}
public function testGetValueInArray()
{
$stack = new RequestStack();
$request = new Request();
$date = new \DateTime('2018-06-01');
$request->headers->set('If-Modified-Since', [$date->format(\DATE_RSS)]);
$stack->push($request);
$modifiedSince = new ModifiedSince($stack, new NullLogger());
$this->assertEquals($date, $modifiedSince->getValue());
}
}
| php | MIT | 29e624c428d4284726e5da5e0d245cbc93d1f17a | 2026-01-05T04:51:13.799383Z | false |
alexdebril/rss-atom-bundle | https://github.com/alexdebril/rss-atom-bundle/blob/29e624c428d4284726e5da5e0d245cbc93d1f17a/tests/DependencyInjection/ConfigurationTest.php | tests/DependencyInjection/ConfigurationTest.php | <?php
namespace Debril\RssAtomBundle\Tests\DependencyInjection;
use Debril\RssAtomBundle\DependencyInjection\Configuration;
use PHPUnit\Framework\TestCase;
class ConfigurationTest extends TestCase
{
public function testGetConfigTreeBuilder()
{
$configuration = new Configuration();
$tree = $configuration->getConfigTreeBuilder();
$this->assertInstanceOf('\Symfony\Component\Config\Definition\Builder\TreeBuilder', $tree);
}
}
| php | MIT | 29e624c428d4284726e5da5e0d245cbc93d1f17a | 2026-01-05T04:51:13.799383Z | false |
alexdebril/rss-atom-bundle | https://github.com/alexdebril/rss-atom-bundle/blob/29e624c428d4284726e5da5e0d245cbc93d1f17a/tests/Response/FeedBuilderTest.php | tests/Response/FeedBuilderTest.php | <?php
namespace Debril\RssAtomBundle\Tests\Response;
use Debril\RssAtomBundle\Request\ModifiedSince;
use Debril\RssAtomBundle\Response\FeedBuilder;
use Debril\RssAtomBundle\Response\HeadersBuilder;
use FeedIo\Factory;
use FeedIo\Feed;
use FeedIo\FeedIo;
use PHPUnit\Framework\TestCase;
use Psr\Log\NullLogger;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
class FeedBuilderTest extends TestCase
{
/**
* @var FeedIo
*/
private $feedIo;
/**
* @var HeadersBuilder
*/
private $headersBuilder;
/**
* @var ModifiedSince
*/
private $modifiedSince;
public function setUp()
{
$stack = new RequestStack();
$request = new Request();
$stack->push($request);
$this->feedIo = Factory::create()->getFeedIo();
$this->headersBuilder = new HeadersBuilder();
$this->modifiedSince = new ModifiedSince($stack, new NullLogger());
parent::setUp();
}
public function testGetResponse()
{
$feedBuilder = new FeedBuilder($this->feedIo, $this->headersBuilder, $this->modifiedSince);
$response = $feedBuilder->getResponse('atom', $this->getFeed());
$this->assertEquals('200', $response->getStatusCode());
}
private function getFeed(): Feed
{
$feed = new Feed();
$feed->setTitle('rss-atom');
$feed->setPublicId('http://public-id');
$feed->setLink('http://link');
$feed->setLastModified(new \DateTime('2018-06-01'));
$item = new Feed\Item();
$item->setLastModified(new \DateTime('2018-06-01'));
$item->setDescription("lorem ipsum");
$item->setTitle('title');
$feed->add($item);
return $feed;
}
}
| php | MIT | 29e624c428d4284726e5da5e0d245cbc93d1f17a | 2026-01-05T04:51:13.799383Z | false |
alexdebril/rss-atom-bundle | https://github.com/alexdebril/rss-atom-bundle/blob/29e624c428d4284726e5da5e0d245cbc93d1f17a/tests/Response/HeadersBuilderTest.php | tests/Response/HeadersBuilderTest.php | <?php declare(strict_types=1);
namespace Debril\RssAtomBundle\Tests\Response;
use Debril\RssAtomBundle\Response\HeadersBuilder;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Response;
class HeadersBuilderTest extends TestCase
{
public function testSetResponseHeadersPublic()
{
$builder = new HeadersBuilder();
$response = new Response();
$builder->setResponseHeaders($response, 'xml', new \DateTime());
$this->assertTrue($response->headers->getCacheControlDirective('public'));
$this->assertEquals(3600, $response->getMaxAge());
}
public function testSetResponseHeadersPrivate()
{
$builder = new HeadersBuilder(false, 30);
$response = new Response();
$builder->setResponseHeaders($response, 'xml', new \DateTime());
$this->assertTrue($response->headers->getCacheControlDirective('private'));
$this->assertEquals(30, $response->getMaxAge());
}
public function testSetLastModified()
{
$builder = new HeadersBuilder();
$response = new Response();
$date = new \DateTime('2018-01-01');
$builder->setResponseHeaders($response, 'xml', $date);
$this->assertEquals($date, $response->getLastModified());
}
}
| php | MIT | 29e624c428d4284726e5da5e0d245cbc93d1f17a | 2026-01-05T04:51:13.799383Z | false |
alexdebril/rss-atom-bundle | https://github.com/alexdebril/rss-atom-bundle/blob/29e624c428d4284726e5da5e0d245cbc93d1f17a/tests/Provider/MockProviderTest.php | tests/Provider/MockProviderTest.php | <?php
namespace Debril\RssAtomBundle\Tests\Provider;
use Debril\RssAtomBundle\Provider\MockProvider;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
/**
* Generated by PHPUnit_SkeletonGenerator 1.2.0 on 2013-01-25 at 23:47:50.
*/
class MockProviderTest extends TestCase
{
/**
* @var MockProvider
*/
protected $object;
/**
* Sets up the fixture, for example, opens a network connection.
* This method is called before a test is executed.
*/
protected function setUp()
{
$this->object = new MockProvider();
}
/**
* Tears down the fixture, for example, closes a network connection.
* This method is called after a test is executed.
*/
protected function tearDown()
{
}
/**
* @covers Debril\RssAtomBundle\Provider\MockProvider::getFeed
*/
public function testGetContent()
{
$request = new Request(['id' => 'some-id']);
$feed = $this->object->getFeed($request);
$this->assertInstanceOf('FeedIo\FeedInterface', $feed);
}
/**
* @covers Debril\RssAtomBundle\Provider\MockProvider::getFeed
* @expectedException \Debril\RssAtomBundle\Exception\FeedException\FeedNotFoundException
*/
public function testGet404()
{
$request = new Request(['id' => 'not-found']);
$feed = $this->object->getFeed($request);
$this->object->getFeed($request);
}
}
| php | MIT | 29e624c428d4284726e5da5e0d245cbc93d1f17a | 2026-01-05T04:51:13.799383Z | false |
sproctor/php-calendar | https://github.com/sproctor/php-calendar/blob/e9473676f311aac8e9577cb3371ed362418441d9/index.php | index.php | <?php
/*
* Copyright 2012 Sean Proctor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* The following variables are intended to be modified to fit your
* setup.
*/
/*
* If you want different scripts with different default calendars, you can
* copy this script and modify $default_calendar_id to contain the CID of
* the calendar you want to be the default
*/
$default_calendar_id = 1;
/*
* $phpc_root_path gives the location of the base calendar install.
* if you move this file to a new location, modify $phpc_root_path to point
* to the location where the support files for the calendar are located.
*/
$phpc_root_path = dirname(__FILE__);
$phpc_includes_path = "$phpc_root_path/src";
$phpc_config_file = "$phpc_root_path/config.php";
$phpc_locale_path = "$phpc_root_path/locale";
$phpc_script = htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES, 'UTF-8');
$phpc_server = $_SERVER['SERVER_NAME'];
if(!empty($_SERVER["SERVER_PORT"]) && $_SERVER["SERVER_PORT"] != 80)
$phpc_server .= ":{$_SERVER["SERVER_PORT"]}";
// Protcol ex. http or https
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off'
|| $_SERVER['SERVER_PORT'] == 443
|| isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https'
|| isset($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') {
$phpc_proto = "https";
} else {
$phpc_proto = "http";
}
$phpc_home_url="$phpc_proto://$phpc_server$phpc_script";
$phpc_url = $phpc_home_url . (empty($_SERVER['QUERY_STRING']) ? ''
: '?' . $_SERVER['QUERY_STRING']);
// Remove this line if you must
ini_set('arg_separator.output', '&');
/*
* Do not modify anything under this point
*/
if (!defined('IN_PHPC'))
define('IN_PHPC', true);
try {
require_once("$phpc_includes_path/calendar.php");
require_once("$phpc_includes_path/setup.php");
$calendar_title = $phpc_cal->get_title();
$content = display_phpc();
} catch(Exception $e) {
$calendar_title = $e->getMessage();
$content = tag('div', attributes('class="php-calendar"'),
$e->getMessage());
}
$html = tag('html', attrs("lang=\"$phpc_lang\""),
tag('head',
tag('title', $calendar_title),
tag('link', attrs('rel="icon"',
"href=\"static/office-calendar.png\"")),
get_header_tags("static"),
tag('meta', attrs('http-equiv="Content-Type"',
'content="text/html; charset=UTF-8"'))),
tag('body', $content));
echo '<!DOCTYPE html>', "\n", $html->toString();
| php | Apache-2.0 | e9473676f311aac8e9577cb3371ed362418441d9 | 2026-01-05T04:51:20.275579Z | false |
sproctor/php-calendar | https://github.com/sproctor/php-calendar/blob/e9473676f311aac8e9577cb3371ed362418441d9/install.php | install.php | <?php
/*
* Copyright 2014 Sean Proctor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
Run this file to install the calendar
it needs very much work
*/
$phpc_db_version = 1;
$phpc_root_path = dirname(__FILE__);
$phpc_includes_path = "$phpc_root_path/includes";
$phpc_config_file = "$phpc_root_path/config.php";
define('IN_PHPC', true);
if(!function_exists("mysqli_connect"))
soft_error("You must have the mysqli extension for PHP installed to use this calendar.");
echo '<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="stylesheet" type="text/css" href="static/phpc.css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<title>PHP Calendar Installation</title>
</head>
<body>
<h1>PHP Calendar</h1>';
$must_upgrade = false;
if(file_exists($phpc_config_file)) {
require_once $phpc_config_file;
if(defined("SQL_HOST")) {
$dbh = connect_db(SQL_HOST, SQL_USER, SQL_PASSWD, SQL_DATABASE);
$query = "SELECT *\n"
."FROM `" . SQL_PREFIX . "calendars`\n";
$sth = $dbh->query($query);
$have_calendar = $sth && $sth->fetch_assoc();
$existing_version = 0;
$query = "SELECT version\n"
."FROM `" . SQL_PREFIX . "version`\n";
$sth = $dbh->query($query);
if($sth) {
$result = $sth->fetch_assoc();
if(!empty($result['version']))
$existing_version = $result['version'];
}
if($have_calendar) {
$must_upgrade = true;
if($existing_version > $phpc_db_version) {
echo "<p>DB version is newer than the upgrader.</p>";
exit;
} elseif($existing_version == $phpc_db_version) {
echo '<p>The calendar has already been installed. <a href="index.php">Installed calendar</a></p>';
echo '<p>If you want to install again, manually delete config.php</p>';
exit;
}
}
}
}
echo '<p>Welcome to the PHP Calendar installation process.</p>
<form method="post" action="install.php">
';
foreach($_POST as $key => $value) {
echo "<input name=\"$key\" value=\"$value\" type=\"hidden\">\n";
}
$drop_tables = isset($_POST["drop_tables"]) && $_POST["drop_tables"] == "yes";
if(empty($_POST['action'])) {
get_action();
} elseif($_POST['action'] == 'upgrade') {
if(empty($_POST['version'])) {
get_upgrade_version();
} else {
if ($_POST['version'] == "2.0rc2") {
upgrade_20rc2();
echo "<p>Update complete.</p>";
} elseif ($_POST['version'] == "2.0beta11") {
upgrade_20beta11();
echo "<p>Update complete.</p>";
} elseif($_POST['version'] == "2.0beta10") {
upgrade_20beta10();
echo "<p>Update complete.</p>";
} elseif($_POST['version'] == "2.0beta9") {
if(empty($_POST['timezone']))
upgrade_20_form();
else
upgrade_20_action();
} elseif($_POST['version'] == "1.1") {
echo "<p>You must first install the calendar into a new location, then import the old events through the Admin section.</p>";
} else {
echo "<p>Invalid version identifier.</p>";
}
}
} elseif(!isset($_POST['my_hostname'])
&& !isset($_POST['my_username'])
&& !isset($_POST['my_passwd'])
&& !isset($_POST['my_prefix'])
&& !isset($_POST['my_database'])) {
get_server_setup();
} elseif((isset($_POST['create_user']) || isset($_POST['create_db']))
&& !isset($_POST['done_user_db'])) {
add_sql_user_db();
} elseif(!isset($_POST['base'])) {
install_base();
} elseif(!isset($_POST['admin_user'])
&& !isset($_POST['admin_pass'])) {
get_admin();
} else {
add_calendar();
}
function get_action() {
echo '<input type="submit" name="action" value="install"/><span style="display: inline-block; width:50px;"></span>';
echo '<input type="submit" name="action" value="upgrade"/>';
}
function get_upgrade_version() {
global $phpc_config_file;
if(!file_exists($phpc_config_file)) {
echo '<p><span style="font-weight:bold;">ERROR</span>: You must copy over your config.php from the version you are updating. Only versions 2.0 beta4 and later are supported.';
echo '<br/><input type="button" onclick="window.location.reload()" value="Reload"/>';
return;
}
echo '<h3>Pick the version you are updating from</h3>';
echo '<input type="hidden" name="action" value="upgrade"/>';
echo '<select name="version">';
echo '<option value="1.1">version 1.1</option>';
echo '<option value="2.0beta9">version 2.0-beta4 to beta9</option>';
echo '<option value="2.0beta10">version 2.0-beta10</option>';
echo '<option value="2.0beta11">version 2.0-beta11 to rc1</option>';
echo '<option value="2.0rc2">version 2.0-rc2</option>';
echo '</select><span style="display: inline-block; width:50px;"></span>';
echo '<input type="submit" value="Submit">';
}
function upgrade_20_form() {
echo '<div>Timezone: <select name="timezone">';
foreach(timezone_identifiers_list() as $timezone) {
echo "<option value=\"$timezone\">$timezone</option>\n";
}
echo "</select></div>";
echo "<input type=\"submit\" value=\"Submit\"/>";
}
function upgrade_20_action() {
global $phpc_config_file, $dbh;
$query = "ALTER TABLE `" . SQL_PREFIX . "users`\n"
."ADD `password_editable` tinyint(1) NOT NULL DEFAULT '1',\n"
."ADD `timezone` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n"
."ADD `language` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL\n";
$dbh->query($query)
or db_error($dbh, 'Error adding elements to users table.', $query);
$query = "ALTER TABLE `" . SQL_PREFIX . "occurrences`\n"
."ADD `start_ts` timestamp NULL default NULL,\n"
."ADD `end_ts` timestamp NULL default NULL,\n"
."CHANGE `startdate` `start_date` date default NULL,\n"
."CHANGE `enddate` `end_date` date default NULL,\n"
."CHANGE `timetype` `time_type` tinyint(4) NOT NULL default '0'\n";
$dbh->query($query)
or db_error($dbh, 'Error adding elements to occurrences table.',
$query);
echo "<p>Occurrences table update";
$query = "SELECT `oid`, YEAR(`start_date`) AS `start_year`, "
."MONTH(`start_date`) AS `start_month`, "
."DAY(`start_date`) AS `start_day`, "
."HOUR(`starttime`) AS `start_hour`, "
."MINUTE(`starttime`) AS `start_minute`, "
."SECOND(`starttime`) AS `start_second`, "
."YEAR(`end_date`) AS `end_year`, "
."MONTH(`end_date`) AS `end_month`, "
."DAY(`end_date`) AS `end_day`, "
."HOUR(`endtime`) AS `end_hour`, "
."MINUTE(`endtime`) AS `end_minute`, "
."SECOND(`endtime`) AS `end_second` "
."FROM `" . SQL_PREFIX . "occurrences`\n";
$occ_result = $dbh->query($query)
or db_error($dbh, 'Error selecting old occurrences.', $query);
while($row = $occ_result->fetch_assoc()) {
if($row['start_hour'] !== NULL) {
$start_ts = mktime($row['start_hour'],
$row['start_minute'],
$row['start_second'],
$row['start_month'],
$row['start_day'],
$row['start_year']);
$end_ts = mktime($row['end_hour'],
$row['end_minute'],
$row['end_second'],
$row['end_month'],
$row['end_day'],
$row['end_year']);
$query = "UPDATE `" . SQL_PREFIX . "occurrences`\n"
. "SET `start_date` = NULL, "
. "`start_ts` = FROM_UNIXTIME($start_ts), "
. "`end_ts` = FROM_UNIXTIME($end_ts)\n"
. "WHERE `oid` = {$row['oid']}";
$dbh->query($query)
or db_error($dbh, 'Error updating occurrences.',
$query);
}
}
echo "<p>Occurrences updated.</p>";
upgrade_20beta10();
echo "<p>Update complete.</p>";
}
function upgrade_20beta10() {
create_logins_table();
upgrade_20beta11();
}
function upgrade_20beta11() {
add_event_time();
add_calendar_config();
add_categories_gid();
echo "<p>Adding groups table.</p>";
create_table("groups",
"`gid` int(11) NOT NULL AUTO_INCREMENT,\n"
."`cid` int(11),\n"
."`name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n"
."PRIMARY KEY (`gid`)\n");
echo "<p>Adding user_groups table.</p>";
create_table("user_groups",
"`gid` int(11),\n"
."`uid` int(11)\n");
create_version_table();
upgrade_20rc2();
}
function upgrade_20rc2()
{
global $dbh;
$query = "ALTER TABLE `" . SQL_PREFIX . "users`\n"
."ADD `gid` int(11)\n";
$dbh->query($query)
or db_error($dbh, 'Error adding elements to users table.', $query);
}
function add_categories_gid() {
global $dbh;
echo "<p>Adding gid to categories</p>";
$query = "ALTER TABLE `" . SQL_PREFIX . "categories`\n"
."ADD `gid` int(11) unsigned DEFAULT NULL";
$dbh->query($query)
or db_warning($dbh, 'Error adding gid to categories table.',
$query);
}
function add_event_time() {
global $dbh;
phpc_debug("Adding \"ctime\" and \"mtime\" columns.");
$query = "ALTER TABLE `" . SQL_PREFIX . "events`\n"
."ADD `ctime` timestamp NOT NULL default CURRENT_TIMESTAMP,\n"
."ADD `mtime` timestamp NULL default NULL";
$dbh->query($query)
or db_warning($dbh, 'Error adding time elements to events table.',
$query);
}
function add_calendar_config() {
global $dbh;
$query = "ALTER TABLE `" . SQL_PREFIX . "calendars`\n"
."ADD `hours_24` tinyint(1) NOT NULL DEFAULT 0,\n"
."ADD `date_format` tinyint(1) NOT NULL DEFAULT 0,\n"
."ADD `week_start` tinyint(1) NOT NULL DEFAULT 0,\n"
."ADD `subject_max` smallint(5) unsigned NOT NULL DEFAULT 50,\n"
."ADD `events_max` tinyint(3) unsigned NOT NULL DEFAULT 8,\n"
."ADD `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'PHP-Calendar',\n"
."ADD `anon_permission` tinyint(1) NOT NULL DEFAULT 1,\n"
."ADD `timezone` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n"
."ADD `language` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n"
."ADD `theme` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL";
$dbh->query($query)
or db_warning($dbh, 'Error adding time elements to events table.',
$query);
}
function create_version_table() {
global $phpc_db_version, $dbh;
create_table("version",
"`version` SMALLINT unsigned NOT NULL DEFAULT '$phpc_db_version'");
$query = "REPLACE INTO `" . SQL_PREFIX . "version`\n"
."SET `version`='$phpc_db_version'";
$dbh->query($query)
or db_error($dbh, 'Error creating version row.', $query);
}
function check_config()
{
global $phpc_config_file;
if(is_writable($phpc_config_file))
return true;
// Check if we can create the file
if($file = @fopen($phpc_config_file, 'a')) {
fclose($file);
return true;
}
return false;
}
function report_config()
{
echo '<p>Your configuration file could not be written to. This file '
.'probably does not yet exist. If that is the case, you need to '
.'create it. You need to make sure this script can write to '
.'it. We suggest logging in with a shell and typing:</p>
<pre>
touch config.php
chmod 666 config.php
</pre>
<p>or if you only have ftp access, upload a blank file named '
.'config.php to your php-calendar directory then use the chmod '
.'command to change the permissions of config.php to 666.</p>
<p><input type="submit" value="Retry"/></p>';
}
function get_server_setup()
{
if(!check_config())
return report_config();
echo '
<h3>Step 1: Database</h3>
<table class="display">
<tr>
<td><label for="my_hostname">SQL Server Hostname:</label></td>
<td><input type="text" name="my_hostname" id="my_hostname" value="localhost"></td>
</tr>
<tr>
<td><label for="my_database">SQL Database name:</label></td>
<td><input type="text" name="my_database" id="my_database" value="calendar"></td>
</tr>
<tr>
<td><label for="my_prefix">SQL Table prefix:</label></td>
<td><input type="text" name="my_prefix" id="my_prefix" value="phpc_"></td>
</tr>
<tr>
<td><label for="my_username">SQL Username:</label></td>
<td><input type="text" name="my_username" id="my_username" value="calendar"></td>
</tr>
<tr>
<td><label for="my_passwd">SQL Password:</label></td>
<td><input type="password" name="my_passwd" id="my_passwd"></td>
</tr>
<tr>
<td colspan="2">
<input type="checkbox" name="create_db" id="create_db" value="yes"/>
<label for="create_db">Create the database (don\'t check this if it already exists)</label>
</td>
</tr>
<tr>
<td colspan="2">
<input type="checkbox" name="drop_tables" id="drop_tables" value="yes">
<label for="drop_tables">Drop tables before creating them</label>
</td>
</tr>
<tr><td colspan="2">
<span style="font-weight:bold;">Optional: user creation on database</span>
</td></tr>
<tr><td colspan="2">
If the credentials supplied above are new, you have to be the database administrator.
</td></tr>
<tr><td colspan="2">
<input type="checkbox" name="create_user" id="create_user" value="yes">
<label for="create_user">Check this if you want to do it and provide admin user and password.</label>
</td></tr>
<tr>
<td><label for="my_adminname">SQL Admin name:</label></td>
<td><input type="text" name="my_adminname" id="my_adminname"></td>
</tr>
<tr>
<td><label for="my_adminpasswd">SQL Admin Password:</label></td>
<td><input type="password" name="my_adminpasswd" id="my_adminpasswd"></td>
</tr>
<tr>
<td colspan="2">
<input name="action" type="submit" value="Install">
</td>
</tr>
</table>';
}
function add_sql_user_db()
{
global $dbh;
$my_hostname = $_POST['my_hostname'];
$my_username = $_POST['my_username'];
$my_passwd = $_POST['my_passwd'];
$my_prefix = $_POST['my_prefix'];
$my_database = $_POST['my_database'];
$my_adminname = $_POST['my_adminname'];
$my_adminpasswd = $_POST['my_adminpasswd'];
$create_user = isset($_POST['create_user'])
&& $_POST['create_user'] == 'yes';
$create_db = isset($_POST['create_db']) && $_POST['create_db'] == 'yes';
// Make the database connection.
if($create_user) {
$dbh = connect_db($my_hostname, $my_adminname, $my_adminpasswd);
} else {
$dbh = connect_db($my_hostname, $my_username, $my_passwd);
}
$string = "<h3>Step 2: Database Setup</h3>";
if($create_db) {
phpc_debug("Creating database \"$my_database\".");
$query = "CREATE DATABASE $my_database";
$dbh->query($query)
or db_error($dbh, 'error creating db', $query);
$string .= "<p>Successfully created database</p>";
}
if($create_user) {
phpc_debug("Creating user \"$my_username\".");
$query = "GRANT ALL ON accounts.* TO $my_username@$my_hostname identified by '$my_passwd'";
$dbh->query($query)
or db_error($dbh, 'Could not grant:', $query);
$query = "GRANT ALL ON $my_database.*\n"
."TO $my_username IDENTIFIED BY '$my_passwd'";
$dbh->query($query)
or db_error($dbh, 'Could not grant:', $query);
$query = "FLUSH PRIVILEGES";
$dbh->query($query)
or db_error($dbh, "Could not flush privileges", $query);
$string .= "<p>Successfully added user</p>";
}
echo "$string\n"
."<div><input type=\"submit\" name=\"done_user_db\" value=\"continue\"/>"
."</div>\n";
}
function install_base()
{
global $phpc_config_file, $dbh;
$sql_type = "mysqli";
$sql_hostname = $_POST['my_hostname'];
$sql_username = $_POST['my_username'];
$sql_passwd = $_POST['my_passwd'];
$sql_prefix = $_POST['my_prefix'];
$sql_database = $_POST['my_database'];
$fp = fopen($phpc_config_file, 'w')
or soft_error('Couldn\'t open config file.');
// Make the database connection.
$dbh = connect_db($sql_hostname, $sql_username, $sql_passwd, $sql_database);
phpc_debug("Writing config file \"$phpc_config_file\".");
$defines = "define('SQL_HOST', '$sql_hostname');\n"
."define('SQL_USER', '$sql_username');\n"
."define('SQL_PASSWD', '$sql_passwd');\n"
."define('SQL_DATABASE', '$sql_database');\n"
."define('SQL_PREFIX', '$sql_prefix');\n"
."define('SQL_TYPE', '$sql_type');\n";
fwrite($fp, "<"."?php\n$defines?".">\n") // Break this up to fix syntax HL in vim
or soft_error("Could not write to file");
fclose($fp);
eval($defines);
create_tables();
echo "<p>Config file created at \"". realpath($phpc_config_file) ."\"</p>"
."<p>Calendars database created</p>\n"
."<div><input type=\"submit\" name=\"base\" value=\"continue\">"
."</div>\n";
}
function create_tables()
{
global $dbh;
create_table("events",
"`eid` int(11) unsigned NOT NULL auto_increment,\n"
."`cid` int(11) unsigned NOT NULL,\n"
."`owner` int(11) unsigned NOT NULL default 0,\n"
."`subject` varchar(255) collate utf8_unicode_ci NOT NULL,\n"
."`description` text collate utf8_unicode_ci NOT NULL,\n"
."`readonly` tinyint(1) NOT NULL default 0,\n"
."`catid` int(11) unsigned default NULL,\n"
."`ctime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,\n"
."`mtime` timestamp NULL DEFAULT NULL,\n"
."PRIMARY KEY (`eid`)\n",
"AUTO_INCREMENT=1");
create_table("occurrences",
"`oid` int(11) unsigned NOT NULL auto_increment,\n"
."`eid` int(11) unsigned NOT NULL,\n"
."`start_date` date default NULL,\n"
."`end_date` date default NULL,\n"
."`start_ts` timestamp NULL default NULL,\n"
."`end_ts` timestamp NULL default NULL,\n"
."`time_type` tinyint(4) NOT NULL default '0',\n"
."PRIMARY KEY (`oid`),\n"
."KEY `eid` (`eid`)\n",
"AUTO_INCREMENT=1");
create_table("users",
"`uid` int(11) unsigned NOT NULL auto_increment,\n"
."`username` varchar(32) collate utf8_unicode_ci NOT NULL,\n"
."`password` varchar(32) collate utf8_unicode_ci NOT NULL default '',\n"
."`admin` tinyint(4) NOT NULL DEFAULT '0',\n"
."`password_editable` tinyint(1) NOT NULL DEFAULT '1',\n"
."`timezone` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n"
."`language` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n"
."`gid` int(11),\n"
."PRIMARY KEY (`uid`),\n"
."UNIQUE KEY `username` (`username`)\n",
"AUTO_INCREMENT=1");
// added in 2.0-rc3
create_table("groups",
"`gid` int(11) NOT NULL AUTO_INCREMENT,\n"
."`cid` int(11),\n"
."`name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n"
."PRIMARY KEY (`gid`)\n");
// added in 2.0-rc3
create_table("user_groups",
"`gid` int(11),\n"
."`uid` int(11)\n");
create_logins_table();
create_table("permissions",
"`cid` int(11) unsigned NOT NULL,\n"
."`uid` int(11) unsigned NOT NULL,\n"
."`read` tinyint(1) NOT NULL,\n"
."`write` tinyint(1) NOT NULL,\n"
."`readonly` tinyint(1) NOT NULL,\n"
."`modify` tinyint(1) NOT NULL,\n"
."`admin` tinyint(1) NOT NULL,\n"
."UNIQUE KEY `cid` (`cid`,`uid`)\n");
create_table("calendars",
"`cid` int(11) unsigned NOT NULL auto_increment,\n"
."`hours_24` tinyint(1) NOT NULL DEFAULT 0,\n"
."`date_format` tinyint(1) NOT NULL DEFAULT 0,\n"
."`week_start` tinyint(1) NOT NULL DEFAULT 0,\n"
."`subject_max` smallint(5) unsigned NOT NULL DEFAULT 50,\n"
."`events_max` tinyint(4) unsigned NOT NULL DEFAULT 8,\n"
."`title` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'PHP-Calendar',\n"
."`anon_permission` tinyint(1) NOT NULL DEFAULT 1,\n"
."`timezone` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n"
."`language` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n"
."`theme` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n"
."PRIMARY KEY (`cid`)\n",
"AUTO_INCREMENT=1");
create_table("categories",
"`catid` int(11) unsigned NOT NULL auto_increment,\n"
."`cid` int(11) unsigned NOT NULL,\n"
."`gid` int(11) unsigned DEFAULT NULL,\n"
."`name` varchar(255) collate utf8_unicode_ci NOT NULL,\n"
."`text_color` varchar(255) collate utf8_unicode_ci default NULL,\n"
."`bg_color` varchar(255) collate utf8_unicode_ci default NULL,\n"
."PRIMARY KEY (`catid`),\n"
."KEY `cid` (`cid`)\n",
"AUTO_INCREMENT=1");
create_version_table();
}
function get_admin()
{
echo '<h3>Step 4: Administration account</h3>';
echo "<table>\n"
."<tr><td colspan=\"2\">Now you must create the calendar administrative "
."account.</td></tr>\n"
."<tr><td>\n"
."Admin name:\n"
."</td><td>\n"
."<input type=\"text\" name=\"admin_user\" />\n"
."</td></tr><tr><td>\n"
."Admin password:"
."</td><td>\n"
."<input type=\"password\" name=\"admin_pass\" />\n"
."</td></tr><tr><td colspan=\"2\">"
."<input type=\"submit\" value=\"Create Admin Account\" />\n"
."</td></tr></table>\n";
}
function add_calendar()
{
global $dbh, $phpc_config_file;
$calendar_title = 'PHP-Calendar';
// Make the database connection.
$dbh = connect_db(SQL_HOST, SQL_USER, SQL_PASSWD, SQL_DATABASE);
$query = "INSERT INTO ".SQL_PREFIX."calendars\n"
."(`cid`) VALUE (1)";
$dbh->query($query)
or db_error($dbh, 'Error reading options', $query);
$cid = $dbh->insert_id;
echo "<h3>Final Step</h3>\n";
echo "<p>Saved default configuration</p>\n";
$passwd = md5($_POST['admin_pass']);
$query = "INSERT INTO `" . SQL_PREFIX . "users`\n"
."(`username`, `password`, `admin`) VALUES\n"
."('$_POST[admin_user]', '$passwd', 1)";
$dbh->query($query)
or db_error($dbh, 'Error adding admin.', $query);
echo "<p>Admin account created.</p>";
echo "<p>Now you should delete install.php file from root directory (for security reasons).</p>";
echo "<p>You should also change the permissions on config.php so only your webserver can read it.</p>";
echo "<p><a href=\"index.php\">View calendar</a></p>";
}
echo '</form></body></html>';
// called when there is an error involving the DB
function db_error($dbh, $str, $query = "")
{
$string = "$str<br />" . $dbh->error;
if($query != "")
$string .= "<br />SQL query: $query";
soft_error($string);
}
// called when there is an error involving the DB that we should keep trying
// to procede after
function db_warning($dbh, $str, $query = "")
{
$string = "$str<br />" . $dbh->error;
if($query != "")
$string .= "<br />SQL query: $query";
echo $string;
}
function connect_db($hostname, $username, $passwd, $database = false)
{
phpc_debug("Connecting to SQL server $hostname with user $username.");
$dbh = new mysqli($hostname, $username, $passwd);
if(mysqli_connect_errno()) {
soft_error("Database connect failed (" . mysqli_connect_errno()
. "): " . mysqli_connect_error());
}
if($database) {
phpc_debug("Selecting database $database");
$dbh->select_db($database)
or soft_error("Could not select database \"$database\".");
}
$dbh->query("SET NAMES 'utf8'");
return $dbh;
}
// called when some error happens
function soft_error($str)
{
echo "<h1>Software Error</h1>\n",
"<h2>Message:</h2>\n",
"<pre>$str</pre>\n",
"<h2>Backtrace</h2>\n",
"<ol>\n";
foreach(debug_backtrace() as $bt) {
echo "<li>$bt[file]:$bt[line] - $bt[function]</li>\n";
}
echo "</ol>\n";
exit;
}
function create_logins_table() {
global $dbh;
echo '<h3>Step 3: Database Created</h3>';
create_table("logins",
"`uid` int(11) unsigned NOT NULL,\n"
."`series` char(43) collate utf8_unicode_ci NOT NULL,\n"
."`token` char(43) collate utf8_unicode_ci NOT NULL,\n"
."`atime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,\n"
."PRIMARY KEY (`uid`, `series`)\n");
echo "<p>Logins table updated.</p>";
}
function create_table($suffix, $columns, $table_args = "") {
global $drop_tables, $dbh;
$table_name = SQL_PREFIX . $suffix;
phpc_debug("Creating table \"$table_name\".");
if($drop_tables) {
$query = "DROP TABLE IF EXISTS `$table_name`";
$dbh->query($query)
or db_error($dbh, "Error dropping table `$table_name`.",
$query);
}
$query = "CREATE TABLE `$table_name` (\n"
.$columns
.") ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci $table_args;\n";
$dbh->query($query)
or db_error($dbh, "Error creating table `$table_name`.",
$query);
}
function phpc_debug($msg) {
echo "<p>$msg</p>";
}
?>
| php | Apache-2.0 | e9473676f311aac8e9577cb3371ed362418441d9 | 2026-01-05T04:51:20.275579Z | false |
sproctor/php-calendar | https://github.com/sproctor/php-calendar/blob/e9473676f311aac8e9577cb3371ed362418441d9/src/logout.php | src/logout.php | <?php
/*
* Copyright 2012 Sean Proctor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
if(!defined('IN_PHPC')) {
die("Hacking attempt");
}
/**
* @return Html
*/
function logout()
{
global $phpc_script;
phpc_do_logout();
redirect($phpc_script);
return tag('h2', __('Loggin out...'));
}
| php | Apache-2.0 | e9473676f311aac8e9577cb3371ed362418441d9 | 2026-01-05T04:51:20.275579Z | false |
sproctor/php-calendar | https://github.com/sproctor/php-calendar/blob/e9473676f311aac8e9577cb3371ed362418441d9/src/display_event.php | src/display_event.php | <?php
/*
* Copyright 2012 Sean Proctor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
This file has the functions for the main displays of the calendar
*/
if ( !defined('IN_PHPC') ) {
die("Hacking attempt");
}
// Full view for a single event
/**
* @return Html|string
*/
function display_event()
{
global $vars;
if(!empty($vars['contentType']) && $vars['contentType'] == 'json')
return display_event_json();
if(isset($vars['oid']))
return display_event_by_oid($vars['oid']);
if(isset($vars['eid']))
return display_event_by_eid($vars['eid']);
// If we get here, we did something wrong
soft_error(__("Invalid arguments."));
}
/**
* @param int $oid
* @return Html
*/
function display_event_by_oid($oid)
{
global $phpcdb, $year, $month, $day;
$event = $phpcdb->get_occurrence_by_oid($oid);
$eid = $event->get_eid();
if(!$event->can_read()) {
return tag('p', __("You do not have permission to read this event."));
}
$event_header = tag('div', attributes('class="phpc-event-header"'),
tag('div',attributes('class="phpc-event-creator"'), __('by').' ',
tag('cite', $event->get_author())));
$category = $event->get_category();
if(!empty($category))
$event_header->add(tag('div',attributes('class="phpc-event-cats"'), __('Category') . ': '
. $category));
$event_header->add(tag('div',attributes('class="phpc-event-time"'),
__('When').": ".$event->get_datetime_string()));
$event_header->add(tag('div', __('Created at: '), $event->get_ctime_string()));
if(!empty($event->mtime))
$event_header->add(tag('div', __('Last modified at: '),
$event->get_mtime_string()));
$menu_tag = tag('div', attrs('class="phpc-bar ui-widget-content"'));
// Add modify/delete links if this user has access to this event.
if($event->can_modify()) {
$menu_tag->add(array(create_event_link(__('Modify'),
'event_form', $eid), "\n",
create_event_link(__('Delete'),
'event_delete', $eid), "\n",
create_occurrence_link(__('Modify Occurrence'),
'occur_form', $oid), "\n",
create_occurrence_link(__('Remove Occurrence'),
'occurrence_delete', $oid),
"\n"));
}
$occurrences = $phpcdb->get_occurrences_by_eid($eid);
//$occurrence_div = tag('div', );
$i = 0;
while($i < sizeof($occurrences)) {
if($occurrences[$i]->get_oid() == $oid)
break;
$i++;
}
// if we have a previous event
$prev = $i - 1;
if($prev >= 0) {
$prev_occur = $occurrences[$prev];
$menu_tag->add(create_occurrence_link(
__('Previous occurrence on') . " " .
$prev_occur->get_date_string(),
'display_event',
$prev_occur->get_oid()), ' ');
}
// if we have a future event
$next = $i + 1;
if($next < sizeof($occurrences)) {
$next_occur = $occurrences[$next];
$menu_tag->add(create_occurrence_link(
__('Next occurrence on') . " " .
$next_occur->get_date_string(),
'display_event',
$next_occur->get_oid()), ' ');
}
$menu_tag->add(create_event_link(__('View All Occurrences'),
'display_event', $eid));
$event_header->add($menu_tag);
$year = $event->get_start_year();
$month = $event->get_start_month();
$day = $event->get_start_day();
$desc_tag = tag('div',
tag('h3', __("Description")),
tag('p', attributes('class="phpc-desc"'),
$event->get_desc()));
return tag('div', attributes('class="phpc-main phpc-event"'),
tag('h2', $event->get_subject()), $event_header,
$desc_tag);
}
/**
* @param int $eid
* @return Html
*/
function display_event_by_eid($eid)
{
global $phpcdb, $year, $month, $day;
$event = new PhpcEvent($phpcdb->get_event_by_eid($eid));
if(!$event->can_read()) {
return tag('p', __("You do not have permission to read this event."));
}
$event_header = tag('div', attributes('class="phpc-event-header"'),
tag('div', __('by').' ',
tag('cite', $event->get_author())));
$event_header->add(tag('div', __('Created at: '), $event->get_ctime_string()));
if(!empty($event->mtime))
$event_header->add(tag('div', __('Last modified at: '),
$event->get_mtime_string()));
$category = $event->get_category();
if(!empty($category))
$event_header->add(tag('div', __('Category') . ': '
. $category));
// Add modify/delete links if this user has access to this event.
if($event->can_modify()) {
$event_header->add(tag('div', attrs('class="phpc-bar ui-widget-content"'),
create_event_link(__('Modify'),
'event_form', $eid), "\n",
create_event_link(__('Add Occurrence'),
'occur_form', $eid), "\n",
create_event_link(__('Delete'),
'event_delete', $eid)));
}
$desc_tag = tag('div',
tag('h3', __("Description")),
tag('p', attributes('class="phpc-desc"'), $event->get_desc()));
$occurrences_tag = tag('ul');
$occurrences = $phpcdb->get_occurrences_by_eid($eid);
$set_date = false;
foreach($occurrences as $occurrence) {
if(!$set_date) {
$year = $occurrence->get_start_year();
$month = $occurrence->get_start_month();
$day = $occurrence->get_start_day();
}
$oid = $occurrence->get_oid();
$occ_tag = tag('li', attrs('class="ui-widget-content"'),
create_occurrence_link(
$occurrence->get_date_string()
. ' ' . __('at') . ' '
. $occurrence->get_time_span_string(),
'display_event',
$oid));
if($event->can_modify()) {
$occ_tag->add(" ",
create_occurrence_link(__('Edit'), 'occur_form', $oid), " ",
create_occurrence_link(__('Remove'), 'occurrence_delete', $oid));
}
$occurrences_tag->add($occ_tag);
}
return tag('div', attributes('class="phpc-main phpc-event"'),
tag('h2', $event->get_subject()), $event_header,
$desc_tag, tag ('div',attributes('class="phpc-occ"'),tag('h3', __('Occurrences')),
$occurrences_tag));
}
// generates a JSON data structure for a particular event
/**
* @return string
*/
function display_event_json()
{
global $phpcdb, $vars;
if(!isset($vars['oid']))
return "";
$event = $phpcdb->get_occurrence_by_oid($vars['oid']);
if(!$event->can_read())
return "";
$author = __("by") . " " . $event->get_author();
$time_str = $event->get_time_span_string();
$date_str = $event->get_date_string();
$category = $event->get_category();
if(empty($category))
$category_text = '';
else
$category_text = __('Category') . ': ' . $event->get_category();
if ($time_str!="") $time="$date_str " . __("from") . " $time_str";
else $time="$date_str ";
return json_encode(array("title" => $event->get_subject(),
"author" => $author,
"time" => $time,
"category" => $category_text,
"body" => $event->get_desc()));
}
| php | Apache-2.0 | e9473676f311aac8e9577cb3371ed362418441d9 | 2026-01-05T04:51:20.275579Z | false |
sproctor/php-calendar | https://github.com/sproctor/php-calendar/blob/e9473676f311aac8e9577cb3371ed362418441d9/src/globals.php | src/globals.php | <?php
/*
* Copyright 2010 Sean Proctor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
if ( !defined('IN_PHPC') ) {
die("Hacking attempt");
}
$month_names = array(
1 => __('January'),
__('February'),
__('March'),
__('April'),
__('May'),
__('June'),
__('July'),
__('August'),
__('September'),
__('October'),
__('November'),
__('December'),
);
$day_names = array(
__('Sunday'),
__('Monday'),
__('Tuesday'),
__('Wednesday'),
__('Thursday'),
__('Friday'),
__('Saturday'),
);
$short_month_names = array(
1 => __('Jan'),
__('Feb'),
__('Mar'),
__('Apr'),
__('May'),
__('Jun'),
__('Jul'),
__('Aug'),
__('Sep'),
__('Oct'),
__('Nov'),
__('Dec'),
);
// config stuff
define('PHPC_CHECK', 1);
define('PHPC_TEXT', 2);
define('PHPC_DROPDOWN', 3);
define('PHPC_MULTI_DROPDOWN', 4);
$sort_options = array(
'start_date' => __('Start Date'),
'subject' => __('Subject')
);
$order_options = array(
'ASC' => __('Ascending'),
'DESC' => __('Descending')
);
| php | Apache-2.0 | e9473676f311aac8e9577cb3371ed362418441d9 | 2026-01-05T04:51:20.275579Z | false |
sproctor/php-calendar | https://github.com/sproctor/php-calendar/blob/e9473676f311aac8e9577cb3371ed362418441d9/src/display_day.php | src/display_day.php | <?php
/*
* Copyright 2014 Sean Proctor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
This file has the functions for the main displays of the calendar
*/
if ( !defined('IN_PHPC') ) {
die("Hacking attempt");
}
// View for a single day
/**
* @return Html
*/
function display_day()
{
global $phpcid, $phpc_cal, $phpc_script, $phpcdb, $day, $month, $year;
$monthname = month_name($month);
$results = $phpcdb->get_occurrences_by_date($phpcid, $year, $month, $day);
$have_events = false;
$html_table = tag('table', attributes('class="phpc-main"'),
tag('caption', "$day $monthname $year"),
tag('thead',
tag('tr',
tag('th', __('Title')),
tag('th', __('Time')),
tag('th', __('Description'))
)));
if($phpc_cal->can_modify()) {
$html_table->add(tag('tfoot',
tag('tr',
tag('td',
attributes('colspan="4"'),
create_hidden('action', 'event_delete'),
create_hidden('day', $day),
create_hidden('month', $month),
create_hidden('year', $year),
create_submit(__('Delete Selected'))))));
}
$html_body = tag('tbody');
while($row = $results->fetch_assoc()) {
$event = new PhpcOccurrence($row);
if(!$event->can_read())
continue;
$have_events = true;
$eid = $event->get_eid();
$oid = $event->get_oid();
$html_subject = tag('td');
if($event->can_modify()) {
$html_subject->add(create_checkbox('eid[]',
$eid));
}
$html_subject->add(create_occurrence_link(tag('strong',
$event->get_subject()),
'display_event', $oid));
if($event->can_modify()) {
$html_subject->add(" (");
$html_subject->add(create_event_link(
__('Modify'), 'event_form',
$eid));
$html_subject->add(')');
}
$html_body->add(tag('tr',
$html_subject,
tag('td', $event->get_time_span_string()),
tag('td', attributes('class="phpc-desc"'), $event->get_desc())));
}
$html_table->add($html_body);
if($phpc_cal->can_modify()) {
$output = tag('form',
attributes("action=\"$phpc_script\""),
$html_table);
} else {
$output = $html_table;
}
if(!$have_events)
$output = tag('h2', __('No events on this day.'));
return tag('', create_day_menu(), $output);
}
/**
* @return Html
*/
function create_day_menu() {
global $month, $day, $year;
$html = tag('div', attrs('class="phpc-bar ui-widget-content"'));
$lasttime = mktime(0, 0, 0, $month, $day - 1, $year);
$lastday = date('j', $lasttime);
$lastmonth = date('n', $lasttime);
$lastyear = date('Y', $lasttime);
$lastmonthname = month_name($lastmonth);
$last_args = array('year' => $lastyear, 'month' => $lastmonth,
'day' => $lastday);
menu_item_prepend($html, "$lastmonthname $lastday", 'display_day',
$last_args);
$nexttime = mktime(0, 0, 0, $month, $day + 1, $year);
$nextday = date('j', $nexttime);
$nextmonth = date('n', $nexttime);
$nextyear = date('Y', $nexttime);
$nextmonthname = month_name($nextmonth);
$next_args = array('year' => $nextyear, 'month' => $nextmonth,
'day' => $nextday);
menu_item_append($html, "$nextmonthname $nextday", 'display_day',
$next_args);
return $html;
}
| php | Apache-2.0 | e9473676f311aac8e9577cb3371ed362418441d9 | 2026-01-05T04:51:20.275579Z | false |
sproctor/php-calendar | https://github.com/sproctor/php-calendar/blob/e9473676f311aac8e9577cb3371ed362418441d9/src/category_delete.php | src/category_delete.php | <?php
/*
* Copyright 2012 Sean Proctor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
if ( !defined('IN_PHPC') ) {
die("Hacking attempt");
}
/**
* @return Html
*/
function category_delete()
{
global $vars, $phpcdb, $phpcid, $phpc_script;
$html = tag('div', attributes('class="phpc-container"'));
if(empty($vars["catid"])) {
return message_redirect(__('No category selected.'),
"$phpc_script?action=cadmin&phpcid=$phpcid");
}
if (is_array($vars["catid"])) {
$ids = $vars["catid"];
} else {
$ids = array($vars["catid"]);
}
$categories = array();
foreach ($ids as $id) {
$categories[] = $phpcdb->get_category($id);
}
if (empty($vars["confirm"])) {
$list = tag('ul');
foreach ($categories as $category) {
$list->add(tag('li', $category['name']));
}
$html->add(tag('p', __('Confirm you want to delete:')));
$html->add($list);
$html->add(" [ ", create_action_link(__('Confirm'),
"category_delete", array("catid" => $ids,
"confirm" => "1")), " ] ");
$html->add(" [ ", create_action_link(__('Deny'),
"display_month"), " ] ");
return $html;
}
foreach($categories as $category) {
if((empty($category['cid']) && !is_admin()) ||
!$phpcdb->get_calendar($category['cid'])
->can_admin()) {
$html->add(tag('p', __("You do not have permission to delete category: ") . $category['catid']));
continue;
}
if($phpcdb->delete_category($category['catid'])) {
$html->add(tag('p', __("Removed category: ")
. $category['catid']));
} else {
$html->add(tag('p', __("Could not remove category: ")
. $category['catid']));
}
}
return message_redirect($html, "$phpc_script?action=cadmin&phpcid=$phpcid");
}
| php | Apache-2.0 | e9473676f311aac8e9577cb3371ed362418441d9 | 2026-01-05T04:51:20.275579Z | false |
sproctor/php-calendar | https://github.com/sproctor/php-calendar/blob/e9473676f311aac8e9577cb3371ed362418441d9/src/translate.php | src/translate.php | <?php
/*
* Copyright 2013 Sean Proctor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
if ( !defined('IN_PHPC') ) {
die("Hacking attempt");
}
require_once("$phpc_includes_path/msgfmt-functions.php");
/**
* @return Html
*/
function translate() {
global $phpc_locale_path;
if(!is_admin()) {
permission_error(__('Need to be admin'));
exit;
}
$handle = opendir($phpc_locale_path);
if(!$handle) {
soft_error("Error reading locale directory.");
}
$output_tag = tag('div', tag('h2', __('Translate')));
while(($filename = readdir($handle)) !== false) {
$pathname = "$phpc_locale_path/$filename";
if(strncmp($filename, ".", 1) == 0 || !is_dir($pathname))
continue;
$msgs_path = "$pathname/LC_MESSAGES";
$hash= parse_po_file("$msgs_path/messages.po");
if ($hash === FALSE) {
print(nl2br("Error reading '$msgs_path/messages.po', aborted.\n"));
} else {
$out="$msgs_path/messages.mo";
write_mo_file($hash, $out);
}
$output_tag->add(tag('div', sprintf(__('Translated "%s"'),
$filename)));
}
closedir($handle);
return $output_tag;
}
| php | Apache-2.0 | e9473676f311aac8e9577cb3371ed362418441d9 | 2026-01-05T04:51:20.275579Z | false |
sproctor/php-calendar | https://github.com/sproctor/php-calendar/blob/e9473676f311aac8e9577cb3371ed362418441d9/src/occurrence_delete.php | src/occurrence_delete.php | <?php
/*
* Copyright 2012 Sean Proctor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
if ( !defined('IN_PHPC') ) {
die("Hacking attempt");
}
/**
* @return Html
*/
function occurrence_delete()
{
global $vars, $phpcdb, $phpcid, $phpc_script;
$html = tag('div', attributes('class="phpc-container"'));
if(empty($vars["oid"])) {
$message = __('No occurrence selected.');
$html->add(tag('p', $message));
return $html;
}
if (is_array($vars["oid"])) {
$oids = $vars["oid"];
} else {
$oids = array($vars["oid"]);
}
if (empty($vars["confirm"])) {
$list = tag('ul');
foreach ($oids as $oid) {
$occur = $phpcdb->get_occurrence_by_oid($oid);
$list->add(tag('li', "$oid: \"" . $occur->get_subject()
. "\" " . __("at") . " " .
$occur->get_date_string()));
}
$html->add(tag('p', __('Confirm you want to delete:')));
$html->add($list);
$html->add(" [ ", create_action_link(__('Confirm'),
"occurrence_delete", array("oid" => $oids,
"confirm" => "1")), " ] ");
$html->add(" [ ", create_action_link(__('Deny'),
"display_month"), " ] ");
return $html;
}
$removed_occurs = array();
$unremoved_occurs = array();
$permission_denied = array();
foreach($oids as $oid) {
$occur = $phpcdb->get_occurrence_by_oid($oid);
if(!$occur->can_modify()) {
$permission_denied[] = $oid;
} else {
if($phpcdb->delete_occurrence($oid)) {
$removed_occurs[] = $oid;
// TODO: Verify that the event still has occurences.
$eid = $occur->get_eid();
} else {
$unremoved_occurs[] = $oid;
}
}
}
if(sizeof($removed_occurs) > 0) {
if(sizeof($removed_occurs) == 1)
$text = __("Removed occurrence");
else
$text = __("Removed occurrences");
$text .= ': ' . implode(', ', $removed_occurs);
$html->add(tag('p', $text));
}
if(sizeof($unremoved_occurs) > 0) {
if(sizeof($unremoved_occurs) == 1)
$text = __("Could not remove occurrence");
else
$text = __("Could not remove occurrences");
$text .= ': ' . implode(', ', $unremoved_occurs);
$html->add(tag('p', $text));
}
if(sizeof($permission_denied) > 0) {
if(sizeof($permission_denied) == 1)
$text = __("You do not have permission to remove the occurrence.");
else
$text = __("You do not have permission to remove occurrences.");
$text .= ': ' . implode(', ', $permission_denied);
$html->add(tag('p', $text));
}
return message_redirect($html,
"$phpc_script?action=display_event&phpcid=$phpcid&eid=$eid");
}
| php | Apache-2.0 | e9473676f311aac8e9577cb3371ed362418441d9 | 2026-01-05T04:51:20.275579Z | false |
sproctor/php-calendar | https://github.com/sproctor/php-calendar/blob/e9473676f311aac8e9577cb3371ed362418441d9/src/cadmin.php | src/cadmin.php | <?php
/*
* Copyright 2012 Sean Proctor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
if (!defined('IN_PHPC')) {
die("Hacking attempt");
}
/**
* @return Html
*/
function cadmin()
{
global $phpc_cal;
if (!$phpc_cal->can_admin()) {
permission_error(__('You must be logged in as an admin.'));
}
$index = tag('ul',
tag('li', tag('a', attrs('href="#phpc-config"'),
__('Calendar Configuration'))),
tag('li', tag('a', attrs('href="#phpc-users"'),
__('Users'))),
tag('li', tag('a', attrs('href="#phpc-categories"'),
__('Categories'))),
tag('li', tag('a', attrs('href="#phpc-groups"'),
__('Groups'))));
return tag('div', attrs("class=\"phpc-tabs\""), $index, config_form(),
user_list(), category_list(), group_list());
}
function config_form()
{
global $phpc_cal, $phpc_script, $vars;
$tbody = tag('tbody');
foreach (get_config_options() as $element) {
$name = $element[0];
$text = $element[1];
$default = $phpc_cal->$name;
$input = create_config_input($element, $default);
$tbody->add(tag('tr',
tag('th', $text),
tag('td', $input)));
}
$hidden_div = tag('div',
create_hidden('action', 'cadmin_submit'));
if (isset($vars['phpcid']))
$hidden_div->add(create_hidden('phpcid', $vars['phpcid']));
$form = tag('form', attributes("action=\"$phpc_script\"",
'method="post"'),
$hidden_div,
tag('table', attributes("class=\"phpc-container\""),
tag('caption', __('Options')),
tag('tfoot',
tag('tr',
tag('td', attributes('colspan="2"'),
create_submit(__('Submit'))))),
$tbody));
return tag('div', attrs('id="phpc-config"'), $form);
}
function user_list()
{
global $phpc_script, $phpcid, $phpcdb, $vars;
$users = $phpcdb->get_users_with_permissions($phpcid);
$tbody = tag('tbody');
foreach ($users as $user) {
$phpc_user = new PhpcUser($user);
$group_list = array();
foreach ($phpc_user->get_groups() as $group) {
if ($group['cid'] == $phpcid)
$group_list[] = $group['name'];
}
$groups = implode(', ', $group_list);
$tbody->add(tag('tr',
tag('th', $user['username'],
create_hidden('uid[]',
$user['uid'])),
tag('td', create_checkbox("read{$user['uid']}", "1", !empty($user['read']), __('Read'))),
tag('td', create_checkbox("write{$user['uid']}", "1", !empty($user['write']), __('Write'))),
tag('td', create_checkbox("readonly{$user['uid']}", "1", !empty($user['readonly']), __('Read-only'))),
tag('td', create_checkbox("modify{$user['uid']}", "1", !empty($user['modify']), __('Modify'))),
tag('td', create_checkbox("admin{$user['uid']}", "1", !empty($user['calendar_admin']), __('Admin'))),
tag('td', $groups),
tag('td', create_action_link(__("Edit Groups"), "user_groups", array("uid" => $user["uid"])))
));
}
$hidden_div = tag('div',
create_hidden('action', 'user_permissions_submit'));
if (isset($vars['phpcid']))
$hidden_div->add(create_hidden('phpcid', $vars['phpcid']));
$form = tag('form', attributes("action=\"$phpc_script\"",
'method="post"'),
$hidden_div,
tag('table', attributes("class=\"phpc-container\""),
tag('caption', __('User Permissions')),
tag('tfoot',
tag('tr',
tag('td', attributes('colspan="8"'),
create_submit(__('Submit'))))),
tag('thead',
tag('tr',
tag('th', __('User Name')),
tag('th', __('Read')),
tag('th', __('Write')),
tag('th', __('Can Create Read-Only')),
tag('th', __('Modify')),
tag('th', __('Admin')),
tag('th', __('Groups')),
tag('th', __('Edit Groups'))
)), $tbody));
return tag('div', attrs('id="phpc-users"'), $form);
}
function category_list()
{
global $phpcid, $phpc_cal;
$categories = $phpc_cal->get_categories();
$tbody = tag('tbody');
foreach ($categories as $category) {
$name = empty($category['name']) ? __('No Name')
: $category['name'];
$catid = $category['catid'];
$group = empty($category['group_name']) ? __('None')
: $category['group_name'];
$tbody->add(tag('tr',
tag('th', $name),
tag('td', phpc_html_escape($category['text_color'])),
tag('td', phpc_html_escape($category['bg_color'])),
tag('td', phpc_html_escape($group)),
tag('td', create_action_link(__('Edit'),
'category_form',
array('catid'
=> $catid)),
" ",
create_action_link(__('Delete'),
'category_delete',
array('catid'
=> $catid)))
));
}
$create_link = create_action_link(__('Create category'), 'category_form',
array('cid' => $phpcid));
$table = tag('table', attributes("class=\"phpc-container\""),
tag('caption', __('Calendar Categories')),
tag('thead',
tag('tr',
tag('th', __('Name')),
tag('th', __('Text Color')),
tag('th', __('Background Color')),
tag('th', __('Visible to User Group')),
tag('th', __('Actions'))
)),
$tbody,
tag('tfoot',
tag('tr',
tag('td', attributes('colspan="5"'),
$create_link))));
return tag('div', attributes('id="phpc-categories"'), $table);
}
function group_list()
{
global $phpcid, $phpc_cal;
$groups = $phpc_cal->get_groups();
$tbody = tag('tbody');
foreach ($groups as $group) {
$name = empty($group['name']) ? __('No Name')
: $group['name'];
$id = $group['gid'];
$tbody->add(tag('tr',
tag('th', $name),
tag('td', create_action_link(__('Edit'),
'group_form',
array('gid' => $id)),
" ",
create_action_link(__('Delete'),
'group_delete',
array('gid' => $id)))
));
}
$create_link = create_action_link(__('Create group'), 'group_form',
array('cid' => $phpcid));
$table = tag('table', attributes("class=\"phpc-container\""),
tag('caption', __('Calendar Groups')),
tag('thead',
tag('tr',
tag('th', __('Name')),
tag('th', __('Actions'))
)),
$tbody,
tag('tfoot',
tag('tr',
tag('td', attributes('colspan="2"'),
$create_link))));
return tag('div', attrs('id="phpc-groups"'), $table);
}
| php | Apache-2.0 | e9473676f311aac8e9577cb3371ed362418441d9 | 2026-01-05T04:51:20.275579Z | false |
sproctor/php-calendar | https://github.com/sproctor/php-calendar/blob/e9473676f311aac8e9577cb3371ed362418441d9/src/phpcdatabase.class.php | src/phpcdatabase.class.php | <?php
/*
* Copyright 2012 Sean Proctor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require_once("$phpc_includes_path/phpccalendar.class.php");
require_once("$phpc_includes_path/phpcevent.class.php");
require_once("$phpc_includes_path/phpcoccurrence.class.php");
require_once("$phpc_includes_path/phpcuser.class.php");
class PhpcDatabase {
/** @var mysqli */
var $dbh;
/** @var PhpcCalendar[] */
var $calendars;
/** @var */
var $perms = array();
/**
* PhpcDatabase constructor.
* @param string $host
* @param string $username
* @param string $passwd
* @param string $dbname
* @param string $port
*/
function __construct($host, $username, $passwd, $dbname, $port) {
// Make the database connection.
$this->dbh = new mysqli($host, $username, $passwd, $dbname,
$port);
if(mysqli_connect_errno()) {
soft_error("Database connect failed ("
. mysqli_connect_errno() . "): "
. mysqli_connect_error());
}
$this->dbh->set_charset("utf8");
}
function __destruct() {
$this->dbh->close();
}
/**
* @return string
*/
private function get_event_fields() {
$events_table = SQL_PREFIX . "events";
$cats_table = SQL_PREFIX . "categories";
$fields = array('subject', 'description', 'owner', 'eid', 'cid',
'readonly', 'catid');
return "`$cats_table`.`gid`, `$events_table`.`"
. implode("`, `$events_table`.`", $fields) . "`, "
. "UNIX_TIMESTAMP(`ctime`) AS `ctime`, "
. "UNIX_TIMESTAMP(`mtime`) AS `mtime`";
}
/**
* @return string
*/
private function get_occurrence_fields() {
return $this->get_event_fields() . ", `time_type`, `oid`, "
. "UNIX_TIMESTAMP(`start_ts`) AS `start_ts`, "
. "DATE_FORMAT(`start_date`, '%Y%m%d') AS `start_date`, "
. "UNIX_TIMESTAMP(`end_ts`) AS `end_ts`, "
. "DATE_FORMAT(`end_date`, '%Y%m%d') AS `end_date`\n";
}
/**
* @return string
*/
private function get_user_fields() {
$users_table = SQL_PREFIX . "users";
return "`$users_table`.`uid`, `username`, `password`, `$users_table`.`admin`, `password_editable`, `timezone`, `language`";
}
// returns all the events for a particular day
// $from and $to are timestamps only significant to the date.
// an event that happens later in the day of $to is included
/**
* @param int $cid
* @param int $from
* @param int $to
* @return mysqli_result
*/
function get_occurrences_by_date_range($cid, $from, $to)
{
$from_str = "FROM_UNIXTIME('$from')";
$to_str = "FROM_UNIXTIME('$to')";
$events_table = SQL_PREFIX . "events";
$occurrences_table = SQL_PREFIX . "occurrences";
$users_table = SQL_PREFIX . 'users';
$cats_table = SQL_PREFIX . 'categories';
$query = "SELECT " . $this->get_occurrence_fields()
.", `username`, `name`, `bg_color`, `text_color`\n"
."FROM `$events_table`\n"
."INNER JOIN `$occurrences_table` USING (`eid`)\n"
."LEFT JOIN `$users_table` ON `uid` = `owner`\n"
."LEFT JOIN `$cats_table` ON `$events_table`.`catid` "
."= `$cats_table`.`catid`\n"
."WHERE `$events_table`.`cid` = '$cid'\n"
." AND IF(`start_ts`, `start_ts` <= $to_str, `start_date` <= DATE($to_str))\n"
." AND IF(`end_ts`, `end_ts` >= $from_str, `end_date` >= DATE($from_str))\n"
." ORDER BY `start_ts`, `start_date`, `oid`";
$results = $this->dbh->query($query)
or $this->db_error(__('Error in get_occurrences_by_date_range'),
$query);
return $results;
}
/* if category is visible to user id */
/**
* @param int $uid
* @param int $catid
* @return bool
*/
function is_cat_visible($uid, $catid) {
$users_table = SQL_PREFIX . 'users';
$user_groups_table = SQL_PREFIX . 'user_groups';
$cats_table = SQL_PREFIX . 'categories';
if (is_admin())
return true;
$query = "SELECT * FROM `$users_table` u\n"
."JOIN `$user_groups_table` ug USING (`uid`)\n"
."JOIN `$cats_table` c ON c.`gid`=ug.`gid`\n"
."WHERE c.`catid`='$catid' AND u.`uid`='$uid'";
$results = $this->dbh->query($query);
if(!$results)
return false;
return $results->num_rows>0;
}
// returns all the events for a particular day
/**
* @param int $cid
* @param int $year
* @param int $month
* @param int $day
* @return mysqli_result
*/
function get_occurrences_by_date($cid, $year, $month, $day)
{
$from_stamp = mktime(0, 0, 0, $month, $day, $year);
$to_stamp = mktime(23, 59, 59, $month, $day, $year);
return $this->get_occurrences_by_date_range($cid, $from_stamp, $to_stamp);
}
// returns the event that corresponds to eid
/**
* @param int $eid
* @return array
*/
function get_event_by_eid($eid)
{
$events_table = SQL_PREFIX . 'events';
$users_table = SQL_PREFIX . 'users';
$cats_table = SQL_PREFIX . 'categories';
$query = "SELECT " . $this->get_event_fields()
.", `username`, `name`, `bg_color`, `text_color`\n"
."FROM `$events_table`\n"
."LEFT JOIN `$users_table` ON `uid` = `owner`\n"
."LEFT JOIN `$cats_table` USING (`catid`)\n"
."WHERE `eid` = '$eid'\n";
$sth = $this->dbh->query($query)
or $this->db_error(__('Error in get_event_by_eid'),
$query);
$result = $sth->fetch_assoc()
or soft_error(__("Event doesn't exist") . ": $eid");
return $result;
}
// returns the event that corresponds to oid
/**
* @param int $oid
* @return array
*/
function get_event_by_oid($oid)
{
$events_table = SQL_PREFIX . 'events';
$occurrences_table = SQL_PREFIX . 'occurrences';
$users_table = SQL_PREFIX . 'users';
$cats_table = SQL_PREFIX . 'categories';
$query = "SELECT " . $this->get_event_fields()
.", `username`, `name`, `bg_color`, `text_color`\n"
."FROM `$events_table`\n"
."LEFT JOIN `$occurrences_table` USING (`eid`)\n"
."LEFT JOIN `$users_table` ON `uid` = `owner`\n"
."LEFT JOIN `$cats_table` USING (`catid`)\n"
."WHERE `oid` = '$oid'\n";
$sth = $this->dbh->query($query)
or $this->db_error(__('Error in get_event_by_oid'),
$query);
$result = $sth->fetch_assoc()
or soft_error(__("Event doesn't exist with oid")
. ": $oid");
return $result;
}
// returns the category that corresponds to $catid
/**
* @param int $catid
* @return array
*/
function get_category($catid) {
$cats_table = SQL_PREFIX . 'categories';
$groups_table = SQL_PREFIX . 'groups';
$query = "SELECT `$cats_table`.`name` AS `name`, `text_color`, "
."`bg_color`, `$cats_table`.`cid` AS `cid`, "
."`$cats_table`.`gid`, `catid`, "
."`$groups_table`.`name` AS `group_name`\n"
."FROM `$cats_table`\n"
."LEFT JOIN `$groups_table` USING (`gid`)\n"
."WHERE `catid` = $catid";
$sth = $this->dbh->query($query)
or $this->db_error(__('Error in get_category'), $query);
$result = $sth->fetch_assoc()
or soft_error(__("Category doesn't exist with catid")
. ": $catid");
return $result;
}
/**
* @param int $gid
* @return array
*/
function get_group($gid) {
$groups_table = SQL_PREFIX . 'groups';
$query = "SELECT `name`, `gid`, `cid`\n"
."FROM `$groups_table`\n"
."WHERE `gid` = $gid";
$sth = $this->dbh->query($query)
or $this->db_error(__('Error in get_group'), $query);
$result = $sth->fetch_assoc()
or soft_error(__("Group doesn't exist with gid")
. ": $gid");
return $result;
}
/**
* @param bool|int $cid
* @return array
*/
function get_groups($cid = false) {
$groups_table = SQL_PREFIX . 'groups';
$query = "SELECT `gid`, `name`, `cid`\n"
."FROM `$groups_table`\n";
if($cid !== false)
$query .= "WHERE `cid` = $cid";
$sth = $this->dbh->query($query)
or $this->db_error(__('Error in get_groups'), $query);
$groups = array();
while($row = $sth->fetch_assoc()) {
$groups[] = $row;
}
return $groups;
}
/**
* @param int $uid
* @return array
*/
function get_user_groups($uid) {
$groups_table = SQL_PREFIX . 'groups';
$user_groups_table = SQL_PREFIX . 'user_groups';
$query = "SELECT `gid`, `cid`, `name`\n"
."FROM `$groups_table`\n"
."INNER JOIN `$user_groups_table` USING (`gid`)\n"
."WHERE `uid` = $uid";
$sth = $this->dbh->query($query)
or $this->db_error(__('Error in get_user_groups'),
$query);
$groups = array();
while($row = $sth->fetch_assoc()) {
$groups[] = $row;
}
return $groups;
}
// returns the categories for calendar $cid
/**
* @param bool|int $cid
* @return array
*/
function get_categories($cid = false) {
$cats_table = SQL_PREFIX . 'categories';
$groups_table = SQL_PREFIX . 'groups';
if($cid)
$where = "WHERE `$cats_table`.`cid` = '$cid'\n";
else
$where = "WHERE `$cats_table`.`cid` IS NULL\n";
$query = "SELECT `$cats_table`.`name` AS `name`, `text_color`, "
."`bg_color`, `$cats_table`.`cid` AS `cid`, "
."`$cats_table`.`gid`, `catid`, "
."`$groups_table`.`name` AS `group_name`\n"
."FROM `$cats_table`\n"
."LEFT JOIN `$groups_table` USING (`gid`)\n"
.$where;
$sth = $this->dbh->query($query)
or $this->db_error(__('Error in get_categories'),
$query);
$arr = array();
while($result = $sth->fetch_assoc()) {
$arr[] = $result;
}
return $arr;
}
// returns the categories for calendar $cid
// if there are no
/**
* @param int $uid
* @param bool|int $cid
* @return array
*/
function get_visible_categories($uid, $cid = false)
{
$cats_table = SQL_PREFIX . 'categories';
$user_groups_table = SQL_PREFIX . 'user_groups';
$where_cid = "`cid` IS NULL";
if($cid)
$where_cid = "($where_cid OR `cid` = '$cid')";
$query = "SELECT `name`, `text_color`, `bg_color`, `cid`, "
."`gid`, `catid`\n"
."FROM `$cats_table`\n"
."LEFT JOIN `$user_groups_table` USING (`gid`)\n"
."WHERE (`uid` IS NULL OR `uid` = '$uid') AND $where_cid\n";
$sth = $this->dbh->query($query)
or $this->db_error(__('Error in get_visible_categories'),
$query);
$arr = array();
while($result = $sth->fetch_assoc()) {
$arr[] = $result;
}
return $arr;
}
// returns the event that corresponds to $oid
/**
* @param int $oid
* @return PhpcOccurrence
*/
function get_occurrence_by_oid($oid)
{
$events_table = SQL_PREFIX . 'events';
$occurrences_table = SQL_PREFIX . 'occurrences';
$users_table = SQL_PREFIX . 'users';
$cats_table = SQL_PREFIX . 'categories';
$query = "SELECT " . $this->get_occurrence_fields()
.", `username`, `name`, `bg_color`, `text_color`\n"
."FROM `$events_table`\n"
."INNER JOIN `$occurrences_table` USING (`eid`)\n"
."LEFT JOIN `$users_table` ON `uid` = `owner`\n"
."LEFT JOIN `$cats_table` USING (`catid`)\n"
."WHERE `oid` = '$oid'\n";
$sth = $this->dbh->query($query)
or $this->db_error(__('Error in get_occurrence_by_oid'),
$query);
$result = $sth->fetch_assoc()
or soft_error(__("Event doesn't exist with oid") . ": $oid");
return new PhpcOccurrence($result);
}
/**
* @param int $eid
* @return PhpcOccurrence[]
*/
function get_occurrences_by_eid($eid)
{
$events_table = SQL_PREFIX . "events";
$occurrences_table = SQL_PREFIX . "occurrences";
$users_table = SQL_PREFIX . 'users';
$cats_table = SQL_PREFIX . 'categories';
$query = "SELECT " . $this->get_occurrence_fields()
.", `username`, `name`, `bg_color`, `text_color`\n"
."FROM `$events_table`\n"
."INNER JOIN `$occurrences_table` USING (`eid`)\n"
."LEFT JOIN `$users_table` ON `uid` = `owner`\n"
."LEFT JOIN `$cats_table` USING (`catid`)\n"
."WHERE `eid` = '$eid'\n"
." ORDER BY `start_ts`, `start_date`, `oid`";
$result = $this->dbh->query($query)
or $this->db_error(__('Error in get_occurrences_by_eid'),
$query);
$events = array();
while($row = $result->fetch_assoc()) {
$events[] = new PhpcOccurrence($row);
}
return $events;
}
/**
* @param int $eid
* @return bool
*/
function delete_event($eid)
{
$query = 'DELETE FROM `'.SQL_PREFIX ."events`\n"
."WHERE `eid` = '$eid'";
$sth = $this->dbh->query($query)
or $this->db_error(__('Error while removing an event.'),
$query);
$rv = $this->dbh->affected_rows > 0;
$this->delete_occurrences($eid);
return $rv;
}
/**
* @param int $eid
* @return int
*/
function delete_occurrences($eid)
{
$query = 'DELETE FROM `'.SQL_PREFIX ."occurrences`\n"
."WHERE `eid` = '$eid'";
$sth = $this->dbh->query($query)
or $this->db_error(__('Error while removing an event.'),
$query);
return $this->dbh->affected_rows;
}
/**
* @param int $oid
* @return int
*/
function delete_occurrence($oid)
{
$query = 'DELETE FROM `'.SQL_PREFIX ."occurrences`\n"
."WHERE `oid` = '$oid'";
$sth = $this->dbh->query($query)
or $this->db_error(__('Error while removing an occurrence.'),
$query);
return $this->dbh->affected_rows;
}
/**
* @param int $id
* @return bool
*/
function delete_calendar($id)
{
$query1 = 'DELETE FROM `'.SQL_PREFIX ."calendars`\n"
."WHERE cid='$id'";
$sth = $this->dbh->query($query1)
or $this->db_error(__('Error while removing a calendar'),
$query1);
return $this->dbh->affected_rows > 0;
}
/**
* @param int $catid
* @return bool
*/
function delete_category($catid)
{
$query = 'DELETE FROM `'.SQL_PREFIX ."categories`\n"
."WHERE `catid` = '$catid'";
$sth = $this->dbh->query($query)
or $this->db_error(__('Error while removing category.'),
$query);
return $this->dbh->affected_rows > 0;
}
/**
* @param int $gid
* @return bool
*/
function delete_group($gid)
{
$query = 'DELETE FROM `'.SQL_PREFIX ."groups`\n"
."WHERE `gid` = '$gid'";
$sth = $this->dbh->query($query)
or $this->db_error(__('Error while removing group.'),
$query);
return $this->dbh->affected_rows > 0;
}
/**
* @param int $id
* @return bool
*/
function delete_user($id)
{
$query1 = 'DELETE FROM `'.SQL_PREFIX ."users`\n"
."WHERE uid='$id'";
$query2 = 'DELETE FROM `'.SQL_PREFIX ."permissions`\n"
."WHERE uid='$id'";
$this->dbh->query($query1)
or $this->db_error(__('Error while removing a calendar'),
$query1);
$rv = $this->dbh->affected_rows > 0;
$this->dbh->query($query2)
or $this->db_error(__('Error while removing '),
$query2);
return $rv;
}
/**
* @param int $cid
* @param int $uid
* @return string[]
*/
function get_permissions($cid, $uid)
{
static $perms = array();
if (empty($perms[$cid]))
$perms[$cid] = array();
elseif (!empty($perms[$cid][$uid]))
return $perms[$cid][$uid];
$query = "SELECT * from " . SQL_PREFIX .
"permissions WHERE `cid`='$cid' AND `uid`='$uid'";
$sth = $this->dbh->query($query)
or $this->db_error(__('Could not read permissions.'),
$query);
$perms[$cid][$uid] = $sth->fetch_assoc();
return $perms[$cid][$uid];
}
/**
* @return PhpcCalendar[]
*/
function get_calendars() {
if(!empty($this->calendars))
return $this->calendars;
$query = "SELECT *\n"
."FROM `" . SQL_PREFIX . "calendars`\n";
$sth = $this->dbh->query($query)
or $this->db_error(__('Could not get calendars.'),
$query);
while($result = $sth->fetch_assoc()) {
$cid = $result["cid"];
if(empty($this->calendars[$cid]))
$this->calendars[$cid] = new PhpcCalendar
($result);
}
return $this->calendars;
}
/**
* @param int $cid
* @return PhpcCalendar
*/
function get_calendar($cid)
{
// Make sure we've cached the calendars
$calendars = $this->get_calendars();
if (empty($calendars[$cid])) {
soft_error('Calendar $cid does not exist.');
}
return $calendars[$cid];
}
/**
* @param int $cid
* @return bool
*/
function have_calendar($cid)
{
$calendars = $this->get_calendars();
return isset($calendars[$cid]);
}
/**
* @return PhpcUser[]
*/
function get_users()
{
$query = "SELECT * FROM `" . SQL_PREFIX . "users`";
$sth = $this->dbh->query($query)
or $this->db_error(__('Could not get user.'), $query);
$users = array();
while($user = $sth->fetch_assoc()) {
$users[] = new PhpcUser($user);
}
return $users;
}
/**
* @param int $cid
* @return array
*/
function get_users_with_permissions($cid)
{
$permissions_table = SQL_PREFIX . "permissions";
$query = "SELECT *, `permissions`.`admin` AS `calendar_admin`\n"
."FROM `" . SQL_PREFIX . "users`\n"
."LEFT JOIN (SELECT * FROM `$permissions_table`\n"
." WHERE `cid`='$cid') AS `permissions`\n"
."USING (`uid`)\n";
$sth = $this->dbh->query($query)
or $this->db_error(__('Could not get user.'), $query);
$users = array();
while($user = $sth->fetch_assoc()) {
$users[] = $user;
}
return $users;
}
/**
* @param string $username
* @return bool|PhpcUser
*/
function get_user_by_name($username)
{
$query = "SELECT " . $this->get_user_fields()
."\nFROM ".SQL_PREFIX."users\n"
."WHERE username='$username'";
$sth = $this->dbh->query($query)
or $this->db_error(__("Error getting user."), $query);
$result = $sth->fetch_assoc();
if($result)
return new PhpcUser($result);
else
return false;
}
/**
* @param int $uid
* @return PhpcUser
*/
function get_user($uid)
{
$query = "SELECT " . $this->get_user_fields()
."FROM ".SQL_PREFIX."users\n"
."WHERE `uid`='$uid'";
$sth = $this->dbh->query($query)
or $this->db_error(__("Error getting user."), $query);
$result = $sth->fetch_assoc()
or soft_error('Invalid UID');
return new PhpcUser($result);
}
/**
* @param string $username
* @param string $password
* @param bool $make_admin
* @return mixed
*/
function create_user($username, $password, $make_admin) {
$admin = $make_admin ? 1 : 0;
$query = "INSERT into `".SQL_PREFIX."users`\n"
."(`username`, `password`, `admin`) VALUES\n"
."('$username', '$password', $admin)";
$this->dbh->query($query)
or $this->db_error(__('Error creating user.'), $query);
return $this->dbh->insert_id;
}
/**
* @return mixed
*/
function create_calendar()
{
$query = "INSERT INTO ".SQL_PREFIX."calendars\n"
."(`cid`) VALUE (DEFAULT)";
$this->dbh->query($query)
or $this->db_error(__('Error reading options'), $query);
return $this->dbh->insert_id;
}
/**
* @param int $cid
* @param string $name
* @param string $value
*/
function update_config($cid, $name, $value)
{
$query = "UPDATE ".SQL_PREFIX."calendars \n"
."SET `".$name."`='$value'\n"
."WHERE `cid`='$cid'";
$this->dbh->query($query)
or $this->db_error(__('Error updating option'), $query);
}
/**
* @param int $cid
* @param string $name
* @param string $value
*/
function create_config($cid, $name, $value)
{
$query = "UPDATE ".SQL_PREFIX."calendars \n"
."SET `".$name."`='$value'\n"
."WHERE `cid`='$cid'";
$this->dbh->query($query)
or $this->db_error(__('Error creating option'), $query);
}
/**
* @param int $uid
* @param string $password
*/
function set_password($uid, $password)
{
$query = "UPDATE `" . SQL_PREFIX . "users`\n"
."SET `password`='$password'\n"
."WHERE `uid`='$uid'";
$this->dbh->query($query)
or $this->db_error(__('Error updating password.'),
$query);
}
/**
* @param int $uid
* @param string $timezone
*/
function set_timezone($uid, $timezone)
{
$query = "UPDATE `" . SQL_PREFIX . "users`\n"
."SET `timezone`='$timezone'\n"
."WHERE `uid`='$uid'";
$this->dbh->query($query)
or $this->db_error(__('Error updating timezone.'),
$query);
}
/**
* @param int $uid
* @param string $language
*/
function set_language($uid, $language)
{
$query = "UPDATE `" . SQL_PREFIX . "users`\n"
."SET `language`='$language'\n"
."WHERE `uid`='$uid'";
$this->dbh->query($query)
or $this->db_error(__('Error updating language.'),
$query);
}
/**
* @param int $uid
* @param int $gid
*/
function user_add_group($uid, $gid) {
$user_groups_table = SQL_PREFIX . 'user_groups';
$query = "INSERT INTO `$user_groups_table`\n"
."(`gid`, `uid`) VALUES\n"
."('$gid', '$uid')";
$this->dbh->query($query)
or $this->db_error(__('Error adding group to user.'),
$query);
}
/**
* @param int $uid
* @param int $gid
*/
function user_remove_group($uid, $gid) {
$user_groups_table = SQL_PREFIX . 'user_groups';
$query = "DELETE FROM `$user_groups_table`\n"
."WHERE `uid` = '$uid' AND `gid` = '$gid'";
$this->dbh->query($query)
or $this->db_error(__('Error removing group from user.'), $query);
}
/**
* @param int $cid
* @param int $uid
* @param string $subject
* @param string $description
* @param bool $readonly
* @param bool|string $catid
* @return mixed
*/
function create_event($cid, $uid, $subject, $description, $readonly,
$catid = false)
{
$fmt_readonly = asbool($readonly);
if(!$catid)
$catid = 'NULL';
else
$catid = "'$catid'";
$query = "INSERT INTO `" . SQL_PREFIX . "events`\n"
."(`cid`, `owner`, `subject`, `description`, "
."`readonly`, `catid`)\n"
."VALUES ('$cid', '$uid', '$subject', '$description', "
."$fmt_readonly, $catid)";
$this->dbh->query($query)
or $this->db_error(__('Error creating event.'), $query);
$eid = $this->dbh->insert_id;
if($eid <= 0)
soft_error("Bad eid creating event.");
return $eid;
}
/**
* @param int $eid
* @param int $time_type
* @param int $start_ts
* @param int $end_ts
* @return mixed
*/
function create_occurrence($eid, $time_type, $start_ts, $end_ts)
{
$query = "INSERT INTO `" . SQL_PREFIX . "occurrences`\n"
."SET `eid` = '$eid', `time_type` = '$time_type'";
if($time_type == 0) {
$query .= ", `start_ts` = FROM_UNIXTIME('$start_ts')"
. ", `end_ts` = FROM_UNIXTIME('$end_ts')";
} else {
$start_date = date("Y-m-d", $start_ts);
$end_date = date("Y-m-d", $end_ts);
$query .= ", `start_date` = '$start_date'"
. ", `end_date` = '$end_date'";
}
$sth = $this->dbh->query($query)
or $this->db_error(__('Error creating occurrence.'),
$query);
return $this->dbh->insert_id;
}
/**
* @param int $oid
* @param int $time_type
* @param int $start_ts
* @param int $end_ts
* @return bool
*/
function modify_occurrence($oid, $time_type, $start_ts, $end_ts)
{
$query = "UPDATE `" . SQL_PREFIX . "occurrences`\n"
."SET `time_type` = '$time_type'";
if($time_type == 0) {
$query .= ", `start_ts` = FROM_UNIXTIME('$start_ts')"
. ", `end_ts` = FROM_UNIXTIME('$end_ts')"
. ", `start_date` = NULL"
. ", `end_date` = NULL";
} else {
$start_date = date("Y-m-d", $start_ts);
$end_date = date("Y-m-d", $end_ts);
$query .= ", `start_date` = '$start_date'"
. ", `end_date` = '$end_date'"
. ", `start_ts` = NULL"
. ", `end_ts` = NULL";
}
$query .= "\nWHERE `oid`='$oid'";
$sth = $this->dbh->query($query)
or $this->db_error(__('Error modifying occurrence.'),
$query);
return $this->dbh->affected_rows > 0;
}
/**
* @param int $eid
* @param string $subject
* @param string $description
* @param bool $readonly
* @param bool|int $catid
* @return bool
*/
function modify_event($eid, $subject, $description, $readonly,
$catid = false)
{
$fmt_readonly = asbool($readonly);
$query = "UPDATE `" . SQL_PREFIX . "events`\n"
."SET\n"
."`subject`='$subject',\n"
."`description`='$description',\n"
."`readonly`=$fmt_readonly,\n"
."`mtime`=NOW(),\n"
.($catid !== false ? "`catid`='$catid'\n"
: "`catid`=NULL\n")
."WHERE eid='$eid'";
$this->dbh->query($query)
or $this->db_error(__('Error modifying event.'), $query);
return $this->dbh->affected_rows > 0;
}
/**
* @param int $cid
* @param string $name
* @param string $text_color
* @param string $bg_color
* @param bool|int $gid
* @return mixed
*/
function create_category($cid, $name, $text_color, $bg_color,
$gid = false) {
$gid_key = $gid ? ', `gid`' : '';
$gid_value = $gid ? ", '$gid'" : '';
$query = "INSERT INTO `" . SQL_PREFIX . "categories`\n"
."(`cid`, `name`, `text_color`, `bg_color`$gid_key)\n"
."VALUES ('$cid', '$name', '$text_color', '$bg_color'$gid_value)";
$sth = $this->dbh->query($query)
or $this->db_error(__('Error creating category.'),
$query);
return $this->dbh->insert_id;
}
/**
* @param int $cid
* @param string $name
* @return mixed
*/
function create_group($cid, $name)
{
$query = "INSERT INTO `" . SQL_PREFIX . "groups`\n"
."(`cid`, `name`)\n"
."VALUES ('$cid', '$name')";
$sth = $this->dbh->query($query)
or $this->db_error(__('Error creating group.'), $query);
return $this->dbh->insert_id;
}
/**
* @param int $catid
* @param string $name
* @param string $text_color
* @param string $bg_color
* @param int $gid
* @return bool
*/
function modify_category($catid, $name, $text_color, $bg_color, $gid)
{
$query = "UPDATE " . SQL_PREFIX . "categories\n"
."SET\n"
."`name`='$name',\n"
."`text_color`='$text_color',\n"
."`bg_color`='$bg_color',\n"
."`gid`='$gid'\n"
."WHERE `catid`='$catid'";
$sth = $this->dbh->query($query)
or $this->db_error(__('Error modifying category.'),
$query);
return $this->dbh->affected_rows > 0;
}
/**
* @param int $gid
* @param string $name
* @return bool
*/
function modify_group($gid, $name)
{
$query = "UPDATE " . SQL_PREFIX . "groups\n"
."SET `name`='$name'\n"
."WHERE `gid`='$gid'";
$sth = $this->dbh->query($query)
or $this->db_error(__('Error modifying group.'),
$query);
return $this->dbh->affected_rows > 0;
}
/**
* @param int $cid
* @param string[] $keywords
* @param int $start
* @param int $end
* @param string $sort
* @param string $order
* @return PhpcOccurrence[]
*/
function search($cid, $keywords, $start, $end, $sort, $order) {
$events_table = SQL_PREFIX . 'events';
$occurrences_table = SQL_PREFIX . 'occurrences';
$users_table = SQL_PREFIX . 'users';
$cats_table = SQL_PREFIX . 'categories';
$start_str = "FROM_UNIXTIME('$start')";
$end_str = "FROM_UNIXTIME('$end')";
$words = array();
foreach($keywords as $keyword) {
$words[] = "(`subject` LIKE '%$keyword%' "
."OR `description` LIKE '%$keyword%')\n";
}
$where = implode(' AND ', $words);
if($start)
$where .= "AND IF(`start_ts`, `start_ts` <= $end_str, `start_date` <= DATE($start_str))\n";
if($end)
$where .= "AND IF(`end_ts`, `end_ts` >= $start_str, `end_date` >= DATE($end_str))\n";
$query = "SELECT " . $this->get_occurrence_fields()
.", `username`, `name`, `bg_color`, `text_color`\n"
."FROM `$events_table`\n"
."INNER JOIN `$occurrences_table` USING (`eid`)\n"
."LEFT JOIN `$users_table` ON `uid` = `owner`\n"
."LEFT JOIN `$cats_table` USING (`catid`)\n"
."WHERE ($where)\n"
."AND `$events_table`.`cid` = '$cid'\n"
."ORDER BY `$sort` $order";
if(!($result = $this->dbh->query($query)))
$this->db_error(__('Error during searching'), $query);
$events = array();
while($row = $result->fetch_assoc()) {
$events[] = new PhpcOccurrence($row);
}
return $events;
}
/**
* @param int $cid
* @param int $uid
* @param array $perms
*/
function update_permissions($cid, $uid, $perms)
{
$names = array();
$values = array();
$sets = array();
foreach($perms as $name => $value) {
$names[] = "`$name`";
$values[] = $value;
$sets[] = "`$name`=$value";
}
$query = "INSERT INTO ".SQL_PREFIX."permissions\n"
."(`cid`, `uid`, ".implode(", ", $names).")\n"
."VALUES ('$cid', '$uid', ".implode(", ", $values).")\n"
."ON DUPLICATE KEY UPDATE ".implode(", ", $sets);
if(!($sth = $this->dbh->query($query)))
$this->db_error(__('Error updating user permissions.'),
$query);
}
/**
* @param int $uid
* @param int $series
* @return bool
*/
function get_login_token($uid, $series) {
$query = "SELECT token FROM ".SQL_PREFIX."logins\n"
."WHERE `uid`='$uid' AND `series`='$series'";
$sth = $this->dbh->query($query)
or $this->db_error(__("Error getting login token."),
$query);
$result = $sth->fetch_assoc();
if(!$result)
return false;
return $result["token"];
}
/**
* @param int $uid
* @param int $series
* @param int $token
*/
function add_login_token($uid, $series, $token) {
$query = "INSERT INTO ".SQL_PREFIX."logins\n"
."(`uid`, `series`, `token`)\n"
."VALUES ('$uid', '$series', '$token')";
$this->dbh->query($query)
or $this->db_error(__("Error adding login token."),
$query);
}
/**
* @param int $uid
* @param int $series
* @param int $token
*/
function update_login_token($uid, $series, $token) {
$query = "UPDATE ".SQL_PREFIX."logins\n"
."SET `token`='$token', `atime`=NOW()\n"
."WHERE `uid`='$uid' AND `series`='$series'";
$this->dbh->query($query)
or $this->db_error(__("Error updating login token."),
$query);
}
/**
* @param int $uid
*/
function remove_login_tokens($uid) {
$query = "DELETE FROM ".SQL_PREFIX."logins\n"
."WHERE `uid`='$uid'";
$this->dbh->query($query)
or $this->db_error(__("Error removing login tokens."),
$query);
}
function cleanup_login_tokens() {
$query = "DELETE FROM ".SQL_PREFIX."logins\n"
."WHERE `atime` < DATE_SUB(CURDATE(), INTERVAL 30 DAY)";
$this->dbh->query($query)
or $this->db_error(__("Error cleaning login tokens."),
$query);
}
// called when there is an error involving the DB
/**
* @param string $str
* @param string $query
* @throws Exception
*/
function db_error($str, $query = "")
{
$string = $str . "<pre>" . phpc_html_escape($this->dbh->error)
. "</pre>";
if($query != "") {
$string .= "<pre>" . __('SQL query') . ": "
. phpc_html_escape($query)
. "</pre>";
}
throw new Exception($string);
}
}
| php | Apache-2.0 | e9473676f311aac8e9577cb3371ed362418441d9 | 2026-01-05T04:51:20.275579Z | false |
sproctor/php-calendar | https://github.com/sproctor/php-calendar/blob/e9473676f311aac8e9577cb3371ed362418441d9/src/embed_setup.php | src/embed_setup.php | <?php
/*
* Copyright 2012 Sean Proctor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* The following variables are intended to be modified to fit your
* setup.
*/
if (!defined('IN_PHPC'))
define('IN_PHPC', true);
/*
* If you want different scripts with different default calendars, you can
* copy this script and modify $default_calendar_id to contain the CID of
* the calendar you want to be the default
*/
$default_calendar_id = 1;
/*
* $phpc_root_path gives the location of the base calendar install.
* if you move this file to a new location, modify $phpc_root_path to point
* to the location where the support files for the callendar are located.
*/
$phpc_includes_path = dirname(__FILE__);
$phpc_root_path = dirname($phpc_includes_path);
$phpc_config_file = "$phpc_root_path/config.php";
$phpc_locale_path = "$phpc_root_path/locale";
require_once "$phpc_includes_path/util.php";
$phpc_script = phpc_html_escape($_SERVER['PHP_SELF']);
$phpc_server = $_SERVER['SERVER_NAME'];
if(!empty($_SERVER["SERVER_PORT"]) && $_SERVER["SERVER_PORT"] != 80)
$phpc_server .= ":{$_SERVER["SERVER_PORT"]}";
// Protcol ex. http or https
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off'
|| $_SERVER['SERVER_PORT'] == 443
|| isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https'
|| isset($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') {
$phpc_proto = "https";
} else {
$phpc_proto = "http";
}
$phpc_home_url="$phpc_proto://$phpc_server$phpc_script";
$phpc_url = $phpc_home_url
. (empty($_SERVER['QUERY_STRING']) ? ''
: '?' . $_SERVER['QUERY_STRING']);
// Remove this line if you must
ini_set('arg_separator.output', '&');
// Buffer the output until the script ends. Remove this if you must, but it may
// break things in unexpected ways.
ob_start();
require_once("$phpc_includes_path/setup.php");
| php | Apache-2.0 | e9473676f311aac8e9577cb3371ed362418441d9 | 2026-01-05T04:51:20.275579Z | false |
sproctor/php-calendar | https://github.com/sproctor/php-calendar/blob/e9473676f311aac8e9577cb3371ed362418441d9/src/password_submit.php | src/password_submit.php | <?php
/*
* Copyright 2010 Sean Proctor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
if(!defined('IN_PHPC')) {
die("Hacking attempt");
}
/**
* @return Html
*/
function password_submit()
{
/** @var PhpcUser $phpc_user */
global $vars, $phpcdb, $phpc_user;
if(!is_user()) {
return tag('div', __('You must be logged in.'));
}
verify_token();
if(!$phpc_user->is_password_editable())
soft_error(__('You do not have permission to change your password.'));
if(!isset($vars['old_password'])) {
return tag('div', __('You must specify your old password.'));
} else {
$old_password = $vars['old_password'];
}
if($phpc_user->password != md5($old_password)) {
return tag('div', __('The password you entered did not match your old password.'));
}
if(empty($vars['password1'])) {
return tag('div', __('You must specify a password'));
}
if(empty($vars['password2'])
|| $vars['password1'] != $vars['password2']) {
return tag('div', __('Your passwords did not match'));
}
$passwd = md5($vars['password1']);
$phpcdb->set_password($phpc_user->get_uid(), $passwd);
return tag('div', __('Password updated.'));
}
| php | Apache-2.0 | e9473676f311aac8e9577cb3371ed362418441d9 | 2026-01-05T04:51:20.275579Z | false |
sproctor/php-calendar | https://github.com/sproctor/php-calendar/blob/e9473676f311aac8e9577cb3371ed362418441d9/src/phpcuser.class.php | src/phpcuser.class.php | <?php
/*
* Copyright 2009 Sean Proctor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
class PhpcUser {
/** @var int */
var $uid;
/** @var string */
var $username;
/** @var string */
var $password;
/** @var bool */
var $admin;
/** @var bool */
var $password_editable;
/** @var string */
var $timezone;
/** @var string */
var $language;
/** @var array */
var $groups;
/**
* PhpcUser constructor.
* @param string[] $result
*/
function __construct($result)
{
$this->uid = intval($result['uid']);
$this->username = $result['username'];
$this->password = $result['password'];
$this->admin = intval($result['admin']) != 0;
$this->password_editable = intval($result['password_editable']) != 0;
$this->timezone = $result['timezone'];
$this->language = $result['language'];
}
/**
* @return string
*/
function get_username()
{
return $this->username;
}
/**
* @return int
*/
function get_uid()
{
return $this->uid;
}
/**
* @return string
*/
function get_password() {
return $this->password;
}
/**
* @return bool
*/
function is_password_editable() {
return $this->password_editable;
}
/**
* @return string
*/
function get_timezone() {
return $this->timezone;
}
/**
* @return string
*/
function get_language() {
return $this->language;
}
/**
* @return array
*/
function get_groups() {
global $phpcdb;
if(!isset($this->groups))
$this->groups = $phpcdb->get_user_groups($this->uid);
return $this->groups;
}
}
| php | Apache-2.0 | e9473676f311aac8e9577cb3371ed362418441d9 | 2026-01-05T04:51:20.275579Z | false |
sproctor/php-calendar | https://github.com/sproctor/php-calendar/blob/e9473676f311aac8e9577cb3371ed362418441d9/src/occur_form.php | src/occur_form.php | <?php
/*
* Copyright 2012 Sean Proctor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
if(!defined('IN_PHPC')) {
die("Hacking attempt");
}
require_once("$phpc_includes_path/form.php");
/**
* @return Html
*/
function occur_form() {
global $vars;
if(empty($vars["submit_form"]))
return display_form();
// else
return process_form();
}
/**
* @return Html
*/
function display_form() {
global $phpc_script, $year, $month, $day, $vars, $phpcdb, $phpc_cal,
$phpc_token;
$hour24 = $phpc_cal->hours_24;
$date_format = $phpc_cal->date_format;
$form = new Form($phpc_script, __('Occurrence Form'));
$when_group = new FormGroup(__('When'));
$when_group->add_part(new FormDateTimeQuestion('start',
__('From'), $hour24, $date_format));
$when_group->add_part(new FormDateTimeQuestion('end', __('To'),
$hour24, $date_format));
$time_type = new FormDropDownQuestion('time-type', __('Time Type'));
$time_type->add_option('normal', __('Normal'));
$time_type->add_option('full', __('Full Day'));
$time_type->add_option('tba', __('To Be Announced'));
$when_group->add_part($time_type);
$form->add_part($when_group);
if(isset($vars['phpcid']))
$form->add_hidden('phpcid', $vars['phpcid']);
if(isset($vars['oid'])) {
$form->add_hidden('oid', $vars['oid']);
$occ = $phpcdb->get_occurrence_by_oid($vars['oid']);
$datefmt = $phpc_cal->date_format;
$start_date = format_short_date_string($occ->get_start_year(),
$occ->get_start_month(), $occ->get_start_day(),
$datefmt);
$end_date = format_short_date_string($occ->get_end_year(),
$occ->get_end_month(), $occ->get_end_day(),
$datefmt);
$start_time = $occ->get_start_time();
if($start_time == NULL)
$start_time = format_time_string(17, 0, $hour24);
$end_time = $occ->get_end_time();
if($end_time == NULL)
$end_time = format_time_string(18, 0, $hour24);
$defaults = array(
'start-date' => $start_date,
'end-date' => $end_date,
'start-time' => $start_time,
'end-time' => $end_time,
);
switch($occ->get_time_type()) {
case 0:
$defaults['time-type'] = 'normal';
break;
case 1:
$defaults['time-type'] = 'full';
break;
case 2:
$defaults['time-type'] = 'tba';
break;
}
} else {
$form->add_hidden('eid', $vars['eid']);
$defaults = array(
'start-date' => "$month/$day/$year",
'end-date' => "$month/$day/$year",
'start-time' => format_time_string(17, 0, $hour24),
'end-time' => format_time_string(18, 0, $hour24),
);
}
$form->add_hidden('phpc_token', $phpc_token);
$form->add_hidden('action', 'occur_form');
$form->add_hidden('submit_form', 'submit_form');
$form->add_part(new FormSubmitButton(__("Submit Occurrence")));
return $form->get_form($defaults);
}
function process_form()
{
global $vars, $phpcdb, $phpc_cal, $phpcid, $phpc_script;
if(!isset($vars['eid']) && !isset($vars['oid']))
soft_error(__("Cannot create occurrence."));
$start_ts = get_timestamp("start");
$end_ts = get_timestamp("end");
switch($vars["time-type"]) {
case 'normal':
$time_type = 0;
break;
case 'full':
$time_type = 1;
break;
case 'tba':
$time_type = 2;
break;
default:
soft_error(__("Unrecognized Time Type."));
}
$duration = $end_ts - $start_ts;
if($duration < 0)
soft_error(__("An event cannot have an end earlier than its start."));
verify_token();
if(!$phpc_cal->can_write())
permission_error(__('You do not have permission to write to this calendar.'));
if(!isset($vars['oid'])) {
$modify = false;
if(!isset($vars["eid"]))
soft_error(__("EID not set."));
$oid = $phpcdb->create_occurrence($vars["eid"], $time_type, $start_ts,
$end_ts);
} else {
$modify = true;
$oid = $vars["oid"];
$phpcdb->modify_occurrence($oid, $time_type, $start_ts,
$end_ts);
}
if($oid != 0) {
if($modify)
$message = __("Modified occurence: ");
else
$message = __("Created occurence: ");
return message_redirect(tag('', $message,
create_event_link($oid, 'display_event',
$oid)),
"$phpc_script?action=display_event&phpcid=$phpcid&oid=$oid");
} else {
return message_redirect(__('Error submitting occurrence.'),
"$phpc_script?action=display_month&phpcid=$phpcid");
}
}
| php | Apache-2.0 | e9473676f311aac8e9577cb3371ed362418441d9 | 2026-01-05T04:51:20.275579Z | false |
sproctor/php-calendar | https://github.com/sproctor/php-calendar/blob/e9473676f311aac8e9577cb3371ed362418441d9/src/admin.php | src/admin.php | <?php
/*
* Copyright 2013 Sean Proctor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
if ( !defined('IN_PHPC') ) {
die("Hacking attempt");
}
require_once("$phpc_includes_path/form.php");
/**
* @return Html
*/
function admin() {
global $phpc_version;
if (!is_admin()) {
permission_error(__('You must be logged in as an admin.'));
}
$menu = tag('ul',
tag('li', tag('a', attrs('href="#phpc-admin-calendars"'),
__('Calendars'))),
tag('li', tag('a', attrs('href="#phpc-admin-users"'),
__('Users'))),
tag('li', tag('a', attrs('href="#phpc-admin-import"'),
__('Import'))),
tag('li', tag('a', attrs('href="#phpc-admin-translate"'),
__('Translate'))));
$version = tag('div', attrs('class="phpc-bar ui-widget-content"'),
__('Version') . ": $phpc_version");
return tag('', tag('div', attrs('class="phpc-tabs"'), $menu,
calendar_list(), user_list(), import(),
translation_link()), $version);
}
/**
* @return Html
*/
function calendar_list()
{
global $phpcdb;
$tbody = tag('tbody');
$tbody->add(tag('tr', tag('th', __("Calendar")),
tag('th', __("Action"))));
foreach ($phpcdb->get_calendars() as $calendar) {
$title = $calendar->get_title();
$cid = $calendar->get_cid();
$tbody->add(tag('tr',
tag('th', $title),
tag('td', create_action_link(__("Edit"),
"cadmin", array("phpcid" => $cid)),
" ", create_action_link(__("Delete"),
"calendar_delete",
array("cid" => $cid)))));
}
$create_link = create_action_link(__('Create Calendar'),
'calendar_form');
return tag('div', attributes('id="phpc-admin-calendars"'), tag('table',
attributes('class="phpc-container"'),
tag('caption', __('Calendar List')), $tbody,
tag('tfoot',
tag('tr',
tag('td', attributes('colspan="2"'),
$create_link)))));
}
/**
* @return Html
*/
function user_list()
{
global $phpcdb;
$tbody = tag('tbody');
$tbody->add(tag('tr', tag('th', __("Username")),
tag('th', __("Groups")),
tag('th', __("Edit Groups")),
tag('th', __("Action"))));
foreach ($phpcdb->get_users() as $user) {
$group_list = array();
foreach($user->get_groups() as $group) {
$group_list[] = $group['name'];
}
$groups = implode(', ', $group_list);
$tbody->add(tag('tr', tag('th', $user->username),
tag('td', $groups),
tag('td', create_action_link(__("Edit Groups"), "user_groups",
array("uid" => $user->uid))),
tag('td', create_action_link(__("Delete"),
"user_delete",
array("uid" => $user->uid)))));
}
$create_link = create_action_link(__('Create User'),
'user_create');
return tag('div', attributes('id="phpc-admin-users"'), tag('table',
attributes('class="phpc-container"'),
tag('caption', __('User List')), $tbody,
tag('tfoot',
tag('tr',
tag('td', attributes('colspan="3"'),
$create_link)))));
}
/**
* @return Html
*/
function import() {
global $phpc_script;
$form = new Form($phpc_script, __('Import Form'));
$form->add_part(new FormFreeQuestion('host', __('MySQL Host Name')));
$form->add_part(new FormFreeQuestion('dbname', __('MySQL Database Name')));
$form->add_part(new FormFreeQuestion('port', __('MySQL Port Number'), __('Leave blank for default')));
$form->add_part(new FormFreeQuestion('username', __('MySQL User Name')));
$pwq = new FormFreeQuestion('passwd', __('MySQL User Password'));
$pwq->type = 'password';
$form->add_part($pwq);
$form->add_part(new FormFreeQuestion('prefix', __('PHP-Calendar Table Prefix')));
$form->add_hidden('action', 'import');
$form->add_hidden('submit_form', 'submit_form');
$form->add_part(new FormSubmitButton(__("Import Calendar")));
$defaults = array(
'host' => 'localhost',
'dbname' => 'calendar',
'prefix' => 'phpc_',
);
return tag('div', attrs('id="phpc-admin-import"'),
$form->get_form($defaults));
}
/**
* @return Html
*/
function translation_link() {
global $phpc_script;
return tag('div', attrs('id="phpc-admin-translate"'),
tag('p', __('This script needs read access to your calendar directory in order to write the translation files. Alternatively, you could run translate.php from the command line or use msgfmt or any other gettext tool that can generate .mo files from .po files.')),
tag('a', attrs('class="phpc-button"',
"href=\"$phpc_script?action=translate\""),
__('Generate Translations')));
}
| php | Apache-2.0 | e9473676f311aac8e9577cb3371ed362418441d9 | 2026-01-05T04:51:20.275579Z | false |
sproctor/php-calendar | https://github.com/sproctor/php-calendar/blob/e9473676f311aac8e9577cb3371ed362418441d9/src/display_month.php | src/display_month.php | <?php
/*
* Copyright 2012 Sean Proctor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
This file has the functions for the main displays of the calendar
*/
if ( !defined('IN_PHPC') ) {
die("Hacking attempt");
}
// Full display for a month
/**
* @return Html
*/
function display_month()
{
global $month, $year, $phpc_home_url, $phpcid;
$heading_html = tag('tr');
$heading_html->add(tag('th', __p('Week', 'W')));
for($i = 0; $i < 7; $i++) {
$d = ($i + day_of_week_start()) % 7;
$heading_html->add(tag('th', day_name($d)));
}
$months = array();
for($i = 1; $i <= 12; $i++) {
$m = month_name($i);
$months["$phpc_home_url?action=display_month&phpcid=$phpcid&month=$i&year=$year"] = $m;
}
$years = array();
for($i = $year - 5; $i <= $year + 5; $i++) {
$years["$phpc_home_url?action=display_month&phpcid=$phpcid&month=$month&year=$i"] = $i;
}
return tag('',
tag("div", attributes('id="phpc-summary-view"'),
tag("div", attributes('id="phpc-summary-head"'),
tag("div", attributes('id="phpc-summary-title"'), ''),
tag("div", attributes('id="phpc-summary-author"'), ''),
tag("div", attributes('id="phpc-summary-category"'), ''),
tag("div", attributes('id="phpc-summary-time"'), '')),
tag("div", attributes('id="phpc-summary-body"'), '')),
tag('table',
attributes('class="phpc-main phpc-calendar"'),
tag('caption',
create_dropdown_list(month_name($month), $months),
create_dropdown_list($year, $years)),
tag('colgroup',
tag('col', attributes('class="phpc-week"')),
tag('col', attributes('class="phpc-day"')),
tag('col', attributes('class="phpc-day"')),
tag('col', attributes('class="phpc-day"')),
tag('col', attributes('class="phpc-day"')),
tag('col', attributes('class="phpc-day"')),
tag('col', attributes('class="phpc-day"')),
tag('col', attributes('class="phpc-day"'))
),
tag('thead', $heading_html),
create_month($month, $year)));
}
// creates a display for a particular month to be embedded in a full view
/**
* @param int $month
* @param int $year
* @return Html
*/
function create_month($month, $year)
{
global $phpcdb, $phpc_cal, $phpcid;
$wim = weeks_in_month($month, $year);
$first_day = 1 - day_of_week($month, 1, $year);
$from_stamp = mktime(0, 0, 0, $month, $first_day, $year);
$last_day = $wim * 7 - day_of_week($month, 1, $year);
$to_stamp = mktime(23, 59, 59, $month, $last_day, $year);
$max_events = $phpc_cal->events_max;
$results = $phpcdb->get_occurrences_by_date_range($phpcid, $from_stamp,
$to_stamp);
$days_events = array();
while($row = $results->fetch_assoc()) {
$event = new PhpcOccurrence($row);
if(!$event->can_read())
continue;
$end_stamp = mktime(0, 0, 0, $event->get_end_month(),
$event->get_end_day(), $event->get_end_year());
$start_stamp = mktime(0, 0, 0, $event->get_start_month(),
$event->get_start_day(),
$event->get_start_year());
$diff = $from_stamp - $start_stamp;
if($diff > 0)
$add_days = floor($diff / 86400);
else
$add_days = 0;
// put the event in every day until the end
for(; ; $add_days++) {
$stamp = mktime(0, 0, 0, $event->get_start_month(),
$event->get_start_day() + $add_days,
$event->get_start_year());
if($stamp > $end_stamp || $stamp > $to_stamp)
break;
$key = date('Y-m-d', $stamp);
if(!isset($days_events[$key]))
$days_events[$key] = array();
if(sizeof($days_events[$key]) == $max_events)
$days_events[$key][] = false;
if(sizeof($days_events[$key]) > $max_events)
continue;
$days_events[$key][] = $event;
}
}
$month_table = tag('tbody');
for($week_of_month = 1; $week_of_month <= $wim; $week_of_month++) {
$month_table->add(create_week($week_of_month, $month, $year,
$days_events));
}
return $month_table;
}
// creates a display for a particular week to be embedded in a month table
/**
* @param int $week_of_month
* @param int $month
* @param int $year
* @param PhpcOccurrence[][] $days_events
* @return Html
*/
function create_week($week_of_month, $month, $year, $days_events)
{
$start_day = 1 + ($week_of_month - 1) * 7
- day_of_week($month, 1, $year);
$week_of_year = week_of_year($month, $start_day, $year);
$args = array('week' => $week_of_year, 'year' => year_of_week_of_year($month, $start_day, $year));
$click = create_action_url('display_week', false, false, false, $args);
$week_html = tag('tr', tag('th', attrs('class="ui-state-default"',
"onclick=\"window.location.href='$click'\""),
create_action_link($week_of_year,
'display_week', $args)));
for($day_of_week = 0; $day_of_week < 7; $day_of_week++) {
$day = $start_day + $day_of_week;
$week_html->add(create_day($month, $day, $year, $days_events));
}
return $week_html;
}
// displays the day of the week and the following days of the week
/**
* @param int $month
* @param int $day
* @param int $year
* @param PhpcOccurrence[][] $days_events
* @return Html
*/
function create_day($month, $day, $year, $days_events)
{
global $phpc_cal;
$date_class = 'ui-state-default';
if($day <= 0) {
$month--;
if($month < 1) {
$month = 12;
$year--;
}
$day += days_in_month($month, $year);
$date_class .= ' phpc-shadow';
} elseif($day > days_in_month($month, $year)) {
$day -= days_in_month($month, $year);
$month++;
if($month > 12) {
$month = 1;
$year++;
}
$date_class .= ' phpc-shadow';
} else {
$currentday = date('j');
$currentmonth = date('n');
$currentyear = date('Y');
// set whether the date is in the past or future/present
if($currentyear == $year && $currentmonth == $month
&& $currentday == $day) {
$date_class .= ' ui-state-highlight';
}
}
$click = create_action_url('display_day', $year, $month, $day);
$date_tag = tag('div', attributes("class=\"phpc-date $date_class\"",
"onclick=\"window.location.href='$click'\""),
create_action_link_with_date($day,
'display_day', $year, $month, $day));
if($phpc_cal->can_write()) {
$date_tag->add(create_action_link_with_date('+',
'event_form', $year, $month,
$day,
array('class="phpc-add"')));
}
$html_day = tag('td', $date_tag);
$stamp = mktime(0, 0, 0, $month, $day, $year);
$can_read = $phpc_cal->can_read();
$key = date('Y-m-d', $stamp);
if(!$can_read || !array_key_exists($key, $days_events))
return $html_day;
$results = $days_events[$key];
if(empty($results))
return $html_day;
$html_events = tag('ul', attrs('class="phpc-event-list"'));
$html_day->add($html_events);
// Count the number of events
foreach($results as $event) {
if($event == false) {
$event_html = tag('li',
create_action_link_with_date(__("View Additional Events"),
'display_day', $year, $month,
$day,
array('class="phpc-date"')));
$html_events->add($event_html);
break;
}
// TODO - make sure we have permission to read the event
$subject = $event->get_subject();
if($event->get_start_timestamp() >= $stamp)
$event_time = $event->get_time_string();
else
$event_time = '(' . __('continued') . ')';
if(!empty($event_time))
$title = "$event_time - $subject";
else
$title = $subject;
$style = "";
if(!empty($event->text_color))
$style .= "color: {$event->get_text_color()} !important;";
if(!empty($event->bg_color))
$style .= "background: ".$event->get_bg_color()
." !important;";
$event_html = tag('li',
create_occurrence_link($title, "display_event",
$event->get_oid(),
array("style=\"$style\"")));
$html_events->add($event_html);
}
return $html_day;
}
| php | Apache-2.0 | e9473676f311aac8e9577cb3371ed362418441d9 | 2026-01-05T04:51:20.275579Z | false |
sproctor/php-calendar | https://github.com/sproctor/php-calendar/blob/e9473676f311aac8e9577cb3371ed362418441d9/src/user_permissions_submit.php | src/user_permissions_submit.php | <?php
/*
* Copyright 2012 Sean Proctor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
if(!defined('IN_PHPC')) {
die("Hacking attempt");
}
/**
* @return Html
*/
function user_permissions_submit()
{
global $phpcid, $phpc_cal, $vars, $phpcdb, $phpc_script;
if(!$phpc_cal->can_admin()) {
return tag('div', __('Permission denied'));
}
if(empty($vars['uid'])) {
return tag('div', __('No users'));
}
$users = array();
foreach ($vars['uid'] as $uid) {
$perm_names = array('read', 'write', 'readonly', 'modify',
'admin');
$old_perms = $phpcdb->get_permissions($phpcid, $uid);
$new_perms = array();
$different = false;
foreach($perm_names as $perm_name) {
$new_perms[$perm_name] =
asbool(!empty($vars["$perm_name$uid"]));
if(empty($old_perms[$perm_name]) !=
empty($vars["$perm_name$uid"]))
$different = true;
}
if ($different) {
$user = $phpcdb->get_user($uid);
$users[] = $user->get_username();
$phpcdb->update_permissions($phpcid, $uid, $new_perms);
}
}
if(sizeof($users) == 0)
$message = __('No changes to make.');
else
$message = __('Updated user(s):').' ' .implode(', ', $users);
return message_redirect($message, "$phpc_script?action=cadmin&phpcid=$phpcid");
}
| php | Apache-2.0 | e9473676f311aac8e9577cb3371ed362418441d9 | 2026-01-05T04:51:20.275579Z | false |
sproctor/php-calendar | https://github.com/sproctor/php-calendar/blob/e9473676f311aac8e9577cb3371ed362418441d9/src/search.php | src/search.php | <?php
/*
* Copyright 2012 Sean Proctor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
if(!defined('IN_PHPC')) {
die("Hacking attempt");
}
require_once("$phpc_includes_path/form.php");
/**
* @return Html
*/
function search_results()
{
global $vars, $phpcdb, $phpcid, $sort_options, $order_options;
$searchstring = $vars['searchstring'];
if(!empty($vars['search-from-date'])
&& strlen($vars['search-from-date']) > 0)
$start = get_timestamp('search-from');
else
$start = false;
if(!empty($vars['search-to-date'])
&& strlen($vars['search-to-date']) > 0)
$end = get_timestamp('search-to', 23, 59, 59);
else
$end = false;
// make sure sort is valid
$sort = phpc_html_escape($vars['sort']);
if(array_search($sort, array_keys($sort_options)) === false) {
soft_error(__('Invalid sort option') . ": $sort");
}
// make sure order is valid
$order = phpc_html_escape($vars['order']);
if(array_search($order, array_keys($order_options)) === false) {
soft_error(__('Invalid order option') . ": $order");
}
$keywords = explode(" ", $searchstring);
$results = $phpcdb->search($phpcid, $keywords, $start, $end, $sort,
$order);
$tags = array();
foreach ($results as $event) {
if(!$event->can_read())
continue;
$subject = $event->get_subject();
$desc = $event->get_desc();
$date = $event->get_date_string();
$time = $event->get_time_string();
$eid = $event->get_eid();
$tags[] = tag('tr',
tag('td',
tag('strong',
create_event_link(
$subject,
'display_event',
$eid)
)),
tag('td', "$date $time"),
tag('td', $desc));
}
if(sizeof($tags) == 0) {
$html = tag('div', tag('strong',
__('No events matched your search criteria.')));
} else {
$html = tag('table',
attributes('class="phpc-main"'),
tag('caption', __('Search Results')),
tag('thead',
tag('tr',
tag('th', __('Subject')),
tag('th', __('Date Time')),
tag('th', __('Description')))));
foreach($tags as $tag) $html->add($tag);
}
return $html;
}
/**
* @return Html
*/
function search_form()
{
global $phpc_script, $sort_options, $order_options, $phpcid, $phpc_cal;
$date_format = $phpc_cal->date_format;
$form = new Form($phpc_script, __('Search'),'post');
$form->add_part(new FormFreeQuestion('searchstring', __('Phrase'),
false, 32, true));
$form->add_hidden('action', 'search');
$form->add_hidden('phpcid', $phpcid);
$form->add_part(new FormDateQuestion('search-from', __('From'),
$date_format));
$form->add_part(new FormDateQuestion('search-to', __('To'),
$date_format));
$sort = new FormDropdownQuestion('sort', __('Sort By'));
$sort->add_options($sort_options);
$form->add_part($sort);
$order = new FormDropdownQuestion('order', __('Order'));
$order->add_options($order_options);
$form->add_part($order);
$form->add_part(new FormSubmitButton(__("Search")));
return $form->get_form();
}
/**
* @return Html
*/
function search()
{
global $vars;
if(isset($vars['searchstring'])) return search_results();
return search_form();
}
| php | Apache-2.0 | e9473676f311aac8e9577cb3371ed362418441d9 | 2026-01-05T04:51:20.275579Z | false |
sproctor/php-calendar | https://github.com/sproctor/php-calendar/blob/e9473676f311aac8e9577cb3371ed362418441d9/src/display_week.php | src/display_week.php | <?php
/*
* Copyright 2013 Sean Proctor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
This file has the functions for the main displays of the calendar
*/
if ( !defined('IN_PHPC') ) {
die("Hacking attempt");
}
// Full display for a month
/**
* @return Html
*/
function display_week()
{
global $vars;
$heading_html = tag('tr');
$heading_html->add(tag('th', __p('Week', 'W')));
for($i = 0; $i < 7; $i++) {
$d = ($i + day_of_week_start()) % 7;
$heading_html->add(tag('th', day_name($d)));
}
if(!isset($vars['week']) || !isset($vars['year']))
soft_error(__('Invalid date.'));
$week_of_year = intval($vars['week']);
$year = intval($vars['year']);
$week_of_first = week_of_year(1, 1, $year);
if($week_of_first != 1) {
$offset = 0;
} else {
$offset = -1;
}
$day_of_year = 1 + ($week_of_year + $offset) * 7 - day_of_week(1, 1, $year);
$from_stamp = mktime(0, 0, 0, 1, $day_of_year, $year);
$start_month = date("n", $from_stamp);
$start_year = date("Y", $from_stamp);
$last_day = $day_of_year + 6;
$to_stamp = mktime(23, 59, 59, 1, $last_day, $year);
$end_month = date("n", $to_stamp);
$end_year = date("Y", $to_stamp);
$heading = month_name($start_month) . " $start_year";
if($end_month != $start_month)
$heading .= " - " . month_name($end_month) . " $end_year";
return tag('',
tag("div", attributes('id="phpc-summary-view"'),
tag("div", attributes('id="phpc-summary-head"'),
tag("div", attributes('id="phpc-summary-title"'), ''),
tag("div", attributes('id="phpc-summary-author"'), ''),
tag("div", attributes('id="phpc-summary-category"'), ''),
tag("div", attributes('id="phpc-summary-time"'), '')),
tag("div", attributes('id="phpc-summary-body"'), '')),
tag('table',
attributes('class="phpc-main phpc-calendar"'),
tag('caption', $heading),
tag('colgroup',
tag('col', attributes('class="phpc-week"')),
tag('col', attributes('class="phpc-day"')),
tag('col', attributes('class="phpc-day"')),
tag('col', attributes('class="phpc-day"')),
tag('col', attributes('class="phpc-day"')),
tag('col', attributes('class="phpc-day"')),
tag('col', attributes('class="phpc-day"')),
tag('col', attributes('class="phpc-day"'))
),
tag('thead', $heading_html),
create_week($week_of_year, $from_stamp, $to_stamp)));
}
// creates a display for a particular week to be embedded in a month table
/**
* @param int $week_of_year
* @param int $from_stamp
* @param int $to_stamp
* @return Html
*/
function create_week($week_of_year, $from_stamp, $to_stamp)
{
global $phpcdb, $phpcid, $phpc_cal;
$start_day = date("j", $from_stamp);
$start_month = date("n", $from_stamp);
$start_year = date("Y", $from_stamp);
$max_events = $phpc_cal->events_max;
$results = $phpcdb->get_occurrences_by_date_range($phpcid, $from_stamp, $to_stamp);
$days_events = array();
while($row = $results->fetch_assoc()) {
$event = new PhpcOccurrence($row);
if(!$event->can_read())
continue;
$end_stamp = mktime(0, 0, 0, $event->get_end_month(),
$event->get_end_day(), $event->get_end_year());
$start_stamp = mktime(0, 0, 0, $event->get_start_month(),
$event->get_start_day(),
$event->get_start_year());
$diff = $from_stamp - $start_stamp;
if($diff > 0)
$add_days = floor($diff / 86400);
else
$add_days = 0;
// put the event in every day until the end
for(; ; $add_days++) {
$stamp = mktime(0, 0, 0, $event->get_start_month(),
$event->get_start_day() + $add_days,
$event->get_start_year());
if($stamp > $end_stamp || $stamp > $to_stamp)
break;
$key = date('Y-m-d', $stamp);
if(!isset($days_events[$key]))
$days_events[$key] = array();
if(sizeof($days_events[$key]) == $max_events)
$days_events[$key][] = false;
if(sizeof($days_events[$key]) > $max_events)
continue;
$days_events[$key][] = $event;
}
}
$week_table = tag('tbody');
$week_html = tag('tr', tag('th', $week_of_year));
$week_table->add($week_html);
for($day_of_week = 0; $day_of_week < 7; $day_of_week++) {
$day = $start_day + $day_of_week;
$week_html->add(create_day($start_month, $day, $start_year,
$days_events));
}
return $week_table;
}
// displays the day of the week and the following days of the week
/**
* @param int $month
* @param int $day
* @param int $year
* @param PhpcOccurrence[][] $days_events
* @return Html
*/
function create_day($month, $day, $year, $days_events)
{
global $phpc_cal;
$date_class = 'ui-state-default';
if($day <= 0) {
$month--;
if($month < 1) {
$month = 12;
$year--;
}
$day += days_in_month($month, $year);
$date_class .= ' phpc-shadow';
} elseif($day > days_in_month($month, $year)) {
$day -= days_in_month($month, $year);
$month++;
if($month > 12) {
$month = 1;
$year++;
}
} else {
$currentday = date('j');
$currentmonth = date('n');
$currentyear = date('Y');
// set whether the date is in the past or future/present
if($currentyear == $year && $currentmonth == $month
&& $currentday == $day) {
$date_class .= ' ui-state-highlight';
}
}
$click = create_action_url('display_day', $year, $month, $day);
$date_tag = tag('div', attributes("class=\"phpc-date $date_class\"",
"onclick=\"window.location.href='$click'\""),
create_action_link_with_date($day,
'display_day', $year, $month, $day));
if($phpc_cal->can_write()) {
$date_tag->add(create_action_link_with_date('+',
'event_form', $year, $month,
$day,
array('class="phpc-add"')));
}
$html_day = tag('td', $date_tag);
$stamp = mktime(0, 0, 0, $month, $day, $year);
$can_read = $phpc_cal->can_read();
$key = date('Y-m-d', $stamp);
if(!$can_read || !array_key_exists($key, $days_events))
return $html_day;
$results = $days_events[$key];
if(empty($results))
return $html_day;
$html_events = tag('ul', attrs('class="phpc-event-list"'));
$html_day->add($html_events);
// Count the number of events
foreach($results as $event) {
if($event == false) {
$event_html = tag('li',
create_action_link_with_date(__("View Additional Events"),
'display_day', $year, $month,
$day,
array('class="phpc-date"')));
$html_events->add($event_html);
break;
}
// TODO - make sure we have permission to read the event
$subject = $event->get_subject();
if($event->get_start_timestamp() >= $stamp)
$event_time = $event->get_time_string();
else
$event_time = '(' . __('continued') . ')';
if(!empty($event_time))
$title = "$event_time - $subject";
else
$title = $subject;
$style = "";
if(!empty($event->text_color))
$style .= "color: {$event->get_text_color()} !important;";
if(!empty($event->bg_color))
$style .= "background: ".$event->get_bg_color()
." !important;";
$event_html = tag('li',
create_occurrence_link($title, "display_event",
$event->get_oid(),
array("style=\"$style\"")));
$html_events->add($event_html);
}
return $html_day;
}
| php | Apache-2.0 | e9473676f311aac8e9577cb3371ed362418441d9 | 2026-01-05T04:51:20.275579Z | false |
sproctor/php-calendar | https://github.com/sproctor/php-calendar/blob/e9473676f311aac8e9577cb3371ed362418441d9/src/group_form.php | src/group_form.php | <?php
/*
* Copyright 2013 Sean Proctor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
if(!defined('IN_PHPC')) {
die("Hacking attempt");
}
require_once("$phpc_includes_path/form.php");
/**
* @return Html
*/
function group_form() {
global $phpc_script, $vars, $phpcdb, $phpcid;
$form = new Form($phpc_script, __('Group Form'));
$form->add_part(new FormFreeQuestion('name', __('Name'),
false, 32, true));
$form->add_hidden('cid', $phpcid);
$form->add_hidden('action', 'group_submit');
$form->add_part(new FormSubmitButton(__("Submit Group")));
if(isset($vars['gid'])) {
$form->add_hidden('gid', $vars['gid']);
$group = $phpcdb->get_group($vars['gid']);
$defaults = array('name' => phpc_html_escape($group['name']));
} else {
$defaults = array();
}
return $form->get_form($defaults);
}
| php | Apache-2.0 | e9473676f311aac8e9577cb3371ed362418441d9 | 2026-01-05T04:51:20.275579Z | false |
sproctor/php-calendar | https://github.com/sproctor/php-calendar/blob/e9473676f311aac8e9577cb3371ed362418441d9/src/event_form.php | src/event_form.php | <?php
/*
* Copyright 2012 Sean Proctor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
if(!defined('IN_PHPC')) {
die("Hacking attempt");
}
require_once("$phpc_includes_path/form.php");
/**
* @return Html
*/
function event_form() {
global $vars;
if(empty($vars["submit_form"]))
return display_form();
// else
return process_form();
}
/**
* @return Html
*/
function display_form() {
/** @var PhpcUser $phpc_user */
global $phpc_script, $year, $month, $day, $vars, $phpcdb, $phpc_cal,
$phpc_user, $phpc_token;
$hour24 = $phpc_cal->hours_24;
$date_format = $phpc_cal->date_format;
$form = new Form($phpc_script, __('Event Form'));
$form->add_part(new FormFreeQuestion('subject', __('Subject'),
false, $phpc_cal->subject_max, true));
$form->add_part(new FormLongFreeQuestion('description',
__('Description')));
$when_group = new FormGroup(__('When'), 'phpc-when');
if(isset($vars['eid'])) {
$when_group->add_part(new FormCheckBoxQuestion('phpc-modify',
false,
__('Change the event date and time')));
}
$when_group->add_part(new FormDateTimeQuestion('start',
__('From'), $hour24, $date_format));
$when_group->add_part(new FormDateTimeQuestion('end', __('To'),
$hour24, $date_format));
$time_type = new FormDropDownQuestion('time-type', __('Time Type'));
$time_type->add_option('normal', __('Normal'));
$time_type->add_option('full', __('Full Day'));
$time_type->add_option('tba', __('To Be Announced'));
$when_group->add_part($time_type);
$form->add_part($when_group);
$repeat_type = new FormDropdownQuestion('repeats', __('Repeats'),
array(), true, 'never');
$repeat_type->add_option('never', __('Never'));
$daily_group = new FormGroup();
$repeat_type->add_option('daily', __('Daily'), NULL, $daily_group);
$weekly_group = new FormGroup();
$repeat_type->add_option('weekly', __('Weekly'), NULL, $weekly_group);
$monthly_group = new FormGroup();
$repeat_type->add_option('monthly', __('Monthly'), NULL, $monthly_group);
$yearly_group = new FormGroup();
$repeat_type->add_option('yearly', __('Yearly'), NULL, $yearly_group);
$every_day = new FormDropdownQuestion('every-day', __('Every'),
__('Repeat every how many days?'));
$every_day->add_options(create_sequence(1, 30));
$daily_group->add_part($every_day);
$daily_group->add_part(new FormDateQuestion('daily-until', __('Until'),
$date_format));
$every_week = new FormDropdownQuestion('every-week', __('Every'),
__('Repeat every how many weeks?'));
$every_week->add_options(create_sequence(1, 30));
$weekly_group->add_part($every_week);
$weekly_group->add_part(new FormDateQuestion('weekly-until',
__('Until'), $date_format));
$every_month = new FormDropdownQuestion('every-month', __('Every'),
__('Repeat every how many months?'));
$every_month->add_options(create_sequence(1, 30));
$monthly_group->add_part($every_month);
$monthly_group->add_part(new FormDateQuestion('monthly-until',
__('Until'), $date_format));
$every_year = new FormDropdownQuestion('every-year', __('Every'),
__('Repeat every how many years?'));
$every_year->add_options(create_sequence(1, 30));
$yearly_group->add_part($every_year);
$yearly_group->add_part(new FormDateQuestion('yearly-until',
__('Until'), $date_format));
$when_group->add_part($repeat_type);
if($phpc_cal->can_create_readonly())
$form->add_part(new FormCheckBoxQuestion('readonly', false,
__('Read-only')));
$categories = new FormDropdownQuestion('catid', __('Category'));
$categories->add_option('', __('None'));
$have_categories = false;
foreach($phpc_cal->get_visible_categories($phpc_user->get_uid()) as $category) {
$categories->add_option($category['catid'], $category['name']);
$have_categories = true;
}
if($have_categories)
$form->add_part($categories);
if(isset($vars['phpcid']))
$form->add_hidden('phpcid', $vars['phpcid']);
$form->add_hidden('phpc_token', $phpc_token);
$form->add_hidden('action', 'event_form');
$form->add_hidden('submit_form', 'submit_form');
$form->add_part(new FormSubmitButton(__("Submit Event")));
if(isset($vars['eid'])) {
$form->add_hidden('eid', $vars['eid']);
$occs = $phpcdb->get_occurrences_by_eid($vars['eid']);
$event = $occs[0];
$defaults = array(
'subject' => $event->get_raw_subject(),
'description' => $event->get_raw_desc(),
'start-date' => $event->get_short_start_date(),
'end-date' => $event->get_short_end_date(),
'start-time' => $event->get_start_time(),
'end-time' => $event->get_end_time(),
'readonly' => $event->is_readonly(),
);
if(!empty($event->catid))
$defaults['catid'] = $event->catid;
switch($event->get_time_type()) {
case 0:
$defaults['time-type'] = 'normal';
break;
case 1:
$defaults['time-type'] = 'full';
break;
case 2:
$defaults['time-type'] = 'tba';
break;
}
add_repeat_defaults($occs, $defaults);
} else {
$hour24 = $phpc_cal->hours_24;
$datefmt = $phpc_cal->date_format;
$date_string = format_short_date_string($year, $month, $day,
$datefmt);
$defaults = array(
'start-date' => $date_string,
'end-date' => $date_string,
'start-time' => format_time_string(17, 0, $hour24),
'end-time' => format_time_string(18, 0, $hour24),
'daily-until-date' => $date_string,
'weekly-until-date' => $date_string,
'monthly-until-date' => $date_string,
'yearly-until-date' => $date_string,
);
}
return $form->get_form($defaults);
}
/**
* @param PhpcOccurrence[] $occs
* @param $defaults
*/
function add_repeat_defaults($occs, &$defaults) {
// TODO: Handle unevenly spaced occurrences
$defaults['repeats'] = 'never';
if(sizeof($occs) < 2)
return;
$event = $occs[0];
$day = $event->get_start_day();
$month = $event->get_start_month();
$year = $event->get_start_year();
$cur_year = $year;
$cur_month = $month;
$cur_day = $day;
// Test if they repeat every N years
$nyears = $occs[1]->get_start_year() - $event->get_start_year();
$repeats_yearly = true;
$nmonths = ($occs[1]->get_start_year() - $year) * 12
+ $occs[1]->get_start_month() - $month;
$repeats_monthly = true;
$ndays = days_between($event->get_start_ts(), $occs[1]->get_start_ts());
$repeats_daily = true;
for($i = 1; $i < sizeof($occs); $i++) {
$cur_occ = $occs[$i];
$cur_year = $cur_occ->get_start_year();
$cur_month = $cur_occ->get_start_month();
$cur_day = $cur_occ->get_start_day();
// Check year
$cur_nyears = $cur_year - $occs[$i - 1]->get_start_year();
if($cur_day != $day || $cur_month != $month
|| $cur_nyears != $nyears) {
$repeats_yearly = false;
}
// Check month
$cur_nmonths = ($cur_year - $occs[$i - 1]->get_start_year())
* 12 + $cur_month - $occs[$i - 1]->get_start_month();
if($cur_day != $day || $cur_nmonths != $nmonths) {
$repeats_monthly = false;
}
// Check day
$cur_ndays = days_between($occs[$i - 1]->get_start_ts(),
$occs[$i]->get_start_ts());
if($cur_ndays != $ndays) {
$repeats_daily = false;
}
}
$defaults['yearly-until-date'] = "$cur_month/$cur_day/$cur_year";
$defaults['monthly-until-date'] = "$cur_month/$cur_day/$cur_year";
$defaults['weekly-until-date'] = "$cur_month/$cur_day/$cur_year";
$defaults['daily-until-date'] = "$cur_month/$cur_day/$cur_year";
if($repeats_daily) {
// repeats weekly
if($ndays % 7 == 0) {
$defaults['repeats'] = 'weekly';
$defaults['every-week'] = $ndays / 7;
} else {
$defaults['every-week'] = 1;
// repeats daily
$defaults['repeats'] = 'daily';
$defaults['every-day'] = $ndays;
}
} else {
$defaults['every-day'] = 1;
$defaults['every-week'] = 1;
}
if($repeats_monthly) {
$defaults['repeats'] = 'monthly';
$defaults['every-month'] = $nmonths;
} else {
$defaults['every-month'] = 1;
}
if($repeats_yearly) {
$defaults['repeats'] = 'yearly';
$defaults['every-year'] = $nyears;
} else {
$defaults['every-year'] = 1;
}
}
/**
* @return Html
*/
function process_form()
{
/** @var PhpcUser $phpc_user */
global $vars, $phpcdb, $phpc_cal, $phpcid, $phpc_script, $phpc_user;
// When modifying events, this is the value of the checkbox that
// determines if the date should change
$modify_occur = !isset($vars['eid']) || !empty($vars['phpc-modify']);
if($modify_occur) {
$start_ts = get_timestamp("start");
$end_ts = get_timestamp("end");
switch($vars["time-type"]) {
case 'normal':
$time_type = 0;
break;
case 'full':
$time_type = 1;
break;
case 'tba':
$time_type = 2;
break;
default:
soft_error(__("Unrecognized Time Type."));
}
$duration = $end_ts - $start_ts;
if($duration < 0) {
message(__("An event cannot have an end earlier than its start."));
return display_form();
}
}
verify_token();
if(!$phpc_cal->can_write())
permission_error(__('You do not have permission to write to this calendar.'));
if($phpc_cal->can_create_readonly() && !empty($vars['readonly']))
$readonly = true;
else
$readonly = false;
$catid = empty($vars['catid']) ? false : $vars['catid'];
if(!isset($vars['eid'])) {
$modify = false;
$eid = $phpcdb->create_event($phpcid, $phpc_user->get_uid(),
$vars["subject"], $vars["description"],
$readonly, $catid);
} else {
$modify = true;
$eid = $vars['eid'];
$phpcdb->modify_event($eid, $vars['subject'],
$vars['description'], $readonly, $catid);
if($modify_occur)
$phpcdb->delete_occurrences($eid);
}
if($modify_occur) {
$phpcdb->create_occurrence($eid, $time_type, $start_ts, $end_ts);
$occurrences = 1;
switch($vars["repeats"]) {
case "never":
break;
case 'daily':
if(!isset($vars["every-day"]))
soft_error(__("Required field \"every-day\" is not set."));
$ndays = $vars["every-day"];
if($ndays < 1)
soft_error(__("every-day must be greater than 1"));
$daily_until = get_timestamp("daily-until");
while($occurrences <= 730) {
$start_ts = add_days($start_ts, $ndays);
$end_ts = add_days($end_ts, $ndays);
if(days_between($start_ts, $daily_until) < 0)
break;
$phpcdb->create_occurrence($eid, $time_type,
$start_ts, $end_ts);
$occurrences++;
}
break;
case 'weekly':
if(!isset($vars["every-week"]))
soft_error(__("Required field \"every-week\" is not set."));
if($vars["every-week"] < 1)
soft_error(__("every-week must be greater than 1"));
$ndays = $vars["every-week"] * 7;
$weekly_until = get_timestamp("weekly-until");
while($occurrences <= 730) {
$start_ts = add_days($start_ts, $ndays);
$end_ts = add_days($end_ts, $ndays);
if(days_between($start_ts, $weekly_until) < 0)
break;
$phpcdb->create_occurrence($eid, $time_type,
$start_ts, $end_ts);
$occurrences++;
}
break;
case 'monthly':
if(!isset($vars["every-month"]))
soft_error(__("Required field \"every-month\" is not set."));
if($vars["every-month"] < 1)
soft_error(__("every-month must be greater than 1"));
$nmonths = $vars["every-month"];
$monthly_until = get_timestamp("monthly-until");
while($occurrences <= 730) {
$start_ts = add_months($start_ts, $nmonths);
$end_ts = add_months($end_ts, $nmonths);
if(days_between($start_ts, $monthly_until) < 0)
break;
$phpcdb->create_occurrence($eid, $time_type,
$start_ts, $end_ts);
$occurrences++;
}
break;
case 'yearly':
if(!isset($vars["every-year"]))
soft_error(__("Required field \"every-year\" is not set."));
if($vars["every-year"] < 1)
soft_error(__("every-month must be greater than 1"));
$nyears = $vars["every-year"];
$yearly_until = get_timestamp("yearly-until");
while($occurrences <= 730) {
$start_ts = add_years($start_ts, $nyears);
$end_ts = add_years($end_ts, $nyears);
if(days_between($start_ts, $yearly_until) < 0)
break;
$phpcdb->create_occurrence($eid, $time_type,
$start_ts, $end_ts);
$occurrences++;
}
break;
default:
soft_error(__("Invalid event type."));
}
}
if($eid != 0) {
if($modify)
$message = __("Modified event: ");
else
$message = __("Created event: ");
return message_redirect(tag('', $message,
create_event_link($eid, 'display_event',
$eid)),
"$phpc_script?action=display_event&phpcid=$phpcid&eid=$eid");
} else {
return message_redirect(__('Error submitting event.'),
"$phpc_script?action=display_month&phpcid=$phpcid");
}
}
| php | Apache-2.0 | e9473676f311aac8e9577cb3371ed362418441d9 | 2026-01-05T04:51:20.275579Z | false |
sproctor/php-calendar | https://github.com/sproctor/php-calendar/blob/e9473676f311aac8e9577cb3371ed362418441d9/src/phpcevent.class.php | src/phpcevent.class.php | <?php
/*
* Copyright 2012 Sean Proctor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
class PhpcEvent {
/** @var int */
var $eid;
/** @var int */
var $cid;
/** @var int */
var $uid;
/** @var string */
var $author;
/** @var string */
var $subject;
/** @var string */
var $desc;
/** @var bool */
var $readonly;
/** @var string */
var $category;
/** @var string */
var $bg_color;
/** @var string */
var $text_color;
/** @var int */
var $catid;
/** @var int */
var $gid;
var $ctime;
var $mtime;
/** @var PhpcCalendar */
var $cal;
/**
* PhpcEvent constructor.
* @param string[] $event
*/
function __construct($event)
{
global $phpcdb;
$this->eid = intval($event['eid']);
$this->cid = intval($event['cid']);
$this->uid = intval($event['owner']);
if(empty($event['owner']))
$this->author = __('anonymous');
elseif(empty($event['username']))
$this->author = __('unknown');
else
$this->author = $event['username'];
$this->subject = $event['subject'];
$this->desc = $event['description'];
$this->readonly = intval($event['readonly']) != 0;
$this->category = $event['name'];
$this->bg_color = $event['bg_color'];
$this->text_color = $event['text_color'];
$this->catid = intval($event['catid']);
$this->gid = intval($event['gid']);
$this->ctime = $event['ctime'];
$this->mtime = $event['mtime'];
$this->cal = $phpcdb->get_calendar($this->cid);
}
/**
* @return string
*/
function get_raw_subject() {
return phpc_html_escape($this->subject);
}
/**
* @return string
*/
function get_subject()
{
if(empty($this->subject))
return __('(No subject)');
return phpc_html_escape(stripslashes($this->subject));
}
/**
* @return string
*/
function get_author()
{
return $this->author;
}
/**
* @return int
*/
function get_uid()
{
return $this->uid;
}
/**
* @return string
*/
function get_raw_desc() {
// Don't allow tags and make the description HTML-safe
return phpc_html_escape($this->desc);
}
/**
* @return string
*/
function get_desc()
{
return $this->desc;
}
/**
* @return int
*/
function get_eid()
{
return $this->eid;
}
/**
* @return int
*/
function get_cid()
{
return $this->cid;
}
/**
* @return bool
*/
function is_readonly()
{
return $this->readonly;
}
/**
* @return string
*/
function get_text_color()
{
return phpc_html_escape($this->text_color);
}
/**
* @return string
*/
function get_bg_color()
{
return phpc_html_escape($this->bg_color);
}
/**
* @return string
*/
function get_category()
{
if(empty($this->category))
return $this->category;
return phpc_html_escape($this->category);
}
/**
* @return bool
*/
function is_owner() {
global $phpc_user;
/** @var PhpcUser $phpc_user */
return $phpc_user->get_uid() == $this->get_uid();
}
// returns whether or not the current user can modify $event
function can_modify()
{
return $this->cal->can_admin() || $this->is_owner()
|| ($this->cal->can_modify() && !$this->is_readonly());
}
// returns whether or not the current user can read $event
function can_read() {
global $phpcdb, $phpc_user;
/** @var PhpcUser $phpc_user */
$visible_category = empty($this->gid) || !isset($this->catid)
|| $phpcdb->is_cat_visible($phpc_user->get_uid(),
$this->catid);
return $this->cal->can_read() && $visible_category;
}
function get_ctime_string() {
return format_timestamp_string($this->ctime,
$this->cal->date_format,
$this->cal->hours_24);
}
function get_mtime_string() {
return format_timestamp_string($this->mtime,
$this->cal->date_format,
$this->cal->hours_24);
}
}
| php | Apache-2.0 | e9473676f311aac8e9577cb3371ed362418441d9 | 2026-01-05T04:51:20.275579Z | false |
sproctor/php-calendar | https://github.com/sproctor/php-calendar/blob/e9473676f311aac8e9577cb3371ed362418441d9/src/user_groups.php | src/user_groups.php | <?php
/*
* Copyright 2013 Sean Proctor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
if(!defined('IN_PHPC')) {
die("Hacking attempt");
}
/**
* @return Html
*/
function user_groups() {
global $vars, $phpc_cal;
if(!$phpc_cal->can_admin()) {
return tag('div', __('Permission denied'));
}
if(!empty($vars['submit_form']))
process_form();
return display_form();
}
/**
* @return Html
*/
function display_form() {
global $phpc_script, $phpc_token, $phpcdb, $vars, $phpc_cal, $phpcid;
$groups = array();
foreach($phpc_cal->get_groups() as $group) {
$groups[$group['gid']] = $group['name'];
}
$size = sizeof($groups);
if($size > 6)
$size = 6;
$user = $phpcdb->get_user($vars["uid"]);
$user_groups = array();
foreach($user->get_groups() as $group) {
$user_groups[] = $group['gid'];
}
return tag('form', attributes("action=\"$phpc_script\"",
'method="post"'),
tag('div', attributes("class=\"phpc-container\""),
tag('h2', __('Edit User Groups')),
tag('div', create_select('groups[]', $groups,
$user_groups,
attrs('multiple', "size=\"$size\""))),
tag('div',
create_hidden('phpc_token',
$phpc_token),
create_hidden('uid', $vars['uid']),
create_hidden('phpcid', $phpcid),
create_hidden('action', 'user_groups'),
create_hidden('submit_form',
'submit_form'),
create_submit(__('Submit')))));
}
function process_form()
{
global $phpcid, $vars, $phpcdb, $phpc_cal;
verify_token();
$user = $phpcdb->get_user($vars["uid"]);
// Remove existing groups for this calendar
foreach($user->get_groups() as $group) {
if($group["cid"] == $phpcid)
$phpcdb->user_remove_group($vars["uid"], $group["gid"]);
}
$valid_groups = array();
foreach($phpc_cal->get_groups() as $group) {
$valid_groups[] = $group["gid"];
}
if(!empty($vars["groups"])) {
foreach($vars["groups"] as $gid) {
if(!in_array($gid, $valid_groups))
soft_error("Invalid gid");
$phpcdb->user_add_group($vars["uid"], $gid);
}
}
return message(__('Groups updated.'));
}
| php | Apache-2.0 | e9473676f311aac8e9577cb3371ed362418441d9 | 2026-01-05T04:51:20.275579Z | false |
sproctor/php-calendar | https://github.com/sproctor/php-calendar/blob/e9473676f311aac8e9577cb3371ed362418441d9/src/setup.php | src/setup.php | <?php
/*
* Copyright 2012 Sean Proctor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
This file sets up the global variables to be used later
*/
if ( !defined('IN_PHPC') ) {
die("Hacking attempt");
}
// Run the installer if we have no config file
// This doesn't work when embedded from outside
if(!file_exists($phpc_config_file)) {
redirect('install.php');
exit;
}
require_once($phpc_config_file);
if(!defined('SQL_TYPE')) {
redirect('install.php');
exit;
}
if(defined('PHPC_DEBUG')) {
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('html_errors', 1);
}
$phpc_prefix = "phpc_" . SQL_PREFIX . SQL_DATABASE;
require_once("$phpc_includes_path/calendar.php");
// Make the database connection.
require_once("$phpc_includes_path/phpcdatabase.class.php");
if(!defined("SQL_PORT"))
define("SQL_PORT", ini_get("mysqli.default_port"));
$phpcdb = new PhpcDatabase(SQL_HOST, SQL_USER, SQL_PASSWD, SQL_DATABASE,
SQL_PORT);
session_set_cookie_params(0, "", "", false, true);
session_start();
if(empty($_SESSION["{$phpc_prefix}uid"])) {
if(!empty($_COOKIE["{$phpc_prefix}login"])
&& !empty($_COOKIE["{$phpc_prefix}uid"])
&& !empty($_COOKIE["{$phpc_prefix}login_series"])) {
// Cleanup before we check their token so they can't login with
// an ancient token
$phpcdb->cleanup_login_tokens();
$phpc_uid = $_COOKIE["{$phpc_prefix}uid"];
$phpc_login_series = $_COOKIE["{$phpc_prefix}login_series"];
$phpc_token = $phpcdb->get_login_token($phpc_uid,
$phpc_login_series);
if($phpc_token) {
if($phpc_token == $_COOKIE["{$phpc_prefix}login"]) {
$user = $phpcdb->get_user($phpc_uid);
phpc_do_login($user, $phpc_login_series);
} else {
$phpcdb->remove_login_tokens($phpc_uid);
soft_error(__("Possible hacking attempt on your account."));
}
} else {
$phpc_uid = 0;
}
}
} else {
$phpc_token = $_SESSION["{$phpc_prefix}login"];
}
if(empty($phpc_token))
$phpc_token = '';
// Create vars
$vars = array_merge(real_escape_r($_GET), real_escape_r($_POST));
// Find an appropriate calendar id
if(!empty($vars['phpcid'])) {
if(!is_numeric($vars['phpcid']))
soft_error(__("Invalid calendar ID."));
$phpcid = $vars['phpcid'];
} elseif(!empty($default_calendar_id)) {
$phpcid = $default_calendar_id;
} else {
$phpcid = 1;
}
if (!$phpcdb->have_calendar($phpcid)) {
$phpcid = 1;
if (!$phpcdb->have_calendar($phpcid))
soft_error(__("Could not find a calendar."));
}
$phpc_cal = $phpcdb->get_calendar($phpcid);
//set action
if(empty($vars['action'])) {
$action = 'display_month';
} else {
$action = $vars['action'];
}
if(empty($vars['contentType']))
$vars['contentType'] = "html";
if(!empty($_SESSION["{$phpc_prefix}uid"])) {
$phpc_user = $phpcdb->get_user($_SESSION["{$phpc_prefix}uid"]);
} else {
$anonymous = array('uid' => 0,
'username' => 'anonymous',
'password' => '',
'admin' => false,
'password_editable' => false,
'timezone' => NULL,
'language' => NULL,
);
if(isset($_COOKIE["{$phpc_prefix}tz"]))
$anonymous['timezone'] = $_COOKIE["{$phpc_prefix}tz"];
if(isset($_COOKIE["{$phpc_prefix}lang"]))
$anonymous['language'] = $_COOKIE["{$phpc_prefix}lang"];
$phpc_user = new PhpcUser($anonymous);
}
$phpc_user_lang = $phpc_user->get_language();
$phpc_user_tz = $phpc_user->get_timezone();
// setup translation stuff
if(!empty($vars['lang'])) {
$phpc_lang = $vars['lang'];
} elseif(!empty($phpc_user_lang)) {
$phpc_lang = $phpc_user_lang;
} elseif(!empty($phpc_cal->language)) {
$phpc_lang = $phpc_cal->language;
} elseif(!empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
$phpc_lang = substr(phpc_html_escape($_SERVER['HTTP_ACCEPT_LANGUAGE']),
0, 2);
} else {
$phpc_lang = 'en';
}
if(!preg_match('/^\w+$/', $phpc_lang, $matches))
$phpc_lang = 'en';
$phpc_gettext = new Gettext_PHP($phpc_locale_path, 'messages', $phpc_lang);
// Must be included after translation is setup
require_once("$phpc_includes_path/globals.php");
if(!empty($vars['clearmsg']))
$_SESSION["{$phpc_prefix}messages"] = NULL;
$phpc_messages = array();
if(!empty($_SESSION["{$phpc_prefix}messages"])) {
foreach($_SESSION["{$phpc_prefix}messages"] as $message) {
$phpc_messages[] = $message;
}
}
if(!empty($phpc_user_tz))
$phpc_tz = $phpc_user_tz;
else
$phpc_tz = $phpc_cal->timezone;
if(!empty($phpc_tz))
date_default_timezone_set($phpc_tz);
$phpc_tz = date_default_timezone_get();
// set day/month/year
if(isset($vars['month']) && is_numeric($vars['month'])) {
$month = $vars['month'];
if($month < 1 || $month > 12)
display_error(__("Month is out of range."));
} else {
$month = date('n');
}
if(isset($vars['year']) && is_numeric($vars['year'])) {
$time = mktime(0, 0, 0, $month, 1, $vars['year']);
if(!$time || $time < 0) {
display_error(__('Invalid year') . ": {$vars['year']}");
}
$year = date('Y', $time);
} else {
$year = date('Y');
}
if(isset($vars['day']) && is_numeric($vars['day'])) {
$day = ($vars['day'] - 1) % date('t', mktime(0, 0, 0, $month, 1, $year))
+ 1;
} else {
if($month == date('n') && $year == date('Y')) {
$day = date('j');
} else {
$day = 1;
}
}
if ($vars["contentType"] == "json") {
header("Content-Type: application/json; charset=UTF-8");
echo do_action();
exit;
}
header("Content-Type: text/html; charset=UTF-8");
header("X-Content-Type-Options: nosniff");
header("X-Frame-Options: DENY");
| php | Apache-2.0 | e9473676f311aac8e9577cb3371ed362418441d9 | 2026-01-05T04:51:20.275579Z | false |
sproctor/php-calendar | https://github.com/sproctor/php-calendar/blob/e9473676f311aac8e9577cb3371ed362418441d9/src/group_delete.php | src/group_delete.php | <?php
/*
* Copyright 2013 Sean Proctor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
if ( !defined('IN_PHPC') ) {
die("Hacking attempt");
}
/**
* @return Html
*/
function group_delete()
{
global $vars, $phpcdb, $phpcid, $phpc_script;
$html = tag('div', attributes('class="phpc-container"'));
if(empty($vars["gid"])) {
return message_redirect(__('No group selected.'),
"$phpc_script?action=cadmin&phpcid=$phpcid");
}
if (is_array($vars["gid"])) {
$ids = $vars["gid"];
} else {
$ids = array($vars["gid"]);
}
$groups = array();
foreach ($ids as $id) {
$groups[] = $phpcdb->get_group($id);
}
if (empty($vars["confirm"])) {
$list = tag('ul');
foreach ($groups as $group) {
$list->add(tag('li', $group['name']));
}
$html->add(tag('p', __('Confirm you want to delete:')));
$html->add($list);
$html->add(" [ ", create_action_link(__('Confirm'),
"group_delete", array("gid" => $ids,
"confirm" => "1")), " ] ");
$html->add(" [ ", create_action_link(__('Deny'),
"display_month"), " ] ");
return $html;
}
foreach($groups as $group) {
if((empty($group['cid']) && !is_admin()) ||
!$phpcdb->get_calendar($group['cid'])
->can_admin()) {
$html->add(tag('p', __("You do not have permission to delete group: ") . $group['gid']));
continue;
}
if($phpcdb->delete_group($group['gid'])) {
$html->add(tag('p', __("Removed group: ")
. $group['gid']));
} else {
$html->add(tag('p', __("Could not remove group: ")
. $group['gid']));
}
}
return message_redirect($html, "$phpc_script?action=cadmin&phpcid=$phpcid");
}
| php | Apache-2.0 | e9473676f311aac8e9577cb3371ed362418441d9 | 2026-01-05T04:51:20.275579Z | false |
sproctor/php-calendar | https://github.com/sproctor/php-calendar/blob/e9473676f311aac8e9577cb3371ed362418441d9/src/event_delete.php | src/event_delete.php | <?php
/*
* Copyright 2012 Sean Proctor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
if ( !defined('IN_PHPC') ) {
die("Hacking attempt");
}
/**
* @return Html
*/
function event_delete()
{
global $vars, $phpcdb, $phpc_script;
$html = tag('div', attributes('class="phpc-container"'));
if(empty($vars["eid"])) {
$message = __('No event selected.');
$html->add(tag('div', $message));
return $html;
}
if (is_array($vars["eid"])) {
$eids = $vars["eid"];
} else {
$eids = array($vars["eid"]);
}
if (empty($vars["confirm"])) {
$list = tag('ul');
foreach ($eids as $eid) {
$event = new PhpcEvent($phpcdb->get_event_by_eid($eid));
$list->add(tag('li', "$eid: ".$event->get_subject()));
}
$html->add(tag('div', __('Confirm you want to delete:')));
$html->add($list);
$html->add(" [ ", create_action_link(__('Confirm'),
"event_delete", array("eid" => $eids,
"confirm" => "1")), " ] ");
$html->add(" [ ", create_action_link(__('Deny'),
"display_month"), " ] ");
return $html;
}
$removed_events = array();
$unremoved_events = array();
$permission_denied = array();
foreach($eids as $eid) {
$event = new PhpcEvent($phpcdb->get_event_by_eid($eid));
if(!$event->can_modify()) {
$permission_denied[] = $eid;
} else {
if($phpcdb->delete_event($eid)) {
$removed_events[] = $eid;
} else {
$unremoved_events[] = $eid;
}
}
}
if(sizeof($removed_events) > 0) {
if(sizeof($removed_events) == 1)
$text = __("Removed event");
else
$text = __("Removed events");
$text .= ': ' . implode(', ', $removed_events);
$html->add(tag('div', $text));
}
if(sizeof($unremoved_events) > 0) {
if(sizeof($unremoved_events) == 1)
$text = __("Could not remove event");
else
$text = __("Could not remove events");
$text .= ': ' . implode(', ', $unremoved_events);
$html->add(tag('div', $text));
}
if(sizeof($permission_denied) > 0) {
if(sizeof($permission_denied) == 1)
$text = __("You do not have permission to remove event");
else
$text = __("You do not have permission to remove events");
$text .= ': ' . implode(', ', $permission_denied);
$html->add(tag('div', $text));
}
return message_redirect($html, $phpc_script);
}
| php | Apache-2.0 | e9473676f311aac8e9577cb3371ed362418441d9 | 2026-01-05T04:51:20.275579Z | false |
sproctor/php-calendar | https://github.com/sproctor/php-calendar/blob/e9473676f311aac8e9577cb3371ed362418441d9/src/user_create.php | src/user_create.php | <?php
/*
* Copyright 2012 Sean Proctor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
if(!defined('IN_PHPC')) {
die("Hacking attempt");
}
/**
* @return Html
*/
function user_create() {
global $vars;
if(!is_admin()) {
return tag('div', __('Permission denied'));
}
if(!empty($vars['submit_form']))
process_form();
return display_form();
}
/**
* @return Html
*/
function display_form() {
global $phpc_script, $phpc_token, $phpcdb;
$groups = array();
foreach($phpcdb->get_groups() as $group) {
$groups[$group['gid']] = $group['name'];
}
$size = sizeof($groups);
if($size > 6)
$size = 6;
return tag('form', attributes("action=\"$phpc_script\"",
'method="post"'),
tag('table', attributes("class=\"phpc-container\""),
tag('caption', __('Create User')),
tag('tfoot',
tag('tr',
tag('td', attributes('colspan="2"'),
create_hidden('phpc_token', $phpc_token),
create_hidden('action', 'user_create'),
create_hidden('submit_form', 'submit_form'),
create_submit(__('Submit'))))),
tag('tbody',
tag('tr',
tag('th', __('User Name')),
tag('td', create_text('user_name'))),
tag('tr',
tag('th', __('Password')),
tag('td', create_password('password1'))),
tag('tr',
tag('th', __('Confirm Password')),
tag('td', create_password('password2'))),
tag('tr',
tag('th', __('Make Admin')),
tag('td', create_checkbox('make_admin', '1', false, __('Admin')))),
tag('tr',
tag('th', __('Groups')),
tag('td', create_select('groups[]',
$groups, false, attrs('multiple', "size=\"$size\""))))
)));
}
function process_form()
{
global $vars, $phpcdb;
verify_token();
if(empty($vars['user_name'])) {
return message(__('You must specify a user name'));
}
if(empty($vars['password1'])) {
return message(__('You must specify a password'));
}
if(empty($vars['password2'])
|| $vars['password1'] != $vars['password2']) {
return message(__('Your passwords did not match'));
}
$make_admin = empty($vars['make_admin']) ? 0 : 1;
$passwd = md5($vars['password1']);
if($phpcdb->get_user_by_name($vars["user_name"]))
return message(__('User already exists.'));
$uid = $phpcdb->create_user($vars["user_name"], $passwd, $make_admin);
if(!empty($vars['groups'])) {
foreach($vars['groups'] as $gid) {
$phpcdb->user_add_group($uid, $gid);
}
}
return message(__('Added user.'));
}
| php | Apache-2.0 | e9473676f311aac8e9577cb3371ed362418441d9 | 2026-01-05T04:51:20.275579Z | false |
sproctor/php-calendar | https://github.com/sproctor/php-calendar/blob/e9473676f311aac8e9577cb3371ed362418441d9/src/login.php | src/login.php | <?php
/*
* Copyright 2012 Sean Proctor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
if(!defined('IN_PHPC')) {
die("Hacking attempt");
}
/**
* @return Html
*/
function login()
{
global $vars, $phpc_script;
$html = tag('div');
//Check password and username
if(isset($vars['username'])){
$user = $vars['username'];
$password = $vars['password'];
if(login_user($user, $password)){
$url = $phpc_script;
if(!empty($vars['lasturl'])) {
$url .= '?' . urldecode($vars['lasturl']);
}
redirect($url);
return tag('h2', __('Logged in.'));
}
$html->add(tag('h2', __('Sorry, Invalid Login')));
}
$html->add(login_form());
return $html;
}
/**
* @return Html
*/
function login_form()
{
global $vars, $phpc_script;
$submit_data = tag('td', attributes('colspan="2"'),
create_hidden('action', 'login'),
create_submit(__('Log in')));
if(!empty($vars['lasturl'])) {
$lasturl = phpc_html_escape(rawurlencode($vars['lasturl']));
$submit_data->prepend(create_hidden('lasturl',
$lasturl));
}
return tag('form', attributes("action=\"$phpc_script\"",
'method="post"'),
tag('table',
tag('caption', __('Log in')),
tag('thead',
tag('tr',
tag('th', attributes('colspan="2"'),
__('You must have cookies enabled to login.')))),
tag('tfoot',
tag('tr', $submit_data)),
tag('tbody',
tag('tr',
tag('th', tag('label', attributes('for="username"'), __('Username'))),
tag('td', create_text('username'))),
tag('tr',
tag('th', tag('label', attributes('for="password"'), __('Password'))),
tag('td', create_password('password'))))));
}
| php | Apache-2.0 | e9473676f311aac8e9577cb3371ed362418441d9 | 2026-01-05T04:51:20.275579Z | false |
sproctor/php-calendar | https://github.com/sproctor/php-calendar/blob/e9473676f311aac8e9577cb3371ed362418441d9/src/category_form.php | src/category_form.php | <?php
/*
* Copyright 2010 Sean Proctor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
if(!defined('IN_PHPC')) {
die("Hacking attempt");
}
require_once("$phpc_includes_path/form.php");
/**
* @return Html
*/
function category_form() {
global $phpc_script, $vars, $phpcdb, $phpcid;
$form = new Form($phpc_script, __('Category Form'));
$form->add_part(new FormFreeQuestion('name', __('Name'),
false, 32, true));
if(isset($vars['cid'])) {
$form->add_hidden('cid', $vars['cid']);
$cid = $vars['cid'];
} else {
$cid = $phpcid;
}
$form->add_hidden('action', 'category_submit');
$form->add_hidden('phpcid', $phpcid);
$form->add_part(new FormColorPicker('text-color',__('Text Color')));
$form->add_part(new FormColorPicker('bg-color',__('Background Color')));
$group_question = new FormDropDownQuestion('gid',
__('Visible to groups'));
$group_question->add_option('', __('None'));
foreach($phpcdb->get_groups($cid) as $group) {
$group_question->add_option($group['gid'], $group['name']);
}
$form->add_part($group_question);
$form->add_part(new FormSubmitButton(__("Submit Category")));
if(isset($vars['catid'])) {
$form->add_hidden('catid', $vars['catid']);
$category = $phpcdb->get_category($vars['catid']);
$defaults = array(
'name' => phpc_html_escape($category['name']),
'text-color' => phpc_html_escape(str_replace('#', '', $category['text_color'])),
'bg-color' => phpc_html_escape(str_replace('#', '', $category['bg_color'])),
'gid' => phpc_html_escape($category['gid']),
);
} else {
$defaults = array(
'text-color' => '#000000',
'bg-color' => '#FFFFFF',
);
}
return $form->get_form($defaults);
}
| php | Apache-2.0 | e9473676f311aac8e9577cb3371ed362418441d9 | 2026-01-05T04:51:20.275579Z | false |
sproctor/php-calendar | https://github.com/sproctor/php-calendar/blob/e9473676f311aac8e9577cb3371ed362418441d9/src/calendar_form.php | src/calendar_form.php | <?php
/*
* Copyright 2013 Sean Proctor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
if (!defined('IN_PHPC')) {
die("Hacking attempt");
}
/**
* @return Html
*/
function calendar_form()
{
global $vars;
if (!is_admin()) {
return tag('div', __('Permission denied'));
}
if (!empty($vars['submit_form']))
process_form();
return display_form();
}
function process_form()
{
global $vars, $phpcdb;
verify_token();
$cid = $phpcdb->create_calendar();
foreach (get_config_options() as $item) {
$name = $item[0];
$type = $item[2];
if ($type == PHPC_CHECK) {
if (isset($vars[$name]))
$value = "1";
else
$value = "0";
} else {
if (isset($vars[$name])) {
$value = $vars[$name];
} else {
soft_error(__("$name was not set."));
}
}
$phpcdb->create_config($cid, $name, $value);
}
message(__('Calendar created.'));
}
/**
* @return Html
*/
function display_form()
{
global $phpc_script, $phpc_token;
$tbody = tag('tbody');
foreach (get_config_options() as $element) {
$text = $element[1];
$input = create_config_input($element);
$tbody->add(tag('tr',
tag('th', $text),
tag('td', $input)));
}
return tag('form', attributes("action=\"$phpc_script\"",
'method="post"'),
tag('table', attributes("class=\"phpc-container\""),
tag('caption', __('Create Calendar')),
tag('tfoot',
tag('tr',
tag('td', attributes('colspan="2"'),
create_hidden('phpc_token', $phpc_token),
create_hidden('action', 'calendar_form'),
create_hidden('submit_form', 'submit_form'),
create_submit(__('Submit'))))),
$tbody));
}
| php | Apache-2.0 | e9473676f311aac8e9577cb3371ed362418441d9 | 2026-01-05T04:51:20.275579Z | false |
sproctor/php-calendar | https://github.com/sproctor/php-calendar/blob/e9473676f311aac8e9577cb3371ed362418441d9/src/msgfmt-functions.php | src/msgfmt-functions.php | <?php
/**
* php-msgfmt
*
* php-msgfmt is dual-licensed under
* the GNU Lesser General Public License, version 2.1, and
* the Apache License, version 2.0.
*
* For the terms of the licenses, see the LICENSE-LGPL.txt and LICENSE-AL2.txt
* files, respectively.
*
*
* Copyright (C) 2007 Matthias Bauer
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License, version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*
* Copyright 2007 Matthias Bauer
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @package php-msgfmt
* @version $Id$
* @copyright 2007 Matthias Bauer
* @author Matthias Bauer
* @license http://opensource.org/licenses/lgpl-license.php GNU Lesser General Public License 2.1
* @license http://opensource.org/licenses/apache2.0.php Apache License 2.0
*/
function _po_clean_helper($x) {
if (is_array($x)) {
foreach ($x as $k => $v) {
$x[$k]= _po_clean_helper($v);
}
} else {
if ($x[0] == '"')
$x= substr($x, 1, -1);
$x= str_replace("\"\n\"", '', $x);
$x= str_replace('$', '\\$', $x);
$x= @ eval ("return \"$x\";");
}
return $x;
}
/* Parse gettext .po files. */
/* @link http://www.gnu.org/software/gettext/manual/gettext.html#PO-Files */
function parse_po_file($in) {
// read .po file
$fc= file_get_contents($in);
// normalize newlines
$fc= str_replace(array (
"\r\n",
"\r"
), array (
"\n",
"\n"
), $fc);
// results array
$hash= array ();
// temporary array
$temp= array ();
// state
$state= null;
$fuzzy= false;
// iterate over lines
foreach (explode("\n", $fc) as $line) {
$line= trim($line);
if ($line === '')
continue;
$linexp=explode(' ', $line, 2);
$key=$linexp[0];
if(isset($linexp[1])) $data=$linexp[1];
switch ($key) {
case '#,' : // flag...
$fuzzy= in_array('fuzzy', preg_split('/,\s*/', $data));
case '#' : // translator-comments
case '#.' : // extracted-comments
case '#:' : // reference...
case '#|' : // msgid previous-untranslated-string
// start a new entry
if (sizeof($temp) && array_key_exists('msgid', $temp) && array_key_exists('msgstr', $temp)) {
if (!$fuzzy)
$hash[]= $temp;
$temp= array ();
$state= null;
$fuzzy= false;
}
break;
case 'msgctxt' :
// context
case 'msgid' :
// untranslated-string
case 'msgid_plural' :
// untranslated-string-plural
$state= $key;
$temp[$state]= $data;
break;
case 'msgstr' :
// translated-string
$state= 'msgstr';
$temp[$state][]= $data;
break;
default :
if (strpos($key, 'msgstr[') !== FALSE) {
// translated-string-case-n
$state= 'msgstr';
$temp[$state][]= $data;
} else {
// continued lines
switch ($state) {
case 'msgctxt' :
case 'msgid' :
case 'msgid_plural' :
$temp[$state] .= "\n" . $line;
break;
case 'msgstr' :
$temp[$state][sizeof($temp[$state]) - 1] .= "\n" . $line;
break;
default :
// parse error
return FALSE;
}
}
break;
}
}
// add final entry
if ($state == 'msgstr')
$hash[]= $temp;
// Cleanup data, merge multiline entries, reindex hash for ksort
$temp= $hash;
$hash= array ();
foreach ($temp as $entry) {
foreach ($entry as & $v) {
$v= _po_clean_helper($v);
if ($v === FALSE) {
// parse error
return FALSE;
}
}
$hash[$entry['msgid']]= $entry;
}
return $hash;
}
/* Write a GNU gettext style machine object. */
/* @link http://www.gnu.org/software/gettext/manual/gettext.html#MO-Files */
function write_mo_file($hash, $out) {
// sort by msgid
ksort($hash, SORT_STRING);
// our mo file data
$mo= '';
// header data
$offsets= array ();
$ids= '';
$strings= '';
foreach ($hash as $entry) {
$id= $entry['msgid'];
if (isset ($entry['msgid_plural']))
$id .= "\x00" . $entry['msgid_plural'];
// context is merged into id, separated by EOT (\x04)
if (array_key_exists('msgctxt', $entry))
$id= $entry['msgctxt'] . "\x04" . $id;
// plural msgstrs are NUL-separated
$str= implode("\x00", $entry['msgstr']);
// keep track of offsets
$offsets[]= array (
strlen($ids
), strlen($id), strlen($strings), strlen($str));
// plural msgids are not stored (?)
$ids .= $id . "\x00";
$strings .= $str . "\x00";
}
// keys start after the header (7 words) + index tables ($#hash * 4 words)
$key_start= 7 * 4 + sizeof($hash) * 4 * 4;
// values start right after the keys
$value_start= $key_start +strlen($ids);
// first all key offsets, then all value offsets
$key_offsets= array ();
$value_offsets= array ();
// calculate
foreach ($offsets as $v) {
list ($o1, $l1, $o2, $l2)= $v;
$key_offsets[]= $l1;
$key_offsets[]= $o1 + $key_start;
$value_offsets[]= $l2;
$value_offsets[]= $o2 + $value_start;
}
$offsets= array_merge($key_offsets, $value_offsets);
// write header
$mo .= pack('Iiiiiii', 0x950412de, // magic number
0, // version
sizeof($hash), // number of entries in the catalog
7 * 4, // key index offset
7 * 4 + sizeof($hash) * 8, // value index offset,
0, // hashtable size (unused, thus 0)
$key_start // hashtable offset
);
// offsets
foreach ($offsets as $offset)
$mo .= pack('i', $offset);
// ids
$mo .= $ids;
// strings
$mo .= $strings;
file_put_contents($out, $mo);
}
| php | Apache-2.0 | e9473676f311aac8e9577cb3371ed362418441d9 | 2026-01-05T04:51:20.275579Z | false |
sproctor/php-calendar | https://github.com/sproctor/php-calendar/blob/e9473676f311aac8e9577cb3371ed362418441d9/src/util.php | src/util.php | <?php
/*
* Copyright 2014 Sean Proctor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
if ( !defined('IN_PHPC') ) {
die("Hacking attempt");
}
// called when some error happens
/**
* @param string $message
* @throws Exception
*/
function soft_error($message)
{
throw new Exception(phpc_html_escape($message));
}
class PermissionException extends Exception {
}
/**
* @param string $message
* @throws PermissionException
*/
function permission_error($message)
{
throw new PermissionException(phpc_html_escape($message));
}
/**
* @param int $minute
* @return string
*/
function minute_pad($minute)
{
return sprintf('%02d', $minute);
}
/**
* @param string $page
*/
function redirect($page) {
global $phpc_script, $phpc_server, $phpc_redirect, $phpc_proto;
session_write_close();
$phpc_redirect = true;
if($page[0] == "/") {
$dir = '';
} else {
$dir = dirname($phpc_script) . "/";
}
$url = "$phpc_proto://$phpc_server$dir$page";
header("Location: $url");
}
/**
* @param string $message
* @param string $page
* @return Html
*/
function message_redirect($message, $page) {
global $phpc_prefix;
if(empty($_SESSION["{$phpc_prefix}messages"]))
$_SESSION["{$phpc_prefix}messages"] = array();
if (is_a($message, 'Html'))
$message = $message->toString();
$_SESSION["{$phpc_prefix}messages"][] = $message;
redirect($page);
$continue_url = $page . '&clearmsg=1';
return tag('div', attrs('class="phpc-box"'), "$message ",
tag('a', attrs("href=\"$continue_url\""), __("continue")));
}
/**
* @param string $message
*/
function message($message) {
global $phpc_messages;
$phpc_messages[] = $message;
}
/**
* @param array|string $var
* @return array|string
*/
function stripslashes_r($var) {
if (is_array($var))
return array_map("stripslashes_r", $var);
else
return stripslashes($var);
}
/**
* @param array|string $var
* @return array|string
*/
function real_escape_r($var) {
global $phpcdb;
if(is_array($var))
return array_map("real_escape_r", $var);
else
return mysqli_real_escape_string($phpcdb->dbh, $var);
}
/**
* @param bool $val
* @return string
*/
function asbool($val)
{
return $val ? "1" : "0";
}
/**
* @param int $timestamp
* @param int $date_format
* @param bool $hours24
* @return string
*/
function format_timestamp_string($timestamp, $date_format, $hours24) {
$year = date('Y', $timestamp);
$month = date('n', $timestamp);
$day = date('j', $timestamp);
$hour = date('H', $timestamp);
$minute = date('i', $timestamp);
return format_date_string($year, $month, $day, $date_format) . ' '
. __('at') . ' ' . format_time_string($hour, $minute, $hours24);
}
/**
* @param int $year
* @param int $month
* @param int $day
* @param int $date_format
* @return string
*/
function format_date_string($year, $month, $day, $date_format)
{
$month_name = short_month_name($month);
switch($date_format) {
case 0: // Month Day Year
return "$month_name $day, $year";
case 1: // Year Month Day
return "$year $month_name $day";
case 2: // Day Month Year
return "$day $month_name $year";
default:
soft_error("Invalid date_format");
}
}
/**
* @param int $year
* @param int $month
* @param int $day
* @param int $date_format
* @return string
*/
function format_short_date_string($year, $month, $day, $date_format)
{
switch($date_format) {
case 0: // Month Day Year
return "$month/$day/$year";
case 1: // Year Month Day
return "$year-$month-$day";
case 2: // Day Month Year
return "$day-$month-$year";
default:
soft_error("Invalid date_format");
}
}
/**
* @param int $hour
* @param int $minute
* @param bool $hour24
* @return string
*/
function format_time_string($hour, $minute, $hour24)
{
if(!$hour24) {
if($hour >= 12) {
$hour -= 12;
$pm = ' PM';
} else {
$pm = ' AM';
}
if($hour == 0) {
$hour = 12;
}
} else {
$pm = '';
}
return sprintf('%d:%02d%s', $hour, $minute, $pm);
}
// called when some error happens
/**
* @param string $str
*/
function display_error($str)
{
echo '<html><head><title>', __('Error'), "</title></head>\n",
'<body><h1>', __('Software Error'), "</h1>\n",
"<h2>", __('Message:'), "</h2>\n",
"<pre>$str</pre>\n",
"<h2>", __('Backtrace'), "</h2>\n",
"<ol>\n";
foreach(debug_backtrace() as $bt) {
echo "<li>$bt[file]:$bt[line] - $bt[function]</li>\n";
}
echo "</ol>\n",
"</body></html>\n";
exit;
}
/**
* @param int $timestamp
* @return int
*/
function days_in_year($timestamp) {
return 365 + date('L', $timestamp);
}
/**
* @param int|null $stamp
* @param int $days
* @return false|int|null
*/
function add_days($stamp, $days)
{
if ($stamp == null)
return null;
return mktime(date('H', $stamp), date('i', $stamp), date('s', $stamp),
date('n', $stamp), date('j', $stamp) + $days,
date('Y', $stamp));
}
/**
* @param int|null $stamp
* @param int $months
* @return false|int|null
*/
function add_months($stamp, $months)
{
if ($stamp == null)
return null;
return mktime(date('H', $stamp), date('i', $stamp), date('s', $stamp),
date('m', $stamp) + $months, date('d', $stamp),
date('Y', $stamp));
}
/**
* @param int|null $stamp
* @param int $years
* @return false|int|null
*/
function add_years($stamp, $years)
{
if ($stamp == null)
return null;
return mktime(date('H', $stamp), date('i', $stamp), date('s', $stamp),
date('m', $stamp), date('d', $stamp),
date('Y', $stamp) + $years);
}
/**
* @param int $ts1
* @param int $ts2
* @return int
*/
function days_between($ts1, $ts2) {
// First date always comes first
if($ts1 > $ts2)
return -days_between($ts2, $ts1);
// If we're in different years, keep adding years until we're in
// the same year
if(date('Y', $ts2) > date('Y', $ts1))
return days_in_year($ts1)
+ days_between(add_years($ts1, 1), $ts2);
// The years are equal, subtract day of the year of each
return intval(date('z', $ts2)) - intval(date('z', $ts1));
}
// Stolen from Drupal
function phpc_random_bytes($count) {
// $random_state does not use drupal_static as it stores random bytes.
static $random_state, $bytes, $php_compatible;
// Initialize on the first call. The contents of $_SERVER includes a
// mix of user-specific and system information that varies a little
// with each page.
if (!isset($random_state)) {
$random_state = print_r($_SERVER, TRUE);
if (function_exists('getmypid')) {
// Further initialize with the somewhat random PHP process ID.
$random_state .= getmypid();
}
$bytes = '';
}
if (strlen($bytes) < $count) {
// PHP versions prior 5.3.4 experienced openssl_random_pseudo_bytes()
// locking on Windows and rendered it unusable.
if (!isset($php_compatible)) {
$php_compatible = version_compare(PHP_VERSION, '5.3.4', '>=');
}
// /dev/urandom is available on many *nix systems and is
// considered the best commonly available pseudo-random source.
if ($fh = @fopen('/dev/urandom', 'rb')) {
// PHP only performs buffered reads, so in reality it
// will always read at least 4096 bytes. Thus, it costs
// nothing extra to read and store that much so as to
// speed any additional invocations.
$bytes .= fread($fh, max(4096, $count));
fclose($fh);
}
// openssl_random_pseudo_bytes() will find entropy in a
// system-dependent way.
elseif ($php_compatible && function_exists('openssl_random_pseudo_bytes')) {
$bytes .= openssl_random_pseudo_bytes($count - strlen($bytes));
}
// If /dev/urandom is not available or returns no bytes, this
// loop will generate a good set of pseudo-random bytes on any
// system.
// Note that it may be important that our $random_state is
// passed through hash() prior to being rolled into $output,
// that the two hash()
// invocations are different, and that the extra input into the
// first one - the microtime() - is prepended rather than
// appended. This is to avoid directly leaking $random_state
// via the $output stream, which could allow for trivial
// prediction of further "random" numbers.
while (strlen($bytes) < $count) {
$random_state = hash('sha256', microtime() . mt_rand() . $random_state);
$bytes .= hash('sha256', mt_rand() . $random_state, TRUE);
}
}
$output = substr($bytes, 0, $count);
$bytes = substr($bytes, $count);
return $output;
}
// Adapted from Drupal
function phpc_get_private_key() {
static $key;
if(!isset($key))
$key = phpc_hash_base64(phpc_random_bytes(55));
return $key;
}
function phpc_get_token($value='') {
return phpc_hmac_base64($value, session_id() . phpc_get_private_key()
. phpc_get_hash_salt());
}
// Stolen from Drupal
function phpc_hmac_base64($data, $key) {
$hmac = base64_encode(hash_hmac('sha256', $data, $key, TRUE));
// Modify the hmac so it's safe to use in URLs.
return strtr($hmac, array('+' => '-', '/' => '_', '=' => ''));
}
// Stolen from Drupal
function phpc_hash_base64($data) {
$hash = base64_encode(hash('sha256', $data, TRUE));
// Modify the hash so it's safe to use in URLs.
return strtr($hash, array('+' => '-', '/' => '_', '=' => ''));
}
// Adapted from Drupal
function phpc_get_hash_salt() {
return hash('sha256', SQL_HOST . SQL_USER . SQL_PASSWD . SQL_DATABASE . SQL_PREFIX);
}
function phpc_html_escape($str) {
return htmlspecialchars($str, ENT_COMPAT, "UTF-8");
}
| php | Apache-2.0 | e9473676f311aac8e9577cb3371ed362418441d9 | 2026-01-05T04:51:20.275579Z | false |
sproctor/php-calendar | https://github.com/sproctor/php-calendar/blob/e9473676f311aac8e9577cb3371ed362418441d9/src/category_submit.php | src/category_submit.php | <?php
/*
* Copyright 2012 Sean Proctor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
if ( !defined('IN_PHPC') ) {
die("Hacking attempt");
}
/**
* @return Html
*/
function category_submit()
{
global $vars, $phpcdb, $phpc_script;
if(empty($vars["text-color"]) || empty($vars["bg-color"])) {
$page = "$phpc_script?action=category_form";
if(!empty($vars["cid"]))
$page .= "&cid={$vars["cid"]}";
if(!empty($vars["catid"]))
$page .= "&catid={$vars["catid"]}";
return message_redirect(__("Color not specified."), $page);
}
// The current widget produces hex values without the "#".
// We may in the future want to allow different input, so store the
// values with the "#"
$text_color = $vars["text-color"];
$bg_color = $vars["bg-color"];
if(empty($vars['gid']) || strlen($vars['gid']) == 0)
$gid = 0;
else
$gid = $vars['gid'];
if(!check_color($text_color)) {
soft_error(__("Invalid color: ") . "\"$text_color\"");
}
if(!check_color($bg_color)) {
soft_error(__("Invalid color: ") . "\"$bg_color\"");
}
if(!isset($vars['catid'])) {
$modify = false;
if(!isset($vars['cid'])) {
$cid = null;
if(!is_admin())
permission_error(__('You do not have permission to add categories to all calendars.'));
} else {
$cid = $vars['cid'];
$calendar = $phpcdb->get_calendar($cid);
if(!$calendar->can_admin())
permission_error(__('You do not have permission to add categories to this calendar.'));
}
$catid = $phpcdb->create_category($cid, $vars["name"],
$text_color, $bg_color, $gid);
} else {
$modify = true;
$catid = $vars['catid'];
$category = $phpcdb->get_category($catid);
if(!(empty($category['cid']) && is_admin() ||
$phpcdb->get_calendar($category["cid"])
->can_admin()))
soft_error(__("You do not have permission to modify this category."));
$phpcdb->modify_category($catid, $vars['name'],
$text_color, $bg_color, $gid);
}
$page = "$phpc_script?action=cadmin&phpcid=".$vars['phpcid'];
if($modify)
return message_redirect(__("Modified category: ") . $catid,
$page);
if($catid > 0)
return message_redirect(__("Created category: ") . $catid,
$page);
return tag('div', attributes('class="phpc-error"'),
__('Error submitting category.'));
}
function check_color($color) {
return preg_match('/^#[0-9a-fA-F]{6}$/', $color) == 1;
}
| php | Apache-2.0 | e9473676f311aac8e9577cb3371ed362418441d9 | 2026-01-05T04:51:20.275579Z | false |
sproctor/php-calendar | https://github.com/sproctor/php-calendar/blob/e9473676f311aac8e9577cb3371ed362418441d9/src/calendar.php | src/calendar.php | <?php
/*
* Copyright 2017 Sean Proctor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
this file contains all the re-usable functions for the calendar
*/
if ( !defined('IN_PHPC') ) {
die("Hacking attempt");
}
require_once("$phpc_includes_path/Gettext_PHP.php");
require_once("$phpc_includes_path/html.php");
require_once("$phpc_includes_path/util.php");
// Displayed in admin
$phpc_version = "2.0.10";
/**
* @param string $msg
* @return string
*/
function __($msg) {
global $phpc_gettext;
if (empty($phpc_gettext))
return $msg;
return $phpc_gettext->gettext($msg);
}
/**
* @param string $context
* @param string $msg
* @return string
*/
function __p($context, $msg) {
global $phpc_gettext;
return $phpc_gettext->pgettext($context, $msg);
}
// checks global variables to see if the user is logged in.
/**
* @return bool
*/
function is_user() {
global $phpc_user;
return $phpc_user->uid > 0;
}
/**
* @return bool
*/
function is_admin() {
global $phpc_user;
return $phpc_user->admin;
}
/**
* @param string $username
* @param string $password
* @return bool
*/
function login_user($username, $password)
{
global $phpcdb;
$user = $phpcdb->get_user_by_name($username);
if(!$user || $user->password !== md5($password))
return false;
phpc_do_login($user);
return true;
}
/**
* @param PhpcUser $user
* @param bool $series_token
* @return bool
*/
function phpc_do_login($user, $series_token = false) {
global $phpcdb, $phpc_prefix;
$uid = $user->uid;
$login_token = phpc_get_token();
$_SESSION["{$phpc_prefix}uid"] = $uid;
$_SESSION["{$phpc_prefix}login"] = $login_token;
if(!$series_token) {
$series_token = phpc_get_token();
$phpcdb->add_login_token($uid, $series_token,
$login_token);
} else {
$phpcdb->update_login_token($uid, $series_token,
$login_token);
}
// TODO: Add a remember me checkbox to the login form, and have the
// cookies expire at the end of the session if it's not checked
// expire credentials in 30 days.
$expiration_time = time() + 30 * 24 * 60 * 60;
phpc_set_cookie("{$phpc_prefix}uid", $uid, $expiration_time);
phpc_set_cookie("{$phpc_prefix}login", $login_token, $expiration_time);
phpc_set_cookie("{$phpc_prefix}login_series", $series_token,
$expiration_time);
return true;
}
function phpc_do_logout() {
global $phpc_prefix;
session_destroy();
$past_time = time() - 3600;
phpc_set_cookie("{$phpc_prefix}uid", "", $past_time);
phpc_set_cookie("{$phpc_prefix}login", "", $past_time);
phpc_set_cookie("{$phpc_prefix}login_series", "", $past_time);
}
// returns tag data for the links at the bottom of the calendar
/**
* @return Html
*/
function footer()
{
global $phpc_url, $phpc_tz, $phpc_lang;
$tag = tag('div', attributes('class="phpc-bar ui-widget-content"'),
"[" . __('Language') . ": $phpc_lang]" .
" [" . __('Timezone') . ": $phpc_tz]");
if(defined('PHPC_DEBUG')) {
$tag->add(tag('a', attributes('href="http://validator.w3.org/check?url='
. phpc_html_escape(rawurlencode($phpc_url))
. '"'), 'Validate HTML'));
$tag->add(tag('a', attributes('href="http://jigsaw.w3.org/css-validator/check/referer"'),
'Validate CSS'));
}
return $tag;
}
/**
* @return array
*/
function get_languages() {
global $phpc_locale_path;
static $langs;
if(!empty($langs))
return $langs;
// create links for each existing language translation
$handle = opendir($phpc_locale_path);
if(!$handle)
soft_error("Error reading locale directory.");
$langs = array('en');
while(($filename = readdir($handle)) !== false) {
$pathname = "$phpc_locale_path/$filename";
if(strncmp($filename, ".", 1) == 0 || !is_dir($pathname))
continue;
if(file_exists("$pathname/LC_MESSAGES/messages.mo"))
$langs[] = $filename;
}
closedir($handle);
return $langs;
}
/**
* @return int
*/
function day_of_week_start()
{
global $phpc_cal;
return $phpc_cal->week_start;
}
// returns the number of days in the week before the
// taking into account whether we start on sunday or monday
/**
* @param int $month
* @param int $day
* @param int $year
* @return int
*/
function day_of_week($month, $day, $year)
{
return day_of_week_ts(mktime(0, 0, 0, $month, $day, $year));
}
// returns the number of days in the week before the
// taking into account whether we start on sunday or monday
/**
* @param int $timestamp
* @return int
*/
function day_of_week_ts($timestamp)
{
$days = date('w', $timestamp);
return ($days + 7 - day_of_week_start()) % 7;
}
// returns the number of days in $month
/**
* @param int $month
* @param int $year
* @return false|string
*/
function days_in_month($month, $year)
{
return date('t', mktime(0, 0, 0, $month, 1, $year));
}
//returns the number of weeks in $month
function weeks_in_month($month, $year)
{
$days = days_in_month($month, $year);
// days not in this month in the partial weeks
$days_before_month = day_of_week($month, 1, $year);
$days_after_month = 6 - day_of_week($month, $days, $year);
// add up the days in the month and the outliers in the partial weeks
// divide by 7 for the weeks in the month
return ($days_before_month + $days + $days_after_month) / 7;
}
// return the week number corresponding to the $day.
function week_of_year($month, $day, $year)
{
$timestamp = mktime(0, 0, 0, $month, $day, $year);
// week_start = 1 uses ISO 8601 and contains the Jan 4th,
// Most other places the first week contains Jan 1st
// There are a few outliers that start weeks on Monday and use
// Jan 1st for the first week. We'll ignore them for now.
if(day_of_week_start() == 1) {
$year_contains = 4;
// if the week is in December and contains Jan 4th, it's a week
// from next year
if($month == 12 && $day - 24 >= $year_contains) {
$year++;
$month = 1;
$day -= 31;
}
} else {
$year_contains = 1;
}
// $day is the first day of the week relative to the current month,
// so it can be negative. If it's in the previous year, we want to use
// that negative value, unless the week is also in the previous year,
// then we want to switch to using that year.
if($day < 1 && $month == 1 && $day > $year_contains - 7) {
$day_of_year = $day - 1;
} else {
$day_of_year = date('z', $timestamp);
$year = date('Y', $timestamp);
}
/* Days in the week before Jan 1. */
$days_before_year = day_of_week(1, $year_contains, $year);
// Days left in the week
$days_left = 8 - day_of_week_ts($timestamp) - $year_contains;
/* find the number of weeks by adding the days in the week before
* the start of the year, days up to $day, and the days left in
* this week, then divide by 7 */
return ($days_before_year + $day_of_year + $days_left) / 7;
}
function year_of_week_of_year($month, $day, $year) {
$timestamp = mktime(0, 0, 0, $month, $day, $year);
// week_start = 1 uses ISO 8601 and contains the Jan 4th,
// Most other places the first week contains Jan 1st
// There are a few outliers that start weeks on Monday and use
// Jan 1st for the first week. We'll ignore them for now.
if(day_of_week_start() == 1) {
$year_contains = 4;
// if the week is in December and contains Jan 4th, it's a week
// from next year
if($month == 12 && $day - 24 >= $year_contains) {
return $year + 1;
}
} else {
return $year;
}
// $day is the first day of the week relative to the current month,
// so it can be negative. If it's in the previous year, we want to use
// that negative value, unless the week is also in the previous year,
// then we want to switch to using that year.
if($day < 1 && $month == 1 && $day > $year_contains - 7) {
return $year;
} else {
return date('Y', $timestamp);
}
}
function create_event_link($text, $action, $eid, $attribs = false)
{
return create_action_link($text, $action, array('eid' => $eid),
$attribs);
}
function create_occurrence_link($text, $action, $oid, $attribs = false)
{
return create_action_link($text, $action, array('oid' => $oid),
$attribs);
}
function create_action_link_with_date($text, $action, $year = false,
$month = false, $day = false, $attribs = false)
{
$args = array();
if($year !== false) $args["year"] = $year;
if($month !== false) $args["month"] = $month;
if($day !== false) $args["day"] = $day;
return create_action_link($text, $action, $args, $attribs);
}
/**
* @param $action
* @param bool $year
* @param bool $month
* @param bool $day
* @param array $args
* @return string
*/
function create_action_url($action, $year = false, $month = false, $day = false, $args = array())
{
global $phpc_script, $vars;
if($year !== false) $args["year"] = $year;
if($month !== false) $args["month"] = $month;
if($day !== false) $args["day"] = $day;
$url ="".$phpc_script."?";
if(isset($vars["phpcid"]))
$url .= "phpcid=" . phpc_html_escape($vars["phpcid"]) . "&";
$url .= "action=" . phpc_html_escape($action);
foreach ($args as $key => $value) {
if (empty($value))
continue;
if (is_array($value)) {
foreach ($value as $v) {
$url .= "&"
. phpc_html_escape("{$key}[]=$v");
}
} else
$url .= "&" . phpc_html_escape("$key=$value");
}
return $url;
}
/**
* @param string $text
* @param string $action
* @param string[] $args
* @param bool|AttributeList $attribs
* @return Html
*/
function create_action_link($text, $action, $args = array(), $attribs = false)
{
global $phpc_script, $vars;
$url = "href=\"$phpc_script?";
if(isset($vars["phpcid"]))
$url .= "phpcid=" . phpc_html_escape($vars["phpcid"]) . "&";
$url .= "action=" . phpc_html_escape($action);
foreach ($args as $key => $value) {
if (empty($value))
continue;
if (is_array($value)) {
foreach ($value as $v) {
$url .= "&"
. phpc_html_escape("{$key}[]=$v");
}
} else
$url .= "&" . phpc_html_escape("$key=$value");
}
$url .= '"';
if($attribs !== false) {
$as = attributes($url, $attribs);
} else {
$as = attributes($url);
}
return tag('a', $as, $text);
}
// takes a menu $html and appends an entry
/**
* @param Html $html
* @param string $name
* @param string $action
* @param string[] $args
* @param bool|AttributeList $attribs
*/
function menu_item_append(&$html, $name, $action, $args = array(),
$attribs = false)
{
$name=str_replace(' ',' ',$name); /*not breaking space on menus*/
if(!is_object($html)) {
soft_error('Html is not a valid Html class.');
}
$html->add(create_action_link($name, $action, $args, $attribs));
$html->add("\n");
}
// takes a menu $html and appends an entry with the date
/**
* @param Html $html
* @param string $name
* @param string $action
* @param bool|int $year
* @param bool|int $month
* @param bool|int $day
* @param bool|AttributeList $attribs
*/
function menu_item_append_with_date(&$html, $name, $action, $year = false,
$month = false, $day = false, $attribs = false)
{
$name = str_replace(' ',' ',$name);
if(!is_object($html)) {
soft_error('Html is not a valid Html class.');
}
$html->add(create_action_link_with_date($name, $action, $year, $month,
$day, $attribs));
$html->add("\n");
}
// same as above, but prepends the entry
/**
* @param Html $html
* @param string $name
* @param string $action
* @param string[] $args
* @param bool|AttributeList $attribs
*/
function menu_item_prepend(&$html, $name, $action, $args = array(),
$attribs = false)
{
if(!is_object($html)) {
soft_error('Html is not a valid Html class.');
}
$html->prepend("\n");
$html->prepend(create_action_link($name, $action, $args, $attribs));
}
// creates a hidden input for a form
// returns tag data for the input
/**
* @param string $name
* @param mixed $value
* @return Html
*/
function create_hidden($name, $value)
{
return tag('input', attributes("name=\"$name\"", "value=\"$value\"",
'type="hidden"'));
}
// creates a submit button for a form
// return tag data for the button
/**
* @param mixed $value
* @return Html
*/
function create_submit($value)
{
return tag('input', attributes('name="submit"', "value=\"$value\"",
'type="submit"'));
}
/**
* creates a text entry for a form
* returns tag data for the entry
*
* @param string $name
* @param mixed $value
* @return Html
*/
function create_text($name, $value = false)
{
$attributes = attributes("name=\"$name\"", "id=\"$name\"", 'type="text"');
if($value !== false) {
$attributes->add("value=\"$value\"");
}
return tag('input', $attributes);
}
// creates a password entry for a form
// returns tag data for the entry
/**
* @param string $name
* @return Html
*/
function create_password($name)
{
return tag('input', attributes("name=\"$name\"", "id=\"$name\"", 'type="password"'));
}
// creates a checkbox for a form
// returns tag data for the checkbox
/**
* @param string $name
* @param mixed $value
* @param bool $checked
* @param bool|string $label
* @return array|Html
*/
function create_checkbox($name, $value, $checked = false, $label = false)
{
$attributes = attributes("id=\"$name\"", "name=\"$name\"",
'type="checkbox"', "value=\"$value\"");
if(!empty($checked)) $attributes->add('checked="checked"');
$input = tag('input', $attributes);
if($label !== false)
return array($input, tag('label', attributes("for=\"$name\""),
$label));
else
return $input;
}
// $title - string or html element displayed by default
// $values - Array of URL => title
// returns an html structure for a dropdown box that will change the page
// to the URL from $values when an element is selected
/**
* @param mixed $title
* @param mixed $values
* @return Html
*/
function create_dropdown_list($title, $values)
{
$list = tag('ul');
foreach($values as $key => $value) {
$list->add(tag('li', tag('a', attrs("href=\"$key\""), $value)));
}
return tag('span', attrs('class="phpc-dropdown-list"'),
tag('span', attrs('class="phpc-dropdown-list-header"'),
tag('span', attrs('class="phpc-dropdown-list-title"'),
$title)),
$list);
}
// creates the user menu
// returns tag data for the menu
/**
* @return Html
*/
function userMenu()
{
global $action, $phpc_user;
$welcome = __('Welcome') . ' ' . $phpc_user->username;
$span = tag('span');
$html = tag('div', attributes('class="phpc-logged ui-widget-content"'),
$welcome, $span);
if($action != 'settings')
menu_item_append($span, __('Settings'), 'settings');
if(is_user()) {
menu_item_append($span, __('Log out'), 'logout',
array('lasturl' =>
phpc_html_escape(rawurlencode($_SERVER['QUERY_STRING']))));
} else {
menu_item_append($span, __('Log in'), 'login',
array('lasturl' =>
phpc_html_escape(rawurlencode($_SERVER['QUERY_STRING']))));
}
return $html;
}
// creates the navbar for the top of the calendar
// returns tag data for the navbar
/**
* @return Html
*/
function navbar()
{
global $action, $year, $month, $day, $phpc_cal;
$html = tag('div', attributes('class="phpc-bar ui-widget-header"'));
$args = array('year' => $year, 'month' => $month, 'day' => $day);
if($phpc_cal->can_write() && $action != 'add') {
menu_item_append($html, __('Add Event'), 'event_form', $args);
}
if($action != 'search') {
menu_item_append($html, __('Search'), 'search', $args);
}
if($action != 'display_month') {
menu_item_append($html, __('View Month'), 'display_month',
$args);
}
if($action == 'display_event') {
menu_item_append($html, __('View date'), 'display_day', $args);
}
if($phpc_cal->can_admin() && $action != 'cadmin') {
menu_item_append($html, __('Calendar Admin'), 'cadmin');
}
if(is_admin() && $action != 'admin') {
menu_item_append($html, __('Admin'), 'admin');
}
return $html;
}
// creates an array from $start to $end, with an $interval
/**
* @param int $start
* @param int $end
* @param int $interval
* @param mixed $display
* @return array
*/
function create_sequence($start, $end, $interval = 1, $display = false)
{
$arr = array();
for ($i = $start; $i <= $end; $i += $interval){
if($display) {
$arr[$i] = call_user_func($display, $i);
} else {
$arr[$i] = $i;
}
}
return $arr;
}
/**
* @return array
*/
function get_config_options()
{
static $options = NULL;
if($options === NULL) {
$options = init_config_options();
}
return $options;
}
/**
* @return array
*/
function init_config_options() {
$languages = array("" => __("Default"));
foreach(get_languages() as $language) {
$languages[$language] = $language;
}
// name, text, type, value(s)
return array(
array('week_start', __('Week Start'), PHPC_DROPDOWN,
array(
0 => __('Sunday'),
1 => __('Monday'),
6 => __('Saturday')
)),
array('hours_24', __('24 Hour Time'), PHPC_CHECK),
array('title', __('Calendar Title'), PHPC_TEXT),
array('subject_max', __('Maximum Subject Length'), PHPC_TEXT, 50),
array('events_max', __('Events Display Daily Maximum'), PHPC_TEXT, 8),
array('anon_permission', __('Public Permissions'), PHPC_DROPDOWN,
array(
__('Cannot read nor write events'),
__('Can read but not write events'),
__('Can create but not modify events'),
__('Can create and modify events')
)
),
array('timezone', __('Default Timezone'), PHPC_MULTI_DROPDOWN, get_timezone_list()),
array('language', __('Default Language'), PHPC_DROPDOWN,
$languages),
array('date_format', __('Date Format'), PHPC_DROPDOWN,
get_date_format_list()),
array('theme', __('Theme'), PHPC_DROPDOWN,
get_theme_list()),
);
}
/**
* @return array
*/
function get_theme_list() {
$themes = array('base',
'black-tie',
'blitzer',
'cupertino',
'dark-hive',
'dot-luv',
'eggplant',
'excite-bike',
'flick',
'hot-sneaks',
'humanity',
'le-frog',
'mint-choc',
'overcast',
'pepper-grinder',
'redmond',
'smoothness',
'south-street',
'start',
'sunny',
'swanky-purse',
'trontastic',
'ui-darkness',
'ui-lightness',
'vader');
$theme_list = array(NULL => __('Default'));
foreach($themes as $theme) {
$theme_list[$theme] = $theme;
}
return $theme_list;
}
/**
* @return array
*/
function get_timezone_list() {
$timezones = array();
$timezones[__("Default")] = "";
foreach(timezone_identifiers_list() as $timezone) {
$sp = explode("/", $timezone, 2);
$continent = $sp[0];
if(empty($sp[1])) {
$timezones[$continent] = $timezone;
} else {
$area = $sp[1];
if(empty($timezones[$continent]))
$timezones[$continent] = array();
$timezones[$continent][$timezone] = $area;
}
}
return $timezones;
}
/**
* @return array
*/
function get_date_format_list()
{
return array( __("Month Day Year"),
__("Year Month Day"),
__("Day Month Year"));
}
/**
* @return Html
*/
function display_phpc() {
global $phpc_messages, $phpc_redirect, $phpc_script, $phpc_prefix, $phpc_home_url, $phpc_cal, $phpcdb;
$navbar = false;
try {
$content = do_action();
$navbar = navbar();
if(sizeof($phpc_messages) > 0) {
$messages = tag('div', attrs('class="phpc-message"'));
foreach($phpc_messages as $message) {
$messages->add($message);
}
// If we're redirecting, the messages might not get
// seen, so don't clear them
if(empty($phpc_redirect))
$_SESSION[$phpc_prefix . 'messages'] = null;
} else {
$messages = '';
}
$list = array();
foreach($phpcdb->get_calendars() as $calendar) {
if($calendar->can_read()) {
$list[$phpc_home_url . '?phpcid=' . $calendar->get_cid()] = $calendar->get_title();
}
}
return tag('div', attributes('class="php-calendar ui-widget"'),
userMenu(),
tag('br', attrs('style="clear:both;"')),
tag('h1', attrs('class="ui-widget-header"'),
create_dropdown_list(tag('a', attrs("href='$phpc_home_url?phpcid={$phpc_cal->get_cid()}'",
'class="phpc-dropdown-list-title"'),
$phpc_cal->get_title()), $list)),
$navbar, $messages, $content, footer());
} catch(PermissionException $e) {
$results = tag('');
// TODO: make navbar show if there is an error in do_action()
if($navbar !== false)
$results->add($navbar);
$msg = __('You do not have permission to do that: ')
. $e->getMessage();
$results->add(tag('div', attrs('class="phpc-message ui-state-error"'), $msg));
if(is_user())
return $results;
else
return message_redirect($msg,
"$phpc_script?action=login");
} catch(Exception $e) {
$results = tag('');
if($navbar !== false)
$results->add($navbar);
$results->add(tag('div', attrs('class="phpc-main"'),
tag('h2', __('Error')),
tag('p', $e->getMessage()),
tag('h3', __('Backtrace')),
tag('pre', phpc_html_escape($e->getTraceAsString()))));
return $results;
}
}
/**
* @return mixed
*/
function do_action()
{
global $action, $phpc_includes_path;
$action_file = "$phpc_includes_path/$action.php";
if(!preg_match('/^\w+$/', $action) || !file_exists($action_file))
soft_error(__('Invalid action'));
require_once($action_file);
$action_output = call_user_func($action);
return $action_output;
}
// takes a number of the month, returns the name
/**
* @param int $month
* @return string
*/
function month_name($month)
{
global $month_names;
$month = ($month - 1) % 12 + 1;
return $month_names[$month];
}
//takes a day number of the week, returns a name (0 for the beginning)
/**
* @param int $day
* @return string
*/
function day_name($day)
{
global $day_names;
$day = $day % 7;
return $day_names[$day];
}
/**
* @param int $month
* @return string
*/
function short_month_name($month)
{
global $short_month_names;
$month = ($month - 1) % 12 + 1;
return $short_month_names[$month];
}
function verify_token() {
global $vars, $phpc_token;
if(!is_user())
return;
if(empty($vars["phpc_token"]) || $vars["phpc_token"] != $phpc_token) {
//echo "<pre>real token: $phpc_token\n";
//echo "form token: {$vars["phpc_token"]}</pre>";
soft_error(__("Secret token mismatch. Possible request forgery attempt."));
}
}
/**
* @param string $path
* @return array
*/
function get_header_tags($path)
{
global $phpc_cal;
if(defined('PHPC_DEBUG'))
$jq_min = '';
else
$jq_min = '.min';
$theme = $phpc_cal->theme;
if(empty($theme))
$theme = 'base';
$jquery_version = "3.6.0";
$jqueryui_version = "1.13.1";
$showdown_version = "1.9.1";
return array(
tag('link', attrs('rel="stylesheet"', 'type="text/css"',
"href=\"$path/phpc.css\"")),
tag('link', attrs('rel="stylesheet"', 'type="text/css"',
"href=\"//ajax.googleapis.com/ajax/libs/jqueryui/$jqueryui_version/themes/$theme/jquery-ui$jq_min.css\"")),
tag('link', attrs('rel="stylesheet"', 'type="text/css"',
"href=\"$path/jquery-ui-timepicker.css\"")),
tag("script", attrs("src=\"//ajax.googleapis.com/ajax/libs/jquery/$jquery_version/jquery$jq_min.js\""), ''),
tag("script", attrs("src=\"//ajax.googleapis.com/ajax/libs/jqueryui/$jqueryui_version/jquery-ui$jq_min.js\""), ''),
tag('script', attrs("src=\"$path/phpc.js\""), ''),
tag("script", attrs("src=\"$path/jquery.ui.timepicker.js\""), ''),
tag("script", attrs("src=\"$path/jquery.hoverIntent.minified.js\""), ''),
tag("script", attrs("src=\"$path/spectrum.js\""), ''),
tag('link', attrs('rel="stylesheet"', 'type="text/css"',
"href=\"$path/spectrum.css\"")),
tag("script", attrs("src=\"https://cdnjs.cloudflare.com/ajax/libs/showdown/$showdown_version/showdown.min.js\""), ''),
);
}
/**
* @param $path
*/
function embed_header($path)
{
echo tag('', get_header_tags($path))->toString();
}
// $element: { name, text, type, value(s) }
/**
* @param array $element
* @param mixed $default
* @return array|Html
*/
function create_config_input($element, $default = false)
{
$name = $element[0];
$text = $element[1];
$type = $element[2];
$value = false;
if(isset($element[3]))
$value = $element[3];
switch($type) {
case PHPC_CHECK:
if($default == false)
$default = $value;
$input = create_checkbox($name, '1', $default, $text);
break;
case PHPC_TEXT:
if($default == false)
$default = $value;
$input = create_text($name, $default);
break;
case PHPC_DROPDOWN:
$input = create_select($name, $value, $default);
break;
case PHPC_MULTI_DROPDOWN:
$input = create_multi_select($name, $value, $default);
break;
default:
soft_error(__('Unsupported config type') . ": $type");
}
return $input;
}
/* Make a timestamp from the input fields $prefix-time and $prefix-date
uses $phpc_cal->date_format to determine the format of the date
if there's no $prefix-time, uses values passed as parameters
*/
/**
* @param string $prefix
* @param int $hour
* @param int $minute
* @param int $second
* @return false|int
*/
function get_timestamp($prefix, $hour = 0, $minute = 0, $second = 0)
{
global $vars, $phpc_cal;
if(empty($vars["$prefix-date"]))
soft_error(sprintf(__("Required field \"%s\" was not set."),
"$prefix-date"));
if(!empty($vars["$prefix-time"])) {
if(!preg_match('/(\d+)[:\.](\d+)\s?(\w+)?/', $vars["$prefix-time"],
$time_matches)) {
soft_error(sprintf(__("Malformed \"%s\" time: \"%s\""),
$prefix,
$vars["$prefix-time"]));
}
$hour = $time_matches[1];
$minute = $time_matches[2];
if(isset($time_matches[3])) {
$period = $time_matches[3];
if($hour == 12)
$hour = 0;
if(strcasecmp("am", $period) == 0) {
// AM
} else if(strcasecmp("pm", $period) == 0) {
$hour += 12;
} else {
soft_error(__("Unrecognized period: ")
. $period);
}
}
}
if(!preg_match('/(\d+)[\.\/\-\ ](\d+)[\.\/\-\ ](\d+)/',
$vars["$prefix-date"], $date_matches)) {
soft_error(sprintf(__("Malformed \"%s\" date: \"%s\""),
$prefix, $vars["$prefix-date"]));
}
switch($phpc_cal->date_format) {
case 0: // Month Day Year
$month = $date_matches[1];
$day = $date_matches[2];
$year = $date_matches[3];
break;
case 1: // Year Month Day
$year = $date_matches[1];
$month = $date_matches[2];
$day = $date_matches[3];
break;
case 2: // Day Month Year
$day = $date_matches[1];
$month = $date_matches[2];
$year = $date_matches[3];
break;
default:
soft_error(__("Invalid date_format."));
}
return mktime($hour, $minute, $second, $month, $day, $year);
}
/**
* @param string $name
* @param mixed $value
* @param int $expire
* @return bool
*/
function phpc_set_cookie($name, $value, $expire = 0) {
return setcookie($name, $value, $expire, "", "", false, true);
}
| php | Apache-2.0 | e9473676f311aac8e9577cb3371ed362418441d9 | 2026-01-05T04:51:20.275579Z | false |
sproctor/php-calendar | https://github.com/sproctor/php-calendar/blob/e9473676f311aac8e9577cb3371ed362418441d9/src/cadmin_submit.php | src/cadmin_submit.php | <?php
/*
* Copyright 2012 Sean Proctor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
if ( !defined('IN_PHPC') ) {
die("Hacking attempt");
}
/**
* @return Html
*/
function cadmin_submit() {
global $phpcid, $phpc_cal, $vars, $phpcdb, $phpc_script;
if(!$phpc_cal->can_admin()) {
return tag('div', __('Permission denied'));
}
foreach(get_config_options() as $item) {
if($item[2] == PHPC_CHECK) {
if(isset($vars[$item[0]]))
$value = "1";
else
$value = "0";
} else {
if(isset($vars[$item[0]])) {
$value = $vars[$item[0]];
} else {
soft_error($item[0] . __(" was not set."));
}
}
$phpcdb->update_config($phpcid, $item[0], $value);
}
return message_redirect(__('Updated options'),
"$phpc_script?action=cadmin&phpcid=$phpcid");
}
| php | Apache-2.0 | e9473676f311aac8e9577cb3371ed362418441d9 | 2026-01-05T04:51:20.275579Z | false |
sproctor/php-calendar | https://github.com/sproctor/php-calendar/blob/e9473676f311aac8e9577cb3371ed362418441d9/src/group_submit.php | src/group_submit.php | <?php
/*
* Copyright 2013 Sean Proctor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
if ( !defined('IN_PHPC') ) {
die("Hacking attempt");
}
/**
* @return Html
*/
function group_submit()
{
global $vars, $phpcdb, $phpc_script;
if(!isset($vars['gid'])) {
$modify = false;
if(!isset($vars['cid'])) {
$cid = null;
if(!is_admin())
permission_error(__('You do not have permission to add a global group.'));
} else {
$cid = $vars['cid'];
$calendar = $phpcdb->get_calendar($cid);
if(!$calendar->can_admin())
permission_error(__('You do not have permission to add a group to this calendar.'));
}
$gid = $phpcdb->create_group($cid, $vars["name"]);
} else {
$modify = true;
$gid = $vars['gid'];
$group = $phpcdb->get_group($gid);
if(!(empty($group['cid']) && is_admin() ||
$phpcdb->get_calendar($group["cid"])
->can_admin()))
soft_error(__("You do not have permission to modify this group."));
$phpcdb->modify_group($gid, $vars['name']);
}
$page = "$phpc_script?action=cadmin&phpcid=".$vars['cid'];
if($modify)
return message_redirect(__("Modified group: ") . $gid,
$page);
if($gid > 0)
return message_redirect(__("Created group: ") . $gid,
$page);
return tag('div', attributes('class="phpc-error"'),
__('Error submitting group.'));
}
| php | Apache-2.0 | e9473676f311aac8e9577cb3371ed362418441d9 | 2026-01-05T04:51:20.275579Z | false |
sproctor/php-calendar | https://github.com/sproctor/php-calendar/blob/e9473676f311aac8e9577cb3371ed362418441d9/src/html.php | src/html.php | <?php
/*
* Copyright 2009 Sean Proctor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
if (!defined('IN_PHPC')) {
die("Hacking attempt");
}
/*
* data structure to display XHTML
* see function tag() below for usage
* Cateat: this class does not understand HTML, it just approximates it.
* do not give an empty tag that needs to be closed without content, it
* won't be closed. ex tag('div') to get a closed tag use tag('div', '')
*/
class Html
{
/** @var string */
var $tagName;
/** @var AttributeList */
var $attributeList;
/** @var array */
var $childElements;
/** @var array */
var $error_func;
/**
* Html constructor.
*/
function __construct()
{
$this->error_func = array(&$this, 'default_error_handler');
$args = func_get_args();
$this->tagName = array_shift($args);
if ($this->tagName === NULL) $this->tagName = '';
$this->attributeList = null;
$this->childElements = array();
$arg = array_shift($args);
if ($arg === NULL) return;
while ($arg !== NULL) {
$this->add($arg);
$arg = array_shift($args);
}
}
function add()
{
$htmlElements = func_get_args();
foreach ($htmlElements as $htmlElement) {
if (is_a($htmlElement, 'AttributeList')) {
$this->attributeList = $htmlElement;
} elseif (is_array($htmlElement)) {
foreach ($htmlElement as $element) {
$this->add($element);
}
} elseif (is_object($htmlElement)
&& !is_a($htmlElement, 'Html')
) {
$this->html_error('Invalid class: '
. get_class($htmlElement));
} else {
$this->childElements[] = $htmlElement;
}
}
}
function prepend()
{
$htmlElements = func_get_args();
foreach (array_reverse($htmlElements) as $htmlElement) {
if (is_array($htmlElement)) {
foreach (array_reverse($htmlElement)
as $element) {
$this->prepend($element);
}
} elseif (is_object($htmlElement)
&& !is_a($htmlElement, 'Html')
) {
$this->html_error('Invalid class: '
. get_class($htmlElement));
} else {
array_unshift($this->childElements,
$htmlElement);
}
}
}
/**
* @return string
*/
function toString()
{
$output = '';
if ($this->tagName != '') {
$output .= "<{$this->tagName}";
if ($this->attributeList != NULL) {
$output .= ' '
. $this->attributeList->toString();
}
if (sizeof($this->childElements) == 0) {
$output .= "/>\n";
return $output;
}
$output .= ">";
}
foreach ($this->childElements as $child) {
if (is_object($child)) {
if (is_a($child, 'Html')) {
$output .= $child->toString();
} else {
$this->html_error('Invalid class: '
. get_class($child));
}
} else {
$output .= $child;
}
}
if ($this->tagName != '') {
$output .= "</{$this->tagName}>\n";
}
return $output;
}
/**
* @param string $str
*/
function default_error_handler($str)
{
echo "<html><head><title>Error</title></head>\n"
. "<body><h1>Software Error</h1>\n"
. "<h2>Message:</h2>\n"
. "<pre>$str</pre>\n";
echo "<h2>Backtrace</h2>\n";
echo "<ol>\n";
foreach (debug_backtrace() as $bt) {
echo "<li>{$bt['file']}:{$bt['line']} - ";
if (!empty($bt['class']))
echo "{$bt['class']}{$bt['type']}";
echo "{$bt['function']}(" . implode(', ',
$bt['args'])
. ")</li>\n";
}
echo "</ol>\n";
echo "</body></html>\n";
exit;
}
/* call this function if you want a non-default error handler */
function html_set_error_handler($func)
{
$this->error_func = $func;
}
function html_error()
{
$args = func_get_args();
return call_user_func_array($this->error_func, $args);
}
}
/*
* Data structure to display XML style attributes
* see function attributes() below for usage
*/
class AttributeList
{
/** @var array */
var $list;
/**
* AttributeList constructor.
*/
function __construct()
{
$this->list = array();
$args = func_get_args();
$this->add($args);
}
function add()
{
$args = func_get_args();
foreach ($args as $arg) {
if (is_array($arg)) {
foreach ($arg as $attr) {
$this->add($attr);
}
} else {
$this->list[] = $arg;
}
}
}
/**
* @return string
*/
function toString()
{
return implode(' ', $this->list);
}
}
/*
* creates an Html data structure
* arguments are tagName [AttributeList] [Html | array | string] ...
* where array contains an array, Html, or a string, same requirements for that
* array
*/
/**
* @return Html
*/
function tag()
{
$args = func_get_args();
$html = new Html();
call_user_func_array(array(&$html, '__construct'), $args);
return $html;
}
/*
* creates an AttributeList data structure
* arguments are [attribute | array] ...
* where attribute is a string of name="value" and array contains arrays or
* attributes
*/
/**
* @return AttributeList
*/
function attributes()
{
$args = func_get_args();
$attrs = new AttributeList();
call_user_func_array(array(&$attrs, '__construct'), $args);
return $attrs;
}
/**
* @return AttributeList
*/
function attrs()
{
$args = func_get_args();
$attrs = new AttributeList();
call_user_func_array(array(&$attrs, '__construct'), $args);
return $attrs;
}
// creates a select tag element for a form
// returns HTML data for the element
/**
* @param string $name
* @param array $options
* @param bool|string $default
* @param bool|AttributeList $attrs
* @return Html
*/
function create_select($name, $options, $default = false, $attrs = false)
{
if ($attrs === false)
$attrs = attrs();
$attrs->add("name=\"$name\"");
$attrs->add("id=\"$name\"");
$select = tag('select', $attrs);
foreach ($options as $value => $text) {
$attributes = attrs("value=\"$value\"");
if ($default !== false && ($value == $default ||
is_array($default) &&
in_array($value, $default))
) {
$attributes->add('selected');
}
$select->add(tag('option', $attributes, $text));
}
return $select;
}
// creates a two stage select input
// returns HTML data for the elements
/**
* @param string $name
* @param array $option_lists
* @param bool|string $default
* @param bool|AttributeList $attrs
* @return Html
*/
function create_multi_select($name, $option_lists, $default = false,
$attrs = false)
{
if ($attrs === false)
$attrs = attrs();
$attrs->add("name=\"$name\"");
$attrs->add("id=\"$name\"");
$attrs->add("class=\"phpc-multi-select\"");
$select = tag('select', $attrs);
foreach ($option_lists as $category => $options) {
if (is_array($options)) {
$group = tag('optgroup', attrs("label=\"$category\""));
$select->add($group);
foreach ($options as $value => $text) {
$attributes = attrs("value=\"$value\"");
if ($value === $default)
$attributes->add('selected');
$text = str_replace('_', ' ', $text);
$group->add(tag('option', $attributes, $text));
}
} else {
$value = $options;
$text = $category;
$attributes = attrs("value=\"$value\"");
if ($value === $default)
$attributes->add('selected');
$select->add(tag('option', $attributes, $text));
}
}
return $select;
}
// creates a select element for a form given a certain range
// returns HTML data for the element
/**
* @param string $name
* @param int $lbound
* @param int $ubound
* @param int $increment
* @param bool|string $default
* @param bool|string $name_function
* @param bool $attrs
* @return Html
*/
function create_select_range($name, $lbound, $ubound, $increment = 1,
$default = false, $name_function = false, $attrs = false)
{
$options = array();
for ($i = $lbound; $i <= $ubound; $i += $increment) {
if ($name_function !== false) {
$text = $name_function($i);
} else {
$text = $i;
}
$options[$i] = $text;
}
return create_select($name, $options, $default, $attrs);
}
| php | Apache-2.0 | e9473676f311aac8e9577cb3371ed362418441d9 | 2026-01-05T04:51:20.275579Z | false |
sproctor/php-calendar | https://github.com/sproctor/php-calendar/blob/e9473676f311aac8e9577cb3371ed362418441d9/src/user_delete.php | src/user_delete.php | <?php
/*
* Copyright 2012 Sean Proctor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
if ( !defined('IN_PHPC') ) {
die("Hacking attempt");
}
/**
* @return Html
*/
function user_delete()
{
global $vars, $phpcid, $phpcdb, $phpc_script;
$html = tag('div', attributes('class="phpc-container"'));
if(!is_admin()) {
$html->add(tag('p', __('You must be an admin to delete users.')));
return $html;
}
if(empty($vars["uid"])) {
$html->add(tag('p', __('No user selected.')));
return $html;
}
if (is_array($vars["uid"])) {
$ids = $vars["uid"];
} else {
$ids = array($vars["uid"]);
}
if (empty($vars["confirm"])) {
$list = tag('ul');
foreach ($ids as $id) {
$user = $phpcdb->get_user($id);
$list->add(tag('li', "$id: ".$user->get_username()));
}
$html->add(tag('p', __('Confirm you want to delete:')));
$html->add($list);
$html->add(" [ ", create_action_link(__('Confirm'),
"user_delete", array("uid" => $ids,
"confirm" => "1")), " ] ");
$html->add(" [ ", create_action_link(__('Deny'),
"display_month"), " ] ");
return $html;
}
foreach($ids as $id) {
if($phpcdb->delete_user($id)) {
$html->add(tag('p', __("Removed user: $id")));
} else {
$html->add(tag('p', __("Could not remove user: $id")));
}
}
return message_redirect($html, "$phpc_script?action=admin&phpcid=$phpcid");
}
| php | Apache-2.0 | e9473676f311aac8e9577cb3371ed362418441d9 | 2026-01-05T04:51:20.275579Z | false |
sproctor/php-calendar | https://github.com/sproctor/php-calendar/blob/e9473676f311aac8e9577cb3371ed362418441d9/src/settings.php | src/settings.php | <?php
/*
* Copyright 2012 Sean Proctor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
if ( !defined('IN_PHPC') ) {
die("Hacking attempt");
}
/**
* @return Html
*/
function settings()
{
/** @var PhpcUser $phpc_user */
global $vars, $phpc_user;
if(!empty($vars["phpc_submit"]))
settings_submit();
$index = tag('ul',
tag('li', tag('a', attrs('href="#phpc-config"'),
__('Settings'))));
$forms = array();
$forms[] = config_form();
if(is_user() && $phpc_user->is_password_editable()) {
$forms[] = password_form();
$index->add(tag('li', tag('a', attrs('href="#phpc-password"'),
__('Password'))));
}
return tag('div', attrs('class="phpc-tabs"'), $index, $forms);
}
/**
* @return Html
*/
function password_form()
{
global $phpc_script, $phpc_token;
$form = tag('form', attributes("action=\"$phpc_script\"",
'method="post"'),
tag('table', attributes("class=\"phpc-container\""),
tag('caption', __('Change Password')),
tag('tfoot',
tag('tr',
tag('td', attributes('colspan="2"'),
create_hidden('phpc_token', $phpc_token),
create_hidden('action', 'password_submit'),
create_submit(__('Submit'))))),
tag('tbody',
tag('tr',
tag('th', __('Old Password')),
tag('td', create_password('old_password'))),
tag('tr',
tag('th', __('New Password')),
tag('td', create_password('password1'))),
tag('tr',
tag('th', __('Confirm New Password')),
tag('td', create_password('password2')))
)));
return tag('div', attrs('id="phpc-password"'), $form);
}
/**
* @return Html
*/
function config_form()
{
global $phpc_script, $phpc_user_tz, $phpc_user_lang, $phpc_token;
$tz_input = create_multi_select('timezone', get_timezone_list(),
$phpc_user_tz);
$languages = array("" => __("Default"));
foreach(get_languages() as $lang) {
$languages[$lang] = $lang;
}
$lang_input = create_select('language', $languages,
$phpc_user_lang);
$form = tag('form', attributes("action=\"$phpc_script\"",
'method="post"'),
tag('table', attributes("class=\"phpc-container\""),
tag('caption', __('Settings')),
tag('tfoot',
tag('tr',
tag('td', attributes('colspan="2"'),
create_hidden('phpc_token', $phpc_token),
create_hidden('action', 'settings'),
create_hidden('phpc_submit', 'settings'),
create_submit(__('Submit'))))),
tag('tbody',
tag('tr',
tag('th', __('Timezone')),
tag('td', $tz_input)),
tag('tr',
tag('th', __('Language')),
tag('td', $lang_input))
)));
return tag('div', attrs('id="phpc-config"'), $form);
}
function settings_submit()
{
/** @var PhpcUser $phpc_user */
global $vars, $phpcdb, $phpc_user_tz, $phpc_user_lang,
$phpc_prefix, $phpc_user;
verify_token();
// Expire 20 years in the future, give or take.
$expiration_time = time() + 20 * 365 * 24 * 60 * 60;
// One hour in the past
$past_time = time() - 3600;
if(!empty($vars["timezone"]))
phpc_set_cookie("{$phpc_prefix}tz", $vars['timezone'], $expiration_time);
else
phpc_set_cookie("{$phpc_prefix}tz", '', $past_time);
if(!empty($vars["language"]))
phpc_set_cookie("{$phpc_prefix}lang", $vars['language'], $expiration_time);
else
phpc_set_cookie("{$phpc_prefix}lang", '', $past_time);
if(is_user()) {
$uid = $phpc_user->get_uid();
$phpcdb->set_timezone($uid, $vars['timezone']);
$phpcdb->set_language($uid, $vars['language']);
$phpc_user_tz = $vars["timezone"];
$phpc_user_lang = $vars["language"];
}
message(__('Settings updated.'));
}
| php | Apache-2.0 | e9473676f311aac8e9577cb3371ed362418441d9 | 2026-01-05T04:51:20.275579Z | false |
sproctor/php-calendar | https://github.com/sproctor/php-calendar/blob/e9473676f311aac8e9577cb3371ed362418441d9/src/calendar_delete.php | src/calendar_delete.php | <?php
/*
* Copyright 2012 Sean Proctor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
if ( !defined('IN_PHPC') ) {
die("Hacking attempt");
}
/**
* @return Html
*/
function calendar_delete()
{
global $vars, $phpcdb, $phpc_script;
$html = tag('div', attributes('class="phpc-container"'));
if(empty($vars["cid"])) {
$html->add(tag('p', __('No calendar selected.')));
return $html;
}
$id = $vars["cid"];
$calendar = $phpcdb->get_calendar($id);
if(empty($calendar))
soft_error(__("Invalid calendar ID."));
if (empty($vars["confirm"])) {
$html->add(tag('p', __('Confirm you want to delete calendar:'). $calendar->get_title()));
$html->add(" [ ", create_action_link(__('Confirm'),
"calendar_delete", array("cid" => $id,
"confirm" => "1")), " ] ");
$html->add(" [ ", create_action_link(__('Deny'),
"display_month"), " ] ");
return $html;
}
if(!$calendar->can_admin()) {
$html->add(tag('p', __("You do not have permission to remove calendar") . ": $id"));
return $html;
}
if($phpcdb->delete_calendar($id)) {
$html->add(tag('p', __("Removed calendar") . ": $id"));
} else {
$html->add(tag('p', __("Could not remove calendar")
. ": $id"));
}
return message_redirect($html, "$phpc_script?action=admin");
}
| php | Apache-2.0 | e9473676f311aac8e9577cb3371ed362418441d9 | 2026-01-05T04:51:20.275579Z | false |
sproctor/php-calendar | https://github.com/sproctor/php-calendar/blob/e9473676f311aac8e9577cb3371ed362418441d9/src/import.php | src/import.php | <?php
/*
* Copyright 2013 Sean Proctor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
if(!defined('IN_PHPC')) {
die("Hacking attempt");
}
/**
* @return Html
*/
function import() {
global $vars, $phpcdb, $phpcid, $phpc_script;
if(!is_admin()) {
permission_error(__('Need to be admin'));
exit;
}
$form_page = "$phpc_script?action=admin#phpc-import";
if(!empty($vars['port']) && strlen($vars['port']) > 0) {
$port = $vars['port'];
} else {
$port = ini_get("mysqli.default_port");
}
$old_dbh = @new mysqli($vars['host'], $vars['username'], $vars['passwd'],
$vars['dbname'], $port);
if(!$old_dbh || mysqli_connect_errno()) {
return message_redirect("Database connect failed ("
. mysqli_connect_errno() . "): "
. mysqli_connect_error(),
$form_page);
}
$events_table = $vars['prefix'] . 'events';
$users_table = $vars['prefix'] . 'users';
// Create user lookup table
$users = array('anonymous' => '0');
foreach($phpcdb->get_users() as $user) {
$users[$user->get_username()] = $user->get_uid();
}
// Lookup old events
$query = "SELECT YEAR(`startdate`) as `year`, "
."MONTH(`startdate`) as `month`, "
."DAY(`startdate`) as `day`, YEAR(`enddate`) as `endyear`,"
."MONTH(`enddate`) as `endmonth`, DAY(`enddate`) as `endday`,"
."HOUR(`starttime`) as `hour`, MINUTE(`starttime`) as `minute`,"
."`duration`, `eventtype`, `subject`, `description`,"
."`username`, `password`\n"
."FROM `$events_table`\n"
."LEFT JOIN `$users_table` USING (`uid`)\n";
$sth = $old_dbh->query($query)
or $phpcdb->db_error(__('Error selecting events in import'),
$query);
$events = 0;
$occurrences = 0;
while($result = $sth->fetch_assoc()) {
$username = $result['username'];
if(empty($username) || strlen($username) == 0) {
$uid = 0;
} else {
if(!isset($users[$username])) {
$users[$username] = $phpcdb->create_user($username,
$result['password'], false);
}
$uid = $users[$username];
}
$eid = $phpcdb->create_event($phpcid, $uid,
$phpcdb->dbh->escape_string($result["subject"]),
$phpcdb->dbh->escape_string($result["description"]),
false, false);
$events++;
$eventtype = $result['eventtype'];
// Full Day or None
if($eventtype == 2 || $eventtype == 4)
$time_type = 1;
// TBA
elseif($eventtype == 3)
$time_type = 2;
// Normal (and all of the recurring)
else
$time_type = 0;
$year = $result['year'];
$month = $result['month'];
$day = $result['day'];
$hour = $result['hour'];
$minute = $result['minute'];
$duration = $result['duration'];
$final_ts = mktime($hour, $minute, 0, $result['endmonth'],
$result['endday'], $result['endyear']);
while(true) {
$start_ts = mktime($hour, $minute, 0, $month, $day,
$year);
if($start_ts > $final_ts)
break;
$endminute = $minute + ($duration % 60);
$endhour = ($hour + floor($duration / 60)) % 24;
$endday = $day + floor($endhour / 24);
$end_ts = mktime($endhour, $endminute, 0, $month,
$endday, $year);
$phpcdb->create_occurrence($eid, $time_type, $start_ts, $end_ts);
$occurrences++;
// Increment start time
switch($eventtype) {
case 1: // Normal
case 2: // Full Day
case 3: // TBA
case 4: // None
$day++;
break;
case 5: // Weekly
$day += 7;
break;
case 6: // Monthly
$month++;
break;
case 7: // Yearly
$year++;
break;
default:
echo "bad event!!";
exit;
}
}
}
return message_redirect(sprintf(__("Created %s events with %s occurences"),
$events, $occurrences),
$form_page);
}
| php | Apache-2.0 | e9473676f311aac8e9577cb3371ed362418441d9 | 2026-01-05T04:51:20.275579Z | false |
sproctor/php-calendar | https://github.com/sproctor/php-calendar/blob/e9473676f311aac8e9577cb3371ed362418441d9/src/phpccalendar.class.php | src/phpccalendar.class.php | <?php
/*
* Copyright 2012 Sean Proctor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
class PhpcCalendar {
/** @var int */
var $cid;
/** @var string */
var $title;
/** @var string[] */
var $user_perms;
/** @var array */
var $categories;
/** @var bool */
var $hours_24;
/** @var int */
var $date_format;
/** @var int */
var $week_start;
/** @var int */
var $subject_max;
/** @var int */
var $events_max;
/** @var int */
var $anon_permission;
/** @var string */
var $timezone;
/** @var string */
var $language;
/** @var string */
var $theme;
/** @var array */
var $groups;
/**
* PhpcCalendar constructor.
* @param string[] $result
*/
function __construct($result)
{
$this->cid = intval($result['cid']);
$this->title = $result['title'];
$this->hours_24 = intval($result['hours_24']) != 0;
$this->date_format = intval($result['date_format']);
$this->week_start = intval($result['week_start']);
$this->subject_max = intval($result['subject_max']);
$this->events_max = intval($result['events_max']);
$this->anon_permission = intval($result['anon_permission']);
$this->timezone = $result['timezone'];
$this->language = $result['language'];
$this->theme = $result['theme'];
}
/**
* @return string
*/
function get_title()
{
if(empty($this->title))
return __('(No title)');
return phpc_html_escape($this->title);
}
/**
* @return int
*/
function get_cid()
{
return $this->cid;
}
/**
* @return bool
*/
function can_read()
{
if ($this->anon_permission >= 1)
return true;
if (!is_user())
return false;
$this->require_user_perms();
return $this->can_admin() || !empty($this->user_perms["read"]);
}
/**
* @return bool
*/
function can_write()
{
if ($this->anon_permission >= 2)
return true;
if (!is_user())
return false;
$this->require_user_perms();
return $this->can_admin() || !empty($this->user_perms["write"]);
}
/**
* @return bool
*/
function can_admin()
{
if (!is_user())
return false;
$this->require_user_perms();
return is_admin() || !empty($this->user_perms["admin"]);
}
function require_user_perms() {
global $phpcdb, $phpc_user;
if(!isset($this->user_perms))
$this->user_perms = $phpcdb->get_permissions($this->cid,
$phpc_user->get_uid());
}
/**
* @return bool
*/
function can_modify()
{
if ($this->anon_permission >= 3)
return true;
if (!is_user())
return false;
$this->require_user_perms();
return $this->can_admin()
|| !empty($this->user_perms["modify"]);
}
/**
* @return bool
*/
function can_create_readonly()
{
if (!is_user())
return false;
$this->require_user_perms();
return $this->can_admin()
|| !empty($this->user_perms["readonly"]);
}
/**
* @param int $uid
* @return array
*/
function get_visible_categories($uid) {
global $phpcdb;
return $phpcdb->get_visible_categories($uid, $this->cid);
}
/**
* @return array
*/
function get_categories() {
global $phpcdb;
if(!isset($this->categories)) {
$this->categories = $phpcdb->get_categories($this->cid);
}
return $this->categories;
}
/**
* @return array
*/
function get_groups() {
global $phpcdb;
if(!isset($this->groups)) {
$this->groups = $phpcdb->get_groups($this->cid);
}
return $this->groups;
}
}
| php | Apache-2.0 | e9473676f311aac8e9577cb3371ed362418441d9 | 2026-01-05T04:51:20.275579Z | false |
sproctor/php-calendar | https://github.com/sproctor/php-calendar/blob/e9473676f311aac8e9577cb3371ed362418441d9/src/embed.php | src/embed.php | <?php
/*
* Copyright 2012 Sean Proctor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
if ( !defined('IN_PHPC') ) {
die("Invalid setup");
}
try {
require_once("$phpc_includes_path/calendar.php");
require_once("$phpc_includes_path/setup.php");
$calendar_title = $phpc_cal->get_title();
$content = display_phpc();
} catch(Exception $e) {
$calendar_title = $e->getMessage();
$content = tag('div', attributes('class="php-calendar"'),
$e->getMessage());
}
$head = tag('div', attrs('class="phpc-head"'),
get_header_tags("static"));
echo $head->toString();
echo $content->toString();
| php | Apache-2.0 | e9473676f311aac8e9577cb3371ed362418441d9 | 2026-01-05T04:51:20.275579Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.